Exemplo n.º 1
0
    def de_json(data):
        """
        Args:
            data (dict):

        Returns:
            telegram.Message:
        """
        if not data:
            return None

        data['from_user'] = User.de_json(data.get('from'))
        data['date'] = datetime.fromtimestamp(data['date'])
        data['chat'] = Chat.de_json(data.get('chat'))
        data['entities'] = MessageEntity.de_list(data.get('entities'))
        data['forward_from'] = User.de_json(data.get('forward_from'))
        data['forward_date'] = Message._fromtimestamp(data.get('forward_date'))
        data['reply_to_message'] = \
            Message.de_json(data.get('reply_to_message'))
        data['audio'] = Audio.de_json(data.get('audio'))
        data['document'] = Document.de_json(data.get('document'))
        data['photo'] = PhotoSize.de_list(data.get('photo'))
        data['sticker'] = Sticker.de_json(data.get('sticker'))
        data['video'] = Video.de_json(data.get('video'))
        data['voice'] = Voice.de_json(data.get('voice'))
        data['contact'] = Contact.de_json(data.get('contact'))
        data['location'] = Location.de_json(data.get('location'))
        data['venue'] = Venue.de_json(data.get('venue'))
        data['new_chat_member'] = User.de_json(data.get('new_chat_member'))
        data['left_chat_member'] = User.de_json(data.get('left_chat_member'))
        data['new_chat_photo'] = PhotoSize.de_list(data.get('new_chat_photo'))
        data['pinned_message'] = Message.de_json(data.get('pinned_message'))

        return Message(**data)
Exemplo n.º 2
0
    def de_json(cls, data, bot):
        if not data:
            return None

        data = super(Message, cls).de_json(data, bot)

        data['from_user'] = User.de_json(data.get('from'), bot)
        data['date'] = from_timestamp(data['date'])
        data['chat'] = Chat.de_json(data.get('chat'), bot)
        data['entities'] = MessageEntity.de_list(data.get('entities'), bot)
        data['forward_from'] = User.de_json(data.get('forward_from'), bot)
        data['forward_from_chat'] = Chat.de_json(data.get('forward_from_chat'), bot)
        data['forward_date'] = from_timestamp(data.get('forward_date'))
        data['reply_to_message'] = Message.de_json(data.get('reply_to_message'), bot)
        data['edit_date'] = from_timestamp(data.get('edit_date'))
        data['audio'] = Audio.de_json(data.get('audio'), bot)
        data['document'] = Document.de_json(data.get('document'), bot)
        data['game'] = Game.de_json(data.get('game'), bot)
        data['photo'] = PhotoSize.de_list(data.get('photo'), bot)
        data['sticker'] = Sticker.de_json(data.get('sticker'), bot)
        data['video'] = Video.de_json(data.get('video'), bot)
        data['voice'] = Voice.de_json(data.get('voice'), bot)
        data['video_note'] = VideoNote.de_json(data.get('video_note'), bot)
        data['contact'] = Contact.de_json(data.get('contact'), bot)
        data['location'] = Location.de_json(data.get('location'), bot)
        data['venue'] = Venue.de_json(data.get('venue'), bot)
        data['new_chat_member'] = User.de_json(data.get('new_chat_member'), bot)
        data['new_chat_members'] = User.de_list(data.get('new_chat_members'), bot)
        data['left_chat_member'] = User.de_json(data.get('left_chat_member'), bot)
        data['new_chat_photo'] = PhotoSize.de_list(data.get('new_chat_photo'), bot)
        data['pinned_message'] = Message.de_json(data.get('pinned_message'), bot)
        data['invoice'] = Invoice.de_json(data.get('invoice'), bot)
        data['successful_payment'] = SuccessfulPayment.de_json(data.get('successful_payment'), bot)

        return cls(bot=bot, **data)
    def test_de_json(self, bot):
        json_dict = {
            'type': self.type,
            'offset': self.offset,
            'length': self.length
        }
        entity = MessageEntity.de_json(json_dict, bot)

        assert entity.type == self.type
        assert entity.offset == self.offset
        assert entity.length == self.length
Exemplo n.º 4
0
    def de_json(cls, data, bot):
        if not data:
            return None

        data = super(Game, cls).de_json(data, bot)

        data['photo'] = PhotoSize.de_list(data.get('photo'), bot)
        data['text_entities'] = MessageEntity.de_list(data.get('text_entities'), bot)
        data['animation'] = Animation.de_json(data.get('animation'), bot)

        return cls(**data)
