コード例 #1
0
 def get_media_input(self, image: Image):
     caption = self.format_caption(image)
     if image.animated:
         inp = InputMediaVideo(image.url, caption=caption)
     else:
         inp = InputMediaPhoto(image.url, caption=caption)
     return inp
コード例 #2
0
ファイル: job.py プロジェクト: k-walter/NUSummiteers
def SendMediaGroup(media, text):
    parseMode = "HTML"
    out = list()
    for m in media:
        if "photo" in m:
            i = InputMediaPhoto(media=m["photo"],
                                caption=text,
                                parse_mode=parseMode)
        elif "video" in m:
            i = InputMediaVideo(media=m["video"],
                                caption=text,
                                parse_mode=parseMode)
        else:
            continue

        out.append(i)
        # set caption for first media only
        text, parseMode = None, None

    def callback(context):
        def fn(tid):
            return context.bot.send_media_group(chat_id=tid, media=out)

        Broadcast(fn)

    return callback
コード例 #3
0
ファイル: main.py プロジェクト: Poolitzer/channelforwarder
def edited_post(update: Update, context: CallbackContext):
    message = update.effective_message
    msg_id = context.bot_data["messages"][message.message_id]
    bot = context.bot
    if message.text:
        bot.edit_message_text(chat_id=GROUP_ID,
                              message_id=msg_id,
                              text=message.text_html)
        return
    elif message.effective_attachment:
        media = None
        if message.location:
            bot.edit_message_live_location(chat_id=GROUP_ID,
                                           message_id=msg_id,
                                           **message.location.to_dict())
            return
        elif message.photo:
            media = InputMediaPhoto(media=message.photo[-1].file_id,
                                    caption=message.caption_html)
        elif message.video:
            media = InputMediaVideo(media=message.video.file_id,
                                    caption=message.caption_html)
        if not media:
            media = InputMediaDocument(
                media=message.effective_attachment.file_id,
                caption=message.caption_html)
        bot.edit_message_media(chat_id=GROUP_ID,
                               message_id=msg_id,
                               media=media)
コード例 #4
0
def send_album(bot, job):
    user_id, media_group_id = job.context
    items = ALBUM_DICT[media_group_id]
    # delete from ALBUM_DICT
    del ALBUM_DICT[media_group_id]
    media = []
    for item in items:
        if item['type'] == 'photo':
            media.append(
                InputMediaPhoto(
                    media=item['file_id'],
                    caption=item['caption'],
                    parse_mode=ParseMode.HTML
                )
            )
        elif item['type'] == 'video':
            media.append(
                InputMediaVideo(
                    media=item['file_id'],
                    caption=item['caption'],
                    parse_mode=ParseMode.HTML
                )
            )
    bot.sendMediaGroup(
        chat_id=user_id,
        media=media
    )
コード例 #5
0
    def test_send_media_group_custom_filename(
        self,
        bot,
        chat_id,
        photo_file,  # noqa: F811
        animation_file,  # noqa: F811
        audio_file,  # noqa: F811
        video_file,  # noqa: F811
        monkeypatch,
    ):
        def make_assertion(url, data, **kwargs):
            result = all(im.media.filename == 'custom_filename'
                         for im in data['media'])
            # We are a bit hacky here b/c Bot.send_media_group expects a list of Message-dicts
            return [Message(0, None, None, text=result).to_dict()]

        monkeypatch.setattr(bot.request, 'post', make_assertion)

        media = [
            InputMediaAnimation(animation_file, filename='custom_filename'),
            InputMediaAudio(audio_file, filename='custom_filename'),
            InputMediaPhoto(photo_file, filename='custom_filename'),
            InputMediaVideo(video_file, filename='custom_filename'),
        ]

        assert bot.send_media_group(chat_id, media)[0].text is True
