コード例 #1
0
ファイル: utils.py プロジェクト: Kylmakalle/assistant-bot
def get_time_args(args: str):
    args_list = args.split(' ')
    invalid_tokens = []
    while True:
        try:
            time_string = ''.join(args_list)
            is_valid_duration = valid_duration(time_string)
            if is_valid_duration and time_string.isascii():
                break
            else:
                raise InvalidTokenError
        except InvalidTokenError:
            if args_list:
                invalid_tokens.append(args_list[-1])
                del args_list[-1]
            else:
                break
    return args_list, list(reversed(invalid_tokens))
コード例 #2
0
    def test_valid_duration_with_invalid_complex_representation(self):
        representation = 'days 2 3 hours'

        self.assertFalse(valid_duration(representation))
コード例 #3
0
    def test_valid_duration_with_invalid_simple_representation(self):
        representation = 'd1'

        self.assertFalse(valid_duration(representation))
コード例 #4
0
    def test_valid_duration_with_valid_complex_representation(self):
        representation = '2 days 3 hours 20 minutes'

        self.assertTrue(valid_duration(representation))
コード例 #5
0
    def test_valid_duration_with_valid_simple_representation(self):
        representation = '1d'

        self.assertTrue(valid_duration(representation))
コード例 #6
0
async def timed_restriction(m: types.Message,
                            user: dict,
                            chat: dict,
                            action='ban'):
    try:
        user_request = await bot.get_chat_member(chat['id'], m.from_user.id)
    except:
        await m.reply('Не могу получить информацию о юзере.')
        return
    if not (user_request.can_restrict_members
            or user_request.status == 'creator' or user.get('status', 0) >= 3):
        return await m.reply('Ты куда лезишь?')

    chat_id = chat['id']
    target_user_id = m.reply_to_message.from_user.id
    ban_user = m.reply_to_message.from_user.to_python()
    log_event = LogEvents.TEMPBAN if action == 'ban' else LogEvents.UNMEDIA

    until_date = None

    command, _, msg_args = m.text.partition(' ')
    if msg_args:
        time_tokens, other_tokens = get_time_args(msg_args)
        time_string = ''.join(time_tokens)
        if not time_tokens:
            now = datetime.utcnow().replace()
            until_date = get_next_day_msk().astimezone(
                pytz.utc)  # 21:00 UTC, 00:00 MSK
            time_string = f"{(until_date.replace(tzinfo=None) - now).total_seconds()}s"
    else:
        other_tokens = None
        now = datetime.utcnow()
        until_date = get_next_day_msk().astimezone(
            pytz.utc)  # 21:00 UTC, 00:00 MSK
        time_string = f"{(until_date.replace(tzinfo=None) - now).total_seconds()}s"

    if valid_duration(time_string):
        duration = Duration(time_string)

        ban_seconds = duration.to_seconds()
        # Чтобы без пермачей
        if ban_seconds <= 30:
            ban_seconds = 31
        if ban_seconds > 31_536_000:
            ban_seconds = 31_536_000 - 1
        human_time = format_seconds(ban_seconds)
        try:
            await bot.restrict_chat_member(
                chat_id,
                target_user_id,
                until_date=until_date if until_date else timedelta(
                    seconds=ban_seconds),
                can_send_messages=action != 'ban',
                can_send_media_messages=False,
                can_send_other_messages=False,
                can_add_web_page_previews=False)
        except Exception as e:
            return await m.reply('штото пошло не так :((')
        kb = types.InlineKeyboardMarkup()
        kb.add(
            types.InlineKeyboardButton('Unban',
                                       callback_data=unban_cb.new(
                                           chat_id=str(chat['id']),
                                           user_id=str(ban_user['id']))))
        await add_log(chat_id, target_user_id, log_event, by=m.from_user.id)

        text_kwargs = {'duration': human_time}
        if other_tokens:
            text_kwargs['reason'] = ' '.join(other_tokens)

        await log(event=log_event,
                  chat=chat,
                  user=ban_user,
                  message_id=m.message_id,
                  admin=user,
                  text_kwargs=text_kwargs,
                  log_kwargs={'reply_markup': kb})
        await mp.track(m.from_user.id, StatsEvents.TEMPBAN, m)

        await m.reply(
            get_restrict_text(chat, action,
                              till_next_day=bool(until_date)).format(
                                  human_time=hbold(human_time)))
    else:
        return await m.reply('Я такие даты не понимаю')