olgram/server/custom.py

106 lines
4.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
2021-09-10 22:38:29 +03:00
from aiogram import exceptions
2021-09-10 21:32:06 +03:00
from aiogram import types
2021-09-10 22:07:02 +03:00
from contextvars import ContextVar
from aiohttp.web_exceptions import HTTPNotFound
2021-09-10 22:42:47 +03:00
from aioredis.commands import create_redis_pool
from aioredis import Redis
2021-09-10 22:38:29 +03:00
import typing as ty
from olgram.settings import ServerSettings
2021-09-10 21:32:06 +03:00
from olgram.models.models import Bot
2021-09-10 22:07:02 +03:00
db_bot_instance: ContextVar[Bot] = ContextVar('db_bot_instance')
2021-09-10 22:42:47 +03:00
_redis: ty.Optional[Redis] = None
2021-09-10 22:38:29 +03:00
async def init_redis():
global _redis
2021-09-10 22:42:47 +03:00
_redis = await create_redis_pool(ServerSettings.redis_path())
2021-09-10 22:38:29 +03:00
def _message_unique_id(bot_id: int, message_id: int) -> str:
return f"{bot_id}_{message_id}"
2021-09-10 21:32:06 +03:00
async def message_handler(message, *args, **kwargs):
2021-09-10 22:38:29 +03:00
bot = db_bot_instance.get()
2021-09-10 21:32:06 +03:00
if message.text and message.text.startswith("/start"):
# На команду start нужно ответить, не пересылая сообщение никуда
2021-09-10 22:07:02 +03:00
return SendMessage(chat_id=message.chat.id,
2021-09-10 22:38:29 +03:00
text=bot.start_text)
super_chat_id = await bot.super_chat_id()
if message.chat.id != super_chat_id:
# Это обычный чат: сообщение нужно переслать в супер-чат
new_message = await message.forward(super_chat_id)
await _redis.set(_message_unique_id(bot.pk, new_message.message_id), message.chat.id)
else:
# Это супер-чат
if message.reply_to_message:
# Ответ из супер-чата переслать тому пользователю,
chat_id = await _redis.get(_message_unique_id(bot.pk, message.reply_to_message.message_id))
if not chat_id:
chat_id = message.reply_to_message.forward_from_chat
if not chat_id:
return SendMessage(chat_id=message.chat.id, text="Невозможно переслать сообщение: автор не найден")
chat_id = int(chat_id)
try:
await message.copy_to(chat_id)
2021-09-10 22:59:07 +03:00
except (exceptions.MessageError, exceptions.BotBlocked):
2021-09-10 22:38:29 +03:00
await message.reply("Невозможно переслать сообщение: возможно, автор заблокировал бота")
return
else:
await message.forward(super_chat_id)
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)
async def _create_dispatcher(self):
key = self.request.url.path[1:]
bot = await Bot.filter(code=key).first()
if not bot:
return None
2021-09-10 22:07:02 +03:00
db_bot_instance.set(bot)
2021-09-10 21:32:06 +03:00
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()
2021-09-10 22:07:02 +03:00
if not dispatcher:
raise HTTPNotFound()
2021-09-10 21:57:17 +03:00
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()