Telegram Bot API
创建 Bot
与 BotFather 对话:
-
发送
/newbot。 -
发送你要给 Bot 起的名字
-
发送你要给 Bot 设置的用户名,必须全球唯一。
-
你会得到一条含有 Bot HTTP API Token 的信息。Token 内容类似如下:
1234567890:ABCdeFgHijklMNoPqrs_tu1v2w3x4y5ZaBC下文将以
<token>代替。
HTTP API
所有对 Telegram Bot API 的查询都以这种形式呈现:
https://api.telegram.org/bot<token>/METHOD_NAME
比如说,查询 Bot 的基本信息:
https://api.telegram.org/bot1234567890:ABCdeFgHijklMNoPqrs_tu1v2w3x4y5ZaBC/getMe
获取消息
使用 getUpdates API。接口返回所有用户和 Bot 的对话记录。
{
"ok": true,
"result": [ // 更新对象列表
{
"update_id": 193997045, // 更新 ID
"message": { // 消息对象
"message_id": 1, // 消息 ID
"from": {...}, // 发送者
"chat": {...}, // 对话对象,每个用户有唯一的 Chat ID
"date": 1746262658, // 日期
"text": "some text", // 消息内容
"entities": [...] // 特殊实体列表
}
}
]
}
发送消息
使用 sendMessage API。
{
"chat_id": "<ChatID>",
"text": "你好,这是来自机器人的消息!"
}
import requests
bot_token = 'YOUR_BOT_TOKEN'
chat_id = 'USER_CHAT_ID'
message = 'Hello from Telegram Bot!'
url = f'https://api.telegram.org/bot{bot_token}/sendMessage'
payload = {
'chat_id': chat_id,
'text': message
}
response = requests.post(url, json=payload)
if response.ok:
print('Message sent successfully!')
else:
print('Send failed:', response.text)
Python
Reference
Introduction to the API
pip install python-telegram-bot
示例代码:
参见:

浙公网安备 33010602011771号