Example #1
0
    def test_media_group(self):
        b = Bot()
        b.send_media_group = Mock()

        media = [
            InputMediaPhoto(pic1, caption='1'),
            InputMediaPhoto(InputFileFromURL(pic1), caption='2'),
            InputMediaVideo(vid1, caption='3'),
            InputMediaVideo(InputFileFromURL(vid1), thumb=tmb1, caption='4'),
            InputMediaVideo(InputFileFromURL(vid1),
                            thumb=InputFileFromURL(tmb1),
                            caption='5'),
        ]

        m = MediaGroupMessage(media, disable_notification=True)

        receiver = 123
        reply_id = 532
        m.send(b, receiver, reply_id)
        b.send_media_group.assert_called_once_with(
            receiver,
            media,
            disable_notification=True,
            reply_to_message_id=reply_id)
        self.assertTrue(True)
Example #2
0
 def test_InputFileFromURL(self):
     i = InputFileFromURL(
         "https://derpicdn.net/img/view/2017/5/16/1438309.png")
     self.assertEqual(
         i.file_url, "https://derpicdn.net/img/view/2017/5/16/1438309.png")
     self.assertEqual(i.file_name, '1438309.png')
     self.assertEqual(i.file_mime, 'image/png')
     self.assertEqual(i.get_request_files('pony'),
                      {'pony': ('1438309.png', i.file_blob, 'image/png')})
Example #3
0
    def test_edit_message_media(self):
        # upload by url
        url1 = 'https://derpicdn.net/img/view/2012/1/22/1382.jpg'
        url2 = 'https://derpicdn.net/img/view/2016/2/3/1079240.png'

        msg = self.bot.send_photo(TEST_CHAT,
                                  url1,
                                  caption="unittest",
                                  disable_notification=True)
        self.messages.append(msg)
        print("msg 1: {!r}".format(msg))
        self.assertIsInstance(msg, Message)
        self.assertEqual(msg.caption, 'unittest')
        self.assertIn('photo', msg)
        self.assertIsInstance(msg.photo, list)

        msg_id = msg.message_id
        file_id = self._get_biggest_photo_fileid(msg)

        # edit by url
        msg2 = self.bot.edit_message_media(InputMediaPhoto(url2),
                                           TEST_CHAT,
                                           message_id=msg_id)
        self.messages.append(msg2)
        print("msg 2: {!r}".format(msg2))
        self.assertIsInstance(msg2, Message)
        self.assertIn('photo', msg2)
        self.assertIsInstance(msg2.photo, list)
        self.assertEqual(msg2.caption, None)
        file_id2 = self._get_biggest_photo_fileid(msg2)

        # edit by file_id
        msg3 = self.bot.edit_message_media(InputMediaPhoto(file_id),
                                           TEST_CHAT,
                                           message_id=msg_id)
        self.messages.append(msg3)
        print("msg 3: {!r}".format(msg3))
        self.assertIsInstance(msg3, Message)
        self.assertIn('photo', msg3)
        self.assertIsInstance(msg3.photo, list)
        file_id3 = self._get_biggest_photo_fileid(msg3)
        self.assertEqual(msg2.caption, None)
        self.assertEqual(file_id3, file_id)

        # edit by upload (url)
        msg4 = self.bot.edit_message_media(InputMediaPhoto(
            InputFileFromURL(url2)),
                                           TEST_CHAT,
                                           message_id=msg_id)
        self.messages.append(msg4)
        print("msg 4: {!r}".format(msg4))
        self.assertIsInstance(msg4, Message)
        self.assertIn('photo', msg4)
        self.assertIsInstance(msg4.photo, list)
        self.assertEqual(msg4.caption, None)
        file_id4 = self._get_biggest_photo_fileid(msg4)

        self.messages.append(self.bot.send_message(TEST_CHAT, 'done.'))
Example #4
0
    def test_media_group(self):
        media = [
            InputMediaPhoto(pic1, caption='1'),
            InputMediaPhoto(InputFileFromURL(pic1), caption='2'),
            InputMediaVideo(vid1, caption='3'),
            InputMediaVideo(InputFileFromURL(vid1), thumb=tmb1, caption='4'),
            InputMediaVideo(InputFileFromURL(vid1),
                            thumb=InputFileFromURL(tmb1),
                            caption='5'),
        ]

        m = MediaGroupMessage(media, disable_notification=True)

        msg = m.send(self.bot, TEST_CHAT, self.reply_to)
        self.messages.extend(msg)
        self.messages.append(
            self.bot.send_message(TEST_CHAT,
                                  'done with unittest {}.'.format(self.id())))
Example #5
0
def send_gif(bot, channel, url, caption):
    import pytgbot
    from magic import MagicException

    assert isinstance(bot, pytgbot.bot.Bot)
    assert isinstance(url, str)
    assert isinstance(caption, str)

    if url.endswith(".gif"):
        url_mp4 = url[:-4] + ".mp4"
        try:
            return send_gif(bot, channel, url_mp4, caption)
        except:
            pass
            # end try
    # end if

    try:
        return bot.send_document(channel, document=url, caption=caption)
    except TgApiException:
        logger.warning("Gif via Telegram failed: {url}\n{caption}".format(
            url=url, caption=caption))
    # end try
    from pytgbot.api_types.sendable.files import InputFileFromURL, InputFileFromDisk
    try:
        bot.send_document(channel,
                          document=InputFileFromURL(url),
                          caption=caption)
    except (TgApiException, MagicException):
        logger.warning(
            "Gif via InputFileFromURL failed: {url}\n{caption}".format(
                url=url, caption=caption))
        import os
        from utils import download_file, telegram_autoplay_limit
        filename = '{channel}.{suffix}'.format(
            channel=channel, suffix=".gif" if url.endswith(".gif") else ".mp4")
        if not download_file(url, filename):
            return False
        if os.path.getsize(filename) > telegram_autoplay_limit:
            return False
        bot.send_document(channel,
                          InputFileFromDisk(
                              file_path=filename,
                              file_name=filename,
                              file_mime="image/gif"
                              if url.endswith(".gif") else "video/mp4"),
                          caption=caption)
    # end try


