· 6 years ago · Feb 19, 2020, 03:38 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 = '127.0.0.1' # 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
43 # insert code here to run it after start
44
45
46async def on_shutdown(dp):
47 logging.warning('Shutting down..')
48
49 # insert code here to run it before shutdown
50
51 # Remove webhook (not acceptable in some cases)
52 await bot.delete_webhook()
53
54 # Close DB connection (if used)
55 await dp.storage.close()
56 await dp.storage.wait_closed()
57
58 logging.warning('Bye!')
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 )