Telegram机器人定时发消息报错:User.send_message()意外参数'chat_id'
Telegram机器人定时推送报错排查与解决
错误原因
你调用了User.send_message()方法却传入了chat_id参数,这是核心问题。不管用的是哪个Telegram Bot库,User对象的send_message方法不需要额外传chat_id(因为User本身就关联了聊天身份),但更大概率是你搞混了调用对象——应该用机器人实例(bot)的send_message方法,而不是User对象的。
解决步骤
1. 修正调用对象
如果你的错误代码是类似这样:
user.send_message(chat_id=xxx, text="用户数量统计")
直接改成用bot实例调用:
bot.send_message(chat_id=xxx, text="当前循环内用户数量:{}".format(user_count))
2. 结合schedule库的正确示例
假设你已经有可用的bot实例,下面是定时推送的完整可行写法:
import schedule import time # 模拟获取当前循环内用户数量的函数 def get_current_user_count(): return len(active_user_list) # active_user_list是你的用户列表 def push_user_count(): user_count = get_current_user_count() # 替换成你要推送的聊天ID列表 target_chat_ids = [123456789, 987654321] for chat_id in target_chat_ids: try: bot.send_message(chat_id=chat_id, text=f"定时推送:当前循环内共有 {user_count} 位用户") except Exception as e: print(f"给{chat_id}推送失败:{str(e)}") # 设置定时规则,比如每天14点推送 schedule.every().day.at("14:00").do(push_user_count) # 保持定时任务运行 while True: schedule.run_pending() time.sleep(60) # 每分钟检查一次任务
3. 适配新版本库的注意事项
如果用的是python-telegram-bot v20及以上版本,库是异步架构,schedule同步任务需要套一层异步执行的包装:
import asyncio import schedule async def async_push_count(): user_count = get_current_user_count() target_chat_ids = [123456789, 987654321] for chat_id in target_chat_ids: try: await bot.send_message(chat_id=chat_id, text=f"定时推送:当前循环内共有 {user_count} 位用户") except Exception as e: print(f"推送失败:{str(e)}") # 包装异步函数为同步调用 def sync_wrapper(): asyncio.run(async_push_count()) schedule.every().day.at("14:00").do(sync_wrapper) while True: schedule.run_pending() time.sleep(60)
内容的提问来源于stack exchange,提问作者yyq1
相关产品推荐
相关产品推荐

