olgram/server/server.py

62 lines
1.5 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
2021-09-10 21:32:06 +03:00
from aiogram import types
2021-09-09 23:35:13 +03:00
from olgram.models.models import Bot
from aiohttp import web
2021-09-10 01:51:03 +03:00
from asyncio import get_event_loop
2021-09-09 20:38:33 +03:00
from olgram.settings import ServerSettings
2021-09-10 21:34:55 +03:00
from .custom import CustomRequestHandler
2021-09-10 21:32:06 +03:00
2021-09-10 01:06:56 +03:00
import logging
2021-09-10 21:32:06 +03:00
2021-09-10 01:06:56 +03:00
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:
2021-09-10 01:41:32 +03:00
return "/" + str(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
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-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
def main():
2021-09-10 01:51:03 +03:00
loop = get_event_loop()
2021-09-09 23:35:13 +03:00
app = web.Application()
app.router.add_route('*', r"/{name}", CustomRequestHandler, name='webhook_handler')
2021-09-10 01:51:03 +03:00
runner = web.AppRunner(app)
2021-09-09 23:35:13 +03:00
loop.run_until_complete(runner.setup())
2021-09-10 01:51:03 +03:00
logger.info("Server initialization done")
site = web.TCPSite(runner, host=ServerSettings.app_host(), port=ServerSettings.app_port())
2021-09-09 23:35:13 +03:00
return site