add webhook and polling methods

This commit is contained in:
Dmitry Afanasyev 2022-08-14 21:08:57 +03:00
parent 62cec9687a
commit e03efa736b
5 changed files with 35 additions and 3 deletions

View File

@ -21,3 +21,7 @@ killall geckodriver
killall firefox
killall python
```
## Help article
[Пишем асинхронного Телеграм-бота](https://habr.com/ru/company/kts/blog/598575/)

View File

@ -8,4 +8,7 @@ WEBHOOK_PATH=
WEBAPP_HOST= # or ip
WEBAPP_PORT=
# set to 1 to start with webhook. Else bot will start on polling method
START_WITH_WEBHOOK=
GECKO_DRIVER_VERSION=0.31.0

BIN
app/geckodriver Executable file

Binary file not shown.

View File

@ -1,9 +1,15 @@
from aiogram import Dispatcher
from aiogram.utils.executor import start_webhook
from aiogram.utils.executor import start_polling, start_webhook
from core.bot import bot, dispatcher
from core.logger import logger
from core.scheduler import asyncio_schedule
from settings import WEBAPP_HOST, WEBAPP_PORT, WEBHOOK_PATH, WEBHOOK_URL
from settings import (
START_WITH_WEBHOOK,
WEBAPP_HOST,
WEBAPP_PORT,
WEBHOOK_PATH,
WEBHOOK_URL,
)
async def on_startup(dp: Dispatcher) -> None:
@ -24,8 +30,18 @@ async def on_shutdown(dp: Dispatcher) -> None:
logger.warning('Bye!')
if __name__ == '__main__':
def bot_polling() -> None:
logger.info("Start bot in polling mode")
start_polling(
dispatcher=dispatcher,
skip_updates=True,
on_startup=on_startup,
on_shutdown=on_shutdown,
)
def bot_webhook() -> None:
logger.info("Start bot with webhook")
start_webhook(
dispatcher=dispatcher,
webhook_path=WEBHOOK_PATH,
@ -35,3 +51,10 @@ if __name__ == '__main__':
host=WEBAPP_HOST,
port=WEBAPP_PORT,
)
if __name__ == '__main__':
if START_WITH_WEBHOOK:
bot_webhook()
else:
bot_polling()

View File

@ -25,3 +25,5 @@ WEBHOOK_URL = f"{WEBHOOK_HOST}{WEBHOOK_PATH}"
# webserver settings
WEBAPP_HOST = config('WEBAPP_HOST') # or ip
WEBAPP_PORT = config('WEBAPP_PORT', cast=int)
START_WITH_WEBHOOK = config('START_WITH_WEBHOOK', cast=bool)