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
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()
async def func(): return await bot.send_media_group( chat_id, [ InputMediaVideo(video_file), InputMediaPhoto(photo_file), InputMediaPhoto(data_file("telegram.jpg").read_bytes()), ], )
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)
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"
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()), ], )
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)
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)
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)
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, )
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])
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
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 ]
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)
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)
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)
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), )
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
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)
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)
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)
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)
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)
def _download(post, filename): logging.debug(f"Downloading {post}") with tempfile.TemporaryDirectory() as dirname: prefix = '' if post.is_video: prefix = 'video_' elif not isinstance(post, instaloader.Post): prefix = 'display_' url = getattr(post, f'{prefix}url') INSTALOADER.download_pic(f'{dirname}/{filename}', url, datetime.datetime.now()) logging.debug("Post has been downloaded") urlmatch = re.search('\\.[a-z0-9]*\\?', url) file_extension = url[-3:] if urlmatch is None else urlmatch.group( 0)[1:-1] with open(f'{dirname}/{filename}.{file_extension}', 'rb') as f: if post.is_video: return InputMediaVideo(f) else: return InputMediaPhoto(f)
async def test_send_media_group_with_thumbs( self, bot, chat_id, video_file, photo_file, monkeypatch # noqa: F811 ): async def make_assertion(method, url, request_data: RequestData, *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.send_media_group(chat_id, [input_video, input_video])
def test_with_video_file(self, video_file): # noqa: F811 # fixture found in test_video input_media_video = InputMediaVideo(video_file, caption="test 3") assert input_media_video.type == self.type assert isinstance(input_media_video.media, InputFile) assert input_media_video.caption == "test 3"
def func(): return bot.send_media_group( chat_id, [InputMediaVideo(video_file), InputMediaPhoto(photo_file)])
def input_media_video() -> InputMediaVideo: return InputMediaVideo( media=data_file("telegram.mp4").read_bytes(), thumb=data_file("telegram.jpg").read_bytes(), parse_mode=None, )
def process_post(self, post, group): chat_id = group.telegram_username bot = self.bot.bot text = html.escape(post['text']) media_groups = [] photos = [] gifs = [] videos = [] audios = [] if 'attachments' in post: for attachment in post['attachments']: type = attachment['type'] value = attachment[type] if type == 'photo': value = self.get_biggest_photo_size(value) photos.append(value) media_groups.append(InputMediaPhoto(value)) elif type == 'doc' and value['ext'] == 'gif': gifs.append(value['url']) elif type == 'video': video_id = '{}_{}'.format(value['owner_id'], value['id']) video_url = self.vkapi.get_video(video_id) if video_url is not None: videos.append(video_url) media_groups.append(InputMediaVideo(video_url)) elif type == 'audio': audios.append((value['url'], value['artist'] + ' - ' + value['title'])) def send_text(): if text: bot.send_message(chat_id, text, parse_mode='HTML') has_attachments = len(media_groups) + len(gifs) > 0 if not has_attachments: send_text() elif len(media_groups) > 1: send_text() for i in range(0, len(media_groups), 10): bot.send_media_group(chat_id, media_groups[i:i + 10]) for gif in gifs: bot.send_animation(chat_id, gif) else: def send_encoded(attachment, send_specific, send_common): if not text or len(text) < 200: send_specific(chat_id, attachment, caption=text, parse_mode='HTML') else: send_common(chat_id, self.encode_attachment_url(attachment, text), parse_mode='HTML') attachment_count = len(photos) + len(videos) + len(gifs) if attachment_count > 1: send_text() text = None for photo in photos: send_encoded(photo, bot.send_photo, bot.send_message) for video in videos: send_encoded(video, bot.send_video, bot.send_message) for gif in gifs: send_encoded(gif, bot.send_animation, bot.send_message) for audio, caption in audios: bot.send_audio(chat_id, audio, caption=caption, timeout=228)
def test_error_with_file(self, video_file): # fixture found in test_video with pytest.raises(ValueError, match="file_id, url or Video"): InputMediaVideo(video_file)