Exemplo n.º 5
0
 def test_parse_entities_url_emoji(self):
     url = b'http://github.com/?unicode=\\u2713\\U0001f469'.decode('unicode-escape')
     text = 'some url'
     link_entity = MessageEntity(type=MessageEntity.URL, offset=0, length=8, url=url)
     message = Message(1,
                       self.from_user,
                       self.date,
                       self.chat,
                       text=text,
                       entities=[link_entity])
     assert message.parse_entities() == {link_entity: text}
     assert next(iter(message.parse_entities())).url == url
    def test_entities_filter(self, message, message_entity):
        message.entities = [message_entity]
        assert Filters.entity(message_entity.type)(message)

        message.entities = []
        assert not Filters.entity(MessageEntity.MENTION)(message)

        second = message_entity.to_dict()
        second['type'] = 'bold'
        second = MessageEntity.de_json(second, None)
        message.entities = [message_entity, second]
        assert Filters.entity(message_entity.type)(message)
class TestInputTextMessageContent:
    message_text = '*message text*'
    parse_mode = ParseMode.MARKDOWN
    entities = [MessageEntity(MessageEntity.ITALIC, 0, 7)]
    disable_web_page_preview = True

    def test_slot_behaviour(self, input_text_message_content, mro_slots,
                            recwarn):
        inst = input_text_message_content
        for attr in inst.__slots__:
            assert getattr(inst, attr,
                           'err') != 'err', f"got extra slot '{attr}'"
        assert not inst.__dict__, f"got missing slot(s): {inst.__dict__}"
        assert len(mro_slots(inst)) == len(set(
            mro_slots(inst))), "duplicate slot"
        inst.custom, inst.message_text = 'should give warning', self.message_text
        assert len(recwarn) == 1 and 'custom' in str(
            recwarn[0].message), recwarn.list

    def test_expected_values(self, input_text_message_content):
        assert input_text_message_content.parse_mode == self.parse_mode
        assert input_text_message_content.message_text == self.message_text
        assert input_text_message_content.disable_web_page_preview == self.disable_web_page_preview
        assert input_text_message_content.entities == self.entities

    def test_to_dict(self, input_text_message_content):
        input_text_message_content_dict = input_text_message_content.to_dict()

        assert isinstance(input_text_message_content_dict, dict)
        assert (input_text_message_content_dict['message_text'] ==
                input_text_message_content.message_text)
        assert (input_text_message_content_dict['parse_mode'] ==
                input_text_message_content.parse_mode)
        assert input_text_message_content_dict['entities'] == [
            ce.to_dict() for ce in input_text_message_content.entities
        ]
        assert (input_text_message_content_dict['disable_web_page_preview'] ==
                input_text_message_content.disable_web_page_preview)

    def test_equality(self):
        a = InputTextMessageContent('text')
        b = InputTextMessageContent('text', parse_mode=ParseMode.HTML)
        c = InputTextMessageContent('label')
        d = ParseMode.HTML

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

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

        assert a != d
        assert hash(a) != hash(d)
Exemplo n.º 8
0
def message_entity(request):
    type_ = request.param
    url = None
    if type_ == MessageEntity.TEXT_LINK:
        url = 't.me'
    user = None
    if type_ == MessageEntity.TEXT_MENTION:
        user = User(1, 'test_user', False)
    language = None
    if type_ == MessageEntity.PRE:
        language = "python"
    return MessageEntity(type_, 1, 3, url=url, user=user, language=language)
Exemplo n.º 9
0
    def de_json(cls, data: Optional[JSONDict], bot: 'Bot') -> Optional['Poll']:
        """See :meth:`telegram.TelegramObject.de_json`."""
        data = cls._parse_data(data)

        if not data:
            return None

        data['options'] = [PollOption.de_json(option, bot) for option in data['options']]
        data['explanation_entities'] = MessageEntity.de_list(data.get('explanation_entities'), bot)
        data['close_date'] = from_timestamp(data.get('close_date'))

        return cls(**data)
Exemplo n.º 10
0
 async def test_send_media_group_photo(self, bot, chat_id, media_group):
     messages = await bot.send_media_group(chat_id, media_group)
     assert isinstance(messages, list)
     assert len(messages) == 3
     assert all(isinstance(mes, Message) for mes in messages)
     assert all(mes.media_group_id == messages[0].media_group_id
                for mes in messages)
     assert all(mes.caption == f"photo {idx+1}"
                for idx, mes in enumerate(messages))
     assert all(
         mes.caption_entities == [MessageEntity(MessageEntity.BOLD, 0, 5)]
         for mes in messages)
Exemplo n.º 11
0
    def de_json(cls, data, bot):
        if not data:
            return None

        data = super(Game, cls).de_json(data, bot)

        data['photo'] = PhotoSize.de_list(data.get('photo'), bot)
        data['text_entities'] = MessageEntity.de_list(
            data.get('text_entities'), bot)
        data['animation'] = Animation.de_json(data.get('animation'), bot)

        return cls(**data)
