olgram/server/server.py

105 lines
2.8 KiB
Python
Raw Normal View History

2021-09-09 23:35:13 +03:00
from aiogram import Bot as AioBot, Dispatcher
from aiogram.dispatcher.webhook import SendMessage, WebhookRequestHandler
from olgram.models.models import Bot
from aiohttp import web
import asyncio
import aiohttp
2021-09-09 20:38:33 +03:00
from olgram.settings import ServerSettings
2021-09-10 01:06:56 +03:00
import logging
logger = logging.getLogger(__name__)
2021-09-09 20:38:33 +03:00
2021-09-09 23:35:13 +03:00
def path_for_bot(bot: Bot) -> str:
return "/" + bot.code
2021-09-09 20:38:33 +03:00
2021-09-09 23:35:13 +03:00
def url_for_bot(bot: Bot) -> str:
return f"https://{ServerSettings.hook_host()}:{ServerSettings.hook_port()}" + path_for_bot(bot)
2021-09-09 20:38:33 +03:00
2021-09-09 23:35:13 +03:00
async def register_token(bot: Bot) -> bool:
2021-09-09 20:38:33 +03:00
"""
Зарегистрировать токен
2021-09-09 23:35:13 +03:00
:param bot: Бот
2021-09-09 20:38:33 +03:00
:return: получилось ли
"""
2021-09-10 00:00:18 +03:00
await unregister_token(bot.token)
2021-09-10 01:06:56 +03:00
logger.info(f"register token {bot.name}")
2021-09-09 23:35:13 +03:00
a_bot = AioBot(bot.token)
res = await a_bot.set_webhook(url_for_bot(bot))
2021-09-10 01:30:17 +03:00
await a_bot.session.close()
2021-09-10 01:20:40 +03:00
del a_bot
2021-09-09 20:38:33 +03:00
return res
async def unregister_token(token: str):
"""
Удалить токен
:param token: токен
:return:
"""
2021-09-10 01:06:56 +03:00
logger.info(f"unregister token {token}")
2021-09-09 23:35:13 +03:00
bot = AioBot(token)
2021-09-09 20:38:33 +03:00
await bot.delete_webhook()
2021-09-10 01:30:17 +03:00
await bot.session.close()
2021-09-10 01:20:40 +03:00
del bot
2021-09-09 23:35:13 +03:00
async def cmd_start(message, *args, **kwargs):
2021-09-10 01:06:56 +03:00
logger.info("cmd start")
2021-09-09 23:35:13 +03:00
return SendMessage(chat_id=message.chat.id, text=f'Hi from webhook, bot {message.via_bot}',
reply_to_message_id=message.message_id)
class CustomRequestHandler(WebhookRequestHandler):
2021-09-10 00:32:36 +03:00
def __init__(self, *args, **kwargs):
self._dispatcher = None
super(CustomRequestHandler, self).__init__(*args, **kwargs)
2021-09-10 00:35:36 +03:00
async def _create_dispatcher(self):
2021-09-09 23:35:13 +03:00
key = self.request.url.path[1:]
2021-09-10 01:06:56 +03:00
logger.info(f"create dispatcher {key}")
2021-09-10 00:32:36 +03:00
bot = await Bot.filter(code=key).first()
2021-09-09 23:35:13 +03:00
if not bot:
return None
dp = Dispatcher(AioBot(bot.token))
dp.register_message_handler(cmd_start, commands=['start'])
return dp
2021-09-10 00:35:36 +03:00
async def post(self):
2021-09-10 00:32:36 +03:00
# TODO: refactor
2021-09-10 01:06:56 +03:00
logger.info(f"post request {self.request.url.path}")
2021-09-10 00:35:36 +03:00
self._dispatcher = await self._create_dispatcher()
2021-09-10 01:00:19 +03:00
res = await super(CustomRequestHandler, self).post()
2021-09-10 00:32:36 +03:00
self._dispatcher = None
2021-09-10 01:00:19 +03:00
return res
2021-09-10 00:32:36 +03:00
def get_dispatcher(self):
"""
Get Dispatcher instance from environment
:return: :class:`aiogram.Dispatcher`
"""
2021-09-10 01:06:56 +03:00
logger.info("get dispatcher")
2021-09-10 00:32:36 +03:00
return self._dispatcher
2021-09-09 23:35:13 +03:00
def main():
loop = asyncio.get_event_loop()
app = web.Application()
app.router.add_route('*', r"/{name}", CustomRequestHandler, name='webhook_handler')
runner = aiohttp.web.AppRunner(app)
loop.run_until_complete(runner.setup())
2021-09-10 01:06:56 +03:00
logger.info("server initialization done")
2021-09-09 23:35:13 +03:00
site = aiohttp.web.TCPSite(runner, host=ServerSettings.app_host(), port=ServerSettings.app_port())
return site