Webhook example

webhook_example.py
 1import logging
 2
 3from aiogram import Bot, types
 4from aiogram.contrib.middlewares.logging import LoggingMiddleware
 5from aiogram.dispatcher import Dispatcher
 6from aiogram.dispatcher.webhook import SendMessage
 7from aiogram.utils.executor import start_webhook
 8
 9
10API_TOKEN = 'BOT_TOKEN_HERE'
11
12# webhook settings
13WEBHOOK_HOST = 'https://your.domain'
14WEBHOOK_PATH = '/path/to/api'
15WEBHOOK_URL = f"{WEBHOOK_HOST}{WEBHOOK_PATH}"
16
17# webserver settings
18WEBAPP_HOST = 'localhost'  # or ip
19WEBAPP_PORT = 3001
20
21logging.basicConfig(level=logging.INFO)
22
23bot = Bot(token=API_TOKEN)
24dp = Dispatcher(bot)
25dp.middleware.setup(LoggingMiddleware())
26
27
28@dp.message_handler()
29async def echo(message: types.Message):
30    # Regular request
31    # await bot.send_message(message.chat.id, message.text)
32
33    # or reply INTO webhook
34    return SendMessage(message.chat.id, message.text)
35
36
37async def on_startup(dp):
38    await bot.set_webhook(WEBHOOK_URL)
39    # insert code here to run it after start
40
41
42async def on_shutdown(dp):
43    logging.warning('Shutting down..')
44
45    # insert code here to run it before shutdown
46
47    # Remove webhook (not acceptable in some cases)
48    await bot.delete_webhook()
49
50    # Close DB connection (if used)
51    await dp.storage.close()
52    await dp.storage.wait_closed()
53
54    logging.warning('Bye!')
55
56
57if __name__ == '__main__':
58    start_webhook(
59        dispatcher=dp,
60        webhook_path=WEBHOOK_PATH,
61        on_startup=on_startup,
62        on_shutdown=on_shutdown,
63        skip_updates=True,
64        host=WEBAPP_HOST,
65        port=WEBAPP_PORT,
66    )