def message(bot):
    return Message(message_id=1,
                   from_user=User(id=1, first_name='', is_bot=False),
                   date=None,
                   chat=Chat(id=1, type=''),
                   message='/test',
                   bot=bot,
                   entities=[
                       MessageEntity(type=MessageEntity.BOT_COMMAND,
                                     offset=0,
                                     length=len('/test'))
                   ])
Exemplo n.º 13
0
 def test_parse_caption_entities(self):
     text = (b'\\U0001f469\\u200d\\U0001f469\\u200d\\U0001f467'
             b'\\u200d\\U0001f467\\U0001f431http://google.com'
             ).decode('unicode-escape')
     entity = MessageEntity(type=MessageEntity.URL, offset=13, length=17)
     entity_2 = MessageEntity(type=MessageEntity.BOLD, offset=13, length=1)
     message = Message(
         1,
         self.from_user,
         self.date,
         self.chat,
         caption=text,
         caption_entities=[entity_2, entity],
     )
     assert message.parse_caption_entities(MessageEntity.URL) == {
         entity: 'http://google.com'
     }
     assert message.parse_caption_entities() == {
         entity: 'http://google.com',
         entity_2: 'h'
     }
 def test_parse_caption_entity(self):
     caption = (b'\\U0001f469\\u200d\\U0001f469\\u200d\\U0001f467'
                b'\\u200d\\U0001f467\\U0001f431http://google.com'
                ).decode('unicode-escape')
     entity = MessageEntity(type=MessageEntity.URL, offset=13, length=17)
     message = Message(1,
                       self.from_user,
                       self.date,
                       self.chat,
                       caption=caption,
                       caption_entities=[entity])
     assert message.parse_caption_entity(entity) == 'http://google.com'
    def test_conversation_timeout_keeps_extending(self, dp, bot, user1):
        handler = ConversationHandler(entry_points=self.entry_points,
                                      states=self.states,
                                      fallbacks=self.fallbacks,
                                      conversation_timeout=0.5)
        dp.add_handler(handler)

        # Start state machine, wait, do something, verify the timeout is extended.
        # t=0 /start (timeout=.5)
        # t=.25 /brew (timeout=.75)
        # t=.5 original timeout
        # t=.6 /pourCoffee (timeout=1.1)
        # t=.75 second timeout
        # t=1.1 actual timeout
        message = Message(0,
                          user1,
                          None,
                          self.group,
                          text='/start',
                          entities=[
                              MessageEntity(type=MessageEntity.BOT_COMMAND,
                                            offset=0,
                                            length=len('/start'))
                          ],
                          bot=bot)
        dp.process_update(Update(update_id=0, message=message))
        assert handler.conversations.get(
            (self.group.id, user1.id)) == self.THIRSTY
        sleep(0.25)  # t=.25
        dp.job_queue.tick()
        assert handler.conversations.get(
            (self.group.id, user1.id)) == self.THIRSTY
        message.text = '/brew'
        message.entities[0].length = len('/brew')
        dp.process_update(Update(update_id=0, message=message))
        assert handler.conversations.get(
            (self.group.id, user1.id)) == self.BREWING
        sleep(0.35)  # t=.6
        dp.job_queue.tick()
        assert handler.conversations.get(
            (self.group.id, user1.id)) == self.BREWING
        message.text = '/pourCoffee'
        message.entities[0].length = len('/pourCoffee')
        dp.process_update(Update(update_id=0, message=message))
        assert handler.conversations.get(
            (self.group.id, user1.id)) == self.DRINKING
        sleep(.4)  # t=1
        dp.job_queue.tick()
        assert handler.conversations.get(
            (self.group.id, user1.id)) == self.DRINKING
        sleep(.1)  # t=1.1
        dp.job_queue.tick()
        assert handler.conversations.get((self.group.id, user1.id)) is None
Exemplo n.º 16
0
    def test_entities_filter(self, message, message_entity):
        message.entities = [message_entity]
        assert Filters.entity(message_entity.type)(message)

        message.entities = []
        assert not Filters.entity(MessageEntity.MENTION)(message)

        second = message_entity.to_dict()
        second['type'] = 'bold'
        second = MessageEntity.de_json(second, None)
        message.entities = [message_entity, second]
        assert Filters.entity(message_entity.type)(message)
