bbf*_*bfl 3 python scheduled-tasks telegram python-telegram-bot telegram-bot
我在构建机器人方面相当新,所以我创建了一个非常简单的 Telegram 机器人,它工作得很好,但无法弄清楚如何让机器人在启动 /start_auto 命令时每 n 分钟或 n 小时发送消息。
我使用 while 循环做了一个解决方法,但它看起来很愚蠢,并且在循环期间用户将无法与机器人就其他主题进行交互。
我希望用户能够通过 /start_auto 和 /stop_auto 等命令启动和停止此计划任务。
我知道还有许多其他已回答的与该主题相关的问题,但似乎没有一个问题适用于我的代码。
import logging
import os
import time
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
logger = logging.getLogger(__name__)
PORT = int(os.environ.get('PORT', '8443'))
def start(update, context):
"""Sends a message when the command /start is issued."""
update.message.reply_text('Hi!')
def help(update, context):
"""Sends a message when the command /help is issued."""
update.message.reply_text('Help!')
def start_auto(update, context):
"""Sends a message when the command /start_auto is issued."""
n = 0
while n < 12:
time.sleep(3600)
update.message.reply_text('Auto message!')
n += 1
def error(update, context):
"""Logs Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, context.error)
def main():
TOKEN = 'TOKEN_GOES_HERE'
APP_NAME = 'https://my-tele-test.herokuapp.com/'
updater = Updater(TOKEN, use_context=True)
# Get the dispatcher to register handlers
dp = updater.dispatcher
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
dp.add_handler(CommandHandler("start_auto", start_auto))
# log all errors
dp.add_error_handler(error)
updater.start_webhook(listen="0.0.0.0", port=PORT, url_path=TOKEN, webhook_url=APP_NAME + TOKEN)
updater.idle()
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
python-telegram-bot有一个用于调度任务的内置功能,称为JobQueue. 请查看此 wiki 页面的版本 <20 或更高版本的文档以获取更多信息。
免责声明:我目前是python-telegram-bot.
| 归档时间: |
|
| 查看次数: |
16499 次 |
| 最近记录: |