您只需将 POST 请求发送到:
https://api.telegram.org/bot{token}/{method}
例如:
https://api.telegram.org/bot123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11/sendMessage
在请求的正文中,您对参数进行 URL 编码:
chat_id=12345&text=hello%20friend
例如,在 Python 中使用requests
模块:
import requests
response = requests.post(
url='https://api.telegram.org/bot{0}/{1}'.format(token, method),
data={'chat_id': 12345, 'text': 'hello friend'}
).json()
当用户与您的机器人聊天时,您将获得一个具有聊天 ID(以及用户 ID,您可以用它代替聊天 ID)的Message
对象。除非您已经知道他们的用户 ID,否则无法启动与用户的聊天,因此您必须等待用户与您交谈。您可以通过使用深层链接并让用户单击一个链接来简化这一过程,当他们点击“开始”按钮时,该链接会发送一条预制消息。
编辑:对于那些努力寻找chat_id的人,这里有一种方法:
1.-创建一个机器人:在 Telegram 的搜索中寻找@BotFather。点击开始,写 /newbot,给它一个名字和一个用户名。您应该获得一个令牌来访问 HTTP API。保存此令牌。
2.-使用其用户名在 Telegram 上找到您的机器人。给它写一些东西,例如“测试”。这将在以后派上用场。
3.- 打印chat_id 。在运行此功能之前,请确保您至少已在 Telegram 上向您的机器人写了一条消息(步骤 2)
Javascript代码:
var token = "123456:kioASDdjicOljd_ijsdf"; // Fill this in with your token
var telegramUrl = "https://api.telegram.org/bot" + token;
function getChat_id(){
var res = UrlFetchApp.fetch(telegramUrl+"/getUpdates").getContentText();
var res = JSON.parse(res);
Logger.log(res.result[0].message.chat.id.toString());
}