Exemplo n.º 17
0
    def de_json(cls, data: Optional[JSONDict], bot: 'Bot') -> Optional['Game']:
        data = cls.parse_data(data)

        if not data:
            return None

        data['photo'] = PhotoSize.de_list(data.get('photo'), bot)
        data['text_entities'] = MessageEntity.de_list(
            data.get('text_entities'), bot)
        data['animation'] = Animation.de_json(data.get('animation'), bot)

        return cls(**data)
Exemplo n.º 18
0
    def test_text_markdown_new_in_v2(self, message):
        message.text = 'test'
        message.entities = [
            MessageEntity(MessageEntity.BOLD, offset=0, length=4),
            MessageEntity(MessageEntity.ITALIC, offset=0, length=4),
        ]
        with pytest.raises(ValueError):
            assert message.text_markdown

        message.entities = [
            MessageEntity(MessageEntity.UNDERLINE, offset=0, length=4)
        ]
        with pytest.raises(ValueError):
            message.text_markdown

        message.entities = [
            MessageEntity(MessageEntity.STRIKETHROUGH, offset=0, length=4)
        ]
        with pytest.raises(ValueError):
            message.text_markdown

        message.entities = []
Exemplo n.º 19
0
    def test_end_on_first_message(self, dp, bot, user1):
        handler = ConversationHandler(
            entry_points=[CommandHandler('start', self.start_end)], states={},
            fallbacks=[])
        dp.add_handler(handler)

        # User starts the state machine and immediately ends it.
        message = Message(0, user1, None, self.group, text='/start',
                          entities=[MessageEntity(type=MessageEntity.BOT_COMMAND,
                                                  offset=0, length=len('/start'))],
                          bot=bot)
        dp.process_update(Update(update_id=0, message=message))
        assert len(handler.conversations) == 0
Exemplo n.º 20
0
 def test_send_media_group_all_args(self, bot, chat_id, media_group):
     m1 = bot.send_message(chat_id, text="test")
     messages = bot.send_media_group(
         chat_id, media_group, disable_notification=True, reply_to_message_id=m1.message_id
     )
     assert isinstance(messages, list)
     assert len(messages) == 3
     assert all(isinstance(mes, Message) for mes in messages)
     assert all(mes.media_group_id == messages[0].media_group_id for mes in messages)
     assert all(mes.caption == f'photo {idx+1}' for idx, mes in enumerate(messages))
     assert all(
         mes.caption_entities == [MessageEntity(MessageEntity.BOLD, 0, 5)] for mes in messages
     )
Exemplo n.º 21
0
    def test_regex_inverted(self, update):
        update.message.text = '/start deep-linked param'
        update.message.entities = [MessageEntity(MessageEntity.BOT_COMMAND, 0, 5)]
        filter = ~Filters.regex(r'deep-linked param')
        result = filter(update)
        assert not result
        update.message.text = 'not it'
        result = filter(update)
        assert result
        assert isinstance(result, bool)

        filter = (~Filters.regex('linked') & Filters.command)
        update.message.text = "it's linked"
        result = filter(update)
        assert not result
        update.message.text = '/start'
        update.message.entities = [MessageEntity(MessageEntity.BOT_COMMAND, 0, 6)]
        result = filter(update)
        assert result
        update.message.text = '/linked'
        result = filter(update)
        assert not result

        filter = (~Filters.regex('linked') | Filters.command)
        update.message.text = "it's linked"
        update.message.entities = []
        result = filter(update)
        assert not result
        update.message.text = '/start linked'
        update.message.entities = [MessageEntity(MessageEntity.BOT_COMMAND, 0, 6)]
        result = filter(update)
        assert result
        update.message.text = '/start'
        result = filter(update)
        assert result
        update.message.text = 'nothig'
        update.message.entities = []
        result = filter(update)
        assert result
Exemplo n.º 22
0
    def test_caption_entities_filter(self, update, message_entity):
        update.message.caption_entities = [message_entity]
        assert Filters.caption_entity(message_entity.type)(update)

        update.message.caption_entities = []
        assert not Filters.caption_entity(MessageEntity.MENTION)(update)

        second = message_entity.to_dict()
        second['type'] = 'bold'
        second = MessageEntity.de_json(second, None)
        update.message.caption_entities = [message_entity, second]
        assert Filters.caption_entity(message_entity.type)(update)
        assert not Filters.entity(message_entity.type)(update)
