为什么 Flask 不适用于 gunicorn 和电报机器人 api?

Why flask doesn't work with gunicorn and telegram bot api?

我正在使用电报机器人 api(远程机器人)、flask 和 gunicorn。 当我使用命令 python app.py 时,一切正常,但是当我使用 python wsgi.py 时,烧瓶在 http://127.0.0.1:5000/ 上说明并且机器人不回答,如果我使用 gunicorn --bind 0.0.0.0:8443 wsgi:app webhook 正在设置,但电报机器人没有回答。我尝试将 app.run 从 app.py 添加到 wsgi.py 但它不起作用

app.py

import logging
import time
import flask
import telebot

API_TOKEN = '111111111:token_telegram'

WEBHOOK_HOST = 'droplet ip'
WEBHOOK_PORT = 8443  # 443, 80, 88 or 8443 (port need to be 'open')
WEBHOOK_LISTEN = '0.0.0.0'  # In some VPS you may need to put here the IP addr

WEBHOOK_SSL_CERT = 'webhook_cert.pem'  # Path to the ssl certificate
WEBHOOK_SSL_PRIV = 'webhook_pkey.pem'  # Path to the ssl private key

WEBHOOK_URL_BASE = "https://%s:%s" % (WEBHOOK_HOST, WEBHOOK_PORT)
WEBHOOK_URL_PATH = "/%s/" % (API_TOKEN)

logger = telebot.logger
telebot.logger.setLevel(logging.DEBUG)

bot = telebot.TeleBot(API_TOKEN)

app = flask.Flask(__name__)


# Empty webserver index, return nothing, just http 200
@app.route('/', methods=['GET', 'HEAD'])
def index():
    return ''


# Process webhook calls
@app.route(WEBHOOK_URL_PATH, methods=['POST'])
def webhook():
    if flask.request.headers.get('content-type') == 'application/json':
        json_string = flask.request.get_data().decode('utf-8')
        update = telebot.types.Update.de_json(json_string)
        bot.process_new_updates([update])
        return ''
    else:
        flask.abort(403)


# Handle all other messages
@bot.message_handler(func=lambda message: True, content_types=['text'])
def echo_message(message):
    bot.reply_to(message, message.text)


# Remove webhook, it fails sometimes the set if there is a previous webhook
bot.remove_webhook()
#
time.sleep(1)

# Set webhook
bot.set_webhook(url=WEBHOOK_URL_BASE + WEBHOOK_URL_PATH,
                certificate=open(WEBHOOK_SSL_CERT, 'r'))

if __name__ == "__main__":
    # Start flask server
    app.run(host=WEBHOOK_LISTEN,
            port=WEBHOOK_PORT,
            ssl_context=(WEBHOOK_SSL_CERT, WEBHOOK_SSL_PRIV),
            debug=True)

wsgi.py

from app import app  

if __name__ == "__main__":
    app.run()
app.run(host=0.0.0.0, port=5000, debug=True)

根据您的情况更改端口号和调试参数。

向全世界展示 python 网络服务器是一种不好的做法。这不安全。 好的做法 - 使用反向代理,例如nginx

连锁店

所以链应该是:

api.telegram.org -> your_domain -> your_nginx -> your_webserver -> your_app

SSL

您的 ssl 证书应该在 nginx 级别进行检查。成功后只需将请求传递给您的网络服务器(烧瓶或其他东西)。这也是关于 how to use infitity amount of bots on one host/port :)

的提示

如何配置 nginx 反向代理 - 你可以在 startoverflow 或 google.

中找到

电报 Webhooks

telebot 使用 webhook 太复杂了。 尝试使用 aiogram 示例。这很简单:

from aiogram import Bot, Dispatcher, executor
from aiogram.types import Message

WEBHOOK_HOST = 'https://your.domain'
WEBHOOK_PATH = '/path/to/api'

bot = Bot('BOT:TOKEN')
dp = Dispatcher(bot)


@dp.message_handler()
async def echo(message: Message):
    return message.answer(message.text)


async def on_startup(dp: Dispatcher):
    await bot.set_webhook(f"{WEBHOOK_HOST}{WEBHOOK_PATH}")


if __name__ == '__main__':
    executor.start_webhook(dispatcher=dp, on_startup=on_startup,
                           webhook_path=WEBHOOK_PATH, host='localhost', port=3000)