利用 Telegram Bot 发送消息

发布于 2022-08-21  38 次阅读


在写自动化脚本的时候,时常需要推送运行结果给用户,方式有许多,除了传统的邮件,也有PushDeerServer酱之类的即时推送服务。

本文将分享一种简单、易用且稳定的即时推送方式——Telegram Bot。

注意:使用Telegram需要科学上网。

创建机器人

  1. 打开Telegram,搜索BotFather,并点击SEND MESSAGE打开聊天页面。
  2. 发送/newbot以开始创建机器人。
  3. 对方会提示输入机器人的名字,发送你想要的名字即可。此处设定的实际上是机器人的昵称,不要求唯一性。
  4. 而后会提示输入机器人的用户名username,同样发送即可。这个用户名要求唯一性,如果已被占用,会提示你重新发送。
  5. 用户名设定完成后即成功创建了机器人,对方会发送你的机器人token,请妥善保管,不要泄露。

如:

Use this token to access the HTTP API:
xxxxxxxxxxxxxxxx //此为token
Keep your token secure and store it safely, it can be used by anyone to control your bot.

获取chat_id

要调用机器人发送消息,除了token,还需要一个chat_id,表示向哪个聊天窗口发送消息

方才机器人创建成功后,对方发送的消息中除了token,还包含了蓝色字样、带下划线的,与你的机器人开始聊天的链接,如t.me/xxxx,斜杠右边为你的机器人名。

  1. 点击该链接开启聊天窗口,随便向其发送一点文字。
  2. 访问如下链接:https://api.telegram.org/bot{token}/getUpdates ,请将{token}替换为你的机器人token
  3. 页面显示应当如下:
{  
    "ok" : true,  
    "result" : [{  
            "update_id" : xxx,  
            "message" : {  
                "message_id" : 4,  
                "from" : {  
                    "id" : xxx,  
                    "first_name" : "david",  
                    "last_name" : "huang",  
                    "username" : "davidhuang"  
                },  
                "chat" : {  
                    "id" : xxx, //此处为chat_id
                    "title" : "bot",  
                    "type" : "group",  
                    "all_members_are_administrators" : true  
                },  
                "date" : xxx,  
                "text" : "/hello @GZ_David_Bot",  
                "entities" : [{  
                        "type" : "bot_command",  
                        "offset" : 0,  
                        "length" : 6  
                    }  
                ]  
            }  
        },  
    ]  
} 
  1. 其中包含的chat_id指向你与机器人的聊天窗口。

发送消息

有了tokenchat_id,现在我们可以利用机器人发送消息了。

只需访问链接:https://api.telegram.org/bot{token}/sendMessage?chat_id={chat_id}&text={message},即可调用机器人向聊天窗口发送消息。

请注意将{token}{chat_id}做相应替换,{message}为要发送的消息。

另外,如果在消息中需要换行,请使用%0a,而非\n

这一步的实现方式多种多样,可以在selenium程序中,使用webdriverget方法;也可以在shell中使用curl -X POST 链接,视具体项目而定。

全文完