You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于telebot的Python定时通知机器人技术咨询

解决telebot开发中的两个核心问题:无处理器发消息+定时推送

嘿,我来帮你搞定这两个问题,都是telebot开发中很常见的需求,咱们一个个说:

1. 不依赖@bot.message_handler发送消息

当然可以脱离处理器直接发消息!你之前尝试没效果大概率是没拿到正确的chat_id,或者调用时机不对。只要你有目标用户的chat_id,直接调用bot.send_message()就可以,完全不需要绑定任何消息处理器。

怎么获取用户的chat_id?

你可以先在现有复读功能里加一行打印,这样用户给bot发消息时,控制台就会输出对应的chat_id:

import telebot
bot = telebot.TeleBot('你的Bot Token')

@bot.message_handler(content_types=["text"])
def repeat(message):
    print(f"当前用户chat_id: {message.chat.id}")  # 新增这行
    bot.send_message(message.chat.id, message.text)

if __name__ == '__main__':
    bot.polling(none_stop=True)

拿到chat_id后,就可以在任意地方调用发送消息了,比如程序启动时发一条测试消息:

if __name__ == '__main__':
    # 直接发送消息,不需要处理器
    target_chat_id = 123456789  # 替换成你拿到的实际chat_id
    bot.send_message(target_chat_id, "这是一条不需要处理器的测试消息!")
    bot.polling(none_stop=True)

2. 实现每日两次定时推送通知

telebot本身没有内置定时任务功能,咱们可以用Python的第三方定时任务库来实现,推荐APScheduler(功能强大,支持多种定时规则),或者轻量的schedule库,这里用APScheduler来演示。

步骤:

  1. 先安装APScheduler:
pip install apscheduler
  1. 编写定时任务逻辑,注意要把定时任务放在独立线程中运行,避免和bot.polling()的阻塞冲突。

完整示例代码

import telebot
from apscheduler.schedulers.background import BackgroundScheduler
import time

# 初始化Bot
bot = telebot.TeleBot('你的Bot Token')
TARGET_CHAT_ID = 123456789  # 替换成目标用户的chat_id

# 复读功能保持不变
@bot.message_handler(content_types=["text"])
def repeat(message):
    bot.send_message(message.chat.id, message.text)

# 定义定时发送通知的函数
def send_daily_notification():
    try:
        bot.send_message(TARGET_CHAT_ID, "早上好!这是每日第一次通知😊")
    except Exception as e:
        print(f"发送通知失败: {e}")

def send_evening_notification():
    try:
        bot.send_message(TARGET_CHAT_ID, "晚上好!这是每日第二次通知🌙")
    except Exception as e:
        print(f"发送通知失败: {e}")

if __name__ == '__main__':
    # 初始化后台调度器
    scheduler = BackgroundScheduler(timezone='Asia/Shanghai')  # 设置时区,比如北京时间
    # 添加定时任务:每天8点发送早间通知
    scheduler.add_job(send_daily_notification, 'cron', hour=8, minute=0)
    # 添加定时任务:每天20点发送晚间通知
    scheduler.add_job(send_evening_notification, 'cron', hour=20, minute=0)
    
    # 启动调度器
    scheduler.start()
    print("定时任务已启动")
    
    # 启动Bot的polling
    try:
        bot.polling(none_stop=True)
    except KeyboardInterrupt:
        # 停止调度器
        scheduler.shutdown()
        print("程序已退出")

代码说明:

  • BackgroundScheduler是后台调度器,不会阻塞主进程,适合和bot.polling()配合使用
  • cron表达式用来设置定时规则,hour=8, minute=0就是每天8点整执行
  • 加上异常捕获是为了避免网络问题导致程序崩溃
  • 时区设置很重要,不然定时时间可能会偏差

内容的提问来源于stack exchange,提问作者X21

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:37:21