Exemplo n.º 23
0
    def de_json(data, bot):
        """
        Args:
            data (dict):
            bot (telegram.Bot):

        Returns:
            telegram.Message:
        """
        if not data:
            return None

        data = super(Message, Message).de_json(data, bot)

        data['from_user'] = User.de_json(data.get('from'), bot)
        data['date'] = from_timestamp(data['date'])
        data['chat'] = Chat.de_json(data.get('chat'), bot)
        data['entities'] = MessageEntity.de_list(data.get('entities'), bot)
        data['forward_from'] = User.de_json(data.get('forward_from'), bot)
        data['forward_from_chat'] = Chat.de_json(data.get('forward_from_chat'),
                                                 bot)
        data['forward_date'] = from_timestamp(data.get('forward_date'))
        data['reply_to_message'] = Message.de_json(
            data.get('reply_to_message'), bot)
        data['edit_date'] = from_timestamp(data.get('edit_date'))
        data['audio'] = Audio.de_json(data.get('audio'), bot)
        data['document'] = Document.de_json(data.get('document'), bot)
        data['game'] = Game.de_json(data.get('game'), bot)
        data['photo'] = PhotoSize.de_list(data.get('photo'), bot)
        data['sticker'] = Sticker.de_json(data.get('sticker'), bot)
        data['video'] = Video.de_json(data.get('video'), bot)
        data['voice'] = Voice.de_json(data.get('voice'), bot)
        data['video_note'] = VideoNote.de_json(data.get('video_note'), bot)
        data['contact'] = Contact.de_json(data.get('contact'), bot)
        data['location'] = Location.de_json(data.get('location'), bot)
        data['venue'] = Venue.de_json(data.get('venue'), bot)
        data['new_chat_member'] = User.de_json(data.get('new_chat_member'),
                                               bot)
        data['new_chat_members'] = User.de_list(data.get('new_chat_members'),
                                                bot)
        data['left_chat_member'] = User.de_json(data.get('left_chat_member'),
                                                bot)
        data['new_chat_photo'] = PhotoSize.de_list(data.get('new_chat_photo'),
                                                   bot)
        data['pinned_message'] = Message.de_json(data.get('pinned_message'),
                                                 bot)
        data['invoice'] = Invoice.de_json(data.get('invoice'), bot)
        data['successful_payment'] = SuccessfulPayment.de_json(
            data.get('successful_payment'), bot)

        return Message(bot=bot, **data)
Exemplo n.º 24
0
    def de_json(cls, data, bot):
        if not data:
            return None

        data = super().de_json(data, bot)

        data['options'] = [
            PollOption.de_json(option, bot) for option in data['options']
        ]
        data['explanation_entities'] = MessageEntity.de_list(
            data.get('explanation_entities'), bot)
        data['close_date'] = from_timestamp(data.get('close_date'))

        return cls(**data)
Exemplo n.º 25
0
 def test_penalty_swatting_bot(self):
     self.call_handler_with_message("@%s +%d" % (self.mock_bot.username, 5),
                                    entities=[
                                        MessageEntity(
                                            MessageEntity.MENTION,
                                            0,
                                            len(self.mock_bot.username) + 1,
                                            user=self.mock_bot)
                                    ])
     expected_messages = [
         PENALTY_SCOLDS["SWATTING_BOT"], SWAT_UPDATE_STRING %
         (self.from_user_text, "increased", env_vars["PENALTY"])
     ]
     self.assert_chat_called_with(expected_messages)
Exemplo n.º 26
0
def _from_celery_entities_to_entities(celery_entities: Optional[List[Dict]] = None) -> Optional[List[MessageEntity]]:
    entities = None
    if celery_entities:
        entities = [
            MessageEntity(
                type=entity['type'],
                offset=entity['offset'],
                length=entity['length'],
                url=entity.get('url'),
                language=entity.get('language'),
            )
            for entity in celery_entities
        ]
    return entities
Exemplo n.º 27
0
class TestInputMediaPhoto:
    type_ = "photo"
    media = "NOTAREALFILEID"
    caption = "My Caption"
    parse_mode = "Markdown"
    caption_entities = [MessageEntity(MessageEntity.BOLD, 0, 2)]

    def test_slot_behaviour(self, input_media_photo, mro_slots):
        inst = input_media_photo
        for attr in inst.__slots__:
            assert getattr(inst, attr,
                           "err") != "err", f"got extra slot '{attr}'"
        assert len(mro_slots(inst)) == len(set(
            mro_slots(inst))), "duplicate slot"

    def test_expected_values(self, input_media_photo):
        assert input_media_photo.type == self.type_
        assert input_media_photo.media == self.media
        assert input_media_photo.caption == self.caption
        assert input_media_photo.parse_mode == self.parse_mode
        assert input_media_photo.caption_entities == self.caption_entities

    def test_to_dict(self, input_media_photo):
        input_media_photo_dict = input_media_photo.to_dict()
        assert input_media_photo_dict["type"] == input_media_photo.type
        assert input_media_photo_dict["media"] == input_media_photo.media
        assert input_media_photo_dict["caption"] == input_media_photo.caption
        assert input_media_photo_dict[
            "parse_mode"] == input_media_photo.parse_mode
        assert input_media_photo_dict["caption_entities"] == [
            ce.to_dict() for ce in input_media_photo.caption_entities
        ]

    def test_with_photo(self, photo):  # noqa: F811
        # fixture found in test_photo
        input_media_photo = InputMediaPhoto(photo, caption="test 2")
        assert input_media_photo.type == self.type_
        assert input_media_photo.media == photo.file_id
        assert input_media_photo.caption == "test 2"

    def test_with_photo_file(self, photo_file):  # noqa: F811
        # fixture found in test_photo
        input_media_photo = InputMediaPhoto(photo_file, caption="test 2")
        assert input_media_photo.type == self.type_
        assert isinstance(input_media_photo.media, InputFile)
        assert input_media_photo.caption == "test 2"

    def test_with_local_files(self):
        input_media_photo = InputMediaPhoto(data_file("telegram.mp4"))
        assert input_media_photo.media == data_file("telegram.mp4").as_uri()
