async def edit_message(m: Message): """ edit any type of pyrogram message using the messages dict. :param m: pyrogram.Message to edit. """ if m.text: messages[m.date] = await messages[m.date].edit(m.text) elif m.caption and m.caption != messages[m.date].caption: messages[m.date] = await messages[m.date].edit_caption(m.caption) elif m.media: caption = {'caption': m.caption + '\n'} if m.caption else {} if m.photo and m.photo != messages[m.date].photo: messages[m.date] = await messages[m.date].edit_media( InputMediaPhoto(m.photo.file_id, m.photo.file_unique_id, **caption)) elif m.video and m.video != messages[m.date].video: messages[m.date] = await messages[m.date].edit_media( InputMediaVideo(m.video.file_id, m.video.file_unique_id, **caption)) elif m.document and m.document != messages[m.date].document: messages[m.date] = await messages[m.date].edit_media( InputMediaDocument(m.document.file_id, m.document.file_unique_id, **caption)) elif m.animation and m.animation != messages[m.date].animation: messages[m.date] = await messages[m.date].edit_media( InputMediaAnimation(m.animation.file_id, m.animation.file_unique_id, **caption)) elif m.audio and m.audio != messages[m.date].audio: messages[m.date] = await messages[m.date].edit_media( InputMediaAudio(m.audio.file_id, m.audio.file_unique_id, **caption))
async def ytdl_download_callback(client: Client, c_q: CallbackQuery): yt_code = c_q.matches[0].group(1) choice_id = c_q.matches[0].group(2) downtype = c_q.matches[0].group(3) if str(choice_id).isdigit(): choice_id = int(choice_id) if choice_id == 0: await c_q.answer("🔄 Processing...", show_alert=False) await c_q.edit_message_reply_markup( reply_markup=(await download_button(yt_code))) return startTime = time() choice_str, disp_str = get_choice_by_id(choice_id, downtype) media_type = "Video" if downtype == "v" else "Audio" callback_continue = f"Downloading {media_type} Please Wait..." callback_continue += f"\n\nFormat Code : {disp_str}" await c_q.answer(callback_continue, show_alert=True) yt_url = BASE_YT_URL + yt_code await c_q.edit_message_text(text=( f"**⬇️ Downloading {media_type} ...**" f"\n\n🔗 <b><a href='{yt_url}'>Link</a></b>\n🆔 <b>Format Code</b> : {disp_str}" ), ) if downtype == "v": k = await _tubeDl(url=yt_url, starttime=startTime, uid=choice_str) else: k = await _mp3Dl(url=yt_url, starttime=startTime, uid=choice_str) if type(k) == list: await c_q.answer(k[1], show_alert=True) return _fpath = "" thumb_pic = None for _path in glob.glob(os.path.join(DOWN_PATH, str(startTime), "*")): if _path.lower().endswith((".jpg", ".png", ".webp")): thumb_pic = _path else: _fpath = _path if not thumb_pic and downtype == "v": thumb_pic = str(await run_in_thread(download)(await get_ytthumb(yt_code))) if downtype == "v": await c_q.edit_message_media(media=(InputMediaVideo( media=str(Path(_fpath)), caption=f"📹 <b><a href = '{yt_url}'>{Path(_fpath).name}</a></b>", thumb=thumb_pic)), ) else: # Audio await c_q.edit_message_media(media=(InputMediaAudio( media=str(Path(_fpath)), caption=f"🎵 <b><a href = '{yt_url}'>{Path(_fpath).name}</a></b>", thumb=thumb_pic)), )
async def yt_dl_video(client, cb): url = cb.matches[0].group(1) audio_or_video = cb.matches[0].group(2) if audio_or_video == "video": file_name, downloaded_thumb, name, dur, u_date, uploader, views = await download_yt( url, as_video=True) else: file_name, downloaded_thumb, name, dur, u_date, uploader, views = await download_yt( url, as_video=False) if not os.path.exists(file_name): await cb.edit_message_text(file_name) return await cb.edit_message_text(f"`Downloaded : {name} | Now Uploading....`") import datetime f_size = humanbytes(os.stat(file_name).st_size) caption = f""" **Title :** `{name}` **Uploader :** `{uploader}` **Views :** `{views}` **Link :** `{url}` **Duration :** `{datetime.timedelta(seconds=dur)}` **File Size :** `{f_size}` """ if audio_or_video == "video": file_ = InputMediaVideo(file_name, thumb=downloaded_thumb, supports_streaming=True, duration=dur, caption=caption) else: file_ = InputMediaAudio(file_name, performer=uploader, title=name, thumb=downloaded_thumb, duration=dur, caption=caption) await cb.edit_message_media(file_) if os.path.exists(file_name): os.remove(file_name)
async def upload_single_file(message, local_file_name, caption_str, from_user, edit_media): await asyncio.sleep(EDIT_SLEEP_TIME_OUT) sent_message = None start_time = time.time() # thumbnail_location = os.path.join(DOWNLOAD_LOCATION, "thumbnails", str(from_user) + ".jpg") LOGGER.info(thumbnail_location) # try: message_for_progress_display = message if not edit_media: message_for_progress_display = await message.reply_text( "starting upload of {}".format( os.path.basename(local_file_name))) if local_file_name.upper().endswith(("MKV", "MP4", "WEBM")): metadata = extractMetadata(createParser(local_file_name)) duration = 0 if metadata.has("duration"): duration = metadata.get('duration').seconds # width = 0 height = 0 thumb_image_path = None if os.path.exists(thumbnail_location): thumb_image_path = await copy_file( thumbnail_location, os.path.dirname(os.path.abspath(local_file_name))) else: thumb_image_path = await take_screen_shot( local_file_name, os.path.dirname(os.path.abspath(local_file_name)), (duration / 2)) # get the correct width, height, and duration for videos greater than 10MB if os.path.exists(thumb_image_path): metadata = extractMetadata(createParser(thumb_image_path)) if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") # resize image # ref: https://t.me/PyrogramChat/44663 # https://stackoverflow.com/a/21669827/4723940 Image.open(thumb_image_path).convert("RGB").save( thumb_image_path) img = Image.open(thumb_image_path) # https://stackoverflow.com/a/37631799/4723940 img.resize((320, height)) img.save(thumb_image_path, "JPEG") # https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#create-thumbnails # thumb = None if thumb_image_path is not None and os.path.isfile( thumb_image_path): thumb = thumb_image_path # send video if edit_media and message.photo: sent_message = await message.edit_media( media=InputMediaVideo(media=local_file_name, thumb=thumb, caption=caption_str, parse_mode="html", width=width, height=height, duration=duration, supports_streaming=True) # quote=True, ) else: sent_message = await message.reply_video( video=local_file_name, # quote=True, caption=caption_str, parse_mode="html", duration=duration, width=width, height=height, thumb=thumb, supports_streaming=True, disable_notification=True, # reply_to_message_id=message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=("trying to upload", message_for_progress_display, start_time)) if thumb is not None: os.remove(thumb) elif local_file_name.upper().endswith( ("MP3", "M4A", "M4B", "FLAC", "WAV")): metadata = extractMetadata(createParser(local_file_name)) duration = 0 title = "" artist = "" if metadata.has("duration"): duration = metadata.get('duration').seconds if metadata.has("title"): title = metadata.get("title") if metadata.has("artist"): artist = metadata.get("artist") thumb_image_path = None if os.path.isfile(thumbnail_location): thumb_image_path = await copy_file( thumbnail_location, os.path.dirname(os.path.abspath(local_file_name))) thumb = None if thumb_image_path is not None and os.path.isfile( thumb_image_path): thumb = thumb_image_path # send audio if edit_media and message.photo: sent_message = await message.edit_media( media=InputMediaAudio(media=local_file_name, thumb=thumb, caption=caption_str, parse_mode="html", duration=duration, performer=artist, title=title) # quote=True, ) else: sent_message = await message.reply_audio( audio=local_file_name, # quote=True, caption=caption_str, parse_mode="html", duration=duration, performer=artist, title=title, thumb=thumb, disable_notification=True, # reply_to_message_id=message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=("trying to upload", message_for_progress_display, start_time)) if thumb is not None: os.remove(thumb) else: thumb_image_path = None if os.path.isfile(thumbnail_location): thumb_image_path = await copy_file( thumbnail_location, os.path.dirname(os.path.abspath(local_file_name))) # if a file, don't upload "thumb" # this "diff" is a major derp -_- 😔😭😭 thumb = None if thumb_image_path is not None and os.path.isfile( thumb_image_path): thumb = thumb_image_path # # send document if edit_media and message.photo: sent_message = await message.edit_media( media=InputMediaDocument(media=local_file_name, thumb=thumb, caption=caption_str, parse_mode="html") # quote=True, ) else: sent_message = await message.reply_document( document=local_file_name, # quote=True, thumb=thumb, caption=caption_str, parse_mode="html", disable_notification=True, # reply_to_message_id=message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=("trying to upload", message_for_progress_display, start_time)) if thumb is not None: os.remove(thumb) except Exception as e: await message_for_progress_display.edit_text("**FAILED**\n" + str(e)) else: if message.message_id != message_for_progress_display.message_id: await message_for_progress_display.delete() # os.remove(local_file_name) return sent_message
async def upload_single_file(path, message, force_edit,database=None,thumb_image_path=None,user_msg=None): if database is not None: if database.get_cancel_status(message.chat_id,message.id): # add os remove here return None if not os.path.exists(path): return None file_name = os.path.basename(path) caption_str = "" caption_str += "<code>" caption_str += file_name caption_str += "</code>" if user_msg is None: user_msg = await message.get_reply_message() force_docs = get_val("FORCE_DOCUMENTS") if user_msg is not None: force_docs = user_db.get_var("FORCE_DOCUMENTS",user_msg.sender_id) # Avoid Flood in Express await asyncio.sleep(int(get_val("EDIT_SLEEP_SECS"))+5) metadata = extractMetadata(createParser(path)) if metadata is not None: # handle none for unknown metadata = metadata.exportDictionary() try: mime = metadata.get("Common").get("MIME type") except: mime = metadata.get("Metadata").get("MIME type") ftype = mime.split("/")[0] ftype = ftype.lower().strip() else: ftype = "unknown" thonmsg = message message = await message.client.pyro.get_messages(message.chat_id, message.id) tout = get_val("EDIT_SLEEP_SECS") sent_message = None start_time = time.time() # if user_msg is not None: dis_thumb = user_db.get_var("DISABLE_THUMBNAIL", user_msg.sender_id) if dis_thumb is False or dis_thumb is None: thumb_image_path = user_db.get_thumbnail(user_msg.sender_id) if not thumb_image_path: thumb_image_path = None # try: message_for_progress_display = message if not force_edit: data = "upcancel {} {} {}".format(message.chat.id,message.message_id,user_msg.sender_id) markup = InlineKeyboardMarkup([[InlineKeyboardButton("Cancel Upload", callback_data=data.encode("UTF-8"))]]) message_for_progress_display = await message.reply_text( "📤 **Starting upload of** `{}`".format(os.path.basename(path)), reply_markup=markup ) if ftype == "video" and not force_docs: metadata = extractMetadata(createParser(path)) duration = 0 if metadata.has("duration"): duration = metadata.get('duration').seconds # width = 0 height = 0 if thumb_image_path is None: thumb_image_path = await thumb_manage.get_thumbnail(path) # get the correct width, height, and duration for videos greater than 10MB thumb = None if thumb_image_path is not None and os.path.isfile(thumb_image_path): thumb = thumb_image_path # send video if force_edit and message.photo: sent_message = await message.edit_media( media=InputMediaVideo( media=path, thumb=thumb, parse_mode="html", width=width, height=height, duration=duration, supports_streaming=True, caption=caption_str ) # quote=True, ) else: sent_message = await message.reply_video( video=path, # quote=True, parse_mode="html", duration=duration, width=width, height=height, thumb=thumb, caption=caption_str, supports_streaming=True, disable_notification=True, # reply_to_message_id=message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=( f"💠 Uploading {os.path.basename(path)}", message_for_progress_display, start_time, tout, thonmsg.client.pyro, message, database, markup ) ) if thumb is not None: os.remove(thumb) elif ftype == "audio" and not force_docs: metadata = extractMetadata(createParser(path)) duration = 0 title = "" artist = "" if metadata.has("duration"): duration = metadata.get('duration').seconds if metadata.has("title"): title = metadata.get("title") if metadata.has("artist"): artist = metadata.get("artist") thumb = None if thumb_image_path is not None and os.path.isfile(thumb_image_path): thumb = thumb_image_path # send audio if force_edit and message.photo: sent_message = await message.edit_media( media=InputMediaAudio( media=path, thumb=thumb, parse_mode="html", duration=duration, performer=artist, title=title, caption=caption_str ) # quote=True, ) else: sent_message = await message.reply_audio( audio=path, # quote=True, parse_mode="html", duration=duration, performer=artist, title=title, caption=caption_str, thumb=thumb, disable_notification=True, # reply_to_message_id=message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=( f"💠 Uploading {os.path.basename(path)}", message_for_progress_display, start_time, tout, thonmsg.client.pyro, message, database, markup ) ) if thumb is not None: os.remove(thumb) else: # if a file, don't upload "thumb" # this "diff" is a major derp -_- 😔😭😭 thumb = None if thumb_image_path is not None and os.path.isfile(thumb_image_path): thumb = thumb_image_path # # send document if force_edit and message.photo: sent_message = await message.edit_media( media=InputMediaDocument( media=path, caption=caption_str, thumb=thumb, parse_mode="html" ) # quote=True, ) else: sent_message = await message.reply_document( document=path, # quote=True, thumb=thumb, parse_mode="html", disable_notification=True, # reply_to_message_id=message.reply_to_message.message_id, progress=progress_for_pyrogram, caption=caption_str, progress_args=( f"💠 Uploading {os.path.basename(path)}", message_for_progress_display, start_time, tout, thonmsg.client.pyro, message, database, markup ) ) if thumb is not None: os.remove(thumb) except Exception as e: if str(e).find("cancel") != -1: torlog.info("Canceled an upload lol") try: await message_for_progress_display.edit(f"Failed to upload {e}") except:pass else: try: await message_for_progress_display.edit(f"Failed to upload {e}") except:pass torlog.exception("IN Pyro upload") else: if message.message_id != message_for_progress_display.message_id: await message_for_progress_display.delete() #os.remove(path) if sent_message is None: return None sent_message = await thonmsg.client.get_messages(sent_message.chat.id, ids=sent_message.message_id) return sent_message
async def note_send(client: Client, message: Message): await message.edit("<code>Loading...</code>") if len(message.text.split()) >= 2: find_note = await db.find_one( {"NAME": f"{message.text.split(' ', maxsplit=1)[1]}"}) if find_note: if "MEDIA_GROUP_ID" in find_note: messages_grouped = await client.get_media_group( int(find_note["CHAT_ID"]), int(find_note["MESSAGE_ID"])) media_grouped_list = [] for _ in messages_grouped: if _.photo: if _.caption: media_grouped_list.append( InputMediaPhoto(_.photo.file_id, _.caption.markdown)) else: media_grouped_list.append( InputMediaPhoto(_.photo.file_id)) elif _.video: if _.caption: media_grouped_list.append( InputMediaVideo(_.video.file_id, _.video.thumbs[0].file_id, _.caption.markdown)) else: media_grouped_list.append( InputMediaVideo(_.video.file_id, _.video.thumbs[0].file_id)) elif _.audio: if _.caption: media_grouped_list.append( InputMediaAudio(_.audio.file_id, _.caption.markdown)) else: media_grouped_list.append( InputMediaAudio(_.audio.file_id)) elif _.document: if _.caption: media_grouped_list.append( InputMediaDocument( _.document.file_id, _.document.thumbs[0].file_id, _.caption.markdown)) else: media_grouped_list.append( InputMediaDocument( _.document.file_id, _.document.thumbs[0].file_id)) if message.reply_to_message: await client.send_media_group( message.chat.id, media_grouped_list, reply_to_message_id=message.reply_to_message.message_id ) else: await client.send_media_group(message.chat.id, media_grouped_list) await message.delete() else: if message.reply_to_message: await client.copy_message( message.chat.id, int(find_note["CHAT_ID"]), int(find_note["MESSAGE_ID"]), reply_to_message_id=message.reply_to_message.message_id ) else: await client.copy_message(message.chat.id, int(find_note["CHAT_ID"]), int(find_note["MESSAGE_ID"])) await message.delete() else: await message.edit("There is no such note") else: await message.edit("Example: <code>.note name note</code>")
async def upload_single_file( message, local_file_name, caption_str, from_user, client, edit_media, yt_thumb ): await asyncio.sleep(EDIT_SLEEP_TIME_OUT) local_file_name = str(Path(local_file_name).resolve()) sent_message = None start_time = time.time() # thumbnail_location = os.path.join( DOWNLOAD_LOCATION, "thumbnails", str(from_user) + ".jpg" ) # LOGGER.info(thumbnail_location) if UPLOAD_AS_DOC.upper() == "TRUE": # todo: this code will be removed in future thumb = None thumb_image_path = None if os.path.exists(thumbnail_location): thumb_image_path = await copy_file( thumbnail_location, os.path.dirname( os.path.abspath(local_file_name)) ) thumb = thumb_image_path message_for_progress_display = message if not edit_media: message_for_progress_display = await message.reply_text( "starting upload of {}".format( os.path.basename(local_file_name)) ) prog = Progress(from_user, client, message_for_progress_display) sent_message = await message.reply_document( document=local_file_name, thumb=thumb, caption=caption_str, parse_mode="html", disable_notification=True, progress=prog.progress_for_pyrogram, progress_args=( f"{os.path.basename(local_file_name)}", start_time, ), ) if edit_media: await message_for_progress_display.delete() if message.message_id != message_for_progress_display.message_id: try: await message_for_progress_display.delete() except FloodWait as gf: time.sleep(gf.x) except Exception as rr: LOGGER.warning(str(rr)) os.remove(local_file_name) if thumb is not None: os.remove(thumb) else: try: message_for_progress_display = message if not edit_media: message_for_progress_display = await message.reply_text( "starting upload of {}".format( os.path.basename(local_file_name)) ) prog = Progress(from_user, client, message_for_progress_display) if local_file_name.upper().endswith(("MKV", "MP4", "WEBM", "M4V", "3GP")): duration = 0 try: metadata = extractMetadata(createParser(local_file_name)) if metadata.has("duration"): duration = metadata.get("duration").seconds except Exception as g_e: LOGGER.info(g_e) width = 0 height = 0 thumb_image_path = None if os.path.exists(thumbnail_location): thumb_image_path = await copy_file( thumbnail_location, os.path.dirname(os.path.abspath(local_file_name)), ) else: if not yt_thumb: thumb_image_path = await take_screen_shot( local_file_name, os.path.dirname(os.path.abspath(local_file_name)), (duration / 2), ) else: req = requests.get(yt_thumb) thumb_image_path = os.path.join( os.path.dirname(os.path.abspath(local_file_name)), str(time.time()) + ".jpg", ) with open(thumb_image_path, "wb") as thum: thum.write(req.content) img = Image.open(thumb_image_path).convert("RGB") img.save(thumb_image_path, format="jpeg") # get the correct width, height, and duration for videos greater than 10MB if os.path.exists(thumb_image_path): metadata = extractMetadata( createParser(thumb_image_path)) if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") # ref: https://t.me/PyrogramChat/44663 # https://stackoverflow.com/a/21669827/4723940 Image.open(thumb_image_path).convert("RGB").save( thumb_image_path ) img = Image.open(thumb_image_path) # https://stackoverflow.com/a/37631799/4723940 img.resize((320, height)) img.save(thumb_image_path, "JPEG") # https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#create-thumbnails # thumb = None if thumb_image_path is not None and os.path.isfile(thumb_image_path): thumb = thumb_image_path # send video if edit_media and message.photo: await asyncio.sleep(EDIT_SLEEP_TIME_OUT) sent_message = await message.edit_media( media=InputMediaVideo( media=local_file_name, thumb=thumb, caption=caption_str, parse_mode="html", width=width, height=height, duration=duration, supports_streaming=True, ) # quote=True, ) else: sent_message = await message.reply_video( video=local_file_name, caption=caption_str, parse_mode="html", duration=duration, width=width, height=height, thumb=thumb, supports_streaming=True, disable_notification=True, progress=prog.progress_for_pyrogram, progress_args=( f"{os.path.basename(local_file_name)}", start_time, ), ) if thumb is not None: os.remove(thumb) elif local_file_name.upper().endswith(("MP3", "M4A", "M4B", "FLAC", "WAV")): metadata = extractMetadata(createParser(local_file_name)) duration = 0 title = "" artist = "" if metadata.has("duration"): duration = metadata.get("duration").seconds if metadata.has("title"): title = metadata.get("title") if metadata.has("artist"): artist = metadata.get("artist") thumb_image_path = None if os.path.isfile(thumbnail_location): thumb_image_path = await copy_file( thumbnail_location, os.path.dirname(os.path.abspath(local_file_name)), ) thumb = None if thumb_image_path is not None and os.path.isfile(thumb_image_path): thumb = thumb_image_path # send audio if edit_media and message.photo: await asyncio.sleep(EDIT_SLEEP_TIME_OUT) sent_message = await message.edit_media( media=InputMediaAudio( media=local_file_name, thumb=thumb, caption=caption_str, parse_mode="html", duration=duration, performer=artist, title=title, ) ) else: sent_message = await message.reply_audio( audio=local_file_name, caption=caption_str, parse_mode="html", duration=duration, performer=artist, title=title, thumb=thumb, disable_notification=True, progress=prog.progress_for_pyrogram, progress_args=( f"{os.path.basename(local_file_name)}", start_time, ), ) if thumb is not None: os.remove(thumb) else: thumb_image_path = None if os.path.isfile(thumbnail_location): thumb_image_path = await copy_file( thumbnail_location, os.path.dirname(os.path.abspath(local_file_name)), ) # if a file, don't upload "thumb" # this "diff" is a major derp -_- 😔😭😭 thumb = None if thumb_image_path is not None and os.path.isfile(thumb_image_path): thumb = thumb_image_path # # send document if edit_media and message.photo: sent_message = await message.edit_media( media=InputMediaDocument( media=local_file_name, thumb=thumb, caption=caption_str, parse_mode="html", ) ) else: sent_message = await message.reply_document( document=local_file_name, thumb=thumb, caption=caption_str, parse_mode="html", disable_notification=True, progress=prog.progress_for_pyrogram, progress_args=( f"{os.path.basename(local_file_name)}", start_time, ), ) if thumb is not None: os.remove(thumb) except MessageNotModified as oY: LOGGER.info(oY) except FloodWait as g: LOGGER.info(g) time.sleep(g.x) except Exception as e: LOGGER.info(e) await message_for_progress_display.edit_text("**FAILED**\n" + str(e)) else: if message.message_id != message_for_progress_display.message_id: try: if sent_message is not None: await message_for_progress_display.delete() except FloodWait as gf: time.sleep(gf.x) except Exception as rr: LOGGER.warning(str(rr)) await asyncio.sleep(5) os.remove(local_file_name) return sent_message
async def upload_single_file(path, message, force_edit,database=None,thumb_image_path=None,user_msg=None): if database is not None: if database.get_cancel_status(message.chat_id,message.id): # add os remove here return None if not os.path.exists(path): return None force_docs = get_val("FORCE_DOCUMENTS") if user_msg is not None: force_docs = user_db.get_var("FORCE_DOCUMENTS",user_msg.sender_id) thonmsg = message message = await message.client.pyro.get_messages(message.chat_id, message.id) tout = get_val("EDIT_SLEEP_SECS") sent_message = None start_time = time.time() # if user_msg is not None: dis_thumb = user_db.get_var("DISABLE_THUMBNAIL", user_msg.sender_id) if dis_thumb is False or dis_thumb is None: thumb_image_path = user_db.get_thumbnail(user_msg.sender_id) if not thumb_image_path: thumb_image_path = None # try: message_for_progress_display = message if not force_edit: data = "upcancel {} {} {}".format(message.chat.id,message.message_id,user_msg.sender_id) markup = InlineKeyboardMarkup([[InlineKeyboardButton("Cancel Upload", callback_data=data.encode("UTF-8"))]]) message_for_progress_display = await message.reply_text( "starting upload of {}".format(os.path.basename(path)), reply_markup=markup ) if str(path).upper().endswith(("MKV", "MP4", "WEBM")) and not force_docs: metadata = extractMetadata(createParser(path)) duration = 0 if metadata.has("duration"): duration = metadata.get('duration').seconds # width = 0 height = 0 if thumb_image_path is None: thumb_image_path = await thumb_manage.get_thumbnail(path) # get the correct width, height, and duration for videos greater than 10MB thumb = None if thumb_image_path is not None and os.path.isfile(thumb_image_path): thumb = thumb_image_path # send video if force_edit and message.photo: sent_message = await message.edit_media( media=InputMediaVideo( media=path, thumb=thumb, parse_mode="html", width=width, height=height, duration=duration, supports_streaming=True ) # quote=True, ) else: sent_message = await message.reply_video( video=path, # quote=True, parse_mode="html", duration=duration, width=width, height=height, thumb=thumb, supports_streaming=True, disable_notification=True, # reply_to_message_id=message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=( "trying to upload", message_for_progress_display, start_time, tout, thonmsg.client.pyro, message, database, markup ) ) if thumb is not None: os.remove(thumb) elif str(path).upper().endswith(("MP3", "M4A", "M4B", "FLAC", "WAV")) and not force_docs: metadata = extractMetadata(createParser(path)) duration = 0 title = "" artist = "" if metadata.has("duration"): duration = metadata.get('duration').seconds if metadata.has("title"): title = metadata.get("title") if metadata.has("artist"): artist = metadata.get("artist") thumb = None if thumb_image_path is not None and os.path.isfile(thumb_image_path): thumb = thumb_image_path # send audio if force_edit and message.photo: sent_message = await message.edit_media( media=InputMediaAudio( media=path, thumb=thumb, parse_mode="html", duration=duration, performer=artist, title=title ) # quote=True, ) else: sent_message = await message.reply_audio( audio=path, # quote=True, parse_mode="html", duration=duration, performer=artist, title=title, thumb=thumb, disable_notification=True, # reply_to_message_id=message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=( "trying to upload", message_for_progress_display, start_time, tout, thonmsg.client.pyro, message, database, markup ) ) if thumb is not None: os.remove(thumb) else: # if a file, don't upload "thumb" # this "diff" is a major derp -_- 😔😭😭 thumb = None if thumb_image_path is not None and os.path.isfile(thumb_image_path): thumb = thumb_image_path # # send document if force_edit and message.photo: sent_message = await message.edit_media( media=InputMediaDocument( media=path, thumb=thumb, parse_mode="html" ) # quote=True, ) else: sent_message = await message.reply_document( document=path, # quote=True, thumb=thumb, parse_mode="html", disable_notification=True, # reply_to_message_id=message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=( "trying to upload", message_for_progress_display, start_time, tout, thonmsg.client.pyro, message, database, markup ) ) if thumb is not None: os.remove(thumb) except Exception as e: if str(e).find("cancel") != -1: torlog.info("cancled an upload lol") await message_for_progress_display.delete() else: torlog.info(traceback.format_exc()) else: if message.message_id != message_for_progress_display.message_id: await message_for_progress_display.delete() #os.remove(path) if sent_message is None: return None sent_message = await thonmsg.client.get_messages(sent_message.chat.id, ids=sent_message.message_id) return sent_message
async def catch_youtube_dldata(bot, update): thumb_image_path = os.getcwd() + "/" + "thumbnails" + "/" + str( update.from_user.id) + ".jpg" yt_thumb_image_path = os.getcwd() + "/" + "YouTubeThumb" + "/" + str( update.from_user.id) + ".jpg" if os.path.exists(thumb_image_path): thumb_image = thumb_image_path else: thumb_image = yt_thumb_image_path file_name = str(Config.PRE_FILE_TXT) cb_data = update.data # Callback Data Check (for Youtube formats) if cb_data.startswith(("video", "audio", "docaudio", "docvideo")): yturl = cb_data.split("||")[-1] format_id = cb_data.split("||")[-2] if not cb_data.startswith(("video", "audio", "docaudio", "docvideo")): print("no data found") raise ContinuePropagation new_filext = "%(title)s.%(ext)s" filext = file_name + new_filext saved_file_path = os.getcwd() + "/" + "downloads" + "/" + str( update.from_user.id) + "/" if not os.path.isdir(saved_file_path): os.makedirs(saved_file_path) dl_folder = [f for f in os.listdir(saved_file_path)] for f in dl_folder: try: os.remove(os.path.join(saved_file_path, f)) except IndexError: pass await update.edit_message_text(text=Translation.DOWNLOAD_START) filepath = os.path.join(saved_file_path, filext) audio_command = [ "youtube-dl", "-c", "--prefer-ffmpeg", "--extract-audio", "--audio-format", "mp3", "--audio-quality", format_id, "-o", filepath, yturl, ] video_command = [ "youtube-dl", "-c", "--embed-subs", "-f", f"{format_id}+bestaudio", "-o", filepath, "--hls-prefer-ffmpeg", yturl ] loop = asyncio.get_event_loop() med = None if cb_data.startswith("audio"): filename = await downloadaudiocli(audio_command) med = InputMediaAudio(media=filename, caption=os.path.basename(filename), title=os.path.basename(filename), thumb=thumb_image) if cb_data.startswith("video"): description = Translation.CUSTOM_CAPTION_VIDEO filename = await downloadvideocli(video_command) dur = round(duration(filename)) med = InputMediaVideo(media=filename, duration=dur, caption=description, thumb=thumb_image, supports_streaming=True) if cb_data.startswith("docaudio"): filename = await downloadaudiocli(audio_command) med = InputMediaDocument(media=filename, caption=os.path.basename(filename), thumb=thumb_image) if cb_data.startswith("docvideo"): description = Translation.CUSTOM_CAPTION_DOC filename = await downloadvideocli(video_command) dur = round(duration(filename)) med = InputMediaDocument(media=filename, caption=description, thumb=thumb_image) if med: loop.create_task(send_file(bot, update, med)) else: print("med not found") ######################################### CB Data query for Bot Settings ############################################### else: # Callback Data Check (for bot settings) if cb_data.startswith( ("close", "view_thumb", "del_thumb", "conf_thumb", "start_help", "settings", "rename_doc", "convert_video", "d_copy", "v_copy", "clear_med")): if "close" in cb_data: await close_button(bot, update) elif "view_thumb" in cb_data: await view_thumbnail(bot, update) elif "del_thumb" in cb_data: await delete_thumbnail(bot, update) elif "conf_thumb" in cb_data: await del_thumb_confirm(bot, update) elif "start_help" in cb_data: await start_bot(bot, update) elif "settings" in cb_data: await bot_settings(bot, update) elif "rename_doc" in cb_data: await rename_file(bot, update) elif "convert_video" in cb_data: await convert_to_video(bot, update) elif "d_copy" in cb_data: await convert_to_doc_copy(bot, update) elif "v_copy" in cb_data: await convert_to_video_copy(bot, update) elif "clear_med" in cb_data: await clear_media(bot, update)
async def youtube_dl_call_back(bot, update, cb_data): LOGGER.info(update) # youtube_dl extractors tg_send_type, youtube_dl_format, youtube_dl_ext = cb_data.split("|") # current_user_id = update.message.reply_to_message.from_user.id current_touched_user_id = update.from_user.id if current_user_id != current_touched_user_id: return False, None user_working_dir = os.path.join(TMP_DOWNLOAD_DIRECTORY, str(current_user_id)) # create download directory, if not exist if not os.path.isdir(user_working_dir): await bot.delete_messages( chat_id=update.message.chat.id, message_ids=[ update.message.message_id, update.message.reply_to_message.message_id, ], revoke=True) return save_ytdl_json_path = user_working_dir + \ "/" + str("ytdleech") + ".json" try: with open(save_ytdl_json_path, "r", encoding="utf8") as f_d: response_json = json.load(f_d) os.remove(save_ytdl_json_path) except FileNotFoundError: await bot.delete_messages( chat_id=update.message.chat.id, message_ids=[ update.message.message_id, update.message.reply_to_message.message_id, ], revoke=True) return False # response_json = response_json[0] # TODO: temporary limitations LOGGER.info(response_json) # youtube_dl_url = response_json.get("webpage_url") LOGGER.info(youtube_dl_url) # custom_file_name = "%(title)s.%(ext)s" # https://superuser.com/a/994060 LOGGER.info(custom_file_name) # await update.message.edit_caption(caption="trying to download") description = "@PyroGramBot" if "fulltitle" in response_json: description = response_json["fulltitle"][0:1021] # escape Markdown and special characters # tmp_directory_for_each_user = os.path.join(TMP_DOWNLOAD_DIRECTORY, str(update.from_user.id)) if not os.path.isdir(tmp_directory_for_each_user): os.makedirs(tmp_directory_for_each_user) download_directory = tmp_directory_for_each_user download_directory = os.path.join(tmp_directory_for_each_user, custom_file_name) command_to_exec = [] if tg_send_type == "audio": command_to_exec = [ "youtube-dl", "-c", "--prefer-ffmpeg", "--extract-audio", "--add-metadata", "--embed-thumbnail", "--audio-format", youtube_dl_ext, "--audio-quality", youtube_dl_format, youtube_dl_url, "-o", download_directory, # "--external-downloader", "aria2c" ] else: # command_to_exec = ["youtube-dl", "-f", youtube_dl_format, "--hls-prefer-ffmpeg", "--recode-video", "mp4", "-k", youtube_dl_url, "-o", download_directory] minus_f_format = youtube_dl_format if "youtu" in youtube_dl_url: for for_mat in response_json["formats"]: format_id = for_mat.get("format_id") if format_id == youtube_dl_format: acodec = for_mat.get("acodec") vcodec = for_mat.get("vcodec") if acodec == "none" or vcodec == "none": minus_f_format = youtube_dl_format + "+bestaudio" break command_to_exec = [ "youtube-dl", "-c", # "--embed-subs", "-f", minus_f_format, "--hls-prefer-ffmpeg", youtube_dl_url, "-o", download_directory, # "--external-downloader", "aria2c" ] # command_to_exec.append("--no-warnings") # command_to_exec.append("--quiet") command_to_exec.append("--restrict-filenames") # if "hotstar" in youtube_dl_url: command_to_exec.append("--geo-bypass-country") command_to_exec.append("IN") LOGGER.info(command_to_exec) start = datetime.now() t_response, e_response = await run_command(command_to_exec) # LOGGER.info(e_response) # LOGGER.info(t_response) ad_string_to_replace = "please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see https://yt-dl.org/update on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output." if e_response and ad_string_to_replace in e_response: error_message = e_response.replace(ad_string_to_replace, "") await update.message.edit_caption(caption=error_message) return False, None if t_response: # LOGGER.info(t_response) # os.remove(save_ytdl_json_path) end_one = datetime.now() time_taken_for_download = (end_one - start).seconds dir_contents = os.listdir(tmp_directory_for_each_user) # dir_contents.sort() await update.message.edit_caption( f"found {len(dir_contents)} files" f"\n Download took {time_taken_for_download} seconds" "\n Trying to Upload, now ...") LOGGER.info(dir_contents) # for single_file in dir_contents: local_file_name = os.path.join(tmp_directory_for_each_user, single_file) thumb = await is_thumb_image_exists(local_file_name) # caption_str = os.path.basename(local_file_name) metadata = extractMetadata(createParser(local_file_name)) duration = 0 artist = "" title = "" if metadata.has("duration"): duration = metadata.get("duration").seconds if metadata.has("title"): title = metadata.get("title") if metadata.has("artist"): artist = metadata.get("artist") width, height = 0, 0 if thumb is not None: metadata = extractMetadata(createParser(thumb)) if metadata.has("height"): height = metadata.get("height") if metadata.has("width"): height = metadata.get("width") if local_file_name.upper().endswith(("MKV", "MP4", "WEBM")): await update.message.edit_media( media=InputMediaVideo(media=local_file_name, thumb=thumb, caption=description, parse_mode="html", width=width, height=height, duration=duration, supports_streaming=True)) elif local_file_name.upper().endswith( ("MP3", "M4A", "M4B", "FLAC", "WAV")): await update.message.edit_media(media=InputMediaAudio( media=local_file_name, thumb=thumb, caption=description, parse_mode="html", duration=duration, performer=artist, title=title) # quote=True, ) else: await update.message.edit_media(media=InputMediaDocument( media=local_file_name, thumb=thumb, caption=description, parse_mode="html") # quote=True, ) # try: shutil.rmtree(tmp_directory_for_each_user) except: pass
def generate_music(self): if "audio" in self.attachments_types: log.info("[AP] Извлечение аудио...") try: tracks = self.audio_session.get_post_audio( self.raw_post["owner_id"], self.raw_post["id"]) except Exception as error: log.error("Ошибка получения аудиозаписей: {0}", error) else: for track in tracks: name = (sub(r"[^a-zA-Z '#0-9.а-яА-Я()-]", "", track["artist"] + " - " + track["title"])[:MAX_FILENAME_LENGTH - 16] + ".mp3") if ".m3u8" in track["url"]: log.warning( "Файлом аудиозаписи является m3u8 плейлист.") file = name streamlink_args = [ "streamlink", "--output", name.replace(".mp3", ".ts"), track["url"], "best" ] ffmpeg_args = [ "ffmpeg", "-i", name.replace(".mp3", ".ts"), "-b:a", "320k", name ] result = start_process(streamlink_args) if result > 0: log.critical( "При запуске команды {} произошла ошибка.", " ".join(streamlink_args)) continue result = start_process(ffmpeg_args) if result > 0: log.critical( "При запуске команды {} произошла ошибка", " ".join(ffmpeg_args)) continue else: try: file = download(track["url"], out=name) except (urllib.error.URLError, IndexError): log.exception( "[AP] Не удалось скачать аудиозапись. Пропускаем ее..." ) continue track_cover = download(track["track_covers"][-1] ) if track["track_covers"] else None log.debug("Adding tags in track") result = add_audio_tags( file, title=track["title"], artist=track["artist"], track_cover=track_cover, ) if result: log.debug("Track {} ready for sending", name) self.tracks.append( InputMediaAudio( name, track_cover, duration=track["duration"], performer=track["artist"], title=track["title"], ))
async def catch_youtube_dldata(c, q): cb_data = q.data # caption = q.message.caption user_id = q.from_user.id # Callback Data Assigning media_type, send_as, format_id, av_codec, video_id = cb_data.split("|") LOGGER.info(cb_data) filext = "%(title)s.%(ext)s" userdir = os.path.join(os.getcwd(), Config.DOWNLOAD_DIR, str(user_id), video_id) if not os.path.isdir(userdir): os.makedirs(userdir) await q.edit_message_reply_markup( InlineKeyboardMarkup( [[InlineKeyboardButton("Downloading...", callback_data="down")]])) filepath = os.path.join(userdir, filext) # await q.edit_message_reply_markup([[InlineKeyboardButton("Processing..")]]) fetch_media, caption = await yt_download(video_id, media_type, av_codec, format_id, filepath) if not fetch_media: await q.message.reply_text(caption) shutil.rmtree(userdir, ignore_errors=True) await q.message.delete() return else: LOGGER.info(os.listdir(userdir)) for content in os.listdir(userdir): if ".jpg" not in content: file_name = os.path.join(userdir, content) thumb = os.path.join(userdir, video_id + ".jpg") width = height = 0 if os.path.isfile(thumb): width, height = width_and_height(thumb) else: thumb = None duration = media_duration(file_name) if send_as == "Audio": med = InputMediaAudio( media=file_name, thumb=thumb, duration=duration, caption=caption, title=caption, ) elif send_as == "Video": med = InputMediaVideo( media=file_name, thumb=thumb, width=width, height=height, duration=duration, caption=caption, supports_streaming=True, ) else: med = InputMediaDocument( media=file_name, thumb=thumb, caption=caption, ) if med: loop = asyncio.get_event_loop() loop.create_task(send_file(c, q, med, video_id, userdir)) else: LOGGER.info("Media not found")
async def ytdl_download_callback(c_q: CallbackQuery): yt_code = c_q.matches[0].group(1) choice_id = c_q.matches[0].group(2) downtype = c_q.matches[0].group(3) if str(choice_id).isdigit(): choice_id = int(choice_id) if choice_id == 0: await c_q.answer("🔄 Processing...", show_alert=False) await c_q.edit_message_reply_markup( reply_markup=(await download_button(yt_code))) return startTime = time() choice_str, disp_str = get_choice_by_id(choice_id, downtype) media_type = "Video" if downtype == "v" else "Audio" callback_continue = f"Downloading {media_type} Please Wait..." callback_continue += f"\n\nFormat Code : {disp_str}" await c_q.answer(callback_continue, show_alert=True) upload_msg = await userge.send_message(Config.LOG_CHANNEL_ID, "Uploading...") yt_url = BASE_YT_URL + yt_code await c_q.edit_message_text(text=( f"**⬇️ Downloading {media_type} ...**" f"\n\n🔗 [<b>Link</b>]({yt_url})\n🆔 <b>Format Code</b> : {disp_str}" ), ) if downtype == "v": retcode = await _tubeDl(url=yt_url, starttime=startTime, uid=choice_str) else: retcode = await _mp3Dl(url=yt_url, starttime=startTime, uid=choice_str) if retcode != 0: return await upload_msg.edit(str(retcode)) _fpath = "" thumb_pic = None for _path in glob.glob( os.path.join(Config.DOWN_PATH, str(startTime), "*")): if _path.lower().endswith((".jpg", ".png", ".webp")): thumb_pic = _path else: _fpath = _path if not _fpath: await upload_msg.err("nothing found !") return if not thumb_pic and downtype == "v": thumb_pic = str(download(await get_ytthumb(yt_code))) uploaded_media = await upload( upload_msg, path=Path(_fpath), callback=c_q, custom_thumb=thumb_pic, log=False, ) refresh_vid = await userge.bot.get_messages(Config.LOG_CHANNEL_ID, uploaded_media.message_id) f_id = get_file_id(refresh_vid) if downtype == "v": await c_q.edit_message_media(media=(InputMediaVideo( media=f_id, caption=f"📹 <b>[{uploaded_media.caption}]({yt_url})</b>", )), ) else: # Audio await c_q.edit_message_media(media=(InputMediaAudio( media=f_id, caption=f"🎵 <b>[{uploaded_media.caption}]({yt_url})</b>", )), )
async def upload_single_file(message, local_file_name, caption_str, from_user, edit_media): await asyncio.sleep(EDIT_SLEEP_TIME_OUT) sent_message = None start_time = time.time() # thumbnail_location = os.path.join(DOWNLOAD_LOCATION, "thumbnails", str(from_user) + ".jpg") LOGGER.info(thumbnail_location) # try: message_for_progress_display = message if not edit_media: message_for_progress_display = await message.reply_text( "starting upload of {}".format( os.path.basename(local_file_name))) if local_file_name.upper().endswith( ("WEBM", "MP4")) and not local_file_name.upper().startswith( ("KDG")): metadata = extractMetadata(createParser(local_file_name)) duration = 0 if metadata.has("duration"): duration = metadata.get('duration').seconds # width = 0 height = 0 thumb_image_path = None if os.path.exists(thumbnail_location): thumb_image_path = await copy_file( thumbnail_location, os.path.dirname(os.path.abspath(local_file_name))) else: thumb_image_path = None thumb = None if thumb_image_path is not None and os.path.isfile( thumb_image_path): thumb = thumb_image_path # send video if edit_media and message.photo: sent_message = await message.edit_media( media=InputMediaVideo(media=local_file_name, thumb=thumb, caption=caption_str, parse_mode="html", width=width, height=height, duration=duration, supports_streaming=True) # quote=True, ) else: sent_message = await message.reply_video( video=local_file_name, # quote=True, caption=caption_str, parse_mode="html", duration=duration, width=width, height=height, thumb=thumb, supports_streaming=True, disable_notification=True, # reply_to_message_id=message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=("trying to upload", message_for_progress_display, start_time)) if thumb is not None: os.remove(thumb) elif local_file_name.upper().endswith( ("MP3", "M4A", "M4B", "FLAC", "WAV")): metadata = extractMetadata(createParser(local_file_name)) duration = 0 title = "" artist = "" if metadata.has("duration"): duration = metadata.get('duration').seconds if metadata.has("title"): title = metadata.get("title") if metadata.has("artist"): artist = metadata.get("artist") thumb_image_path = None if os.path.isfile(thumbnail_location): thumb_image_path = await copy_file( thumbnail_location, os.path.dirname(os.path.abspath(local_file_name))) thumb = None if thumb_image_path is not None and os.path.isfile( thumb_image_path): thumb = thumb_image_path # send audio if edit_media and message.photo: sent_message = await message.edit_media( media=InputMediaAudio(media=local_file_name, thumb=thumb, caption=caption_str, parse_mode="html", duration=duration, performer=artist, title=title) # quote=True, ) else: sent_message = await message.reply_audio( audio=local_file_name, # quote=True, caption=caption_str, parse_mode="html", duration=duration, performer=artist, title=title, thumb=thumb, disable_notification=True, # reply_to_message_id=message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=("trying to upload", message_for_progress_display, start_time)) if thumb is not None: os.remove(thumb) else: base_file_name = os.path.basename(local_file_name) base_new_name = os.path.splitext(base_file_name)[0] extension_new_name = os.path.splitext(base_file_name)[1] thumb_image_path = None if os.path.isfile(thumbnail_location): thumb_image_path = await copy_file( thumbnail_location, os.path.dirname(os.path.abspath(local_file_name))) # if a file, don't upload "thumb" # this "diff" is a major derp -_- 😔😭😭 thumb = None if thumb_image_path is not None and os.path.isfile( thumb_image_path): thumb = thumb_image_path # # send document if edit_media and message.photo: sent_message = await message.edit_media( media=InputMediaDocument(media=local_file_name, thumb=thumb, caption=caption_str, parse_mode="html") # quote=True, ) else: sent_message = await message.reply_document( document=local_file_name, # quote=True, thumb=thumb, caption=caption_str, parse_mode="html", disable_notification=True, # reply_to_message_id=message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=("trying to upload", message_for_progress_display, start_time)) if thumb is not None: os.remove(thumb) except Exception as e: await message_for_progress_display.edit_text("**FAILED**\n" + str(e)) else: if message.message_id != message_for_progress_display.message_id: await message_for_progress_display.delete() os.remove(local_file_name) return sent_message
async def upload_single_file(message, local_file_name, caption_str, from_user, edit_media): base_file_name = os.path.basename(local_file_name) if len(base_file_name) > 64 and base_file_name.lower().startswith( ("@dramaost", "[d&o]")): status_message = await message.reply_text("Renaming start") h = base_file_name c_h = local_file_name out_dir = os.path.dirname(os.path.abspath(local_file_name)) g = f"opus opus2.0 aac aac2.0 ddp5.1 ddp2.0 ddp2 h264 h.264 x264 10bit 2017 2018 2019 2020 2021 nf webdl web-dl webrip webhd web-hd web-rip".split( " ") c = 0 f = h.lower() f = re.sub("_", '.', f) f = re.sub("web.dl", 'webdl', f) if f[:3] == "d&o": f = re.sub("d&o", '[d&o]', f) for i in g: if len(f) <= 64: break if re.search(i, f): f = re.sub("." + i, '', f) if len(f) > 64: f = re.sub("@dramaost.", '', f) p = f.split('.') s = '.'.join(i.capitalize() for i in p) s = re.sub("Nf", 'NF', s) s = re.sub("Web-dl", 'WEB-DL', s) s = re.sub("Webdl", 'WEB-DL', s) s = re.sub("Webrip", 'WEBRip', s) s = re.sub("Sh3lby", 'SH3LBY', s) s = re.sub("sh3lby", 'SH3LBY', s) s = re.sub("ost", 'OST', s) s = re.sub("Mkv", 'mkv', s) s = re.sub("d&o", 'D&O', s) s = re.sub("D&o", 'D&O', s) s = re.sub("S01e", 'S01E', s) s = re.sub("S02e", 'S02E', s) s = re.sub("S03e", 'S03E', s) s = re.sub("S04e", 'S04E', s) s = re.sub("X265", 'x265', s) s = re.sub("X264", 'x264', s) out_file_name = os.path.join(out_dir, s) os.rename(local_file_name, out_file_name) local_file_name = out_file_name await status_message.edit( f"Old Name - <code>{c_h}</code>\n\nNew Name - <code>{local_file_name}</code>" ) elif not base_file_name.lower().startswith( ("kdg")) and re.search('_', base_file_name.lower()): await message.reply_text( f"<code>{local_file_name}</code>\n\nfile name contain underscore please rename it" ) else: await asyncio.sleep(EDIT_SLEEP_TIME_OUT) sent_message = None start_time = time.time() # thumbnail_location = os.path.join(DOWNLOAD_LOCATION, "thumbnails", str(from_user) + ".jpg") LOGGER.info(thumbnail_location) # try: message_for_progress_display = message if not edit_media: message_for_progress_display = await message.reply_text( "starting upload of {}".format( os.path.basename(local_file_name))) if local_file_name.upper().endswith( ("WEBM", "MP4")) and not local_file_name.upper().startswith( ("KDG")): metadata = extractMetadata(createParser(local_file_name)) duration = 0 if metadata.has("duration"): duration = metadata.get('duration').seconds # width = 0 height = 0 thumb_image_path = None if os.path.exists(thumbnail_location): thumb_image_path = await copy_file( thumbnail_location, os.path.dirname(os.path.abspath(local_file_name))) else: thumb_image_path = await take_screen_shot( local_file_name, os.path.dirname(os.path.abspath(local_file_name)), (duration / 2)) # get the correct width, height, and duration for videos greater than 10MB if os.path.exists(thumb_image_path): metadata = extractMetadata( createParser(thumb_image_path)) if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") # resize image # ref: https://t.me/PyrogramChat/44663 # https://stackoverflow.com/a/21669827/4723940 Image.open(thumb_image_path).convert("RGB").save( thumb_image_path) img = Image.open(thumb_image_path) # https://stackoverflow.com/a/37631799/4723940 img.resize((320, height)) img.save(thumb_image_path, "JPEG") # https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#create-thumbnails # thumb = None if thumb_image_path is not None and os.path.isfile( thumb_image_path): thumb = thumb_image_path # send video if edit_media and message.photo: sent_message = await message.edit_media( media=InputMediaVideo(media=local_file_name, thumb=thumb, caption=caption_str, parse_mode="html", width=width, height=height, duration=duration, supports_streaming=True) # quote=True, ) else: sent_message = await message.reply_video( video=local_file_name, # quote=True, caption=caption_str, parse_mode="html", duration=duration, width=width, height=height, thumb=thumb, supports_streaming=True, disable_notification=True, # reply_to_message_id=message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=("trying to upload", message_for_progress_display, start_time)) if thumb is not None: os.remove(thumb) elif local_file_name.upper().endswith( ("MP3", "M4A", "M4B", "FLAC", "WAV")): metadata = extractMetadata(createParser(local_file_name)) duration = 0 title = "" artist = "" if metadata.has("duration"): duration = metadata.get('duration').seconds if metadata.has("title"): title = metadata.get("title") if metadata.has("artist"): artist = metadata.get("artist") thumb_image_path = None if os.path.isfile(thumbnail_location): thumb_image_path = await copy_file( thumbnail_location, os.path.dirname(os.path.abspath(local_file_name))) thumb = None if thumb_image_path is not None and os.path.isfile( thumb_image_path): thumb = thumb_image_path # send audio if edit_media and message.photo: sent_message = await message.edit_media( media=InputMediaAudio(media=local_file_name, thumb=thumb, caption=caption_str, parse_mode="html", duration=duration, performer=artist, title=title) # quote=True, ) else: sent_message = await message.reply_audio( audio=local_file_name, # quote=True, caption=caption_str, parse_mode="html", duration=duration, performer=artist, title=title, thumb=thumb, disable_notification=True, # reply_to_message_id=message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=("trying to upload", message_for_progress_display, start_time)) if thumb is not None: os.remove(thumb) else: base_file_name = os.path.basename(local_file_name) base_new_name = os.path.splitext(base_file_name)[0] extension_new_name = os.path.splitext(base_file_name)[1] thumb_image_path = None if os.path.isfile(thumbnail_location): thumb_image_path = await copy_file( thumbnail_location, os.path.dirname(os.path.abspath(local_file_name))) # if a file, don't upload "thumb" # this "diff" is a major derp -_- 😔😭😭 thumb = None if thumb_image_path is not None and os.path.isfile( thumb_image_path): thumb = thumb_image_path # # send document if edit_media and message.photo: sent_message = await message.edit_media( media=InputMediaDocument(media=local_file_name, thumb=thumb, caption=caption_str, parse_mode="html") # quote=True, ) elif base_file_name.lower().startswith(("@dramaost", "[d&o]")): for l, s in zip(name_ids, chan_ids): h = l.lower() b = base_file_name.lower() if re.search(h, b): m4 = f"<b>Join: {s}</b>" caption_str = re.sub(".mkv", f".mkv</code>\n\n{m4}", caption_str) break sent_message = await message.reply_document( document=local_file_name, # quote=True, thumb=thumb, caption=caption_str, parse_mode="html", disable_notification=True, # reply_to_message_id=message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=("trying to upload", message_for_progress_display, start_time)) else: sent_message = await message.reply_document( document=local_file_name, # quote=True, thumb=thumb, caption=caption_str, parse_mode="html", disable_notification=True, # reply_to_message_id=message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=("trying to upload", message_for_progress_display, start_time)) if thumb is not None: os.remove(thumb) except Exception as e: await message_for_progress_display.edit_text("**FAILED**\n" + str(e)) else: if message.message_id != message_for_progress_display.message_id: await message_for_progress_display.delete() os.remove(local_file_name) return sent_message