【问题标题】:How to make my telegram-bot multi-threading?如何使我的电报机器人多线程?
【发布时间】:2023-01-12 03:34:54
【问题描述】:

我有麻烦了。我需要让我的电报机器人多线程。我的机器人将帮助用户购买电影并将使用数据库。我使用 Webhooks 方法接收来自 Telegram 服务器和 Stripe(模块请求)的请求。我阅读了很多关于 python 中的线程模块和异步函数的内容,但我不确定 100% 如何使我的机器人多线程化。我将非常感谢您的帮助,因为我被困在这个问题上。 现在我给你我的应用程序的主要功能,如果你需要更多,请告诉我:

@app.route('/', methods=["POST"])
def process():
    print(request.json)  # receiving requests (messages) in json format that are sent to the Flask server from the Telegram server and Stripe

    if check_if_successful_payment(request) == True:
        # Processing a request from Stripe
        # chat_id = request.json["data"]["object"]["metadata"]["chat_id"]
        stripe.api_key = get_from_env("PAYMENT_TOKEN")
        webhook_list = stripe.WebhookEndpoint.list()
        chat_id = webhook_list.data[0].metadata.chat_id
        send_message(chat_id, "The payment was successful! Enjoy watching the movie!")
        print("The payment was successful!")
        webhook_id = webhook_list.data[0].id
        stripe.WebhookEndpoint.delete(
            webhook_id,
        )
    else:
        # Processing a request from Telegram
        chat_id = request.json["message"]["chat"]["id"]
        send_message(chat_id, check_message(chat_id, request.json["message"]["text"]))
        send_pay_button(chat_id=chat_id, text="Test payment",
                        price_id=check_price_id(request.json["message"]["text"]))

    return {"ok": True}


if __name__ == '__main__':
    app.run(debug=True)

【问题讨论】:

    标签: async-await telegram-bot python-multithreading


    【解决方案1】:

    如果您的机器人在 Webhooks 上工作,您可以使用 Aiogram 而不是 Flask 来接收来自用户的消息。 Aiogram 有特殊的装饰器,用于同时处理来自许多用户的消息 - async_taskhttps://docs.aiogram.dev/en/latest/_modules/aiogram/dispatcher/dispatcher.html#Dispatcher.async_task

    【讨论】:

      猜你喜欢
      • 2018-02-11
      • 2017-08-18
      • 2019-01-08
      • 2017-09-24
      • 2019-04-25
      • 1970-01-01
      • 2018-03-25
      • 2015-07-21
      • 2017-06-09
      相关资源
      最近更新 更多