olgram/server/server.py

71 lines
1.8 KiB
Python
Raw Normal View History

2021-09-10 23:09:46 +03:00
from aiogram import Bot as AioBot
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-15 22:53:18 +03:00
import ssl
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)
2021-09-15 22:53:18 +03:00
certificate = None
if ServerSettings.use_custom_cert():
2021-09-16 00:15:51 +03:00
with open(ServerSettings.public_path(), "r") as file:
certificate = file.read()
2021-09-15 22:53:18 +03:00
res = await a_bot.set_webhook(url_for_bot(bot), certificate=certificate)
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-15 22:53:18 +03:00
context = None
if ServerSettings.use_custom_cert():
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
context.load_cert_chain(ServerSettings.public_path(), ServerSettings.priv_path())
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")
2021-09-15 22:53:18 +03:00
site = web.TCPSite(runner, host=ServerSettings.app_host(), port=ServerSettings.app_port(), ssl_context=context)
2021-09-09 23:35:13 +03:00
return site