首页 > 解决方案 > Telegram bot api如何安排通知?

问题描述

我制作了一个机器人,可以获取今天的足球比赛,如果用户想要,他可以在所选比赛前 10 分钟收到提醒。

while current_time != new_hour:
        now = datetime.now()
        current_time = now.strftime("%H:%M")
#return notification
    text_caps = "Your match starts in 10 minutes"
    context.bot.send_message(chat_id=update.effective_chat.id, text=text_caps)

显然,当循环运行时,我不能使用另一个命令。我是编程新手,我怎么能实现这个,所以我仍然收到通知,但是在运行时我可以使用其他命令?

谢谢!

标签: pythontelegramtelegram-botpython-telegram-bot

解决方案


您可以安排工作。
假设您有一个CommandHandler("watch_match", watch_match)监听/watch_match命令,10 分钟后应该有一条消息到达

def watch_match(update: Update, context: CallbackContext):
    chat_id = update.effective_chat.id
    ten_minutes = 60 * 10 # 10 minutes in seconds  
    context.job_queue.run_once(callback=send_match_info, when=ten_minutes, context=chat_id) 
    # Whatever you pass here as context is available in the job.context variable of the callback

def send_match_info(context: CallbackContext):
    chat_id = context.job.context
    context.bot.send_message(chat_id=chat_id, text="Yay")

官方存储库中的更详细示例
并且在官方文档中您可以看到该run_once 功能


推荐阅读