# end def send_gif
Example #6
0
def send_gif(bot, channel, url, caption, ext):
    import pytgbot
    from magic import MagicException

    assert isinstance(bot, pytgbot.bot.Bot)
    assert isinstance(url, str)
    assert isinstance(caption, str)

    # Fo not need code below because of it should be .mp4 if possible itself.
    # if url.endswith(".gif"):
    #     url_mp4 = url[:-4] + ".mp4"
    #     try:
    #         return send_gif(bot, channel, url_mp4, caption)
    #     except:
    #         pass
    #         # end try
    # # end if

    try:
        bot.send_document(channel, document=url, caption=caption)
        return True
    except TgApiException:
        logger.warning("Gif via Telegram failed: {url}\n{caption}".format(
            url=url, caption=caption))
    # end try
    from pytgbot.api_types.sendable.files import InputFileFromURL, InputFileFromDisk
    try:
        bot.send_document(channel,
                          document=InputFileFromURL(url),
                          caption=caption)
        return True
    except (TgApiException, MagicException):
        logger.warning(
            "Gif via InputFileFromURL failed: {url}\n{caption}".format(
                url=url, caption=caption))
        import os
        from utils import download_file, TELEGRAM_AUTOPLAY_LIMIT
        filename = '{channel}.{suffix}'.format(channel=channel, suffix=ext)
        if not download_file(url, filename):
            return False
        if os.path.getsize(filename) > TELEGRAM_AUTOPLAY_LIMIT:
            return False
        bot.send_document(channel,
                          InputFileFromDisk(
                              file_path=filename,
                              file_name=filename,
                              file_mime="image/gif"
                              if url.endswith(".gif") else "video/mp4"),
                          caption=caption)
        return True
Example #7
0
    def test_send_media_group(self):
        url1 = 'https://derpicdn.net/img/view/2012/1/22/1382.jpg'
        url2 = 'https://derpicdn.net/img/view/2016/2/3/1079240.png'
        vid1 = 'https://derpicdn.net/img/view/2016/12/21/1322277.mp4'
        pic1 = 'https://derpicdn.net/img/2017/7/21/1491832/thumb.jpeg'

        stuff = [
            InputMediaPhoto(url1, caption='1'),
            InputMediaPhoto(InputFileFromURL(url1), caption='2'),
            InputMediaVideo(vid1, caption='3'),
            InputMediaVideo(InputFileFromURL(vid1), thumb=pic1, caption='4'),
            InputMediaVideo(InputFileFromURL(vid1),
                            thumb=InputFileFromURL(pic1),
                            caption='5'),
        ]
        msgs = self.bot.send_media_group(
            TEST_CHAT,
            stuff,
            disable_notification=True,
        )
        self.messages.extend(msgs)

        self.messages.append(self.bot.send_message(TEST_CHAT, 'done.'))
Example #8
0
 def prepare_file(self):
     """
     This sets `self.file` to a fitting :class:`InputFile`
     or a fitting sublcass (:class:`InputFileFromDisk`, :class:`InputFileFromURL`)
     :return: Nothing
     """
     if self.file_input:
         self.file = self.file_input
     elif self.file_id:
         self.file = self.file_id
     elif self.file_content:
         file_name = "file"
         file_suffix = ".blob"
         if self.file_path:
             file_name = os.path.basename(os.path.normpath(
                 self.file_path))  # http://stackoverflow.com/a/3925147
             file_name, file_suffix = os.path.splitext(
                 file_name)  # http://stackoverflow.com/a/541394/3423324
         elif self.file_url:
             from urllib.parse import urlparse  # http://stackoverflow.com/a/18727481/3423324
             url = urlparse(self.file_url)
             file_name = os.path.basename(url.path)
             file_name, file_suffix = os.path.splitext(file_name)
         # end if
         if self.file_mime:
             import mimetypes
             file_suffix = mimetypes.guess_extension(self.file_mime)
             file_suffix = '.jpg' if file_suffix == '.jpe' else file_suffix  # .jpe -> .jpg
         # end if
         if not file_suffix or not file_suffix.strip().lstrip("."):
             logger.debug("file_suffix was empty. Using '.blob'")
             file_suffix = ".blob"
         # end if
         file_name = "{filename}{suffix}".format(filename=file_name,
                                                 suffix=file_suffix)
         self.file = InputFileFromBlob(self.file_content,
                                       file_name=file_name,
                                       file_mime=self.file_mime)
     elif self.file_path:
         self.file = InputFileFromDisk(self.file_path,
                                       file_mime=self.file_mime)
     elif self.file_url:
         self.file = InputFileFromURL(self.file_url,
                                      file_mime=self.file_mime)