コード例 #6
0
def send_album(context):
    media_group_id = context.job.context[0]
    updates = ALBUM_DICT[media_group_id]

    # delete from ALBUM_DICT
    del ALBUM_DICT[media_group_id]

    # ordering album updates
    updates.sort(key=lambda x: x.message.message_id)

    media = []
    for update in updates:
        if update.message.photo:
            media.append(
                InputMediaPhoto(media=update.message.photo[-1].file_id,
                                caption='' if update.message.caption is None
                                else update.message.caption_html,
                                parse_mode=ParseMode.HTML))
        elif update.message.video:
            media.append(
                InputMediaVideo(media=update.message.video.file_id,
                                caption='' if update.message.caption is None
                                else update.message.caption_html,
                                parse_mode=ParseMode.HTML))
    context.bot.sendMediaGroup(chat_id=updates[0].message.from_user.id,
                               media=media)
コード例 #7
0
    def test_from_input_input_media(self):
        input_media_no_thumb = InputMediaPhoto(
            media=data_file("telegram.jpg").read_bytes())
        input_media_thumb = InputMediaVideo(
            media=data_file("telegram.mp4").read_bytes(),
            thumb=data_file("telegram.jpg").read_bytes(),
        )

        request_parameter = RequestParameter.from_input(
            "key", input_media_no_thumb)
        expected_no_thumb = input_media_no_thumb.to_dict()
        expected_no_thumb.update(
            {"media": input_media_no_thumb.media.attach_uri})
        assert request_parameter.value == expected_no_thumb
        assert request_parameter.input_files == [input_media_no_thumb.media]

        request_parameter = RequestParameter.from_input(
            "key", input_media_thumb)
        expected_thumb = input_media_thumb.to_dict()
        expected_thumb.update({"media": input_media_thumb.media.attach_uri})
        expected_thumb.update({"thumb": input_media_thumb.thumb.attach_uri})
        assert request_parameter.value == expected_thumb
        assert request_parameter.input_files == [
            input_media_thumb.media, input_media_thumb.thumb
        ]

        request_parameter = RequestParameter.from_input(
            "key", [input_media_thumb, input_media_no_thumb])
        assert request_parameter.value == [expected_thumb, expected_no_thumb]
        assert request_parameter.input_files == [
            input_media_thumb.media,
            input_media_thumb.thumb,
            input_media_no_thumb.media,
        ]
コード例 #8
0
def test(url, rotate=False):
    result = web_2_album.get(url)
    suffix = '[source](%s)' % url

    if result.video:
        with open('tmp/video.mp4', 'wb') as f:
            f.write(cached_url.get(result.video, force_cache=True, mode='b'))
        group = [
            InputMediaVideo(open('tmp/video.mp4', 'rb'),
                            caption=cutCaption(result.cap, suffix, 1000),
                            parse_mode='Markdown')
        ]
        return tele.bot.send_media_group(-1001198682178,
                                         group,
                                         timeout=20 * 60)

    imgs = pic_cut.getCutImages(result.imgs, 9)
    if imgs:
        imgs = pic_cut.getCutImages(result.imgs, 9)
        if rotate:
            for img_path in imgs:
                img = Image.open(img_path)
                img = img.rotate(180)
                img.save(img_path)
        group = [InputMediaPhoto(open(imgs[0], 'rb'),
         caption=cutCaption(result.cap, suffix, 1000), parse_mode='Markdown')] + \
         [InputMediaPhoto(open(x, 'rb')) for x in imgs[1:]]
        return tele.bot.send_media_group(-1001198682178,
                                         group,
                                         timeout=20 * 60)

    tele.bot.send_message(-1001198682178,
                          cutCaption(result.cap, suffix, 4000),
                          timeout=20 * 60)
コード例 #9
0
    async def test_edit_message_media_with_thumb(
            self,
            bot,
            chat_id,
            video_file,
            photo_file,
            monkeypatch  # noqa: F811
    ):
        async def make_assertion(method: str,
                                 url: str,
                                 request_data: RequestData = None,
                                 *args,
                                 **kwargs):
            files = request_data.multipart_data
            video_check = files[
                input_video.media.attach_name] == input_video.media.field_tuple
            thumb_check = files[
                input_video.thumb.attach_name] == input_video.thumb.field_tuple
            result = video_check and thumb_check
            raise Exception(
                f"Test was {'successful' if result else 'failing'}")

        monkeypatch.setattr(bot.request, "_request_wrapper", make_assertion)
        input_video = InputMediaVideo(video_file, thumb=photo_file)
        with pytest.raises(Exception, match="Test was successful"):
            await bot.edit_message_media(chat_id=chat_id,
                                         message_id=123,
                                         media=input_video)
