コード例 #1
0
def chat_member_updated():
    return ChatMemberUpdated(
        Chat(1, "chat"),
        User(1, "", False),
        from_timestamp(int(time.time())),
        ChatMember(User(1, "", False), ChatMember.OWNER),
        ChatMember(User(1, "", False), ChatMember.OWNER),
    )
コード例 #2
0
def chat_member_updated():
    return ChatMemberUpdated(
        Chat(1, 'chat'),
        User(1, '', False),
        from_timestamp(int(time.time())),
        ChatMember(User(1, '', False), ChatMember.CREATOR),
        ChatMember(User(1, '', False), ChatMember.CREATOR),
    )
コード例 #3
0
    def test_equality(self, time, old_chat_member, new_chat_member,
                      invite_link):
        a = ChatMemberUpdated(
            Chat(1, 'chat'),
            User(1, '', False),
            time,
            old_chat_member,
            new_chat_member,
            invite_link,
        )
        b = ChatMemberUpdated(Chat(1, 'chat'), User(1, '', False), time,
                              old_chat_member, new_chat_member)
        # wrong date
        c = ChatMemberUpdated(
            Chat(1, 'chat'),
            User(1, '', False),
            time + datetime.timedelta(hours=1),
            old_chat_member,
            new_chat_member,
        )
        # wrong chat & form_user
        d = ChatMemberUpdated(
            Chat(42, 'wrong_chat'),
            User(42, 'wrong_user', False),
            time,
            old_chat_member,
            new_chat_member,
        )
        # wrong old_chat_member
        e = ChatMemberUpdated(
            Chat(1, 'chat'),
            User(1, '', False),
            time,
            ChatMember(User(1, '', False), ChatMember.CREATOR),
            new_chat_member,
        )
        # wrong new_chat_member
        f = ChatMemberUpdated(
            Chat(1, 'chat'),
            User(1, '', False),
            time,
            old_chat_member,
            ChatMember(User(1, '', False), ChatMember.CREATOR),
        )
        # wrong type
        g = ChatMember(User(1, '', False), ChatMember.CREATOR)

        assert a == b
        assert hash(a) == hash(b)
        assert a is not b

        for other in [c, d, e, f, g]:
            assert a != other
            assert hash(a) != hash(other)
 def test_difference_optionals(self, optional_attribute, user, chat):
     # we use datetimes here, because we need that for `until_date` and it doesn't matter for
     # the other attributes
     old_value = datetime.datetime(2020, 1, 1)
     new_value = datetime.datetime(2021, 1, 1)
     old_chat_member = ChatMember(user, "status", **{optional_attribute: old_value})
     new_chat_member = ChatMember(user, "status", **{optional_attribute: new_value})
     chat_member_updated = ChatMemberUpdated(
         chat, user, datetime.datetime.utcnow(), old_chat_member, new_chat_member
     )
     assert chat_member_updated.difference() == {optional_attribute: (old_value, new_value)}
コード例 #5
0
def test_cmd_all(get_admin_mock, context, chat_update):
    admins = [
        ChatMember(User(1, "admin1", False), ChatMember.ADMINISTRATOR),
        ChatMember(User(2, "admin2", False), ChatMember.ADMINISTRATOR),
        ChatMember(User(3, "admin3", False), ChatMember.ADMINISTRATOR),
    ]
    get_admin_mock.return_value = admins

    with patch.object(chat_update.message, "reply_markdown") as m:
        basic.cmd_all(chat_update, context)
        m.assert_called_with(
            "[admin1](tg://user?id=1) [admin2](tg://user?id=2) [admin3](tg://user?id=3)"
        )
