aiogram/examples/webhook_example.py

67 lines
1.5 KiB
Python
Raw Normal View History

2018-07-18 01:21:50 +03:00
import logging
from aiogram import Bot, types
2019-08-11 22:52:54 +03:00
from aiogram.contrib.middlewares.logging import LoggingMiddleware
2018-07-18 01:21:50 +03:00
from aiogram.dispatcher import Dispatcher
2019-08-11 22:52:54 +03:00
from aiogram.dispatcher.webhook import SendMessage
2018-07-18 01:21:50 +03:00
from aiogram.utils.executor import start_webhook
2019-08-11 22:52:54 +03:00
API_TOKEN = 'BOT_TOKEN_HERE'
2018-07-18 01:21:50 +03:00
# 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)
2019-07-15 14:00:38 +07:00
bot = Bot(token=API_TOKEN)
2018-07-18 01:21:50 +03:00
dp = Dispatcher(bot)
2019-08-11 22:52:54 +03:00
dp.middleware.setup(LoggingMiddleware())
2018-07-18 01:21:50 +03:00
@dp.message_handler()
async def echo(message: types.Message):
2019-08-11 22:52:54 +03:00
# Regular request
# await bot.send_message(message.chat.id, message.text)
# or reply INTO webhook
return SendMessage(message.chat.id, message.text)
2018-07-18 01:21:50 +03:00
async def on_startup(dp):
await bot.set_webhook(WEBHOOK_URL)
# insert code here to run it after start
async def on_shutdown(dp):
2019-08-11 22:52:54 +03:00
logging.warning('Shutting down..')
2018-07-18 01:21:50 +03:00
# insert code here to run it before shutdown
2019-08-11 22:52:54 +03:00
# 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!')
2018-07-18 01:21:50 +03:00
if __name__ == '__main__':
2019-08-11 22:52:54 +03:00
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,
)