A
A
alexusbon2020-06-21 11:33:04
Python
alexusbon, 2020-06-21 11:33:04

How to attach WebHook to telegram bot (aiogram library)?

Good afternoon everyone!
I wrote an asynchronous bot, connected long polling for tests, but it periodically loses contact with the telegram server. I googled and realized that I need to use webhooks, I found it in the documentation

EXAMPLE
import logging

from aiogram import Bot, types
from aiogram.contrib.middlewares.logging import LoggingMiddleware
from aiogram.dispatcher import Dispatcher
from aiogram.dispatcher.webhook import SendMessage
from aiogram.utils.executor import start_webhook


API_TOKEN = 'BOT_TOKEN_HERE'

# webhook settings
WEBHOOK_HOST = 'https://your.domain'
WEBHOOK_PATH = '/path/to/api'
WEBHOOK_URL = f"{WEBHOOK_HOST}{WEBHOOK_PATH}"

# webserver settings
WEBAPP_HOST = 'localhost'  # or ip
WEBAPP_PORT = 3001

logging.basicConfig(level=logging.INFO)

bot = Bot(token=API_TOKEN)
dp = Dispatcher(bot)
dp.middleware.setup(LoggingMiddleware())


@dp.message_handler()
async def echo(message: types.Message):
    # Regular request
    # await bot.send_message(message.chat.id, message.text)

    # or reply INTO webhook
    return SendMessage(message.chat.id, message.text)


async def on_startup(dp):
    await bot.set_webhook(WEBHOOK_URL)
    # insert code here to run it after start


async def on_shutdown(dp):
    logging.warning('Shutting down..')

    # insert code here to run it before shutdown

    # Remove webhook (not acceptable in some cases)
    await bot.delete_webhook()

    # Close DB connection (if used)
    await dp.storage.close()
    await dp.storage.wait_closed()

    logging.warning('Bye!')


if __name__ == '__main__':
    start_webhook(
        dispatcher=dp,
        webhook_path=WEBHOOK_PATH,
        on_startup=on_startup,
        on_shutdown=on_shutdown,
        skip_updates=True,
        host=WEBAPP_HOST,
        port=WEBAPP_PORT,
    )

I don't really understand what is what? host, path from where to get and why are they needed, why close the connection with webhooks and where should it be done, at the end of the whole code? can anyone give a little advice?) I wanted to upload the bot itself to pythonanywhere

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
krabodyan, 2020-10-27
@krabodyan

I'll tell you how I did it: I
copied the code from the example from this link: https://github.com/aiogram/aiogram/blob/dev-2.x/ex...
Installed ngrok and created a link to localhost:5000
Port using it you can use any
Rewrote code like this:
WEBHOOK_PATH = "" # yes, it's empty here
WEBHOOK_URL = " https://хххххххххх.ngrok.io "
WEBAPP_HOST = '127.0.0.1'
WEBAPP_PORT = 5000

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question