Telepot开发树莓派CPU温度监控Bot遇发送超时错误求助
解决Telepot Bot 10分钟后发送消息超时及线程错误问题
看起来你碰到了两个关联的问题:Telegram API请求超时,以及后台消息循环线程在程序异常时的报错。咱们一步步拆解解决:
1. 错误根源分析
- ReadTimeoutError:这是bot向Telegram API发送请求时,超过了默认30秒的读取超时时间。大概率是树莓派长时间休眠后网络连接状态波动,或者主循环里的
time.sleep(60)阻塞了主线程,影响了API请求的正常处理。 - 线程TypeError:这个报错出现在
Thread-1,是因为主线程长时间sleep,当程序出现异常退出时,后台的message_loop线程尝试访问已经被销毁的对象,导致NoneType调用错误。
2. 具体解决方案
方案一:重构主循环,避免主线程阻塞
别再用while 1 + time.sleep(60)的方式了,改用threading.Timer实现定时检测,这样不会阻塞主线程,让message_loop的后台线程能正常运行:
import threading import time import telepot TOKEN = "你的TOKEN" users = ["你的用户ID"] LAST_ALARM_TIME = 0 ALARM_COOLDOWN = 600 # 10分钟冷却,单位秒 TEMP_THRESHOLD = 30.0 def get_cpu_temperature(): # 你的CPU温度获取逻辑,示例如下 with open('/sys/class/thermal/thermal_zone0/temp', 'r') as f: temp = float(f.read()) / 1000 return temp def check_temperature(): global LAST_ALARM_TIME current_temp = get_cpu_temperature() current_time = time.time() if current_temp > TEMP_THRESHOLD and (current_time - LAST_ALARM_TIME) > ALARM_COOLDOWN: try: data = f"Temperature: {current_temp} 'C" bot.sendMessage(users[0], data) LAST_ALARM_TIME = current_time print("告警消息已发送") except Exception as e: print(f"发送消息失败: {str(e)}") # 这里可以添加简单的重试逻辑 # 1分钟后再次执行检测 threading.Timer(60, check_temperature).start() def handle(msg): # 你的消息处理逻辑,保持原有实现即可 content_type, chat_type, chat_id = telepot.glance(msg) print(content_type, chat_type, chat_id) if __name__ == "__main__": bot = telepot.Bot(TOKEN) bot.message_loop(handle) print('Bot已启动,开始监控温度...') # 启动第一次温度检测 check_temperature() # 让主线程保持运行,避免直接退出 while True: time.sleep(10)
方案二:调整Telepot的API超时设置
初始化bot时可以设置更长的超时时间,应对网络波动:
# 把超时时间设置为60秒,默认是30秒 bot = telepot.Bot(TOKEN, timeout=60)
如果还是频繁超时,可以添加重试机制,比如用tenacity库(先安装:pip install tenacity):
from tenacity import retry, stop_after_attempt, wait_exponential @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10)) def send_alarm_message(bot, user_id, message): bot.sendMessage(user_id, message) # 在check_temperature里替换原有的sendMessage调用 send_alarm_message(bot, users[0], data)
方案三:升级到Python3(强烈推荐)
你现在用的Python2.7已经停止维护了,telepot对Python3的支持更完善,很多线程和网络相关的问题在Python3里已经被修复。建议迁移代码到Python3,同时更新telepot到最新版本:
pip3 install telepot --upgrade
3. 额外检查点
- 确认你的
alarm()函数逻辑正确,比如是否用了正确的时间戳计算10分钟冷却时间,有没有出现时间重置错误。 - 测试树莓派的网络稳定性,用
ping api.telegram.org看看是否能持续连通。
内容的提问来源于stack exchange,提问作者ScazzoMatto
相关产品推荐
相关产品推荐