コード例 #10
0
 def test_with_local_files(self):
     input_media_video = InputMediaVideo('tests/data/telegram.mp4',
                                         thumb='tests/data/telegram.jpg')
     assert input_media_video.media == (
         Path.cwd() / 'tests/data/telegram.mp4/').as_uri()
     assert input_media_video.thumb == (
         Path.cwd() / 'tests/data/telegram.jpg/').as_uri()
コード例 #11
0
    def test_edit_message_media_with_thumb(
            self,
            bot,
            chat_id,
            video_file,
            photo_file,
            monkeypatch  # noqa: F811
    ):
        def test(*args, **kwargs):
            data = kwargs['fields']
            video_check = data[
                input_video.media.attach] == input_video.media.field_tuple
            thumb_check = data[
                input_video.thumb.attach] == input_video.thumb.field_tuple
            result = video_check and thumb_check
            raise Exception(
                f"Test was {'successful' if result else 'failing'}")

        monkeypatch.setattr('telegram.utils.request.Request._request_wrapper',
                            test)
        input_video = InputMediaVideo(video_file, thumb=photo_file)
        with pytest.raises(Exception, match='Test was successful'):
            bot.edit_message_media(chat_id=chat_id,
                                   message_id=123,
                                   media=input_video)
コード例 #12
0
    async def test_send_media_group_custom_filename(
        self,
        bot,
        chat_id,
        photo_file,  # noqa: F811
        animation_file,  # noqa: F811
        audio_file,  # noqa: F811
        video_file,  # noqa: F811
        monkeypatch,
    ):
        async def make_assertion(url, request_data: RequestData, *args,
                                 **kwargs):
            result = all(
                field_tuple[0] == "custom_filename"
                for field_tuple in request_data.multipart_data.values())
            if result is True:
                raise Exception("Test was successful")

        monkeypatch.setattr(bot.request, "post", make_assertion)

        media = [
            InputMediaAnimation(animation_file, filename="custom_filename"),
            InputMediaAudio(audio_file, filename="custom_filename"),
            InputMediaPhoto(photo_file, filename="custom_filename"),
            InputMediaVideo(video_file, filename="custom_filename"),
        ]

        with pytest.raises(Exception, match="Test was successful"):
            await bot.send_media_group(chat_id, media)
コード例 #13
0
 async def func():
     return await bot.send_media_group(
         chat_id,
         [
             InputMediaVideo(video_file),
             InputMediaPhoto(photo_file),
             InputMediaPhoto(data_file("telegram.jpg").read_bytes()),
         ],
     )
コード例 #14
0
def input_media_video():
    return InputMediaVideo(
        media=TestInputMediaVideo.media,
        caption=TestInputMediaVideo.caption,
        width=TestInputMediaVideo.width,
        height=TestInputMediaVideo.height,
        duration=TestInputMediaVideo.duration,
        parse_mode=TestInputMediaVideo.parse_mode,
        supports_streaming=TestInputMediaVideo.supports_streaming)
コード例 #15
0
 def test_with_video(self, video):  # noqa: F811
     # fixture found in test_video
     input_media_video = InputMediaVideo(video, caption="test 3")
     assert input_media_video.type == self.type
     assert input_media_video.media == video.file_id
     assert input_media_video.width == video.width
     assert input_media_video.height == video.height
     assert input_media_video.duration == video.duration
     assert input_media_video.caption == "test 3"
コード例 #16
0
 def func():
     with open('tests/data/telegram.jpg', 'rb') as file:
         return bot.send_media_group(
             chat_id,
             [
                 InputMediaVideo(video_file),
                 InputMediaPhoto(photo_file),
                 InputMediaPhoto(file.read()),
             ],
         )
コード例 #17
0
def get_input_media(file_id: str, media_type: str):
    from telegram.files import photosize, video, videonote, document, animation, sticker
    from telegram import InputMedia, InputMediaPhoto, InputMediaDocument, InputMediaVideo, InputMediaAnimation, Sticker
    if media_type == f"{photosize.PhotoSize}":
        return InputMediaPhoto(file_id)
    if media_type == f"{video.Video}" or media_type == f"{videonote.VideoNote}":
        return InputMediaVideo(file_id)
    if media_type == f"{document.Document}":
        return InputMediaDocument(file_id)
    if media_type == f"{animation.Animation}":
        return InputMediaAnimation(file_id)
