Ответы пользователя по тегу Flask
  • Как правильно обработать события от Telegram(pytelegrambotapi+flask)?

    @AlmazKayum
    import telebot
    import flask
    import logging
    import time
    
    API_TOKEN = conf.token
    
    WEBHOOK_HOST = 'IP_хостинга'
    WEBHOOK_PORT = 88  # 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://{}:{}".format(WEBHOOK_HOST, WEBHOOK_PORT)
    WEBHOOK_URL_PATH = "/{}/".format(API_TOKEN)
    
    logger = telebot.logger
    telebot.logger.setLevel(logging.INFO)
    
    bot = telebot.TeleBot(API_TOKEN)
    
    app = flask.Flask(__name__)
    
    
    @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)
    
    
    #         START
    @bot.message_handler(commands=['start'])
    def start(message):
        bot.send_message(message.chat.id, 'Hi')
    
    bot.remove_webhook()
    time.sleep(1)
    # Set webhook
    bot.set_webhook(url=WEBHOOK_URL_BASE+WEBHOOK_URL_PATH,
                    certificate=open(WEBHOOK_SSL_CERT, 'r'))
    
    # Start flask server
    app.run(host=WEBHOOK_LISTEN,
            port=WEBHOOK_PORT,
            ssl_context=(WEBHOOK_SSL_CERT, WEBHOOK_SSL_PRIV),
            debug=True)
    Ответ написан
    Комментировать