导入telegram_interface触发Telegram Bot多实例getUpdates报错咨询
报错原因
Telegram Bot API明确规定同一个bot token同一时间只能存在一个活跃的getUpdates请求,你当前的代码问题出在telegram_interface.py的顶级作用域直接写了启动bot消息循环的逻辑:
- 只要其他模块导入该文件,Python会自动执行文件内所有顶级代码,会重复创建bot实例、调用
bot111.message_loop(handle)启动新的getUpdates请求,和原本运行的bot实例冲突,触发报错。 - 末尾的
while True死循环也会在导入时直接执行,导致导入操作直接卡住。
解决方案
推荐两种可行方案,可根据自身需求选择:
方案1:拆分功能模块(最稳妥)
把发消息的通用能力和bot消息监听逻辑拆分成两个独立文件,避免导入时触发监听逻辑:
- 新建
telegram_sender.py,仅保留发消息相关的代码:
import configparser import requests config = configparser.ConfigParser() config.read("config1.ini") bot_token = str(config["TelegramBot1"]["bot_token"]) my_chat_id = str(config["TelegramBot1"]["my_chat_id"]) def send_msg(text): url = f"https://api.telegram.org/bot{bot_token}/sendMessage?chat_id={my_chat_id}&parse_mode=Markdown&text={text}" response = requests.get(url) return response.json()
- 其他模块需要发消息时直接导入
telegram_sender.py的send_msg方法即可,完全不会涉及getUpdates请求,不会产生冲突。 - 原本的
telegram_interface.py保留消息监听、指令处理逻辑,单独作为独立进程运行即可。
方案2:添加入口守卫,避免导入时执行监听逻辑
如果不想拆分模块,可以把启动监听的代码放到if __name__ == "__main__"守卫下,只有直接运行该文件时才会执行监听逻辑,导入时不会触发:
修改后的telegram_interface.py末尾代码调整为:
# 前面的导入、配置加载、函数定义都保持不变 if __name__ == "__main__": bot111.message_loop(handle) while True: time.sleep(20)
调整后其他模块导入telegram_interface.py时,不会启动新的消息循环,也就不会产生多实例冲突。
注意事项
- 同一个bot token调用sendMessage发消息没有数量限制,只有调用getUpdates拉取用户消息的接口会有单实例限制,只要保证只有一个进程调用getUpdates即可。
内容的提问来源于stack exchange,提问作者Mohammed Darwish
相关产品推荐
相关产品推荐