コード例 #6
0
    def test_equality(self):
        a = ChatMember(User(1, ''), ChatMember.ADMINISTRATOR)
        b = ChatMember(User(1, ''), ChatMember.ADMINISTRATOR)
        d = ChatMember(User(2, ''), ChatMember.ADMINISTRATOR)
        d2 = ChatMember(User(1, ''), ChatMember.CREATOR)

        assert a == b
        assert hash(a) == hash(b)
        assert a is not b

        assert a != d
        assert hash(a) != hash(d)

        assert a != d2
        assert hash(a) != hash(d2)
    def test_difference_required(self, user, chat):
        old_chat_member = ChatMember(user, "old_status")
        new_chat_member = ChatMember(user, "new_status")
        chat_member_updated = ChatMemberUpdated(
            chat, user, datetime.datetime.utcnow(), old_chat_member, new_chat_member
        )
        assert chat_member_updated.difference() == {"status": ("old_status", "new_status")}

        # We deliberately change an optional argument here to make sure that comparison doesn't
        # just happens by id/required args
        new_user = User(1, "First name", False, last_name="last name")
        new_chat_member.user = new_user
        assert chat_member_updated.difference() == {
            "status": ("old_status", "new_status"),
            "user": (user, new_user),
        }
コード例 #8
0
    def test_difference_required(self, user, chat):
        old_chat_member = ChatMember(user, 'old_status')
        new_chat_member = ChatMember(user, 'new_status')
        chat_member_updated = ChatMemberUpdated(
            chat, user, datetime.datetime.utcnow(), old_chat_member, new_chat_member
        )
        assert chat_member_updated.difference() == {'status': ('old_status', 'new_status')}

        # We deliberately change an optional argument here to make sure that comparision doesn't
        # just happens by id/required args
        new_user = User(1, 'First name', False, last_name='last name')
        new_chat_member.user = new_user
        assert chat_member_updated.difference() == {
            'status': ('old_status', 'new_status'),
            'user': (user, new_user),
        }
コード例 #9
0
 def get_chat_administrators(self, chat_id):
     ADMIN_JSON = {
         'id': 1,
         'first_name': 'X',
         'is_bot': False,
         'last_name': 'X',
         'username': '******',
         'language_code': 'en'
     }
     return [ChatMember(User.de_json(ADMIN_JSON, self), "administrator")]
コード例 #10
0
    def test_equality(self, chat_member_type):
        a = ChatMember(status="status", user=CMDefaults.user)
        b = ChatMember(status="status", user=CMDefaults.user)
        c = chat_member_type
        d = deepcopy(chat_member_type)
        e = Dice(4, "emoji")

        assert a == b
        assert hash(a) == hash(b)

        assert a != c
        assert hash(a) != hash(c)

        assert a != d
        assert hash(a) != hash(d)

        assert a != e
        assert hash(a) != hash(e)

        assert c == d
        assert hash(c) == hash(d)

        assert c != e
        assert hash(c) != hash(e)
コード例 #11
0
    def test_equality(self, chat_member_types, user):
        a = ChatMember(status='status', user=user)
        b = ChatMember(status='status', user=user)
        c = chat_member_types
        d = deepcopy(chat_member_types)
        e = Dice(4, 'emoji')

        assert a == b
        assert hash(a) == hash(b)

        assert a != c
        assert hash(a) != hash(c)

        assert a != d
        assert hash(a) != hash(d)

        assert a != e
        assert hash(a) != hash(e)

        assert c == d
        assert hash(c) == hash(d)

        assert c != e
        assert hash(c) != hash(e)