Exemplo n.º 28
0
class TestInputMediaPhoto:
    type_ = "photo"
    media = "NOTAREALFILEID"
    caption = "My Caption"
    parse_mode = 'Markdown'
    caption_entities = [MessageEntity(MessageEntity.BOLD, 0, 2)]

    def test_slot_behaviour(self, input_media_photo, recwarn, mro_slots):
        inst = input_media_photo
        for attr in inst.__slots__:
            assert getattr(inst, attr, 'err') != 'err', f"got extra slot '{attr}'"
        assert not inst.__dict__, f"got missing slot(s): {inst.__dict__}"
        assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
        inst.custom, inst.type = 'should give warning', self.type_
        assert len(recwarn) == 1 and 'custom' in str(recwarn[0].message), recwarn.list

    def test_expected_values(self, input_media_photo):
        assert input_media_photo.type == self.type_
        assert input_media_photo.media == self.media
        assert input_media_photo.caption == self.caption
        assert input_media_photo.parse_mode == self.parse_mode
        assert input_media_photo.caption_entities == self.caption_entities

    def test_to_dict(self, input_media_photo):
        input_media_photo_dict = input_media_photo.to_dict()
        assert input_media_photo_dict['type'] == input_media_photo.type
        assert input_media_photo_dict['media'] == input_media_photo.media
        assert input_media_photo_dict['caption'] == input_media_photo.caption
        assert input_media_photo_dict['parse_mode'] == input_media_photo.parse_mode
        assert input_media_photo_dict['caption_entities'] == [
            ce.to_dict() for ce in input_media_photo.caption_entities
        ]

    def test_with_photo(self, photo):  # noqa: F811
        # fixture found in test_photo
        input_media_photo = InputMediaPhoto(photo, caption="test 2")
        assert input_media_photo.type == self.type_
        assert input_media_photo.media == photo.file_id
        assert input_media_photo.caption == "test 2"

    def test_with_photo_file(self, photo_file):  # noqa: F811
        # fixture found in test_photo
        input_media_photo = InputMediaPhoto(photo_file, caption="test 2")
        assert input_media_photo.type == self.type_
        assert isinstance(input_media_photo.media, InputFile)
        assert input_media_photo.caption == "test 2"

    def test_with_local_files(self):
        input_media_photo = InputMediaPhoto('tests/data/telegram.mp4')
        assert input_media_photo.media == (Path.cwd() / 'tests/data/telegram.mp4/').as_uri()
