Python开发Telegram客户端触发无限循环问题求助
Telegram客户端无限循环问题的原因分析
最可能的原因是未正确更新消息偏移量(offset),这是Telegram Bot API长轮询模式下的典型错误:
- 当你通过
getUpdates接口拉取消息时,Telegram服务器会返回所有未被确认的消息。如果每次处理完消息后,你没有将offset参数设置为最后一条消息的update_id + 1,服务器会持续重复返回同一条未确认的消息。 - 你的第一段代码在收到非"ping"消息时,每次循环都会重新获取这条旧消息,然后重复回复"Okay.",看起来就像进入了无限循环。
而你修改后的第二段代码能正常工作,大概率是因为它正确处理了偏移量:要么使用了库自带的更新处理器(比如python-telegram-bot的Updater类,会自动管理offset),要么手动在每次处理完消息后更新了offset值,确保只拉取新的消息。
举个错误代码的例子(模拟你的第一段代码逻辑):
import requests TOKEN = "你的机器人令牌" BASE_URL = f"https://api.telegram.org/bot{TOKEN}/" def fetch_updates(): return requests.get(f"{BASE_URL}getUpdates").json() def send_reply(chat_id, text): requests.get(f"{BASE_URL}sendMessage?chat_id={chat_id}&text={text}") while True: updates = fetch_updates()["result"] if updates: for update in updates: msg_text = update["message"]["text"] chat_id = update["message"]["chat"]["id"] if msg_text == "ping": send_reply(chat_id, "pong") else: send_reply(chat_id, "Okay.")
这段代码的问题就是每次调用getUpdates都不带offset参数,导致Telegram反复返回同一条消息。修正方法是添加offset管理:
import requests TOKEN = "你的机器人令牌" BASE_URL = f"https://api.telegram.org/bot{TOKEN}/" last_update_id = 0 def fetch_updates(offset): return requests.get(f"{BASE_URL}getUpdates?offset={offset}").json() def send_reply(chat_id, text): requests.get(f"{BASE_URL}sendMessage?chat_id={chat_id}&text={text}") while True: updates = fetch_updates(last_update_id)["result"] if updates: for update in updates: msg_text = update["message"]["text"] chat_id = update["message"]["chat"]["id"] if msg_text == "ping": send_reply(chat_id, "pong") else: send_reply(chat_id, "Okay.") # 更新offset,确保下次只拉取新消息 last_update_id = update["update_id"] + 1
内容的提问来源于stack exchange,提问作者thisissifumwike
相关产品推荐
相关产品推荐

