Flask / telebot:Bot 无法同时接收 POST 和工作

Flask / telebot: Bot can't receive POST and work at the same time

各位。我需要远程机器人接收 POST 并回答。我决定使用 Flask。 我有代码:

import telebot
from flask import Flask, request
bot = telebot.TeleBot('dddd')
print("1")


app = Flask(__name__)
print("2")
@bot.message_handler(commands=['start'])
def start_message(message):
    print("5")
    bot.send_message(message.chat.id, message.chat.id)
    bot.send_message(message.chat.id, message.chat.username)

print("3")


@app.route('/', methods=['POST'])
def result():
    dt = request.args.to_dict(flat=False)
    print("6")
    for i in dt["chatIds"]:
        print(i)
        bot.send_message(i, "tema loh")

    return "0"

print("4")

bot.polling()

当我启动 Flask 时,我看到:

F:\Desktop\backend\bot_14_11>flask run
 * Serving Flask app "bot.py"
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off

Bot 正在运行,但我无法将 POST 发送到我的本地主机。 我按 ctrl+c 并看到:

然后我可以发送 POST,但是 bot 没有响应“开始”命令

我需要他们一起工作

bot.polling() 是一个阻塞调用,运行s 在它自己的循环中。 运行 Flask 应用程序同样会永远阻塞。 运行 一个会阻止另一个 运行ning。因此,你不能 运行 这两个像这样在一起。

以下是您的代码中发生的情况以及您看到这种行为的原因:

当您从 运行ning flask run 开始时,Flask 将尝试从您的模块中导入 app 对象。但是,导入永远不会完成,因为 bot.polling() 永远阻塞。然后,如果您按 ctrl+c,机器人将停止 运行ning,允许 Flask 导入并 运行 您的 Flask 应用程序。如您所见,该机器人不会 运行 同时使用 Flask。

您可以 运行 将您的机器人放在一个单独的线程中,但您必须小心使用线程。

import threading
...  # all your code as-is except for the last `bot.polling` line...

t = threading.Thread(target=bot.polling, daemon=True)
t.start()  # start the bot in a thread instead

但是,线程是它自己的主题,您在尝试之前应该非常熟悉它。您还应该考虑您使用的 libraries/code 是否是线程安全的。

相反,为了避免线程可能增加的复杂性,我建议将您的机器人和 Flask 应用拆分为单独的 运行ning 应用程序。如有必要,使用某种其他机制在它们之间进行通信。 IE。 运行 每个应用程序一个单独的 python 进程。