示例#1
0
    def de_json(cls, data: Optional[JSONDict],
                bot: 'Bot') -> Optional['Update']:
        """See :meth:`telegram.TelegramObject.de_json`."""
        data = cls._parse_data(data)

        if not data:
            return None

        data['message'] = Message.de_json(data.get('message'), bot)
        data['edited_message'] = Message.de_json(data.get('edited_message'),
                                                 bot)
        data['inline_query'] = InlineQuery.de_json(data.get('inline_query'),
                                                   bot)
        data['chosen_inline_result'] = ChosenInlineResult.de_json(
            data.get('chosen_inline_result'), bot)
        data['callback_query'] = CallbackQuery.de_json(
            data.get('callback_query'), bot)
        data['shipping_query'] = ShippingQuery.de_json(
            data.get('shipping_query'), bot)
        data['pre_checkout_query'] = PreCheckoutQuery.de_json(
            data.get('pre_checkout_query'), bot)
        data['channel_post'] = Message.de_json(data.get('channel_post'), bot)
        data['edited_channel_post'] = Message.de_json(
            data.get('edited_channel_post'), bot)
        data['poll'] = Poll.de_json(data.get('poll'), bot)
        data['poll_answer'] = PollAnswer.de_json(data.get('poll_answer'), bot)
        data['my_chat_member'] = ChatMemberUpdated.de_json(
            data.get('my_chat_member'), bot)
        data['chat_member'] = ChatMemberUpdated.de_json(
            data.get('chat_member'), bot)
        data['chat_join_request'] = ChatJoinRequest.de_json(
            data.get('chat_join_request'), bot)

        return cls(**data)
示例#2
0
def extract_status_change(
    chat_member_update: ChatMemberUpdated,
) -> Optional[Tuple[bool, bool]]:
    """Takes a ChatMemberUpdated instance and extracts whether the 'old_chat_member' was a member
    of the chat and whether the 'new_chat_member' is a member of the chat. Returns None, if
    the status didn't change.
    """
    status_change = chat_member_update.difference().get("status")
    old_is_member, new_is_member = chat_member_update.difference().get("is_member", (None, None))

    if status_change is None:
        return None

    old_status, new_status = status_change
    was_member = (
        old_status
        in [
            ChatMember.MEMBER,
            ChatMember.CREATOR,
            ChatMember.ADMINISTRATOR,
        ]
        or (old_status == ChatMember.RESTRICTED and old_is_member is True)
    )
    is_member = (
        new_status
        in [
            ChatMember.MEMBER,
            ChatMember.CREATOR,
            ChatMember.ADMINISTRATOR,
        ]
        or (new_status == ChatMember.RESTRICTED and new_is_member is True)
    )

    return was_member, is_member
示例#3
0
def extract_status_change(
        chat_member_update: ChatMemberUpdated,
) -> Optional[Tuple[bool, bool]]:
    status_change = chat_member_update.difference().get("status")
    old_is_member, new_is_member = chat_member_update.difference().get(
        "is_member", (None, None)
    )

    if status_change is None:
        return None

    old_status, new_status = status_change
    was_member = (
            old_status
            in [
                ChatMember.MEMBER,
                ChatMember.CREATOR,
                ChatMember.ADMINISTRATOR,
            ]
            or (old_status == ChatMember.RESTRICTED and old_is_member is True)
    )
    is_member = (
            new_status
            in [
                ChatMember.MEMBER,
                ChatMember.CREATOR,
                ChatMember.ADMINISTRATOR,
            ]
            or (new_status == ChatMember.RESTRICTED and new_is_member is True)
    )

    return was_member, is_member
