从3d参与方侦听器以python电报机器人发送消息的最佳实践

从3d参与方侦听器以python电报机器人发送消息的最佳实践,python,events,callback,python-telegram-bot,apscheduler,Python,Events,Callback,Python Telegram Bot,Apscheduler,我有一个自定义代码来执行它的例行程序,如果出现问题,我想用电报给自己发送一条消息。在我的例子中,我使用了python电报bot库以及apscheduler及其监听器,其中可以捕获某些事件。 我提出了这样的工作代码,但我的问题是:是否有可能改进它,即不使用全局变量?这样做是为了克服侦听器不接受bot发送消息所需的参数的问题 from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.event

我有一个自定义代码来执行它的例行程序,如果出现问题,我想用电报给自己发送一条消息。在我的例子中,我使用了
python电报bot
库以及
apscheduler
及其监听器,其中可以捕获某些事件。 我提出了这样的工作代码,但我的问题是:是否有可能改进它,即不使用全局变量?这样做是为了克服侦听器不接受bot发送消息所需的参数的问题

from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ERROR
from telegram.ext import Updater, CommandHandler
import copy
import my_custom_library

saved_update = None

def my_listener(event): # not related with bot
    if event.exception:
        if saved_update is not None:
            alert(saved_update, 'Scheduler threw event.exception.') # should have bot related args
    else:
        record = event.retval # get returned value from my_custom_library.repetitive_function
        try:
            processed_record = my_custom_library.my_unsafe_business_logic(record) # something might go wrong here
            my_custom_library.add_to_db(processed_record) # and here
        except Exception as e:
            if saved_update is not None:
                alert(saved_update, e) # should have bot related args

def start(update, context):
    global saved_update
    saved_update = copy.deepcopy(update) # this is what I don't like
    update.message.reply_text('You have subscribed for notifications.')

def alert(update, reason):
    update.message.reply_text('Something went wrong: {}'.format(reason))

def main():
    scheduler = BackgroundScheduler()
    scheduler.add_listener(my_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)
    scheduler.add_job(my_custom_library.repetitive_function, args=(my_args,), trigger='interval', minutes=1)
    scheduler.start()

    # bot
    updater = Updater(TOKEN, use_context=True)
    dp = updater.dispatcher
    dp.add_handler(CommandHandler("start", callback=start))
    updater.start_polling()
    updater.idle()


if __name__ == '__main__':
    main()

Telegram Bot API相当简单,只需向此URL发送HTTP GET请求: !

只需使用Botfather创建一个bot并向bot发送一条消息。 使用来自Botfather的指定令牌和此URL:

您可以获取发送到Bot的消息和聊天id


最简单的方法是使用requests模块,将更新程序的输出作为文本参数发送到第一个URL。

我的问题是关于将两个不同回调与不同签名耦合的最佳实践。您的解决方案根本没有使用
python telegram bot
,而我使用了一些简化的原始帖子中没有显示的功能。我看到您试图在运行时出现异常时发送
警报
消息,因此您正在保存
更新
对象。您可以执行,
context.bot.send\u message(chat\u id=yours)
并发送错误消息,这样您就不必保存
update
。您可以做的另一件事是,
python电报bot
错误处理程序
,当程序中任何地方发生异常时,将自动调用该处理程序。@GaganTK不幸的是,您不能使用
context.bot.send\u message,因为它在自定义侦听器中不存在。对!您可以做的最好的事情是,使用
错误处理程序
,当程序中发生异常时,将触发此操作