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