K
K
keshamin2017-04-15 20:17:34
Python
keshamin, 2017-04-15 20:17:34

How to setup webhook for Telegram bot (python3 + pyTelegramBotAPI) on Heroku hosting?

I wrote an elementary telegram bot in Python 3 using the pyTelegramBotAPI library . The bot is on long polling, no webhook, and if you run it locally, it regularly polls the Telegram server for updates, but when I run it on Heroku's free plan (18 hours of work + 6 hours of server sleep per day), it apparently refuses to constantly knock in telegrams for updates and does it every few hours, which of course is unacceptable for the comfortable work of the assistant bot. Therefore, it became necessary to teach the bot to receive updates in a smarter way - a webhook.
From what I read on the net, I realized that it is not difficult to do this with Heroku, since all applications hosted on it are hosted on a sub-domain and automatically receive an SLL certificate, which is necessary for setting up a webhook.
Unfortunately, I'm still a very beginner programmer and don't directly present the webhook setup steps. Help, please, to understand!
Please answer as simply and as detailed as possible. Thanks in advance! :)

Answer the question

In order to leave comments, you need to log in

5 answer(s)
K
keshamin, 2018-02-02
@keshamin

johny2308 , @gavrilka
In general, in the end, back in the spring of 2017, when this ticket was created, I nevertheless coped with this problem through long trials and constant non-working pushes on Heroku ...
I don’t remember all the way to this solution, but in the end, this is how it ends up working for me:

import telebot
import os
from flask import Flask, request
import logging

bot = telebot.TeleBot(token)

# Здесь пишем наши хэндлеры

# Проверим, есть ли переменная окружения Хероку (как ее добавить смотрите ниже)
if "HEROKU" in list(os.environ.keys()):
    logger = telebot.logger
    telebot.logger.setLevel(logging.INFO)

    server = Flask(__name__)
    @server.route("/bot", methods=['POST'])
    def getMessage():
        bot.process_new_updates([telebot.types.Update.de_json(request.stream.read().decode("utf-8"))])
        return "!", 200
    @server.route("/")
    def webhook():
        bot.remove_webhook()
        bot.set_webhook(url="https://min-gallows.herokuapp.com/bot") # этот url нужно заменить на url вашего Хероку приложения
        return "?", 200
    server.run(host="0.0.0.0", port=os.environ.get('PORT', 80))
else:
    # если переменной окружения HEROKU нету, значит это запуск с машины разработчика.  
    # Удаляем вебхук на всякий случай, и запускаем с обычным поллингом.
    bot.remove_webhook()
    bot.polling(none_stop=True)

As for setting the environment variable in Heroku - go to the application settings in Heroku and see the "Config Variables" item. And we add the HEROKU variable there so that our bot can distinguish whether it is running on the server or on the local machine. But this is no longer necessary, it's a matter of taste. It's just convenient for me.
Hope everything works out for you!

V
Vitaly, 2017-04-22
@MrCute

In the folders with examples of using pyTelegramBot, there are examples of how to set it up to work with WebHook even with Heroku. Look here

J
johny2308, 2018-02-02
@johny2308


already tired of searching - faced the same problem, found a solution - did
not
help /app-webhooks... to no avail
)
Let's join forces!

K
Kirill Romanov, 2017-04-15
@Djaler

I use another library - python-telegram-bot, but I think the essence is the same.
https://github.com/Djaler/CoinBot

A
Aram, 2018-02-02
@gavrilka

I have exactly the same question. Unfortunately, it doesn't work.
I wrote my bot, it works for me through pycharm, and even without a webhook, with the longPolling method, I was able to launch it on Heroku, but over time it crashes there. I would really like to learn how to deploy using webhook, who can help??

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question