V
V
VasHan2020-04-23 17:48:18
Python
VasHan, 2020-04-23 17:48:18

How to get messages from telegram bot with webhook?

Good afternoon!

I am transferring bots to webhook, to test the webhook, I took an example from the pytelegramBotAPI module using flask. I receive messages from telegrams on a webhook, but I can’t process them, namely, if I use the function from the example:

@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 '/start' and '/help'
@bot.message_handler(commands=['help', 'start'])
def send_welcome(message):
    bot.reply_to(message,
                 ("Hi there, I am EchoBot.\n"
                  "I am here to echo your kind words back to you."))

Then after starting and sending a message to the bot, nothing happens.
But if I change the function :
@app.route(WEBHOOK_URL_PATH, methods=['POST'])
def webhook():
    update = flask.request.get_json()
    print(update)
    if 'message' in update:
        text = update['message']['text']
        chat_id = update['message']['chat']['id']
        bot.send_message(chat_id, 'you said "{}"'.format(text))
    return "ok", 200

After sending a message to the bot, I get it as an output and a response in telegram. Can you please tell me why the example from the module itself does not work?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question