首页 > 解决方案 > 如何让我的 python 电报机器人每天在特定时间发送消息?

问题描述

我正在尝试制作一个能够在每天特定时间通知用户的机器人。如何让机器人每天在特定时间发送通知?

我尝试使用 while 循环,但它是

@bot.callback_query_handler(func=lambda c:True)
def CalendarAnswer(c):
    Cid = c.message.chat.id
    if c.data == 'ShowTime':
        bot.send_message(Cid, timeToday)
    if c.data == 'ShowDate':
        bot.send_message(Cid, dateToday)
    if c.data == 'SetNotification':
        Ask = bot.send_message(Cid, 'Напиши мне время')
        bot.register_next_step_handler(Ask,SettingNotificationTime)
def SettingNotificationTime(message):
    NotificationTime = message.text
    bot.send_message(message.chat.id, "that's your time:" + NotificationTime)v

我不知道如何解决我的问题

标签: pythonpython-3.xtelegram-botpython-telegram-bot

解决方案


您可以使用类 telegram.ext中的JobQueue

它有一个名为 run_daily 的函数。

run_daily(callback, time, days=(0, 1, 2, 3, 4, 5, 6), context=None, name=None)

这是一个例子:

def callback_alarm(context: telegram.ext.CallbackContext):
  bot.send_message(chat_id=id, text='Hi, This is a daily reminder')

def reminder(update,context):
   bot.send_message(chat_id = update.effective_chat.id , text='Daily reminder has been set! You\'ll get notified at 8 AM daily')
   context.job_queue.run_daily(callback_alarm, context=update.message.chat_id,days=(0, 1, 2, 3, 4, 5, 6),time = time(hour = 10, minute = 10, second = 10))

run_daily函数每天上午10:10:10调用callback_alarm函数


推荐阅读