首页 > 解决方案 > 使用机器人定期发送电报消息

问题描述

给出下面的代码:

def start(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id, text="I'm a bot, please talk to me!")

是否可以定期调用此函数并让我的机器人自动将消息发送给用户,而不是用户键入“/start”

标签: python-3.xtelegramtelegram-botpython-telegram-bot

解决方案


您需要创建一个job由它提供的对象,python-telegram-bot 以便简单地运行该函数,start假设您每分钟都可以使用这种方法:

j= updater.job_queue

def start(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id, text="I'm a bot, please talk to me!")

j.run_repeating(start,interval = 60  ,first= 0 )
updater.start_polling()

如果您想每天在特定时间运行它,您可以使用:

import datetime 
j= updater.job_queue

def start(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id, text="I'm a bot, please talk to me!")

t= datetime.time(6, 15, 00, 000000)

j.run_daily(start, t, days=(0, 1, 2, 3, 4, 5, 6), context=None, name=None)
updater.start_polling()

请注意,没有要添加到调度程序的处理程序。

如果没有修改,您可能应该知道该datetime.time对象使用 UTC 时间。

有关更多信息,请查看Extensions – JobQueue here


推荐阅读