示例#4
0
def tlg_extract_members_status_change(
    chat_member_update: ChatMemberUpdated, ) -> Optional[Tuple[bool, bool]]:
    '''Takes a ChatMemberUpdated instance and extracts whether the
    "old_chat_member" was a member of the chat and whether the
    "new_chat_member" is a member of the chat. Returns None, if the status
    didn't change.'''
    status_change = chat_member_update.difference().get("status")
    old_is_member, new_is_member = chat_member_update.difference().get( \
            "is_member", (None, None))
    if status_change is None:
        if (old_is_member is None) or (new_is_member is None):
            return None
        was_member = old_is_member
        is_member = new_is_member
        return was_member, is_member
    old_status, new_status = status_change
    was_member = old_status in [
        ChatMember.MEMBER,
        ChatMember.CREATOR,
        ChatMember.ADMINISTRATOR,
    ] or (old_status == ChatMember.RESTRICTED and old_is_member is True)
    is_member = new_status in [
        ChatMember.MEMBER,
        ChatMember.CREATOR,
        ChatMember.ADMINISTRATOR,
    ] or (new_status == ChatMember.RESTRICTED and new_is_member is True)
    return was_member, is_member
 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)}
 def test_difference_different_classes(self, user, chat):
     old_chat_member = ChatMemberOwner(user=user, is_anonymous=False)
     new_chat_member = ChatMemberBanned(user=user, until_date=datetime.datetime(2021, 1, 1))
     chat_member_updated = ChatMemberUpdated(
         chat=chat,
         from_user=user,
         date=datetime.datetime.utcnow(),
         old_chat_member=old_chat_member,
         new_chat_member=new_chat_member,
     )
     diff = chat_member_updated.difference()
     assert diff.pop("is_anonymous") == (False, None)
     assert diff.pop("until_date") == (None, datetime.datetime(2021, 1, 1))
     assert diff.pop("status") == (ChatMember.OWNER, ChatMember.BANNED)
     assert diff == {}
    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),
        }
    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 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),
    )
示例#10
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),
    )
    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_de_json_required_args(self, bot, user, chat, old_chat_member, new_chat_member, time):
        json_dict = {
            "chat": chat.to_dict(),
            "from": user.to_dict(),
            "date": to_timestamp(time),
            "old_chat_member": old_chat_member.to_dict(),
            "new_chat_member": new_chat_member.to_dict(),
        }

        chat_member_updated = ChatMemberUpdated.de_json(json_dict, bot)

        assert chat_member_updated.chat == chat
        assert chat_member_updated.from_user == user
        assert abs(chat_member_updated.date - time) < datetime.timedelta(seconds=1)
        assert to_timestamp(chat_member_updated.date) == to_timestamp(time)
        assert chat_member_updated.old_chat_member == old_chat_member
        assert chat_member_updated.new_chat_member == new_chat_member
        assert chat_member_updated.invite_link is None
    def test_de_json_required_args(self, bot, user, chat, old_chat_member, new_chat_member, time):
        json_dict = {
            'chat': chat.to_dict(),
            'from': user.to_dict(),
            'date': to_timestamp(time),
            'old_chat_member': old_chat_member.to_dict(),
            'new_chat_member': new_chat_member.to_dict(),
        }

        chat_member_updated = ChatMemberUpdated.de_json(json_dict, bot)

        assert chat_member_updated.chat == chat
        assert chat_member_updated.from_user == user
        assert pytest.approx(chat_member_updated.date == time)
        assert to_timestamp(chat_member_updated.date) == to_timestamp(time)
        assert chat_member_updated.old_chat_member == old_chat_member
        assert chat_member_updated.new_chat_member == new_chat_member
        assert chat_member_updated.invite_link is None
示例#14
0
    PreCheckoutQuery,
    ShippingQuery,
    Update,
    User,
)
from telegram._utils.datetime 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())),
    ChatMemberOwner(User(1, "", False), True),
    ChatMemberOwner(User(1, "", False), True),
)

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
    },
def chat_member_updated(user, chat, old_chat_member, new_chat_member,
                        invite_link, time):
    return ChatMemberUpdated(chat, user, time, old_chat_member,
                             new_chat_member, invite_link)