コード例 #18
0
def _get_media(message: TMessage, caption: str):
    if message.animation:
        return InputMediaAnimation(media=message.animation, caption=caption)
    if message.audio:
        return InputMediaAudio(media=message.audio, caption=caption)
    if message.document:
        return InputMediaDocument(media=message.document, caption=caption)
    if message.photo:
        return InputMediaPhoto(media=message.photo[-1], caption=caption)
    if message.video:
        return InputMediaVideo(media=message.video, caption=caption)
コード例 #19
0
def sendVideo(chat, result):
    os.system('mkdir tmp > /dev/null 2>&1')
    with open('tmp/video.mp4', 'wb') as f:
        f.write(cached_url.get(result.video, force_cache=True, mode='b'))
    if os.stat('tmp/video.mp4').st_size > 50 * 1024 * 1024:
        return []
    group = [
        InputMediaVideo(open('tmp/video.mp4', 'rb'),
                        caption=getCap(result, 1000),
                        parse_mode=result.getParseMode())
    ]
    return chat.bot.send_media_group(chat.id, group, timeout=20 * 60)
コード例 #20
0
def input_media_video(class_thumb_file):
    return InputMediaVideo(
        media=TestInputMediaVideo.media,
        caption=TestInputMediaVideo.caption,
        width=TestInputMediaVideo.width,
        height=TestInputMediaVideo.height,
        duration=TestInputMediaVideo.duration,
        parse_mode=TestInputMediaVideo.parse_mode,
        caption_entities=TestInputMediaVideo.caption_entities,
        thumb=class_thumb_file,
        supports_streaming=TestInputMediaVideo.supports_streaming,
    )
コード例 #21
0
    def test_send_media_group_with_thumbs(self, bot, chat_id, video_file, photo_file,  # noqa: F811
                                          monkeypatch):
        def test(*args, **kwargs):
            data = kwargs['fields']
            video_check = data[input_video.media.attach] == input_video.media.field_tuple
            thumb_check = data[input_video.thumb.attach] == input_video.thumb.field_tuple
            result = video_check and thumb_check
            raise(Exception('Test was {}'.format('successful' if result else 'failing')))

        monkeypatch.setattr('telegram.utils.request.Request._request_wrapper', test)
        input_video = InputMediaVideo(video_file, thumb=photo_file)
        with pytest.raises(Exception, match='Test was successful'):
            bot.send_media_group(chat_id, [input_video, input_video])
コード例 #22
0
 def test_from_input_inputmedia_without_attach(self):
     """This case will never happen, but we test it for completeness"""
     input_media = InputMediaVideo(
         data_file("telegram.png").read_bytes(),
         thumb=data_file("telegram.png").read_bytes(),
         parse_mode=None,
     )
     input_media.media.attach_name = None
     input_media.thumb.attach_name = None
     request_parameter = RequestParameter.from_input("key", input_media)
     assert request_parameter.value == {"type": "video"}
     assert request_parameter.input_files == [
         input_media.media, input_media.thumb
     ]
コード例 #23
0
def handle_message_edit(bot, update, last_messages):
    try:
        message = update.edited_message

        try:
            video_mes_id = last_messages[(message.chat.id, message.message_id)]
        except KeyError:
            know_message = False
        else:
            know_message = True

        try:
            request = match_request(message.text)
        except ValueError as e:
            if know_message:
                bot.edit_message_caption(message.chat.id,
                                         video_mes_id,
                                         caption=str(e))
            else:
                message.reply_text(str(e))
            return
        else:
            if not request:
                return

        logger.info("Message: %s, request: %s", message.text, request)

        bot.send_chat_action(message.chat.id, telegram.ChatAction.UPLOAD_VIDEO)

        file_url = get_videofile_url('https://youtu.be/' + request.youtube_id)
        downloaded_file = download_clip(file_url, request.start, request.end)

        if know_message:
            bot.edit_message_media(
                message.chat.id,
                video_mes_id,
                media=InputMediaVideo(
                    downloaded_file,
                    caption=request_to_start_timestamp_url(request)))
        else:
            video_mes = bot.send_video(
                message.chat_id,
                downloaded_file,
                reply_to_message_id=message.message_id,
                caption=request_to_start_timestamp_url(request))

            last_messages[(message.chat.id,
                           message.message_id)] = video_mes.message_id
    except Exception as e:
        logger.exception(e)
