olgram/server/custom.py

57 lines
2.2 KiB
Python
Raw Normal View History

2021-09-10 21:32:06 +03:00
from aiogram import Bot as AioBot, Dispatcher
from aiogram.dispatcher.webhook import WebhookRequestHandler
from aiogram.dispatcher.webhook import SendMessage
from aiogram import types
from olgram.models.models import Bot
async def message_handler(message, *args, **kwargs):
if message.text and message.text.startswith("/start"):
# На команду start нужно ответить, не пересылая сообщение никуда
2021-09-10 21:49:07 +03:00
bot = AioBot.get_current()
return SendMessage(chat_id=message.chat.id, text=f'Hi from webhook {args} {kwargs} {bot}')
2021-09-10 21:32:06 +03:00
class CustomRequestHandler(WebhookRequestHandler):
def __init__(self, *args, **kwargs):
self._dispatcher = None
super(CustomRequestHandler, self).__init__(*args, **kwargs)
2021-09-10 21:57:17 +03:00
2021-09-10 21:32:06 +03:00
async def _create_dispatcher(self):
key = self.request.url.path[1:]
bot = await Bot.filter(code=key).first()
if not bot:
return None
dp = Dispatcher(AioBot(bot.token))
dp.register_message_handler(message_handler, content_types=[types.ContentType.TEXT,
types.ContentType.CONTACT,
types.ContentType.ANIMATION,
types.ContentType.AUDIO,
types.ContentType.DOCUMENT,
types.ContentType.PHOTO,
types.ContentType.STICKER,
types.ContentType.VIDEO,
types.ContentType.VOICE])
return dp
async def post(self):
2021-09-10 21:57:17 +03:00
dispatcher = await self._create_dispatcher()
Dispatcher.set_current(dispatcher)
AioBot.set_current(dispatcher.bot)
return await super(CustomRequestHandler, self).post()
2021-09-10 21:32:06 +03:00
def get_dispatcher(self):
"""
Get Dispatcher instance from environment
:return: :class:`aiogram.Dispatcher`
"""
2021-09-10 21:57:17 +03:00
return Dispatcher.get_current()