【问题标题】:Flask / telebot: Bot can't receive POST and work at the same timeFlask / telebot:Bot无法同时接收POST和工作
【发布时间】:2020-11-14 19:49:14
【问题描述】:

每个人。我需要 Telebot 来接收 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,但机器人对“启动”命令没有响应

我需要他们一起工作

【问题讨论】:

标签: python flask telegram


【解决方案1】:

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

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

当您开始运行flask run 时,Flask 将尝试从您的模块中导入app 对象。但是,导入永远不会完成,因为bot.polling() 会永远阻塞。然后,如果您按ctrl+c,机器人将停止运行,从而允许 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

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

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

【讨论】:

    猜你喜欢
    • 2013-04-16
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多