From 58a5da925ab5f89010ff5ac9f43cf8356c5db1b1 Mon Sep 17 00:00:00 2001 From: Suren Khorenyan Date: Sun, 11 Aug 2019 22:52:54 +0300 Subject: [PATCH] Refactor examples/webhook_example.py --- examples/webhook_example.py | 36 ++++++++++++++++++++++++++++++------ 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/examples/webhook_example.py b/examples/webhook_example.py index e2d9225c..6efa8767 100644 --- a/examples/webhook_example.py +++ b/examples/webhook_example.py @@ -1,11 +1,13 @@ -import asyncio 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' + +API_TOKEN = 'BOT_TOKEN_HERE' # webhook settings WEBHOOK_HOST = 'https://your.domain' @@ -20,11 +22,16 @@ 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): - await bot.send_message(message.chat.id, message.text) + # 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): @@ -33,10 +40,27 @@ async def on_startup(dp): async def on_shutdown(dp): + logging.warning('Shutting down..') + # insert code here to run it before shutdown - pass + + # 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) + 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, + )