コード例 #24
0
    def edit_random_post(self, message: Message, subreddit: str) -> None:
        """
        Edit the current Telegram message with another random Reddit post.

        Parameters
        ----------
        message : Message
            python-telegram-bot's instance of the Telegram message.

        subreddit : str
            Subreddit from which to retrieve the random post.

        """
        msg_is_text = message.caption is None
        post = reddit.get_post(helpers.get_random_post_url(subreddit))
        assert post is not None
        if ((msg_is_text and message.text_markdown_v2 == post.get_msg())
                or message.caption_markdown_v2 == post.get_msg() or
            (not msg_is_text
             and post.get_type() in [ContentType.TEXT, ContentType.YOUTUBE])):
            # if post is the same or message is not text and post is: retry
            raise PostEqualsMessageError()

        args = self.get_args({"message_id": message.message_id})
        try:
            if msg_is_text:
                if post.get_type() == ContentType.YOUTUBE:
                    args["disable_web_page_preview"] = False
                self.bot.editMessageText(post.get_msg(), **args)
            else:
                media: Optional[Media] = None
                media_args = dict(
                    media=post.media.url,  # type: ignore
                    caption=post.get_msg(),
                    parse_mode="MarkdownV2",
                )
                if post.get_type() == ContentType.GIF:
                    media = InputMediaDocument(**media_args)
                elif post.get_type() == ContentType.VIDEO:
                    media = InputMediaVideo(**media_args)
                elif post.get_type() == ContentType.PHOTO:
                    media = InputMediaPhoto(**media_args)
                self.bot.editMessageMedia(media=media, **args)
            return
        except Exception as e:
            raise PostSendError({
                "post_url": post.permalink,
                "media_url": post.media.url
            }  # type: ignore
                                ) from e
コード例 #25
0
 def test_send_media_group_new_files(
         bot,
         chat_id,
         video_file,
         photo_file,  # noqa: F811
         animation_file):  # noqa: F811
     messages = bot.send_media_group(
         chat_id,
         [InputMediaVideo(video_file),
          InputMediaPhoto(photo_file)])
     assert isinstance(messages, list)
     assert len(messages) == 2
     assert all(isinstance(mes, Message) for mes in messages)
     assert all(mes.media_group_id == messages[0].media_group_id
                for mes in messages)
コード例 #26
0
def help_button(update, context):
    query = update.callback_query
    query.answer()
    _, hid = query.data.split("_")
    hid = int(hid)

    keyboard = [[]]
    next_button = InlineKeyboardButton("próximo",
                                       callback_data=f"help_{hid+1}")
    prev_button = InlineKeyboardButton("anterior",
                                       callback_data=f"help_{hid-1}")
    media = None
    if hid == 0:
        caption = (
            "Há três tipos de perguntas no bot, sendo elas:\n\n"
            "▪️ *múltiplas escolhas*\n▪️ *única escolha*\n▪️ *texto livre*.\n\nTodas "
            "as respostas _são editáveis antes da finalização_ do questionário."
        )
        media = InputMediaAnimation(
            "CgACAgEAAxkBAAIDz165k3F3dOyCpA0NzXKTkbk2RT_rAAKfAAPJItBFxyufgHgzykAZBA",
            caption=caption,
            parse_mode="markdown")
        keyboard[0].append(next_button)
    elif hid == 1:
        caption = ("As perguntas podem ser obrigatórias ou opcionais, as "
                   "*obrigatórias estão marcadas com estrela*.")
        media = InputMediaPhoto(
            "AgACAgEAAxkBAAIDjF65gy5cp6uTnlUBypOFFJ-dDw5mAAJRqDEbySLQRQ8xPAq4fpQp371uBgAEAQADAgADeAADe5kCAAEZBA",
            caption=caption,
            parse_mode="markdown")
        keyboard[0].append(prev_button)
        keyboard[0].append(next_button)
    elif hid == 2:
        media = InputMediaVideo(
            "BAACAgEAAxkBAAIDfF65f7no-7Wmzex-mYwXmgR-EGuZAAIpAQACvlPJRVufPM2G1aFZGQQ",
            caption="Vídeo demonstrativo de como utilizar o bot.",
            parse_mode="markdown")
        keyboard[0].append(prev_button)

    if media:
        context.bot.edit_message_media(
            query.message.chat.id,
            query.message.message_id,
            media=media,
            reply_markup=InlineKeyboardMarkup(keyboard),
        )
