【问题标题】:how to make my python telegram bot to send message at certain time every day?如何让我的 python 电报机器人每天在特定时间发送消息?
【发布时间】:2020-01-20 20:03:43
【问题描述】:

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

我尝试使用 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

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

【问题讨论】:

  • at 或 cron 怎么样?
  • 你在说什么?

标签: python python-3.x telegram-bot python-telegram-bot


【解决方案1】:

你可以使用类 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 AM

调用 callback_alarm 函数

【讨论】:

  • 如何在更新程序中做广告,我们应该使用消息处理程序还是命令处理程序?
【解决方案2】:

对于定期调度批处理任务,您应该系统内置:

在 Windows 上,它是任务计划程序,以前称为“at”的命令:

https://www.windowscentral.com/how-create-task-using-task-scheduler-command-prompt

在 Windows 10 上,任务计划程序是一种工具,可让您自动创建和运行几乎任何任务。通常,系统和 某些应用程序使用调度程序来自动执行维护任务(例如 磁盘碎片整理、磁盘清理和更新),但任何人都可以使用 它。有了这个经验,你可以启动应用程序,运行命令, 并在特定的日期和时间执行脚本,或者您也可以 当特定事件发生时触发任务。

任务计划程序的工作原理是密切关注您的时间和事件 计算机并在满足条件时立即执行任务。

您是否尝试使用任务计划程序在 特定时间或事件发生时,您可以在 使用基本设置和高级设置的至少两种不同方式。

与此相关的是“at”命令:

https://support.microsoft.com/en-us/help/313565/how-to-use-the-at-command-to-schedule-tasks

at 命令使用以下语法:

at \\computername time /interactive | /every:date,... /next:date,... command
at \\computername id /delete | /delete/yes

在 Linux 上,它是“cron”:

https://opensource.com/article/17/11/how-use-cron-linux

【讨论】:

    猜你喜欢
    • 2019-07-27
    • 1970-01-01
    • 1970-01-01
    • 2021-03-11
    • 1970-01-01
    • 2019-07-11
    • 2017-03-19
    • 2019-05-18
    • 1970-01-01
    相关资源
    最近更新 更多