如何使我的电报机器人多线程



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

@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)

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

最新更新