コード例 #27
0
def __prepare_media_files(op_files):
    media_group = []

    for file in op_files:
        extension = file.split('.')[-1]
        byte_file = open(file, 'rb')

        if extension in IMAGE_EXTENSIONS:
            if extension in IMAGE_EXTENSIONS and os.path.getsize(
                    file) > telegram.constants.MAX_FILESIZE_UPLOAD / 8:
                byte_file = _compress_image(file)

            media_group.append(InputMediaPhoto(media=byte_file))
        elif extension in VIDEO_EXTENSIONS:
            media_group.append(InputMediaVideo(media=byte_file))

    return media_group
コード例 #28
0
        def build_media(parse_mode, med_type):
            kwargs = {}
            if parse_mode != ParseMode.HTML:
                kwargs['parse_mode'] = parse_mode
                kwargs['caption'] = markdown_caption
            else:
                kwargs['caption'] = html_caption

            if med_type == 'animation':
                return InputMediaAnimation(animation, **kwargs)
            if med_type == 'document':
                return InputMediaDocument(document, **kwargs)
            if med_type == 'audio':
                return InputMediaAudio(audio, **kwargs)
            if med_type == 'photo':
                return InputMediaPhoto(photo, **kwargs)
            if med_type == 'video':
                return InputMediaVideo(video, **kwargs)
コード例 #29
0
        def build_media(parse_mode, med_type):
            kwargs = {}
            if parse_mode != ParseMode.HTML:
                kwargs["parse_mode"] = parse_mode
                kwargs["caption"] = markdown_caption
            else:
                kwargs["caption"] = html_caption

            if med_type == "animation":
                return InputMediaAnimation(animation, **kwargs)
            if med_type == "document":
                return InputMediaDocument(document, **kwargs)
            if med_type == "audio":
                return InputMediaAudio(audio, **kwargs)
            if med_type == "photo":
                return InputMediaPhoto(photo, **kwargs)
            if med_type == "video":
                return InputMediaVideo(video, **kwargs)
コード例 #30
0
def link_handle(update, context):
    if update.message is None and update.channel_post is None:
        return
    text = update.message.text or update.channel_post.text

    urls = re.findall(
        'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',
        text)

    if urls:
        logger.info("Got URL(s): " + pprint.pformat(urls))
        for url in urls:
            logger.info("Trying URL: " + url)
            with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                # ydl_results = ydl.download(url=url, download=True)
                try:
                    result = ydl.extract_info(url=url, download=False)
                    new_message = context.bot.send_message(
                        chat_id=update.effective_chat.id,
                        text="Trying to fetch video...",
                        disable_notification=True)
                    result = ydl.extract_info(url=url, download=True)
                    ydl_filename = ydl.prepare_filename(result)
                except youtube_dl.utils.DownloadError as e:
                    if 'new_message' in locals():
                        context.bot.deleteMessage(
                            chat_id=update.effective_chat.id,
                            message_id=new_message.message_id)

            if 'ydl_filename' in locals() and ydl_filename:
                logger.info("Downloaded video: " +
                            pprint.pformat(ydl_filename))
                video = InputMediaVideo(open(ydl_filename, 'rb'))
                caption_text = "Source: " + url
                context.bot.send_video(chat_id=update.effective_chat.id,
                                       video=open(ydl_filename, 'rb'),
                                       supports_streaming=True,
                                       timeout=60,
                                       caption=caption_text)
                context.bot.deleteMessage(chat_id=update.effective_chat.id,
                                          message_id=new_message.message_id)