Exemplo n.º 29
0
 def __parse_text(ptype, message, invalids, tags, text_links):
     entities = []
     mentions = re.compile(r'@[a-zA-Z0-9]{1,}\b')
     hashtags = re.compile(r'#[a-zA-Z0-9]{1,}\b')
     botcommands = re.compile(r'(?<!\/|\w)\/[a-zA-Z0-0_\-]{1,}\b')
     urls = re.compile(
         r'(([hHtTpP]{4}[sS]?|[fFtTpP]{3})://)?([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?'
     )
     inv = invalids.search(message)
     if inv:
         raise BadMarkupException(
             "nested {} is not supported. your text: {}".format(
                 ptype, inv.groups()[0]))
     while tags.search(message):
         tag = tags.search(message)
         text = tag.groups()[2]
         start = tag.start()
         if tag.groups()[1] in ["b", "*"]:
             parse_type = "bold"
         elif tag.groups()[1] in ["i", "_"]:
             parse_type = "italic"
         elif tag.groups()[1] in ["code", "`"]:
             parse_type = "code"
         elif tag.groups()[1] in ["pre", "```"]:
             parse_type = "pre"
         entities.append(MessageEntity(parse_type, start, len(text)))
         message = tags.sub(r'\3', message, count=1)
     while text_links.search(message):
         link = text_links.search(message)
         url = link.group('url')
         text = link.group('text')
         start = link.start()
         length = len(text)
         for x, ent in enumerate(entities):
             if ent.offset > start:
                 entities[x].offset -= link.end() - start - length
         entities.append(MessageEntity('text_link', start, length, url=url))
         message = text_links.sub(r'\g<text>', message, count=1)
     for mention in mentions.finditer(message):
         entities.append(
             MessageEntity('mention',
                           mention.start(), mention.end() - mention.start(
                           )))
     for hashtag in hashtags.finditer(message):
         entities.append(
             MessageEntity('hashtag',
                           hashtag.start(), hashtag.end() - hashtag.start(
                           )))
     for botcommand in botcommands.finditer(message):
         entities.append(
             MessageEntity('bot_command',
                           botcommand.start(),
                           botcommand.end() - botcommand.start()))
     for url in urls.finditer(message):
         entities.append(
             MessageEntity('url', url.start(), url.end() - url.start()))
     return message, entities
Exemplo n.º 30
0
    def de_json(cls, data, bot):
        if not data:
            return None

        data = super(Message, cls).de_json(data, bot)

        data['from_user'] = User.de_json(data.get('from'), bot)
        data['date'] = from_timestamp(data['date'])
        data['chat'] = Chat.de_json(data.get('chat'), bot)
        data['entities'] = MessageEntity.de_list(data.get('entities'), bot)
        data['caption_entities'] = MessageEntity.de_list(data.get('caption_entities'), bot)
        data['forward_from'] = User.de_json(data.get('forward_from'), bot)
        data['forward_from_chat'] = Chat.de_json(data.get('forward_from_chat'), bot)
        data['forward_date'] = from_timestamp(data.get('forward_date'))
        data['reply_to_message'] = Message.de_json(data.get('reply_to_message'), bot)
        data['edit_date'] = from_timestamp(data.get('edit_date'))
        data['audio'] = Audio.de_json(data.get('audio'), bot)
        data['document'] = Document.de_json(data.get('document'), bot)
        data['animation'] = Animation.de_json(data.get('animation'), bot)
        data['game'] = Game.de_json(data.get('game'), bot)
        data['photo'] = PhotoSize.de_list(data.get('photo'), bot)
        data['sticker'] = Sticker.de_json(data.get('sticker'), bot)
        data['video'] = Video.de_json(data.get('video'), bot)
        data['voice'] = Voice.de_json(data.get('voice'), bot)
        data['video_note'] = VideoNote.de_json(data.get('video_note'), bot)
        data['contact'] = Contact.de_json(data.get('contact'), bot)
        data['location'] = Location.de_json(data.get('location'), bot)
        data['venue'] = Venue.de_json(data.get('venue'), bot)
        data['new_chat_members'] = User.de_list(data.get('new_chat_members'), bot)
        data['left_chat_member'] = User.de_json(data.get('left_chat_member'), bot)
        data['new_chat_photo'] = PhotoSize.de_list(data.get('new_chat_photo'), bot)
        data['pinned_message'] = Message.de_json(data.get('pinned_message'), bot)
        data['invoice'] = Invoice.de_json(data.get('invoice'), bot)
        data['successful_payment'] = SuccessfulPayment.de_json(data.get('successful_payment'), bot)
        data['passport_data'] = PassportData.de_json(data.get('passport_data'), bot)

        return cls(bot=bot, **data)
    def test_with_nested_conversationHandler(self, dp, update, good_pickle_files,
                                             pickle_persistence):
        dp.persistence = pickle_persistence
        dp.use_context = True
        NEXT2, NEXT3 = range(1, 3)

        def start(update, context):
            return NEXT2

        start = CommandHandler('start', start)

        def next(update, context):
            return NEXT2

        next = MessageHandler(None, next)

        def next2(update, context):
            return ConversationHandler.END

        next2 = MessageHandler(None, next2)

        nested_ch = ConversationHandler(
            [next],
            {NEXT2: [next2]},
            [],
            name='name3',
            persistent=True,
            map_to_parent={ConversationHandler.END: ConversationHandler.END},
        )

        ch = ConversationHandler([start], {NEXT2: [nested_ch], NEXT3: []}, [], name='name2',
                                 persistent=True)
        dp.add_handler(ch)
        assert ch.conversations[ch._get_key(update)] == 1
        assert nested_ch.conversations[nested_ch._get_key(update)] == 1
        dp.process_update(update)
        assert ch._get_key(update) not in ch.conversations
        assert nested_ch._get_key(update) not in nested_ch.conversations
        update.message.text = '/start'
        update.message.entities = [MessageEntity(MessageEntity.BOT_COMMAND, 0, 6)]
        dp.process_update(update)
        assert ch.conversations[ch._get_key(update)] == 1
        assert ch.conversations == pickle_persistence.conversations['name2']
        assert nested_ch._get_key(update) not in nested_ch.conversations
        dp.process_update(update)
        assert ch.conversations[ch._get_key(update)] == 1
        assert ch.conversations == pickle_persistence.conversations['name2']
        assert nested_ch.conversations[nested_ch._get_key(update)] == 1
        assert nested_ch.conversations == pickle_persistence.conversations['name3']
