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

如何实现Telegram群组机器人按固定周期自动定时发帖功能?

Telegram 机器人定时推送实现方案

你现有的测试方案存在两个核心问题:

  • 单线程sleep只会执行一次推送,无法实现周期性触发,要是套while True会直接阻塞命令处理线程,导致机器人无法响应其他任何交互请求
  • 手动维护定时线程容易出现并发异常、时间不准的问题,完全可以直接用python-telegram-bot内置的JobQueue定时器组件实现,稳定性更高

完整可运行代码

import telegram
from telegram.ext import Updater
from telegram.ext import CommandHandler
from tracker import get_prices

telegram_bot_token = "xxx:xxx"

updater = Updater(token=telegram_bot_token, use_context=True)
dispatcher = updater.dispatcher
job_queue = updater.job_queue

# 抽离公共的发送消息逻辑
def send_crypto_data(context):
    job = context.job
    chat_id = job.context
    message = ""

    crypto_data = get_prices()
    for i in crypto_data:
        coin = crypto_data[i]["coin"]
        price = crypto_data[i]["price"]
        change_day = crypto_data[i]["change_day"]
        change_hour = crypto_data[i]["change_hour"]
        message += f"Coin: {coin}\nPrice: ${price:,.2f}\nHour Change: {change_hour:.3f}%\nDay Change: {change_day:.3f}%\n\n"

    context.bot.send_message(chat_id=chat_id, text=message)

# /start 命令处理:注册定时任务
def start(update, context):
    chat_id = update.effective_chat.id
    # 先立即推送一次
    send_crypto_data(context)
    # 注册周期性任务,间隔6小时(21600秒),把chat_id传给任务上下文
    job_queue.run_repeating(send_crypto_data, interval=21600, first=0, context=chat_id)
    update.message.reply_text("已开启定时推送,后续每6小时将自动为你发送加密货币行情")

dispatcher.add_handler(CommandHandler("start", start))
updater.start_polling()
updater.idle()

关键说明

  • 代码中的interval参数就是定时周期,单位为秒,你需要其他周期直接换算后修改即可,比如1小时就填3600,12小时就填43200
  • 这个实现不会阻塞机器人的正常响应,同时支持多用户使用,每个用户发送/start后都会单独给自己开启定时推送,互不影响
  • 如果你需要机器人重启后不需要用户重新发/start开启推送,可以把已经开启推送的chat_id存入本地文件或者数据库,机器人启动时读取所有有效chat_id,批量调用job_queue.run_repeating注册任务即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 03:36:02