コード例 #12
0
def lift_restriction(bot, chat, target):
    # restore the restriction to what its original state
    upr_lock.acquire()
    member = user_previous_restrictions.get('{chat}|{user}'.format(
        chat=chat, user=target))
    upr_lock.release()
    if not member:
        member = ChatMember(None,
                            '',
                            until_date=None,
                            can_send_messages=True,
                            can_send_media_messages=True,
                            can_send_other_messages=True,
                            can_add_web_page_previews=True)
    else:
        upr_lock.acquire()
        del user_previous_restrictions['{chat}|{user}'.format(chat=chat,
                                                              user=target)]
        upr_lock.release()
    # if until_date - now < 30 seconds the restriction would be infinite
    # use 35 here for safety
    if member.until_date and member.status == 'restricted' and member.until_date < time.time(
    ) + 35:
        member.can_send_messages = member.can_send_media_messages = True
        member.can_send_other_messages = member.can_add_web_page_previews = True
        member.until_date = None
    try:
        bot.restrict_chat_member(
            chat,
            target,
            until_date=member.until_date,
            can_send_messages=member.can_send_messages,
            can_send_media_messages=member.can_send_media_messages,
            can_send_other_messages=member.can_send_other_messages,
            can_add_web_page_previews=member.can_add_web_page_previews)
    except TelegramError as e:
        raise e
コード例 #13
0
    ChatMember,
    ChatJoinRequest,
)
from telegram.poll import PollAnswer
from telegram.utils.helpers import from_timestamp

message = Message(1,
                  None,
                  Chat(1, ''),
                  from_user=User(1, '', False),
                  text='Text')
chat_member_updated = ChatMemberUpdated(
    Chat(1, 'chat'),
    User(1, '', False),
    from_timestamp(int(time.time())),
    ChatMember(User(1, '', False), ChatMember.CREATOR),
    ChatMember(User(1, '', False), ChatMember.CREATOR),
)

chat_join_request = ChatJoinRequest(
    chat=Chat(1, Chat.SUPERGROUP),
    from_user=User(1, 'first_name', False),
    date=from_timestamp(int(time.time())),
    bio='bio',
)