Exemplo n.º 32
0
    def test_extract_message_links(self):
        test_entities = [
            {
                'length': 17,
                'offset': 0,
                'type': 'url',
            },
            {
                'length': 11,
                'offset': 18,
                'type': 'text_link',
                'url': 'https://t.me/group_name/123456',
            },
            {'length': 12, 'offset': 30, 'type': 'text_link', 'url': 't.me/c/1173342352/256'},
            {
                'length': 11,
                'offset': 43,
                'type': 'text_link',
                'url': 'https://t.me/joinchat/BHFkvxrbaIpgGsEJnO_pew',
            },
            {
                'length': 10,
                'offset': 55,
                'type': 'text_link',
                'url': 'https://t.me/pythontelegrambotgroup',
            },
        ]
        test_text = 'https://google.de public_link private_link invite_link group_link'
        test_message = Message(
            message_id=1,
            from_user=None,
            date=None,
            chat=None,
            text=test_text,
            entities=[MessageEntity(**e) for e in test_entities],
        )

        results = extract_urls.extract_message_links(test_message)
        assert len(results) == 2
        assert results[0] == test_entities[1]['url']
        assert results[1] == test_entities[2]['url']

        results = extract_urls.extract_message_links(test_message, private_only=True)
        assert len(results) == 1
        assert results[0] == test_entities[2]['url']

        results = extract_urls.extract_message_links(test_message, public_only=True)
        assert len(results) == 1
        assert results[0] == test_entities[1]['url']
 def test_caption_html_emoji(self):
     caption = b'\\U0001f469\\u200d\\U0001f469\\u200d ABC'.decode(
         'unicode-escape')
     expected = b'\\U0001f469\\u200d\\U0001f469\\u200d <b>ABC</b>'.decode(
         'unicode-escape')
     bold_entity = MessageEntity(type=MessageEntity.BOLD,
                                 offset=7,
                                 length=3)
     message = Message(1,
                       self.from_user,
                       self.date,
                       self.chat,
                       caption=caption,
                       caption_entities=[bold_entity])
     assert expected == message.caption_html
Exemplo n.º 34
0
 def test_multiple_swats(self):
     other_mention_text = "Bobby"
     other_mentioned_user = User(3, "Bobby", False)
     other_mention_entity = MessageEntity(MessageEntity.TEXT_MENTION,
                                          len(self.mention_text) + 5,
                                          len(other_mention_text) + 1,
                                          user=other_mentioned_user)
     self.call_handler_with_message(
         "@%s +4 @%s +2" % (self.mention_text, other_mention_text),
         entities=[self.mention_entity, other_mention_entity])
     expected_messages = [
         SWAT_UPDATE_STRING % (self.mention_text, "increased", 4),
         SWAT_UPDATE_STRING % (other_mention_text, "increased", 2)
     ]
     self.assert_chat_called_with(expected_messages)
Exemplo n.º 35
0
 def test_text_markdown_emoji(self):
     text = b'\\U0001f469\\u200d\\U0001f469\\u200d ABC'.decode(
         'unicode-escape')
     expected = b'\\U0001f469\\u200d\\U0001f469\\u200d *ABC*'.decode(
         'unicode-escape')
     bold_entity = MessageEntity(type=MessageEntity.BOLD,
                                 offset=7,
                                 length=3)
     message = Message(1,
                       self.from_user,
                       self.date,
                       self.chat,
                       text=text,
                       entities=[bold_entity])
     assert expected == message.text_markdown
Exemplo n.º 36
0
    def de_json(data, bot):
        """
        Args:
            data (dict):
            bot (telegram.Bot):

        Returns:
            telegram.Game:

        """
        if not data:
            return None

        data['photo'] = PhotoSize.de_list(data.get('photo'), bot)
        data['text_entities'] = MessageEntity.de_list(data.get('text_entities'), bot)
        data['animation'] = Animation.de_json(data.get('animation'), bot)

        return Game(**data)