2020-07-10 21:53:24 +00:00
|
|
|
# Copyright (C) 2020 by Cathy Hu <cathy.hu@fau.de>
|
|
|
|
#
|
|
|
|
# SPDX-License-Identifier: 0BSD
|
|
|
|
|
|
|
|
from aiogram import Bot, Dispatcher, exceptions, types
|
2020-07-17 13:07:24 +00:00
|
|
|
from asyncio import gather, sleep, CancelledError
|
2020-07-10 21:53:24 +00:00
|
|
|
from kibicara.platformapi import Censor, Message, Spawner
|
|
|
|
from kibicara.platforms.telegram.model import Telegram, TelegramUser
|
|
|
|
from logging import getLogger
|
2020-07-17 13:07:24 +00:00
|
|
|
from ormantic.exceptions import NoMatch
|
|
|
|
from sqlite3 import IntegrityError
|
2020-07-10 21:53:24 +00:00
|
|
|
|
|
|
|
|
|
|
|
logger = getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
class TelegramBot(Censor):
|
|
|
|
def __init__(self, telegram_model):
|
|
|
|
super().__init__(telegram_model.hood)
|
|
|
|
self.telegram_model = telegram_model
|
2020-07-17 21:37:06 +00:00
|
|
|
self.enabled = self.telegram_model.enabled
|
2020-07-17 13:07:24 +00:00
|
|
|
|
2020-09-06 17:11:18 +00:00
|
|
|
@classmethod
|
|
|
|
async def destroy_hood(cls, hood):
|
|
|
|
"""Removes all its database entries."""
|
|
|
|
for telegram in await Telegram.objects.filter(hood=hood).all():
|
|
|
|
for user in await TelegramUser.objects.filter(bot=telegram).all():
|
|
|
|
await user.delete()
|
|
|
|
await telegram.delete()
|
|
|
|
|
2020-07-17 13:07:24 +00:00
|
|
|
def _create_dispatcher(self):
|
|
|
|
dp = Dispatcher(self.bot)
|
|
|
|
dp.register_message_handler(self._send_welcome, commands=['start'])
|
|
|
|
dp.register_message_handler(self._remove_user, commands=['stop'])
|
2020-10-12 11:35:41 +00:00
|
|
|
dp.register_message_handler(self._send_help, commands=['help'])
|
2020-07-17 13:07:24 +00:00
|
|
|
dp.register_message_handler(self._receive_message)
|
|
|
|
return dp
|
2020-07-10 21:53:24 +00:00
|
|
|
|
|
|
|
async def run(self):
|
2020-07-17 13:07:24 +00:00
|
|
|
try:
|
2020-07-17 21:37:06 +00:00
|
|
|
self.bot = Bot(token=self.telegram_model.api_token)
|
|
|
|
self.dp = self._create_dispatcher()
|
2020-07-17 13:07:24 +00:00
|
|
|
logger.debug(f'Bot {self.telegram_model.hood.name} starting.')
|
2020-08-31 12:08:53 +00:00
|
|
|
user = await self.bot.get_me()
|
|
|
|
if user.username:
|
|
|
|
await self.telegram_model.update(username=user.username)
|
2020-07-17 13:07:24 +00:00
|
|
|
await gather(self.dp.start_polling(), self._push())
|
|
|
|
except CancelledError:
|
|
|
|
logger.debug(f'Bot {self.telegram_model.hood.name} received Cancellation.')
|
|
|
|
self.dp = None
|
|
|
|
raise
|
|
|
|
except exceptions.ValidationError:
|
|
|
|
logger.debug(f'Bot {self.telegram_model.hood.name} has invalid auth token.')
|
2020-07-17 21:37:06 +00:00
|
|
|
await self.telegram_model.update(enabled=False)
|
2020-07-17 13:07:24 +00:00
|
|
|
finally:
|
|
|
|
logger.debug(f'Bot {self.telegram_model.hood.name} stopped.')
|
2020-07-10 21:53:24 +00:00
|
|
|
|
2020-07-17 13:07:24 +00:00
|
|
|
async def _push(self):
|
2020-07-10 21:53:24 +00:00
|
|
|
while True:
|
|
|
|
message = await self.receive()
|
|
|
|
logger.debug(
|
|
|
|
'Received message from censor (%s): %s'
|
|
|
|
% (self.telegram_model.hood.name, message.text)
|
|
|
|
)
|
|
|
|
for user in await TelegramUser.objects.filter(
|
|
|
|
bot=self.telegram_model
|
|
|
|
).all():
|
|
|
|
await self._send_message(user.user_id, message.text)
|
|
|
|
|
|
|
|
async def _send_message(self, user_id, message):
|
|
|
|
try:
|
|
|
|
await self.bot.send_message(user_id, message, disable_notification=False)
|
|
|
|
except exceptions.BotBlocked:
|
|
|
|
logger.error(
|
|
|
|
'Target [ID:%s] (%s): blocked by user'
|
|
|
|
% (user_id, self.telegram_model.hood.name)
|
|
|
|
)
|
|
|
|
except exceptions.ChatNotFound:
|
|
|
|
logger.error(
|
|
|
|
'Target [ID:%s] (%s): invalid user ID'
|
|
|
|
% (user_id, self.telegram_model.hood.name)
|
|
|
|
)
|
|
|
|
except exceptions.RetryAfter as e:
|
|
|
|
logger.error(
|
|
|
|
'Target [ID:%s] (%s): Flood limit is exceeded. Sleep %d seconds.'
|
|
|
|
% (user_id, self.telegram_model.hood.name, e.timeout)
|
|
|
|
)
|
|
|
|
await sleep(e.timeout)
|
2020-07-17 17:59:25 +00:00
|
|
|
return await self._send_message(user_id, message)
|
2020-07-10 21:53:24 +00:00
|
|
|
except exceptions.UserDeactivated:
|
|
|
|
logger.error(
|
|
|
|
'Target [ID:%s] (%s): user is deactivated'
|
|
|
|
% (user_id, self.telegram_model.hood.name)
|
|
|
|
)
|
|
|
|
except exceptions.TelegramAPIError:
|
|
|
|
logger.exception(
|
|
|
|
'Target [ID:%s] (%s): failed' % (user_id, self.telegram_model.hood.name)
|
|
|
|
)
|
|
|
|
|
|
|
|
async def _send_welcome(self, message: types.Message):
|
|
|
|
try:
|
|
|
|
if message.from_user.is_bot:
|
|
|
|
await message.reply('Error: Bots can not join here.')
|
|
|
|
return
|
|
|
|
await TelegramUser.objects.create(
|
|
|
|
user_id=message.from_user.id, bot=self.telegram_model
|
|
|
|
)
|
|
|
|
await message.reply(self.telegram_model.welcome_message)
|
|
|
|
except IntegrityError:
|
|
|
|
await message.reply('Error: You are already registered.')
|
|
|
|
|
2020-07-17 13:07:24 +00:00
|
|
|
async def _remove_user(self, message: types.Message):
|
|
|
|
try:
|
|
|
|
telegram_user = await TelegramUser.objects.get(
|
|
|
|
user_id=message.from_user.id, bot=self.telegram_model
|
|
|
|
)
|
|
|
|
await telegram_user.delete()
|
|
|
|
await message.reply('You were removed successfully from this bot.')
|
|
|
|
except NoMatch:
|
|
|
|
await message.reply('Error: You are not subscribed to this bot.')
|
|
|
|
|
2020-10-12 11:35:41 +00:00
|
|
|
async def _send_help(self, message: types.Message):
|
|
|
|
if message.from_user.is_bot:
|
|
|
|
await message.reply('Error: Bots can\'t be helped.')
|
|
|
|
return
|
|
|
|
await message.reply('Send messages here to broadcast them to your hood')
|
|
|
|
|
2020-07-10 21:53:24 +00:00
|
|
|
async def _receive_message(self, message: types.Message):
|
|
|
|
if not message.text:
|
|
|
|
await message.reply('Error: Only text messages are allowed.')
|
|
|
|
return
|
|
|
|
await self.publish(Message(message.text))
|
|
|
|
|
|
|
|
|
|
|
|
spawner = Spawner(Telegram, TelegramBot)
|