params = [
    {
        'message': message
    },
    {
コード例 #14
0
 def get_chat_administrators(self, chat_id, timeout=None, **kwargs):
     return list(
         map(
             lambda user: ChatMember(User(1, user, False), ChatMember.
                                     ADMINISTRATOR), self.admin_user))
コード例 #15
0
def chat_member(user):
    return ChatMember(user, TestChatMember.status)
コード例 #16
0
 def admins(*args, **kwargs):
     return [ChatMember(User(2, 'TestUser0', False), 'administrator')]
コード例 #17
0
def bite(update, context):
    # Схватываем всех админов и помещаем в list
    admins = context.bot.get_chat_administrators(update.message.chat.id)

    # Определяем, есть ли среди отправителя и получателя админы
    sender = ChatMember(update.message.from_user.id, 'unknown')
    for i in range(0, len(admins)):
        if (sender.user == admins[i].user.id):
            sender.status = 'administrator'

    if (sender.status != 'administrator'):
        sender.status = 'member'

    recipient = ChatMember(
        update.effective_message.reply_to_message.from_user.id, 'unknown')
    for i in range(0, len(admins)):
        if (recipient.user == admins[i].user.id):
            recipient.status = 'administrator'

    if (recipient.status != 'administrator'):
        recipient.status = 'member'

    # Обрабатываем сам кусь
    if (update.effective_message.text.lower() == 'кусь'):
        # Подбрасываем монетку
        coin = random.randint(1, 100)
        file_num = random.randint(1, 5)

        # admin vs admin
        if (sender.status == recipient.status == 'administrator'):
            update.message.reply_photo(photo=open('special/love.jpg', 'rb'))
            update.message.reply_text(
                "Воу-воу, битва админов. Я на такое не подписывался!")
            return

        # admin vs member
        if (sender.status == 'administrator' and coin % 2 == 0):
            update.message.reply_photo(photo=open('special/armored.jpg', 'rb'))
            update.message.reply_text(
                "Админу @" + str(update.message.from_user.username) +
                " не удалось укусить пользователя @" +
                str(update.effective_message.reply_to_message.from_user.
                    username) + "!")
            return
        elif (recipient.status != 'administrator'
              and sender.status == 'administrator'):
            context.bot.restrict_chat_member(
                update.message.chat.id,
                update.effective_message.reply_to_message.from_user.id,
                permissions=ChatPermissions(can_send_messages=False),
                until_date=time() + 30)
            update.message.reply_photo(
                photo=open('kus\'/kus\'' + str(file_num) + '.jpg', 'rb'))
            update.message.reply_text(
                "Админ @" + str(update.message.from_user.username) +
                " не оставил шансов пользователю @" +
                str(update.effective_message.reply_to_message.from_user.
                    username) + "!")
            return

        # member vs admin
        if (recipient.status == 'administrator'):
            context.bot.restrict_chat_member(
                update.message.chat.id,
                update.message.from_user.id,
                permissions=ChatPermissions(can_send_messages=False),
                until_date=time() + 30)
            update.message.reply_photo(
                photo=open('antikus\'/antikus\'' + str(file_num) +
                           '.jpg', 'rb'))
            update.message.reply_text("Слабоумие и отвага. Админ @" + str(
                update.effective_message.reply_to_message.from_user.username) +
                                      " даже не почувствовал пользователя @" +
                                      str(update.message.from_user.username) +
                                      " !")
            return

        # member vs member
        if (coin % 2 == 0 and update.message.from_user):
            context.bot.restrict_chat_member(
                update.message.chat.id,
                update.message.from_user.id,
                permissions=ChatPermissions(can_send_messages=False),
                until_date=time() + 30)
            update.message.reply_photo(
                photo=open('antikus\'/antikus\'' + str(file_num) +
                           '.jpg', 'rb'))
            update.message.reply_text(
                "Пользователь  @" + str(update.message.from_user.username) +
                " попробовал укусить @" +
                str(update.effective_message.reply_to_message.from_user.
                    username) + ", но тот увернулся и нанес антикусь!")
        else:
            context.bot.restrict_chat_member(
                update.message.chat.id,
                update.effective_message.reply_to_message.from_user.id,
                permissions=ChatPermissions(can_send_messages=False),
                until_date=time() + 30)
            update.message.reply_photo(
                photo=open('kus\'/kus\'' + str(file_num) + '.jpg', 'rb'))
            update.message.reply_text(
                "Пользователь  @" + str(update.message.from_user.username) +
                " кусил @" + str(update.effective_message.reply_to_message.
                                 from_user.username) + "!")

    # Реализуем мут
    st = update.effective_message.text.lower()
    s = st.split()

    if (s[0] == 'мут'
            and (sender.status == 'administrator' or sender.user == master)
            and recipient.status != 'administrator'
            and recipient.user != master):
        try:
            t = int(s[1])
            if (s[2] == 'мин'): t = t * 60
            elif (s[2] == 'ч'): t = t * 3600
            elif (s[2] == 'cут'): t = t * 3600 * 24
        except:
            update.message.reply_text("Укажи правильно время мута, котик!")
            return
        context.bot.restrict_chat_member(
            update.message.chat.id,
            update.effective_message.reply_to_message.from_user.id,
            permissions=ChatPermissions(can_send_messages=False),
            until_date=time() + t)
        update.message.reply_text(
            "@" +
            str(update.effective_message.reply_to_message.from_user.username) +
            " получил мут на " + s[1] + " " + s[2] + "!")
    elif (s[0] == 'мут'
          and sender.status == recipient.status == 'administrator'):
        update.message.reply_text(
            "Воу-воу, битва админов. Я на такое не подписывался!")
    elif (s[0] == 'мут' and recipient.user == master):
        update.message.reply_photo(photo=open('special/shield.jpg', 'rb'))
        update.message.reply_text(
            "РРРРРРРРРРРРРРР! За что ты так с моим хозяином?!")
    elif (s[0] == 'мут'):
        update.message.reply_text("Котик, не обманывай меня, ты не админ!")

    # Обрабатываем анмут
    if (update.effective_message.text.lower() == 'анмут'
            and (sender.status == 'administrator' or sender.user == master)
            and recipient.status != 'administrator'
            and recipient.user != master):
        context.bot.restrict_chat_member(
            update.message.chat.id,
            update.effective_message.reply_to_message.from_user.id,
            permissions=ChatPermissions(can_send_messages=True),
            until_date=0)
        update.message.reply_text(
            "@" +
            str(update.effective_message.reply_to_message.from_user.username) +
            " вновь может писать!")
    elif (update.effective_message.text.lower() == 'анмут'
          and sender.status == recipient.status == 'administrator'):
        update.message.reply_text(
            "Воу-воу, битва админов. Я на такое не подписывался!")
    elif (update.effective_message.text.lower() == 'анмут'):
        update.message.reply_text("Котик, не обманывай меня, ты не админ!")

    # Обрабатываем бан
    if (update.effective_message.text.lower() == 'бан'
            and (sender.status == 'administrator' or sender.user == master)
            and recipient.status != 'administrator'
            and recipient.user != master):
        context.bot.kick_chat_member(
            update.message.chat.id,
            update.effective_message.reply_to_message.from_user.id,
            until_date=0)
        update.message.reply_text(
            "@" +
            str(update.effective_message.reply_to_message.from_user.username) +
            " получил бан!(")
    elif (update.effective_message.text.lower() == 'бан'
          and sender.status == recipient.status == 'administrator'):
        update.message.reply_text(
            "Воу-воу, битва админов. Я на такое не подписывался!")
    elif (update.effective_message.text.lower() == 'бан'
          and recipient.user == master):
        update.message.reply_photo(photo=open('special/shield.jpg', 'rb'))
        update.message.reply_text(
            "РРРРРРРРРРРРРРР! За что ты так с моим хозяином?!")
    elif (update.effective_message.text.lower() == 'бан'):
        update.message.reply_text("Котик, не обманывай меня, ты не админ!")

    # Обрабатываем анбан
    if (update.effective_message.text.lower() == 'анбан'
            and (sender.status == 'administrator' or sender.user == master)
            and recipient.status != 'administrator'
            and recipient.user != master):
        context.bot.unban_chat_member(
            update.message.chat.id,
            update.effective_message.reply_to_message.from_user.id,
            until_date=0)
        update.message.reply_text(
            "@" +
            str(update.effective_message.reply_to_message.from_user.username) +
            " был разбанен!)")
        link = context.bot.export_chat_invite_link(update.message.chat.id)
        context.bot.send_message(
            update.effective_message.reply_to_message.from_user.id,
            "Котик, тебя разбанили! Ссылка для возврата в чат:" + link)
    elif (update.effective_message.text.lower() == 'анбан'
          and sender.status == recipient.status == 'administrator'):
        update.message.reply_text(
            "Воу-воу, битва админов. Я на такое не подписывался!")
    elif (update.effective_message.text.lower() == 'анбан'
          and recipient.user == master):
        update.message.reply_photo(photo=open('special/shield.jpg', 'rb'))
        update.message.reply_text(
            "РРРРРРРРРРРРРРР! За что ты так с моим хозяином?!")
    elif (update.effective_message.text.lower() == 'анбан'):
        update.message.reply_text("Котик, не обманывай меня, ты не админ!")
コード例 #18
0
def new_chat_member(user):
    return ChatMember(user, TestChatMemberUpdated.new_status)
コード例 #19
0
def old_chat_member(user):
    return ChatMember(user, TestChatMemberUpdated.old_status)
コード例 #20
0
 def admins(*args, **kwargs):
     return [
         ChatMember(User(0, 'TestUser0', False), 'administrator'),
         ChatMember(User(1, 'TestUser1', False), 'creator'),
     ]
コード例 #21
0
 def member(*args, **kwargs):
     if args[1] == 0:
         return ChatMember(User(0, 'TestUser0', False), 'administrator')
     if args[1] == 1:
         return ChatMember(User(1, 'TestUser1', False), 'creator')
     raise TelegramError('User is not a member')