【问题标题】:Python Telegram Bot Queue not Running on HerokuPython Telegram Bot 队列未在 Heroku 上运行
【发布时间】:2021-11-20 22:58:53
【问题描述】:
from telegram.ext import Updater, CommandHandler
from telegram import bot, ParseMode
import os
import datetime
import pytz
import logging
from dotenv import load_dotenv
from flask import Flask
load_dotenv()

TOKEN = os.environ.get('API_KEY')
CHAT_ID = os.environ.get('CHAT_ID')
PORT = int(os.environ.get('PORT', '8443'))

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)

logger = logging.getLogger(__name__)


def daily_job(update, context):
    """ Running on Mon, Tue, Wed, Thu, Fri = tuple(range(5)) """
    sport = datetime.time(15, 12, 10, 000000, tzinfo=pytz.timezone('America/Chicago'))
    trading = datetime.time(15, 13, 10, 000000, tzinfo=pytz.timezone('America/Chicago'))
    forex = datetime.time(15, 14, 10, 000000, tzinfo=pytz.timezone('America/Chicago'))
    print("Time its supposed to post sport", sport)
    print("Time its supposed to post trading", trading)
    print("Time its supposed to post forex", forex)
    context.bot.send_message(chat_id=CHAT_ID, text='Activating daily notification!')
    context.job_queue.run_daily(purchase_forex(update, context), forex, days=tuple(range(7)), context=update)
    context.job_queue.run_daily(purchase_sports(update, context), sport, days=tuple(range(7)), context=update)
    context.job_queue.run_daily(purchase_trading(update, context), trading, days=tuple(range(7)), context=update)

def purchase_forex(update, context):
    print('running forex')
    context.bot.send_message(chat_id=CHAT_ID, text="Daily Forex", parse_mode=ParseMode.HTML)

def purchase_sports(update, context):
    print('running sports')
    context.bot.send_message(chat_id=CHAT_ID, text="Daily Text", parse_mode=ParseMode.HTML)

def purchase_trading(update, context):
    print('running trading')
    context.bot.send_message(chat_id=CHAT_ID, text="Daily Trading Text", parse_mode=ParseMode.HTML)

def error(update, context):
    """Log Errors caused by Updates."""
    logger.warning('Update "%s" caused error "%s"', update, context.error)





def main():

    u = Updater(TOKEN, use_context=True)
    u.dispatcher.add_handler(CommandHandler('start', daily_job, pass_job_queue=True))
    u.dispatcher.add_error_handler(error)

    # Start the Bot
    u.start_webhook(listen="0.0.0.0",
                          port=PORT,
                          url_path=TOKEN,
                          webhook_url="https://<appname>.herokuapp.com/" + TOKEN)


    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    u.idle()

if __name__ == '__main__':
    main()

在 heroku 上运行此代码并没有达到我的预期

2021-09-28T20:11:36.231963+00:00 app[web.1]:应该在 15:14:10 发布外汇 2021-09-28T20:11:36.457226+00:00 app[web.1]:运行外汇

但在此之后,它不再运行任何其他功能,并且总是在 /start 命令完成后立即发布外汇聊天。真的,我正在寻找一种方法来让 /start 命令正常运行并让该命令在每次重新启动时运行,这样我就不必继续返回并手动执行它

【问题讨论】:

    标签: python heroku telegram python-telegram-bot


    【解决方案1】:

    关于您的第一个问题:您使用 run_daily 错误。正如wiki articledocumentation 中所解释的,第一个参数必须是一个函数。而是传递purchase_forex(update, context),这是purchase_forex 的返回值,即None。此外,您传递的函数必须只接受一个参数,而不是两个。请务必阅读 wiki 文章、文档以及 this example,以更好地了解 JobQueue 在 PTB 中的工作原理。

    关于无需调用/start 命令即可调度作业:作业队列可作为u.job_queueu.dispatcher.job_queue 使用(两者都是与context.job_queue 相同的对象。因此您可以正确进行调度在你的main


    免责声明:我目前是python-telegram-bot 的维护者。

    【讨论】:

    • 非常感谢您,您 100% 正确,您链接的文档帮助很大。我很感激。
    猜你喜欢
    • 2022-01-26
    • 2020-07-15
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    相关资源
    最近更新 更多