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

Telegram价格bot无法实现每5分钟定时推送最新价格问题求助

解决方案

你当前的代码仅在用户发送/start命令时才会单次触发价格推送,要实现定时自动推送,可以直接使用python-telegram-bot库内置的JobQueue定时任务模块,不需要额外引入第三方依赖。

修改后的完整代码

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

telegram_bot_token = "mybot"

updater = Updater(token=telegram_bot_token, use_context=True)
dispatcher = updater.dispatcher
job_queue = updater.job_queue # 初始化定时任务队列

# 单独抽离发送价格的通用函数
def send_price(context):
    chat_id = context.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}={price:,.5f}$ \nHour Change: {change_hour:.3f}%\nDay Change: {change_day:.3f}%\n\n"
    context.bot.send_message(chat_id=chat_id, text=message)

def start(update, context):
    chat_id = update.effective_chat.id
    # 先发送一次当前价格
    send_price(context)
    # 新增定时任务:每5分钟执行一次,单位为秒
    # 先判断是否已经有同个chat的定时任务,避免重复添加
    current_jobs = job_queue.get_jobs_by_name(f"price_push_{chat_id}")
    if current_jobs:
        for job in current_jobs:
            job.schedule_removal()
    # 添加新的定时任务,命名方便后续管理
    job_queue.run_repeating(
        send_price,
        interval=5*60, # 间隔时间,秒为单位,要改更长直接改这里就行
        first=0, # 首次执行延迟时间,0表示立即执行
        context=chat_id,
        name=f"price_push_{chat_id}"
    )
    update.message.reply_text("已开启定时价格推送,每5分钟更新一次")

# 可选:加个停止推送的命令
def stop(update, context):
    chat_id = update.effective_chat.id
    current_jobs = job_queue.get_jobs_by_name(f"price_push_{chat_id}")
    if not current_jobs:
        update.message.reply_text("当前没有开启的定时推送任务")
        return
    for job in current_jobs:
        job.schedule_removal()
    update.message.reply_text("已停止定时价格推送")

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

注意事项

  • 定时间隔以秒为单位,如果需要调整为更长时间,直接修改interval参数即可,比如1小时就设为3600
  • 代码里加了重复任务校验,多次发送/start不会重复创建推送任务
  • 新增了/stop命令,可以随时停止定时推送
  • 最后加的updater.idle()是为了保证进程不会异常退出,维持定时任务运行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 03:00:02