def get_video_date(fname): try: parser = createParser(fname) metadata = extractMetadata(parser) v = metadata.getItem('creation_date', 0) except: return None if v is None: return None else: return str(v.text).replace('-', ':')
def extended_info(self): parser = createParser(self.get_path()) if parser is None: return [] try: metadata = extractMetadata(parser) except Exception: metadata = None if metadata is None: return [] info = map( lambda x: {"description": x.description, "values": [val.text for val in x.values]}, filter(lambda y: y.values, metadata._Metadata__data.values()), ) return Response(self, info=info)
def get_meta(filestream): metadata = {} try: filestream.seek(0) stream = InputIOStream(filestream, None, tags=[]) parser = guessParser(stream) if not parser: return metadata tags = extractMetadata(parser).exportPlaintext(human=False, line_prefix='') for text in tags: try: json.dumps(text) key, value = text.split(':', maxsplit=1) key, value = key.strip(), value.strip() if key and value: metadata.update({key: value}) except Exception as ex: logger.exception(ex) except Exception as ex: logger.exception(ex) return metadata return metadata
async def _(event): if event.fwd_from: return mone = await event.edit("Processing ...") extracted = Config.TMP_DOWNLOAD_DIRECTORY + "extracted/" thumb_image_path = Config.TMP_DOWNLOAD_DIRECTORY + "/thumb_image.jpg" if not os.path.isdir(extracted): os.makedirs(extracted) if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY): os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY) if event.reply_to_msg_id: start = datetime.now() reply_message = await event.get_reply_message() try: c_time = time.time() downloaded_file_name = await borg.download_media( reply_message, Config.TMP_DOWNLOAD_DIRECTORY, progress_callback=lambda d, t: asyncio.get_event_loop(). create_task(progress(d, t, mone, c_time, "trying to download")) ) except Exception as e: # pylint:disable=C0103,W0703 await mone.edit(str(e)) else: end = datetime.now() ms = (end - start).seconds await mone.edit("Stored the zip to `{}` in {} seconds.".format( downloaded_file_name, ms)) with zipfile.ZipFile(downloaded_file_name, 'r') as zip_ref: zip_ref.extractall(extracted) filename = sorted(get_lst_of_files(extracted, [])) #filename = filename + "/" await event.edit("Unzipping now") # r=root, d=directories, f = files for single_file in filename: if os.path.exists(single_file): # https://stackoverflow.com/a/678242/4723940 caption_rts = os.path.basename(single_file) force_document = False supports_streaming = True document_attributes = [] if single_file.endswith((".mp4", ".mp3", ".flac", ".webm")): metadata = extractMetadata(createParser(single_file)) duration = 0 width = 0 height = 0 if metadata.has("duration"): duration = metadata.get('duration').seconds 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") document_attributes = [ DocumentAttributeVideo(duration=duration, w=width, h=height, round_message=False, supports_streaming=True) ] try: await borg.send_file( event.chat_id, single_file, caption=f"UnZipped `{caption_rts}`", force_document=force_document, supports_streaming=supports_streaming, allow_cache=False, reply_to=event.message.id, attributes=document_attributes, # progress_callback=lambda d, t: asyncio.get_event_loop().create_task( # progress(d, t, event, c_time, "trying to upload") # ) ) except Exception as e: await borg.send_message(event.chat_id, "{} caused `{}`".format( caption_rts, str(e)), reply_to=event.message.id) # some media were having some issues continue os.remove(single_file) os.remove(downloaded_file_name)
async def youtube_dl_call_back(bot, update): cb_data = update.data # youtube_dl extractors tg_send_type, youtube_dl_format, youtube_dl_ext = cb_data.split("|") thumb_image_path = Config.DOWNLOAD_LOCATION + \ "/" + str(update.from_user.id) + ".jpg" save_ytdl_json_path = Config.DOWNLOAD_LOCATION + \ "/" + str(update.from_user.id) + ".json" try: with open(save_ytdl_json_path, "r", encoding="utf8") as f: response_json = json.load(f) except (FileNotFoundError) as e: await bot.delete_messages( chat_id=update.message.chat.id, message_ids=update.message.message_id, revoke=True ) return False youtube_dl_url = update.message.reply_to_message.text custom_file_name = str(response_json.get("title")) + \ "_" + youtube_dl_format + "." + youtube_dl_ext youtube_dl_username = None youtube_dl_password = None if "|" in youtube_dl_url: url_parts = youtube_dl_url.split("|") if len(url_parts) == 2: youtube_dl_url = url_parts[0] custom_file_name = url_parts[1] elif len(url_parts) == 4: youtube_dl_url = url_parts[0] custom_file_name = url_parts[1] youtube_dl_username = url_parts[2] youtube_dl_password = url_parts[3] else: for entity in update.message.reply_to_message.entities: if entity.type == "text_link": youtube_dl_url = entity.url elif entity.type == "url": o = entity.offset l = entity.length youtube_dl_url = youtube_dl_url[o:o + l] if youtube_dl_url is not None: youtube_dl_url = youtube_dl_url.strip() if custom_file_name is not None: custom_file_name = custom_file_name.strip() # https://stackoverflow.com/a/761825/4723940 if youtube_dl_username is not None: youtube_dl_username = youtube_dl_username.strip() if youtube_dl_password is not None: youtube_dl_password = youtube_dl_password.strip() logger.info(youtube_dl_url) logger.info(custom_file_name) else: for entity in update.message.reply_to_message.entities: if entity.type == "text_link": youtube_dl_url = entity.url elif entity.type == "url": o = entity.offset l = entity.length youtube_dl_url = youtube_dl_url[o:o + l] await bot.edit_message_text( text=Translation.DOWNLOAD_START, chat_id=update.message.chat.id, message_id=update.message.message_id ) description = Translation.CUSTOM_CAPTION_UL_FILE if "fulltitle" in response_json: description = response_json["fulltitle"][0:1021] # escape Markdown and special characters tmp_directory_for_each_user = Config.DOWNLOAD_LOCATION + "/" + 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 + "/" + custom_file_name command_to_exec = [] if tg_send_type == "audio": command_to_exec = [ "youtube-dl", "-c", "--max-filesize", str(Config.TG_MAX_FILE_SIZE), "--prefer-ffmpeg", "--extract-audio", "--audio-format", youtube_dl_ext, "--audio-quality", youtube_dl_format, youtube_dl_url, "-o", download_directory ] 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: minus_f_format = youtube_dl_format + "+bestaudio" command_to_exec = [ "youtube-dl", "-c", "--max-filesize", str(Config.TG_MAX_FILE_SIZE), "--embed-subs", "-f", minus_f_format, "--hls-prefer-ffmpeg", youtube_dl_url, "-o", download_directory ] if Config.HTTP_PROXY != "": command_to_exec.append("--proxy") command_to_exec.append(Config.HTTP_PROXY) if youtube_dl_username is not None: command_to_exec.append("--username") command_to_exec.append(youtube_dl_username) if youtube_dl_password is not None: command_to_exec.append("--password") command_to_exec.append(youtube_dl_password) command_to_exec.append("--no-warnings") # command_to_exec.append("--quiet") logger.info(command_to_exec) start = datetime.now() process = await asyncio.create_subprocess_exec( *command_to_exec, # stdout must a pipe to be accessible as process.stdout stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) # Wait for the subprocess to finish stdout, stderr = await process.communicate() e_response = stderr.decode().strip() t_response = stdout.decode().strip() 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 bot.edit_message_text( chat_id=update.message.chat.id, message_id=update.message.message_id, text=error_message ) return False 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 file_size = Config.TG_MAX_FILE_SIZE + 1 try: file_size = os.stat(download_directory).st_size except FileNotFoundError as exc: download_directory = os.path.splitext(download_directory)[0] + "." + "mkv" # https://stackoverflow.com/a/678242/4723940 file_size = os.stat(download_directory).st_size if file_size > Config.TG_MAX_FILE_SIZE: await bot.edit_message_text( chat_id=update.message.chat.id, text=Translation.RCHD_TG_API_LIMIT.format(time_taken_for_download, humanbytes(file_size)), message_id=update.message.message_id ) else: is_w_f = False images = await generate_screen_shots( download_directory, tmp_directory_for_each_user, is_w_f, Config.DEF_WATER_MARK_FILE, 300, 9 ) logger.info(images) await bot.edit_message_text( text=Translation.UPLOAD_START, chat_id=update.message.chat.id, message_id=update.message.message_id ) # get the correct width, height, and duration for videos greater than 10MB # ref: message from @BotSupport width = 0 height = 0 duration = 0 if tg_send_type != "file": metadata = extractMetadata(createParser(download_directory)) if metadata is not None: if metadata.has("duration"): duration = metadata.get('duration').seconds # get the correct width, height, and duration for videos greater than 10MB if os.path.exists(thumb_image_path): width = 0 height = 0 metadata = extractMetadata(createParser(thumb_image_path)) if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") if tg_send_type == "vm": height = width # 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.thumbnail((90, 90)) if tg_send_type == "file": img.resize((320, height)) else: img.resize((90, height)) img.save(thumb_image_path, "JPEG") # https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#create-thumbnails else: thumb_image_path = None start_time = time.time() # try to upload file if tg_send_type == "audio": await bot.send_audio( chat_id=update.message.chat.id, audio=download_directory, caption=description, parse_mode="HTML", duration=duration, # performer=response_json["uploader"], # title=response_json["title"], # reply_markup=reply_markup, thumb=thumb_image_path, reply_to_message_id=update.message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=( Translation.UPLOAD_START, update.message, start_time ) ) elif tg_send_type == "file": await bot.send_document( chat_id=update.message.chat.id, document=download_directory, thumb=thumb_image_path, caption=description, parse_mode="HTML", # reply_markup=reply_markup, reply_to_message_id=update.message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=( Translation.UPLOAD_START, update.message, start_time ) ) elif tg_send_type == "vm": await bot.send_video_note( chat_id=update.message.chat.id, video_note=download_directory, duration=duration, length=width, thumb=thumb_image_path, reply_to_message_id=update.message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=( Translation.UPLOAD_START, update.message, start_time ) ) elif tg_send_type == "video": await bot.send_video( chat_id=update.message.chat.id, video=download_directory, caption=description, parse_mode="HTML", duration=duration, width=width, height=height, supports_streaming=True, # reply_markup=reply_markup, thumb=thumb_image_path, reply_to_message_id=update.message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=( Translation.UPLOAD_START, update.message, start_time ) ) else: logger.info("Did this happen? :\\") end_two = datetime.now() time_taken_for_upload = (end_two - end_one).seconds # media_album_p = [] if images is not None: i = 0 caption = "𝚂𝙲𝚁𝙴𝙴𝙽𝚂𝙷𝙾𝚃𝚂" if is_w_f: caption = "/upgrade to Plan D to remove the watermark\n© @AnyDLBot" for image in images: if os.path.exists(image): if i == 0: media_album_p.append( pyrogram.InputMediaPhoto( media=image, caption=caption, parse_mode="html" ) ) else: media_album_p.append( pyrogram.InputMediaPhoto( media=image ) ) i = i + 1 await bot.send_media_group( chat_id=update.message.chat.id, disable_notification=True, reply_to_message_id=update.message.message_id, media=media_album_p ) # try: shutil.rmtree(tmp_directory_for_each_user) os.remove(thumb_image_path) except: pass await bot.edit_message_text( text=Translation.AFTER_SUCCESSFUL_UPLOAD_MSG_WITH_TS.format(time_taken_for_download, time_taken_for_upload), chat_id=update.message.chat.id, message_id=update.message.message_id, disable_web_page_preview=True )
async def _(e): if not e.text[0].isalpha() and e.text[0] not in ("/", "#", "@", "!"): if e.fwd_from: return await e.edit("Processing ...") type_of_upload = e.pattern_match.group(1) supports_streaming = False round_message = False spam_big_messages = False if type_of_upload == "stream": supports_streaming = True if type_of_upload == "vn": round_message = True if type_of_upload == "all": spam_big_messages = True input_str = e.pattern_match.group(2) thumb = None file_name = None if "|" in input_str: file_name, thumb = input_str.split("|") file_name = file_name.strip() thumb = thumb.strip() else: file_name = input_str thumb_path = "a_random_f_file_name" + ".jpg" thumb = get_video_thumb(file_name, output=thumb_path) if os.path.exists(file_name): start = datetime.now() metadata = extractMetadata(createParser(file_name)) duration = 0 width = 0 height = 0 if metadata.has("duration"): duration = metadata.get("duration").seconds if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") try: if supports_streaming: await e.client.send_file( e.chat_id, file_name, thumb=thumb, caption=input_str, force_document=False, allow_cache=False, reply_to=e.message.id, attributes=[ DocumentAttributeVideo( duration=duration, w=width, h=height, round_message=False, supports_streaming=True, ) ], progress_callback=progress, ) elif round_message: await e.client.send_file( e.chat_id, file_name, thumb=thumb, allow_cache=False, reply_to=e.message.id, video_note=True, attributes=[ DocumentAttributeVideo( duration=0, w=1, h=1, round_message=True, supports_streaming=True, ) ], progress_callback=progress, ) elif spam_big_messages: await e.edit("TBD: Not (yet) Implemented") return end = datetime.now() ms = (end - start).seconds os.remove(thumb) await e.edit("Uploaded in {} seconds.".format(ms)) except FileNotFoundError as e: await e.edit(str(e)) else: await e.edit("404: File Not Found")
async def uploadir(udir_event): """ For .uploadir command, allows you to upload everything from a folder in the server""" input_str = udir_event.pattern_match.group(1) if os.path.exists(input_str): await udir_event.edit("Processing ...") lst_of_files = [] for r, d, f in os.walk(input_str): for file in f: lst_of_files.append(os.path.join(r, file)) for file in d: lst_of_files.append(os.path.join(r, file)) LOGS.info(lst_of_files) uploaded = 0 await udir_event.edit( "Found {} files. Uploading will start soon. Please wait!".format( len(lst_of_files))) for single_file in lst_of_files: if os.path.exists(single_file): # https://stackoverflow.com/a/678242/4723940 caption_rts = os.path.basename(single_file) c_time = time.time() if not caption_rts.lower().endswith(".mp4"): await udir_event.client.send_file( udir_event.chat_id, single_file, caption=caption_rts, force_document=False, allow_cache=False, reply_to=udir_event.message.id, progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task( progress(d, t, udir_event, c_time, "[UPLOAD]", single_file))) else: thumb_image = os.path.join(input_str, "thumb.jpg") c_time = time.time() metadata = extractMetadata(createParser(single_file)) duration = 0 width = 0 height = 0 if metadata.has("duration"): duration = metadata.get("duration").seconds if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") await udir_event.client.send_file( udir_event.chat_id, single_file, caption=caption_rts, thumb=thumb_image, force_document=False, allow_cache=False, reply_to=udir_event.message.id, attributes=[ DocumentAttributeVideo( duration=duration, w=width, h=height, round_message=False, supports_streaming=True, ) ], progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task( progress(d, t, udir_event, c_time, "[UPLOAD]", single_file))) os.remove(single_file) uploaded = uploaded + 1 await udir_event.edit( "Uploaded {} files successfully !!".format(uploaded)) else: await udir_event.edit("404: Directory Not Found")
async def ddl_call_back(bot, update): logger.info(update) cb_data = update.data # youtube_dl extractors tg_send_type, youtube_dl_format, youtube_dl_ext = cb_data.split("=") thumb_image_path = Config.DOWNLOAD_LOCATION + \ "/" + str(update.from_user.id) + ".jpg" youtube_dl_url = update.message.reply_to_message.text custom_file_name = os.path.basename(youtube_dl_url) if "|" in youtube_dl_url: url_parts = youtube_dl_url.split("|") if len(url_parts) == 2: youtube_dl_url = url_parts[0] custom_file_name = url_parts[1] else: for entity in update.message.reply_to_message.entities: if entity.type == "text_link": youtube_dl_url = entity.url elif entity.type == "url": o = entity.offset l = entity.length youtube_dl_url = youtube_dl_url[o:o + l] if youtube_dl_url is not None: youtube_dl_url = youtube_dl_url.strip() if custom_file_name is not None: custom_file_name = custom_file_name.strip() # https://stackoverflow.com/a/761825/4723940 logger.info(youtube_dl_url) logger.info(custom_file_name) else: for entity in update.message.reply_to_message.entities: if entity.type == "text_link": youtube_dl_url = entity.url elif entity.type == "url": o = entity.offset l = entity.length youtube_dl_url = youtube_dl_url[o:o + l] description = Translation.CUSTOM_CAPTION_UL_FILE start = datetime.now() await bot.edit_message_text( text=Translation.DOWNLOAD_START, chat_id=update.message.chat.id, message_id=update.message.message_id ) tmp_directory_for_each_user = Config.DOWNLOAD_LOCATION + "/" + 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 + "/" + custom_file_name command_to_exec = [] async with aiohttp.ClientSession() as session: c_time = time.time() try: await download_coroutine( bot, session, youtube_dl_url, download_directory, update.message.chat.id, update.message.message_id, c_time ) except asyncio.TimeOutError: await bot.edit_message_text( text=Translation.SLOW_URL_DECED, chat_id=update.message.chat.id, message_id=update.message.message_id ) return False if os.path.exists(download_directory): end_one = datetime.now() await bot.edit_message_text( text=Translation.UPLOAD_START, chat_id=update.message.chat.id, message_id=update.message.message_id ) file_size = Config.TG_MAX_FILE_SIZE + 1 try: file_size = os.stat(download_directory).st_size except FileNotFoundError as exc: download_directory = os.path.splitext(download_directory)[0] + "." + "mkv" # https://stackoverflow.com/a/678242/4723940 file_size = os.stat(download_directory).st_size if file_size > Config.TG_MAX_FILE_SIZE: await bot.edit_message_text( chat_id=update.message.chat.id, text=Translation.RCHD_TG_API_LIMIT, message_id=update.message.message_id ) else: # get the correct width, height, and duration for videos greater than 10MB # ref: message from @BotSupport width = 0 height = 0 duration = 0 if tg_send_type != "file": metadata = extractMetadata(createParser(download_directory)) if metadata is not None: if metadata.has("duration"): duration = metadata.get('duration').seconds # get the correct width, height, and duration for videos greater than 10MB if os.path.exists(thumb_image_path): width = 0 height = 0 metadata = extractMetadata(createParser(thumb_image_path)) if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") if tg_send_type == "vm": height = width # 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.thumbnail((90, 90)) if tg_send_type == "file": img.resize((320, height)) else: img.resize((90, height)) img.save(thumb_image_path, "JPEG") # https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#create-thumbnails else: thumb_image_path = None start_time = time.time() # try to upload file if tg_send_type == "audio": await bot.send_audio( chat_id=update.message.chat.id, audio=download_directory, caption=description, duration=duration, # performer=response_json["uploader"], # title=response_json["title"], # reply_markup=reply_markup, thumb=thumb_image_path, reply_to_message_id=update.message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=( Translation.UPLOAD_START, update.message, start_time ) ) elif tg_send_type == "file": await bot.send_document( chat_id=update.message.chat.id, document=download_directory, thumb=thumb_image_path, caption=description, # reply_markup=reply_markup, reply_to_message_id=update.message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=( Translation.UPLOAD_START, update.message, start_time ) ) elif tg_send_type == "vm": await bot.send_video_note( chat_id=update.message.chat.id, video_note=download_directory, duration=duration, length=width, thumb=thumb_image_path, reply_to_message_id=update.message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=( Translation.UPLOAD_START, update.message, start_time ) ) elif tg_send_type == "video": await bot.send_video( chat_id=update.message.chat.id, video=download_directory, caption=description, duration=duration, width=width, height=height, supports_streaming=True, # reply_markup=reply_markup, thumb=thumb_image_path, reply_to_message_id=update.message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=( Translation.UPLOAD_START, update.message, start_time ) ) else: logger.info("Did this happen? :\\") end_two = datetime.now() try: os.remove(download_directory) os.remove(thumb_image_path) except: pass time_taken_for_download = (end_one - start).seconds time_taken_for_upload = (end_two - end_one).seconds await bot.edit_message_text( text=Translation.AFTER_SUCCESSFUL_UPLOAD_MSG_WITH_TS.format(time_taken_for_download, time_taken_for_upload), chat_id=update.message.chat.id, message_id=update.message.message_id, disable_web_page_preview=True ) else: await bot.edit_message_text( text=Translation.NO_VOID_FORMAT_FOUND.format("Incorrect Link"), chat_id=update.message.chat.id, message_id=update.message.message_id, disable_web_page_preview=True )
async def _(event): reply_to_id = event.message.id if event.reply_to_msg_id: reply_to_id = event.reply_to_msg_id reply = await event.get_reply_message() if event.pattern_match.group(1): query = event.pattern_match.group(1) await event.edit("`Wait..! I am finding your videosong..`") elif reply.message: query = reply.message await event.edit("`Wait..! I am finding your videosong..`") else: await event.edit("`What I am Supposed to find?`") return getmusicvideo(query) l = glob.glob(("*.mp4")) + glob.glob(("*.mkv")) + glob.glob(("*.webm")) if l: await event.edit("`Yeah..! i found something..`") else: await event.edit(f"Sorry..! i can't find anything with `{query}`") loa = l[0] metadata = extractMetadata(createParser(loa)) duration = 0 width = 0 height = 0 if metadata.has("duration"): duration = metadata.get("duration").seconds if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") await event.edit("`Uploading video.. Please wait..`") os.system("cp *mp4 thumb.mp4") os.system("ffmpeg -i thumb.mp4 -vframes 1 -an -s 480x360 -ss 5 thumb.jpg") thumb_image = "thumb.jpg" c_time = time.time() await event.client.send_file( event.chat_id, loa, force_document=False, thumb=thumb_image, allow_cache=False, caption=query, supports_streaming=True, reply_to=reply_to_id, attributes=[ DocumentAttributeVideo( duration=duration, w=width, h=height, round_message=False, supports_streaming=True, ) ], progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress(d, t, event, c_time, "[UPLOAD]", loa)), ) await event.delete() os.remove(thumb_image) os.system("rm -rf *.mkv") os.system("rm -rf *.mp4") os.system("rm -rf *.webm")
async def download_video(v_url): """ For .ytdl command, download media from YouTube and many other sites. """ url = v_url.pattern_match.group(2) type = v_url.pattern_match.group(1).lower() await v_url.edit("`Preparing to download...`") out_folder = Config.TMP_DOWNLOAD_DIRECTORY + "youtubedl/" thumb_image_path = Config.TMP_DOWNLOAD_DIRECTORY + "/thumb_image.jpg" if not os.path.isdir(out_folder): os.makedirs(out_folder) if type == "a": opts = { 'format': 'bestaudio', 'addmetadata': True, 'noplaylist': False, 'key': 'FFmpegMetadata', 'writethumbnail': True, 'embedthumbnail': True, 'prefer_ffmpeg': True, 'geo_bypass': True, 'nocheckcertificate': True, 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '320', }], 'outtmpl': out_folder + '%(title)s.%(ext)s', 'quiet': True, 'logtostderr': False } video = False song = True elif type == "v": opts = { 'format': 'best', 'addmetadata': True, 'noplaylist': False, 'getthumbnail': True, 'embedthumbnail': True, 'xattrs': True, 'writethumbnail': True, 'key': 'FFmpegMetadata', 'prefer_ffmpeg': True, 'geo_bypass': True, 'nocheckcertificate': True, 'postprocessors': [ { 'key': 'FFmpegVideoConvertor', 'preferedformat': 'mp4' }, ], 'outtmpl': out_folder + '%(title)s.%(ext)s', 'logtostderr': False, 'quiet': True } song = False video = True try: await v_url.edit("`Fetching playlist data, please wait..`") with YoutubeDL(opts) as ytdl: ytdl_data = ytdl.extract_info(url) # print(ytdl_data['thumbnail']) filename = sorted(get_lst_of_files(out_folder, [])) except DownloadError as DE: await v_url.edit(f"`{str(DE)}`") return except ContentTooShortError: await v_url.edit("`The download content was too short.`") return except GeoRestrictedError: await v_url.edit( "`Video is not available from your geographic location due to geographic restrictions imposed by a website.`" ) return except MaxDownloadsReached: await v_url.edit("`Max-downloads limit has been reached.`") return except PostProcessingError: await v_url.edit("`There was an error during post processing.`") return except UnavailableVideoError: await v_url.edit("`Media is not available in the requested format.`") return except XAttrMetadataError as XAME: await v_url.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`") return except ExtractorError: await v_url.edit("`There was an error during info extraction.`") return except Exception as e: await v_url.edit(f"{str(type(e)): {str(e)}}") return c_time = time.time() await v_url.edit( "`YouTube Playlist Downloading Processing Now.\nPlease Wait!`") if song: for single_file in filename: if os.path.exists(single_file): caption_rts = os.path.basename(single_file) force_document = True supports_streaming = False document_attributes = [] if single_file.endswith((".mp4", ".mp3", ".flac", ".webm")): metadata = extractMetadata(createParser(single_file)) duration = 0 width = 0 height = 180 if metadata.has("duration"): duration = metadata.get('duration').seconds document_attributes = [ DocumentAttributeVideo( duration=duration, w=width, h=height, round_message=False, supports_streaming=True, ) ] try: ytdl_data_name_audio = os.path.basename(single_file) thumb = out_folder + ytdl_data_name_audio[:( len(ytdl_data_name_audio) - 4)] + ".jpg" print(ytdl_data_name_audio) file_path = single_file song_size = file_size(file_path) await v_url.client.send_file( v_url.chat_id, single_file, caption=f"`{ytdl_data_name_audio}`" + "\n" + f"{song_size}", force_document=force_document, supports_streaming=supports_streaming, allow_cache=False, thumb=thumb, reply_to=v_url.message.id, attributes=document_attributes, progress_callback=lambda d, t: asyncio. get_event_loop().create_task( progress(d, t, v_url, c_time, "Uploading..", f"{ytdl_data_name_audio}"))) # os.remove(thumb) except Exception as e: await v_url.client.send_message( v_url.chat_id, "{} caused `{}`".format(caption_rts, str(e)), ) continue os.remove(single_file) await asyncio.sleep(DELETE_TIMEOUT) # await v_url.delete() shutil.rmtree(out_folder) if video: for single_file in filename: if os.path.exists(single_file): caption_rts = os.path.basename(single_file) force_document = False supports_streaming = True document_attributes = [] if single_file.endswith((".mp4", ".mp3", ".flac", ".webm")): metadata = extractMetadata(createParser(single_file)) duration = 0 width = 0 height = 0 if metadata.has("duration"): duration = metadata.get('duration').seconds document_attributes = [ DocumentAttributeVideo( duration=duration, w=width, h=height, round_message=False, supports_streaming=True, ) ] # print(ytdl_data) # for file in os.listdir("./DOWNLOADS/youtubedl/"): # if file.endswith(".jpg"): # thumb = "./DOWNLOADS/youtubedl/" + file # print(os.path.join("./DOWNLOADS/youtubedl/", file)) # image_link = ytdl_data['thumbnail'] # downloaded_image = wget.download(image_link,out_folder) # thumb = ytdl_data_name_video + ".jpg" file_path = single_file video_size = file_size(file_path) try: ytdl_data_name_video = os.path.basename(single_file) thumb = out_folder + ytdl_data_name_video[:( len(ytdl_data_name_video) - 4)] + ".jpg" await v_url.client.send_file( v_url.chat_id, single_file, caption=f"`{ytdl_data_name_video}`" + "\n" + f"{video_size}", force_document=force_document, supports_streaming=supports_streaming, thumb=thumb, allow_cache=False, reply_to=v_url.message.id, attributes=document_attributes, progress_callback=lambda d, t: asyncio. get_event_loop().create_task( progress(d, t, v_url, c_time, "Uploading..", f"{ytdl_data_name_video}"))) # os.remove(thumb) except Exception as e: await v_url.client.send_message( v_url.chat_id, "{} caused `{}`".format(caption_rts, str(e)), ) continue os.remove(single_file) await asyncio.sleep(DELETE_TIMEOUT) # await v_url.delete() shutil.rmtree(out_folder)
async def _(event): if event.fwd_from: return mone = await event.edit("Processing ...") input_str = event.pattern_match.group(1) thumb = None thumb_image_path = Config.TMP_DOWNLOAD_DIRECTORY + "thumb_image.jpg" logger.info(thumb_image_path) if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY): os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY) if event.reply_to_msg_id: start = datetime.now() reply_message = await event.get_reply_message() try: c_time = time.time() downloaded_file_name = await borg.download_media( reply_message, Config.TMP_DOWNLOAD_DIRECTORY, progress_callback=lambda d, t: asyncio.get_event_loop(). create_task(progress(d, t, mone, c_time, "trying to download")) ) except Exception as e: # pylint:disable=C0103,W0703 await mone.edit(str(e)) else: end = datetime.now() ms = (end - start).seconds await mone.edit("Downloaded now preparing to streaming upload") # if os.path.exists(input_str): if os.path.exists(Config.TMP_DOWNLOAD_DIRECTORY): if not downloaded_file_name.endswith( (".mkv", ".mp4", ".mp3", ".flac", ".webm", ".ts", ".mov")): await mone.edit( "**Supported Formats**: MKV, MP4, MP3, FLAC") return False if downloaded_file_name.upper().endswith( ("MKV", "MP4", "WEBM")): metadata = extractMetadata( createParser(downloaded_file_name)) duration = 0 if metadata.has("duration"): duration = metadata.get('duration').seconds width = 0 height = 0 thumb = None if os.path.exists(thumb_image_path): thumb = thumb_image_path else: thumb = await take_screen_shot( downloaded_file_name, os.path.dirname(os.path.abspath(downloaded_file_name)), (duration / 2)) start = datetime.now() metadata = extractMetadata(createParser(downloaded_file_name)) # duration = 0 width = 0 height = 0 # if metadata.has("duration"): # duration = metadata.get('duration').seconds 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") c_time = time.time() try: await borg.send_file( event.chat_id, downloaded_file_name, thumb=thumb, caption=input_str, force_document=False, allow_cache=False, reply_to=event.message.id, attributes=[ DocumentAttributeVideo(duration=duration, w=width, h=height, round_message=False, supports_streaming=True) ], progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task( progress(d, t, mone, c_time, "trying to upload"))) except Exception as e: await mone.edit(str(e)) else: end = datetime.now() # os.remove(input_str) ms = (end - start).seconds await mone.edit("Uploaded in {} seconds.".format(ms)) os.remove(thumb) await asyncio.sleep(5) os.remove(downloaded_file_name) else: await mone.edit("404: File Not Found")
async def rename_doc(bot, message): mssg = await bot.get_messages(message.chat.id, message.reply_to_message.message_id) media = mssg.reply_to_message if media.empty: await message.reply_text('Why did you delete that 😕', True) return filetype = media.document or media.video or media.audio or media.voice or media.video_note try: actualname = filetype.file_name splitit = actualname.split(".") extension = (splitit[-1]) except: extension = "mkv" await bot.delete_messages(chat_id=message.chat.id, message_ids=message.reply_to_message.message_id, revoke=True) if message.from_user.id not in Config.BANNED_USERS: file_name = message.text description = script.CUSTOM_CAPTION_UL_FILE.format(newname=file_name) download_location = Config.DOWNLOAD_LOCATION + "/" thumb_image_path = download_location + str( message.from_user.id) + ".jpg" if not os.path.exists(thumb_image_path): mes = await thumb(message.from_user.id) if mes != None: m = await bot.get_messages(message.chat.id, mes.msg_id) await m.download(file_name=thumb_image_path) thumb_image_path = thumb_image_path a = await bot.send_message(chat_id=message.chat.id, text=script.DOWNLOAD_START, reply_to_message_id=message.message_id) c_time = time.time() the_real_download_location = await bot.download_media( message=media, file_name=download_location, progress=progress_for_pyrogram, progress_args=(script.DOWNLOAD_START, a, c_time)) if the_real_download_location is not None: await bot.edit_message_text(text=script.SAVED_RECVD_DOC_FILE, chat_id=message.chat.id, message_id=a.message_id) new_file_name = download_location + file_name + "." + extension os.rename(the_real_download_location, new_file_name) await bot.edit_message_text(text=script.UPLOAD_START, chat_id=message.chat.id, message_id=a.message_id) # logger.info(the_real_download_location) if os.path.exists(thumb_image_path): width = 0 height = 0 metadata = extractMetadata(createParser(thumb_image_path)) if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") Image.open(thumb_image_path).convert("RGB").save( thumb_image_path) img = Image.open(thumb_image_path) img.resize((320, height)) img.save(thumb_image_path, "JPEG") else: thumb_image_path = None c_time = time.time() await bot.send_document( chat_id=message.chat.id, document=new_file_name, thumb=thumb_image_path, caption=description, # reply_markup=reply_markup, reply_to_message_id=message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=(script.UPLOAD_START, a, c_time)) try: os.remove(new_file_name) except: pass try: os.remove(thumb_image_path) except: pass await bot.edit_message_text( text=script.AFTER_SUCCESSFUL_UPLOAD_MSG, reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton(text="🙌🏻 SHARE ME 🙌🏻", url="@MonkAno") ]]), chat_id=message.chat.id, message_id=a.message_id, disable_web_page_preview=True) else: await bot.send_message(chat_id=message.chat.id, text="You're B A N N E D", reply_to_message_id=message.message_id)
async def _(event): if event.fwd_from: return await event.edit( "Rename & Upload as Streamable in process 🙄🙇♂️🙇♂️🙇♀️ It might take some time if file size is big" ) input_str = event.pattern_match.group(1) if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY): os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY) if event.reply_to_msg_id: start = datetime.now() file_name = input_str reply_message = await event.get_reply_message() time.time() to_download_directory = Config.TMP_DOWNLOAD_DIRECTORY downloaded_file_name = os.path.join(to_download_directory, file_name) downloaded_file_name = await event.client.download_media( reply_message, downloaded_file_name ) end_one = datetime.now() ms_one = (end_one - start).seconds if os.path.exists(downloaded_file_name): thumb = None if not downloaded_file_name.endswith((".mkv", ".mp4", ".mp3", ".flac")): await event.edit( "Sorry. But I don't think {} is a streamable file. Please try again.\n**Supported Formats**: MKV, MP4, MP3, FLAC".format( downloaded_file_name ) ) return False if os.path.exists(thumb_image_path): thumb = thumb_image_path else: thumb = get_video_thumb(downloaded_file_name, thumb_image_path) start = datetime.now() metadata = extractMetadata(createParser(downloaded_file_name)) duration = 0 width = 0 height = 0 if metadata.has("duration"): duration = metadata.get("duration").seconds 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") # Telegram only works with MP4 files # this is good, since with MKV files sent as streamable Telegram responds, # Bad Request: VIDEO_CONTENT_TYPE_INVALID # c_time = time.time() try: await event.client.send_file( event.chat_id, downloaded_file_name, thumb=thumb, caption="reuploaded by [PikaBot](https://www.github.com/ItzSjDude/PikachuUserbot", force_document=False, allow_cache=False, reply_to=event.message.id, attributes=[ DocumentAttributeVideo( duration=duration, w=width, h=height, round_message=False, supports_streaming=True, ) ], ) except Exception as e: await event.edit(str(e)) else: end = datetime.now() os.remove(downloaded_file_name) ms_two = (end - end_one).seconds await event.edit( "Downloaded in {} seconds. Uploaded in {} seconds.".format( ms_one, ms_two ) ) else: await event.edit("File Not Found {}".format(input_str)) else: await event.edit( "Syntax // .rnstreamupload file.name as reply to a Telegram media" )
async def glitch(event): if not event.reply_to_msg_id: await event.edit("`I Wont Glitch A Ghost!`") return reply_message = await event.get_reply_message() if not reply_message.media: await event.edit("`reply to a image/sticker`") return await event.edit("`Downloading Media..`") if ( DocumentAttributeFilename(file_name="AnimatedSticker.tgs") in reply_message.media.document.attributes ): await bot.download_media( reply_message, "anim.tgs", ) os.system("lottie_convert.py anim.tgs anim.png") glitch_file = "anim.png" elif reply_message.video: video = await bot.download_media( reply_message, "glitch.mp4", ) extractMetadata(createParser(video)) os.system("ffmpeg -i glitch.mp4 -vframes 1 -an -s 480x360 -ss 1 glitch.png") glitch_file = "glitch.png" else: glitch_file = await bot.download_media( reply_message, "glitch.png", ) try: value = int(event.pattern_match.group(1)) if value > 8: raise ValueError except ValueError: value = 2 await event.edit("```Glitching This Media..```") await asyncio.sleep(2) glitcher = ImageGlitcher() img = Image.open(glitch_file) glitch_img = glitcher.glitch_image(img, value, color_offset=True, gif=True) DURATION = 200 LOOP = 0 glitch_img[0].save( Glitched, format="GIF", append_images=glitch_img[1:], save_all=True, duration=DURATION, loop=LOOP, ) await event.edit("`Uploading Glitched Media..`") c_time = time.time() nosave = await event.client.send_file( event.chat_id, Glitched, force_document=False, reply_to=event.reply_to_msg_id, progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress(d, t, event, c_time, "[UPLOAD]") ), ) await event.delete() await bot( functions.messages.SaveGifRequest( id=types.InputDocument( id=nosave.media.document.id, access_hash=nosave.media.document.access_hash, file_reference=nosave.media.document.file_reference, ), unsave=True, ) ) os.remove(glitch_file) os.system("rm *.tgs *.mp4")
async def audio_upload( message: Message, path, del_path: bool = False, callback: CallbackQuery = None, extra: str = "", with_thumb: bool = True, log: bool = True, ): title = None artist = None thumb = None duration = 0 str_path = str(path) file_size = humanbytes(os.stat(str_path).st_size) if with_thumb: try: album_art = stagger.read_tag(str_path) if album_art.picture and not os.path.lexists(Config.THUMB_PATH): bytes_pic_data = album_art[stagger.id3.APIC][0].data bytes_io = io.BytesIO(bytes_pic_data) image_file = Image.open(bytes_io) image_file.save("album_cover.jpg", "JPEG") thumb = "album_cover.jpg" except stagger.errors.NoTagError: pass if not thumb: thumb = await get_thumb(str_path) metadata = extractMetadata(createParser(str_path)) if metadata and metadata.has("title"): title = metadata.get("title") if metadata and metadata.has("artist"): artist = metadata.get("artist") if metadata and metadata.has("duration"): duration = metadata.get("duration").seconds sent: Message = await message.client.send_message( message.chat.id, f"`Uploading {str_path} as audio ... {extra}`") start_t = datetime.now() await message.client.send_chat_action(message.chat.id, "upload_audio") try: msg = await message.client.send_audio( chat_id=message.chat.id, audio=str_path, thumb=thumb, caption=f"{path.name} [ {file_size} ]", title=title, performer=artist, duration=duration, parse_mode="html", disable_notification=True, progress=progress, progress_args=(message, f"uploading {extra}", str_path, callback), ) except ValueError as e_e: await sent.edit(f"Skipping `{str_path}` due to {e_e}") except Exception as u_e: await sent.edit(str(u_e)) raise u_e else: await sent.delete() if log: await finalize(message, msg, start_t) if os.path.exists(str_path) and del_path: os.remove(str_path) if os.path.lexists("album_cover.jpg"): os.remove("album_cover.jpg") return msg
async def vid_upload( message: Message, path, del_path: bool = False, callback: CallbackQuery = None, extra: str = "", with_thumb: bool = True, custom_thumb: str = "", log: bool = True, ): str_path = str(path) thumb = None if with_thumb: if custom_thumb: try: thumb = await check_thumb(custom_thumb) except Exception as e_r: await CHANNEL.log(str(e_r)) if not thumb: thumb = await get_thumb(str_path) duration = 0 metadata = extractMetadata(createParser(str_path)) if metadata and metadata.has("duration"): duration = metadata.get("duration").seconds sent: Message = await message.client.send_message( message.chat.id, f"`Uploading {str_path} as a video ... {extra}`") start_t = datetime.now() await message.client.send_chat_action(message.chat.id, "upload_video") width = 0 height = 0 if thumb: t_m = extractMetadata(createParser(thumb)) if t_m and t_m.has("width"): width = t_m.get("width") if t_m and t_m.has("height"): height = t_m.get("height") try: msg = await message.client.send_video( chat_id=message.chat.id, video=str_path, duration=duration, thumb=thumb, width=width, height=height, caption=path.name, parse_mode="html", disable_notification=True, progress=progress, progress_args=(message, f"uploading {extra}", str_path, callback), ) except ValueError as e_e: await sent.edit(f"Skipping `{str_path}` due to {e_e}") except Exception as u_e: await sent.edit(str(u_e)) raise u_e else: await sent.delete() await remove_thumb(thumb) if log: await finalize(message, msg, start_t) if os.path.exists(str_path) and del_path: os.remove(str_path) return msg
async def split_large_files(input_file): working_directory = os.path.dirname(os.path.abspath(input_file)) new_working_directory = os.path.join(working_directory, str(time.time())) # create download directory, if not exist if not os.path.isdir(new_working_directory): os.makedirs(new_working_directory) # if input_file.upper().endswith(("MKV", "MP4", "WEBM", "MP3", "M4A", "FLAC", "WAV")): """The below logic is DERPed, so removing temporarily """ if False: # handle video / audio files here metadata = extractMetadata(createParser(input_file)) total_duration = 0 if metadata.has("duration"): total_duration = metadata.get('duration').seconds # proprietary logic to get the seconds to trim (at) LOGGER.info(total_duration) total_file_size = os.path.getsize(input_file) LOGGER.info(total_file_size) minimum_duration = (total_duration / total_file_size) * (MAX_TG_SPLIT_FILE_SIZE) LOGGER.info(minimum_duration) # END: proprietary start_time = 0 end_time = minimum_duration base_name = os.path.basename(input_file) input_extension = base_name.split(".")[-1] LOGGER.info(input_extension) i = 0 while end_time < total_duration: LOGGER.info(i) parted_file_name = "" parted_file_name += str(i).zfill(5) parted_file_name += str(base_name) parted_file_name += "_PART_" parted_file_name += str(start_time) parted_file_name += "." parted_file_name += str(input_extension) output_file = os.path.join(new_working_directory, parted_file_name) LOGGER.info(output_file) LOGGER.info(await cult_small_video(input_file, output_file, str(start_time), str(end_time))) start_time = end_time end_time = end_time + minimum_duration i = i + 1 else: # handle normal files here o_d_t = os.path.join(new_working_directory, os.path.basename(input_file)) o_d_t = o_d_t + "." file_genertor_command = [ "split", "--numeric-suffixes=1", "--suffix-length=5", f"--bytes={MAX_TG_SPLIT_FILE_SIZE}", input_file, o_d_t ] process = await asyncio.create_subprocess_exec( *file_genertor_command, # stdout must a pipe to be accessible as process.stdout stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) # Wait for the subprocess to finish stdout, stderr = await process.communicate() e_response = stderr.decode().strip() t_response = stdout.decode().strip() return new_working_directory
async def upload_single_file(message, local_file_name, caption_str, from_user): 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 = 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 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=False, 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 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 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: await message_for_progress_display.delete() os.remove(local_file_name) return sent_message
async def uploadir(udir_event): """ .uploadir komutu bir klasördeki tüm dosyaları uploadlamanıza yarar """ input_str = udir_event.pattern_match.group(1) if os.path.exists(input_str): await udir_event.edit(LANG['TRYING']) lst_of_files = [] for r, d, f in os.walk(input_str): for file in f: lst_of_files.append(os.path.join(r, file)) for file in d: lst_of_files.append(os.path.join(r, file)) LOGS.info(lst_of_files) uploaded = 0 await udir_event.edit(LANG['FOUND_FILES'].format(len(lst_of_files))) for single_file in lst_of_files: if os.path.exists(single_file): # https://stackoverflow.com/a/678242/4723940 caption_rts = os.path.basename(single_file) c_time = time.time() if not caption_rts.lower().endswith(".mp4"): await udir_event.client.send_file( udir_event.chat_id, single_file, caption=caption_rts, force_document=False, allow_cache=False, reply_to=udir_event.message.id, progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task( progress(d, t, udir_event, c_time, LANG[ 'UPLOADING'], single_file))) else: thumb_image = os.path.join(input_str, "thumb.jpg") c_time = time.time() metadata = extractMetadata(createParser(single_file)) duration = 0 width = 0 height = 0 if metadata.has("duration"): duration = metadata.get("duration").seconds if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") await udir_event.client.send_file( udir_event.chat_id, single_file, caption=caption_rts, thumb=thumb_image, force_document=False, allow_cache=False, reply_to=udir_event.message.id, attributes=[ DocumentAttributeVideo( duration=duration, w=width, h=height, round_message=False, supports_streaming=True, ) ], progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task( progress(d, t, udir_event, c_time, LANG[ 'UPLOADING'], single_file))) os.remove(single_file) uploaded = uploaded + 1 await udir_event.edit( LANG['SUCCESSFULLY_MULTI_UPLOADED'].format(uploaded)) else: await udir_event.edit("404: Directory Not Found")
async def _(event): if not event.reply_to_msg_id: await edit_delete(event, "`Mohon Balas Ke Media Apapun`") return reply_message = await event.get_reply_message() if not reply_message.media: await edit_delete(event, "`Mohon Balas Ke Gambar/Sticker/Video`") return xx = await edit_or_reply(event, "`Mendownload Media.....`") if reply_message.photo: await event.client.download_media( reply_message, "wc.png", ) elif (DocumentAttributeFilename(file_name="AnimatedSticker.tgs") in reply_message.media.document.attributes): await event.client.download_media( reply_message, "wc.tgs", ) await bash("lottie_convert.py wc.tgs wc.png") elif reply_message.video: video = await event.client.download_media( reply_message, "wc.mp4", ) extractMetadata(createParser(video)) await bash("ffmpeg -i wc.mp4 -vframes 1 -an -s 480x360 -ss 1 wc.png") else: await event.client.download_media( reply_message, "wc.png", ) try: await xx.edit("`Sedang Memproses....`") text = open("userbot/utils/styles/alice.txt", encoding="utf-8").read() image_color = np.array(Image.open("wc.png")) image_color = image_color[::1, ::1] image_mask = image_color.copy() image_mask[image_mask.sum(axis=2) == 0] = 255 edges = np.mean( [ gaussian_gradient_magnitude(image_color[:, :, i] / 255.0, 2) for i in range(3) ], axis=0, ) image_mask[edges > 0.08] = 255 wc = WordCloud( max_words=2000, mask=image_mask, max_font_size=40, random_state=42, relative_scaling=0, ) wc.generate(text) image_colors = ImageColorGenerator(image_color) wc.recolor(color_func=image_colors) wc.to_file("wc.png") await event.client.send_file( event.chat_id, "wc.png", reply_to=event.reply_to_msg_id, ) await event.delete() await bash("rm *.png *.mp4 *.tgs *.webp") except BaseException as e: await bash("rm *.png *.mp4 *.tgs *.webp") return await event.edit(str(e))
async def zip(event): if event.fwd_from: return mone = await event.edit(LANG['DOWNLOADING']) extracted = TEMP_DOWNLOAD_DIRECTORY + "extracted/" thumb_image_path = TEMP_DOWNLOAD_DIRECTORY + "/thumb_image.jpg" if not os.path.isdir(extracted): os.makedirs(extracted) if not os.path.isdir(TEMP_DOWNLOAD_DIRECTORY): os.makedirs(TEMP_DOWNLOAD_DIRECTORY) if event.reply_to_msg_id: start = time.time() reply_message = await event.get_reply_message() try: c_time = time.time() downloaded_file_name = await event.client.download_media( reply_message, TEMP_DOWNLOAD_DIRECTORY, progress_callback=lambda d, t: asyncio.get_event_loop(). create_task(progress(d, t, mone, c_time, LANG['DOWNLOADING']))) except Exception as e: # pylint:disable=C0103,W0703 await mone.edit(str(e)) else: end = time.time() ms = end - start await mone.edit(LANG['DOWNLOADED'].format(downloaded_file_name, ms)) with zipfile.ZipFile(downloaded_file_name, 'r') as zip_ref: zip_ref.extractall(extracted) filename = sorted(get_lst_of_files(extracted, [])) #filename = filename + "/" await event.edit(LANG['UNZIPPING']) # r=root, d=directories, f = files for single_file in filename: if os.path.exists(single_file): # https://stackoverflow.com/a/678242/4723940 caption_rts = os.path.basename(single_file) force_document = False supports_streaming = True document_attributes = [] if single_file.endswith((".mp4", ".mp3", ".flac", ".webm")): metadata = extractMetadata(createParser(single_file)) duration = 0 width = 0 height = 0 if metadata.has("duration"): duration = metadata.get('duration').seconds 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") document_attributes = [ DocumentAttributeVideo(duration=duration, w=width, h=height, round_message=False, supports_streaming=True) ] await event.client.send_file( event.chat_id, single_file, caption=f"`{caption_rts}`", force_document=force_document, supports_streaming=supports_streaming, allow_cache=False, reply_to=event.message.id, attributes=document_attributes, progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task( progress(d, t, event, c_time, LANG['UPLOADING']))) os.remove(single_file) os.remove(downloaded_file_name) else: await event.edit(LANG['REPLY_TO_ZIP'])
async def uploadas(uas_event): """ For .uploadas command, allows you to specify some arguments for upload. """ await uas_event.edit("Processing ...") type_of_upload = uas_event.pattern_match.group(1) supports_streaming = False round_message = False spam_big_messages = False if type_of_upload == "stream": supports_streaming = True if type_of_upload == "vn": round_message = True if type_of_upload == "all": spam_big_messages = True input_str = uas_event.pattern_match.group(2) thumb = None file_name = None if "|" in input_str: file_name, thumb = input_str.split("|") file_name = file_name.strip() thumb = thumb.strip() else: file_name = input_str thumb_path = "a_random_f_file_name" + ".jpg" thumb = get_video_thumb(file_name, output=thumb_path) if os.path.exists(file_name): metadata = extractMetadata(createParser(file_name)) duration = 0 width = 0 height = 0 if metadata.has("duration"): duration = metadata.get("duration").seconds if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") try: if supports_streaming: c_time = time.time() await uas_event.client.send_file( uas_event.chat_id, file_name, thumb=thumb, caption=input_str, force_document=False, allow_cache=False, reply_to=uas_event.message.id, attributes=[ DocumentAttributeVideo( duration=duration, w=width, h=height, round_message=False, supports_streaming=True, ) ], progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task( progress(d, t, uas_event, c_time, "[UPLOAD]", file_name))) elif round_message: c_time = time.time() await uas_event.client.send_file( uas_event.chat_id, file_name, thumb=thumb, allow_cache=False, reply_to=uas_event.message.id, video_note=True, attributes=[ DocumentAttributeVideo( duration=0, w=1, h=1, round_message=True, supports_streaming=True, ) ], progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task( progress(d, t, uas_event, c_time, "[UPLOAD]", file_name))) elif spam_big_messages: return await uas_event.edit("TBD: Not (yet) Implemented") os.remove(thumb) await uas_event.edit("Uploaded successfully !!") except FileNotFoundError as err: await uas_event.edit(str(err)) else: await uas_event.edit("404: File Not Found")
async def uploadas(uas_event): """ .uploadas komutu size upload yaparken bazı argümanlar belirtmenizi sağlar. """ await uas_event.edit("Lütfen bekleyin...") type_of_upload = uas_event.pattern_match.group(1) supports_streaming = False round_message = False spam_big_messages = False if type_of_upload == "stream": supports_streaming = True if type_of_upload == "vn": round_message = True if type_of_upload == "all": spam_big_messages = True input_str = uas_event.pattern_match.group(2) thumb = None file_name = None if "|" in input_str: file_name, thumb = input_str.split("|") file_name = file_name.strip() thumb = thumb.strip() else: file_name = input_str thumb_path = "a_random_f_file_name" + ".jpg" thumb = get_video_thumb(file_name, output=thumb_path) if os.path.exists(file_name): metadata = extractMetadata(createParser(file_name)) duration = 0 width = 0 height = 0 if metadata.has("duration"): duration = metadata.get("duration").seconds if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") try: if supports_streaming: c_time = time.time() await uas_event.client.send_file( uas_event.chat_id, file_name, thumb=thumb, caption=input_str, force_document=False, allow_cache=False, reply_to=uas_event.message.id, attributes=[ DocumentAttributeVideo( duration=duration, w=width, h=height, round_message=False, supports_streaming=True, ) ], progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task( progress(d, t, uas_event, c_time, "Uploadlanıyor...", file_name))) elif round_message: c_time = time.time() await uas_event.client.send_file( uas_event.chat_id, file_name, thumb=thumb, allow_cache=False, reply_to=uas_event.message.id, video_note=True, attributes=[ DocumentAttributeVideo( duration=0, w=1, h=1, round_message=True, supports_streaming=True, ) ], progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task( progress(d, t, uas_event, c_time, "Uploadlanıyor...", file_name))) elif spam_big_messages: await uas_event.edit("TBD: Halihazırda uygulanamadı.") return os.remove(thumb) await uas_event.edit("Upload başarılı !!") except FileNotFoundError as err: await uas_event.edit(str(err)) else: await uas_event.edit("404: Dosya bulunamadı.")
def video_metadata(file): return extractMetadata(createParser(file))
async def VidWatermarkAdder(bot, cmd): if not await db.is_user_exist(cmd.from_user.id): await db.add_user(cmd.from_user.id) await bot.send_message( Config.LOG_CHANNEL, f"#NEW_USER: \n\nNew User [{cmd.from_user.first_name}](tg://user?id={cmd.from_user.id}) started @{Config.BOT_USERNAME} !!" ) if Config.UPDATES_CHANNEL: invite_link = await bot.create_chat_invite_link( int(Config.UPDATES_CHANNEL)) try: user = await bot.get_chat_member(int(Config.UPDATES_CHANNEL), cmd.from_user.id) if user.status == "kicked": await bot.send_message( chat_id=cmd.from_user.id, text= "Sorry Sir, You are Banned to use me. Contact my [Support Group](https://t.me/VKP_BOTS).", parse_mode="markdown", disable_web_page_preview=True) return except UserNotParticipant: await bot.send_message( chat_id=cmd.from_user.id, text= "**Please Join My Updates Channel to use this Bot!**\n\nDue to Overload, Only Channel Subscribers can use the Bot!", reply_markup=InlineKeyboardMarkup( [[ InlineKeyboardButton("🤖 Join Updates Channel", url=invite_link.invite_link) ], [ InlineKeyboardButton("🔄 Refresh 🔄", callback_data="refreshmeh") ]]), parse_mode="markdown") return except Exception: await bot.send_message( chat_id=cmd.from_user.id, text= "Something went Wrong. Contact my [Support Group](https://t.me/VKP_BOTS).", parse_mode="markdown", disable_web_page_preview=True) return ## --- Noobie Process --- ## working_dir = Config.DOWN_PATH + "/WatermarkAdder/" if not os.path.exists(working_dir): os.makedirs(working_dir) watermark_path = Config.DOWN_PATH + "/" + str( cmd.from_user.id) + "/thumb.jpg" if not os.path.exists(watermark_path): await cmd.reply_text( "You Didn't Set Any Watermark!\n\nSend any JPG or PNG Picture ...") return file_type = cmd.video or cmd.document if not file_type.mime_type.startswith("video/"): await cmd.reply_text("This is not a Video!") return status = Config.DOWN_PATH + "/WatermarkAdder/status.json" if os.path.exists(status): await cmd.reply_text( "Sorry, Currently I am busy with another Task!\n\nTry Again After Sometime!" ) return preset = Config.PRESET editable = await cmd.reply_text("Downloading Video ...", parse_mode="Markdown") with open(status, "w") as f: statusMsg = { 'chat_id': cmd.from_user.id, 'message': editable.message_id } json.dump(statusMsg, f, indent=2) dl_loc = Config.DOWN_PATH + "/WatermarkAdder/" + str( cmd.from_user.id) + "/" if not os.path.isdir(dl_loc): os.makedirs(dl_loc) the_media = None logs_msg = None user_info = f"**UserID:** #id{cmd.from_user.id}\n**Name:** [{cmd.from_user.first_name}](tg://user?id={cmd.from_user.id})" ## --- Done --- ## try: forwarded_video = await cmd.forward(Config.LOG_CHANNEL) logs_msg = await bot.send_message( chat_id=Config.LOG_CHANNEL, text=f"Download Started!\n\n{user_info}", reply_to_message_id=forwarded_video.message_id, disable_web_page_preview=True, parse_mode="Markdown") await asyncio.sleep(5) c_time = time.time() the_media = await bot.download_media( message=cmd, file_name=dl_loc, progress=progress_for_pyrogram, progress_args=("Downloading Sir ...", editable, c_time)) if (the_media is None): await delete_trash(status) await delete_trash(the_media) print(f"Download Failed: {err}") await editable.edit("Unable to Download The Video!") return except Exception as err: await delete_trash(status) await delete_trash(the_media) print(f"Download Failed: {err}") await editable.edit("Unable to Download The Video!") return await editable.edit( "Trying to Add Watermark to the Video at Top Left Corner ...\n\nPlease Wait!" ) duration = 0 metadata = extractMetadata(createParser(the_media)) if metadata.has("duration"): duration = metadata.get('duration').seconds the_media_file_name = os.path.basename(the_media) main_file_name = os.path.splitext(the_media_file_name)[0] output_vid = main_file_name + "_[" + str(cmd.from_user.id) + "]_[" + str( time.time()) + "]_[@VKPROJECTS]" + ".mp4" progress = Config.DOWN_PATH + "/WatermarkAdder/" + str( cmd.from_user.id) + "/progress.txt" try: output_vid = await vidmark(the_media, editable, progress, watermark_path, output_vid, duration, logs_msg, status, preset) except Exception as err: print(f"Unable to Add Watermark: {err}") await editable.edit("Unable to add Watermark!") await logs_msg.edit( f"#ERROR: Unable to add Watermark!\n\n**Error:** `{err}`") await delete_all() return if output_vid == None: await editable.edit("Something went wrong!") await logs_msg.edit("#ERROR: Something went wrong!") await delete_all() return await editable.edit("Watermark Added Successfully!\n\nTrying to Upload ..." ) await logs_msg.edit("Watermark Added Successfully!\n\nTrying to Upload ..." ) width = 100 height = 100 duration = 0 metadata = extractMetadata(createParser(output_vid)) if metadata.has("duration"): duration = metadata.get('duration').seconds if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") video_thumbnail = None try: video_thumbnail = Config.DOWN_PATH + "/WatermarkAdder/" + str( cmd.from_user.id) + "/" + str(time.time()) + ".jpg" ttl = random.randint(0, int(duration) - 1) file_genertor_command = [ "ffmpeg", "-ss", str(ttl), "-i", output_vid, "-vframes", "1", video_thumbnail ] process = await asyncio.create_subprocess_exec( *file_genertor_command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) stdout, stderr = await process.communicate() e_response = stderr.decode().strip() t_response = stdout.decode().strip() print(e_response) print(t_response) Image.open(video_thumbnail).convert("RGB").save(video_thumbnail) img = Image.open(video_thumbnail) img.resize((width, height)) img.save(video_thumbnail, "JPEG") except Exception as err: print(f"Error: {err}") # --- Upload --- # sent_vid = None file_size = os.path.getsize(output_vid) if int(file_size) > 2097152000: await editable.edit( f"Sorry Sir,\n\nFile Size Become {humanbytes(file_size)} !!\nI can't Upload to Telegram!" ) await delete_all() return await asyncio.sleep(5) try: c_time = time.time() sent_vid = await bot.send_video( chat_id=cmd.chat.id, video=output_vid, caption= f"**File Name:** `{output_vid}`\n**Video Duration:** `{format_timespan(duration)}`\n**File Size:** `{humanbytes(file_size)}`\n\n{Config.CAPTION}", thumb=video_thumbnail, duration=duration, width=width, height=height, reply_to_message_id=cmd.message_id, supports_streaming=True, reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton("Updates Channel", url="https://t.me/VKPROJECTS"), InlineKeyboardButton("Support Group", url="https://t.me/VKP_BOTS") ]]), progress=progress_for_pyrogram, progress_args=("Uploading, Wait Sir ...", editable, c_time)) # Any Better Way? :( except FloodWait as e: print(f"Got FloodWait of {e.x}s ...") await asyncio.sleep(e.x) await asyncio.sleep(5) c_time = time.time() sent_vid = await bot.send_video( chat_id=cmd.chat.id, video=output_vid, caption= f"**File Name:** `{output_vid}`\n**Video Duration:** `{format_timespan(duration)}`\n**File Size:** `{humanbytes(file_size)}`\n\n{Config.CAPTION}", thumb=video_thumbnail, duration=duration, width=width, height=height, reply_to_message_id=cmd.message_id, supports_streaming=True, reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton("Updates Channel", url="https://t.me/VKPROJECTS"), InlineKeyboardButton("Support Group", url="https://t.me/VKP_BOTS") ]]), progress=progress_for_pyrogram, progress_args=("Uploading, Wait Sir ...", editable, c_time)) except Exception as err: print(f"Unable to Upload Video: {err}") await logs_msg.edit( f"#ERROR: Unable to Upload Video!\n\n**Error:** `{err}`") await delete_all() return await delete_all() await editable.delete() forward_vid = await sent_vid.forward(Config.LOG_CHANNEL) await logs_msg.delete() await bot.send_message( chat_id=Config.LOG_CHANNEL, text=f"#WATERMARK_ADDED: Video Uploaded!\n\n{user_info}", reply_to_message_id=forward_vid.message_id)
async def uploadir(udir_event): """ For .uploadir command, allows you to upload everything from a folder in the server""" if not udir_event.text[0].isalpha() and udir_event.text[0] not in ( "/", "#", "@", "!"): if udir_event.fwd_from: return input_str = udir_event.pattern_match.group(1) if os.path.exists(input_str): start = datetime.now() await udir_event.edit("Processing ...") lst_of_files = [] for r, d, f in os.walk(input_str): for file in f: lst_of_files.append(os.path.join(r, file)) for file in d: lst_of_files.append(os.path.join(r, file)) LOGS.info(lst_of_files) uploaded = 0 await udir_event.edit( "Found {} files. Uploading will start soon. Please wait!". format(len(lst_of_files))) for single_file in lst_of_files: if os.path.exists(single_file): # https://stackoverflow.com/a/678242/4723940 caption_rts = os.path.basename(single_file) if not caption_rts.lower().endswith(".mp4"): await udir_event.client.send_file( udir_event.chat_id, single_file, caption=caption_rts, force_document=False, allow_cache=False, reply_to=udir_event.message.id, progress_callback=progress, ) else: thumb_image = os.path.join(input_str, "thumb.jpg") metadata = extractMetadata(createParser(single_file)) duration = 0 width = 0 height = 0 if metadata.has("duration"): duration = metadata.get("duration").seconds if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") await udir_event.client.send_file( udir_event.chat_id, single_file, caption=caption_rts, thumb=thumb_image, force_document=False, allow_cache=False, reply_to=udir_event.message.id, attributes=[ DocumentAttributeVideo( duration=duration, w=width, h=height, round_message=False, supports_streaming=True, ) ], progress_callback=progress, ) os.remove(single_file) uploaded = uploaded + 1 end = datetime.now() duration = (end - start).seconds await udir_event.edit("Uploaded {} files in {} seconds.".format( uploaded, duration)) else: await udir_event.edit("404: Directory Not Found")
async def transform(event): if not event.reply_to_msg_id: await event.edit("`Reply to Any media..`") return reply_message = await event.get_reply_message() if not reply_message.media: await event.edit("`Reply to a image/sticker`") return await event.edit("`Downloading Media..`") if reply_message.photo: transform = await bot.download_media( reply_message, "transform.png", ) elif (DocumentAttributeFilename(file_name="AnimatedSticker.tgs") in reply_message.media.document.attributes): await bot.download_media( reply_message, "transform.tgs", ) os.system("lottie_convert.py transform.tgs transform.png") transform = "transform.png" elif reply_message.video: video = await bot.download_media( reply_message, "transform.mp4", ) extractMetadata(createParser(video)) os.system( "ffmpeg -i transform.mp4 -vframes 1 -an -s 480x360 -ss 1 transform.png" ) transform = "transform.png" else: transform = await bot.download_media( reply_message, "transform.png", ) try: await event.edit("`Transforming this media..`") cmd = event.pattern_match.group(1) im = Image.open(transform).convert("RGB") if cmd == "mirror": IMG = ImageOps.mirror(im) elif cmd == "flip": IMG = ImageOps.flip(im) elif cmd == "ghost": IMG = ImageOps.invert(im) elif cmd == "bw": IMG = ImageOps.grayscale(im) elif cmd == "poster": IMG = ImageOps.posterize(im, 2) IMG.save(Converted, quality=95) await event.client.send_file(event.chat_id, Converted, reply_to=event.reply_to_msg_id) await event.delete() os.system("rm *.mp4 *.tgs") os.remove(transform) os.remove(Converted) except BaseException: return
async def _(e): if not e.text[0].isalpha() and e.text[0] not in ("/", "#", "@", "!"): if e.fwd_from: return input_str = e.pattern_match.group(1) if os.path.exists(input_str): start = datetime.now() await e.edit("Processing ...") lst_of_files = lst_of_files(input_str, []) LOGS.info(lst_of_files) u = 0 await e.edit( "Found {} files. Uploading will start soon. Please wait!". format(len(lst_of_files))) for single_file in lst_of_files: if os.path.exists(single_file): # https://stackoverflow.com/a/678242/4723940 caption_rts = os.path.basename(single_file) if not caption_rts.lower().endswith(".mp4"): await e.client.send_file( e.chat_id, single_file, caption=caption_rts, force_document=False, allow_cache=False, reply_to=e.message.id, progress_callback=progress, ) else: thumb_image = os.path.join(input_str, "thumb.jpg") metadata = extractMetadata(createParser(single_file)) duration = 0 width = 0 height = 0 if metadata.has("duration"): duration = metadata.get("duration").seconds if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") await e.client.send_file( e.chat_id, single_file, caption=caption_rts, thumb=thumb_image, force_document=False, allow_cache=False, reply_to=e.message.id, attributes=[ DocumentAttributeVideo( duration=duration, w=width, h=height, round_message=False, supports_streaming=True, ) ], progress_callback=progress, ) os.remove(single_file) u = u + 1 end = datetime.now() ms = (end - start).seconds await e.edit("Uploaded {} files in {} seconds.".format(u, ms)) else: await e.edit("404: Directory Not Found")
async def convert_to_file(bot, update): if update.from_user.id in Config.BANNED_USERS: await bot.send_message(chat_id=update.chat.id, text=Translation.BANNED_USER_TEXT, reply_to_message_id=update.message_id) return TRChatBase(update.from_user.id, update.text, "c2f") if update.reply_to_message is not None: description = Translation.CUSTOM_CAPTION_UL_FILE download_location = Config.DOWNLOAD_LOCATION + "/" a = await bot.send_message(chat_id=update.chat.id, text=Translation.DOWNLOAD_START, reply_to_message_id=update.message_id) c_time = time.time() the_real_download_location = await bot.download_media( message=update.reply_to_message, file_name=download_location, progress=progress_for_pyrogram, progress_args=(Translation.DOWNLOAD_START, a, c_time)) if the_real_download_location is not None: bot.edit_message_text(text=Translation.SAVED_RECVD_DOC_FILE, chat_id=update.chat.id, message_id=a.message_id) # don't care about the extension # await bot.edit_message_text( # text=Translation.UPLOAD_START, # chat_id=update.chat.id, # message_id=a.message_id # ) logger.info(the_real_download_location) # get the correct width, height, and duration for videos greater than 10MB # ref: message from @BotSupport width = 0 height = 0 duration = 0 metadata = extractMetadata( createParser(the_real_download_location)) if metadata.has("duration"): duration = metadata.get('duration').seconds thumb_image_path = Config.DOWNLOAD_LOCATION + "/" + str( update.from_user.id) + ".jpg" if not os.path.exists(thumb_image_path): thumb_image_path = await take_screen_shot( the_real_download_location, os.path.dirname(the_real_download_location), random.randint(0, duration - 1)) logger.info(thumb_image_path) # 'thumb_image_path' will be available now metadata = extractMetadata(createParser(thumb_image_path)) if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") # get the correct width, height, and duration for videos greater than 10MB # 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.thumbnail((90, 90)) img.resize((90, height)) img.save(thumb_image_path, "JPEG") # https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#create-thumbnails # try to upload file c_time = time.time() await bot.send_document( chat_id=update.chat.id, document=the_real_download_location, thumb=thumb_image_path, caption=description, # reply_markup=reply_markup, reply_to_message_id=update.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=(Translation.UPLOAD_START, a, c_time)) try: os.remove(the_real_download_location) # os.remove(thumb_image_path) except: pass await bot.edit_message_text( text=Translation.AFTER_SUCCESSFUL_UPLOAD_MSG, chat_id=update.chat.id, message_id=a.message_id, disable_web_page_preview=True) else: await bot.send_message(chat_id=update.chat.id, text=Translation.REPLY_TO_DOC_FOR_C2V, reply_to_message_id=update.message_id)
async def split_large_files(input_file): working_directory = os.path.dirname(os.path.abspath(input_file)) new_working_directory = os.path.join(working_directory, str(time.time())) # create download directory, if not exist if not os.path.isdir(new_working_directory): os.makedirs(new_working_directory) # if input_file.upper().endswith(("MKV", "MP4", "WEBM", "MP3", "M4A", "FLAC", "WAV")): """The below logic is DERPed, so removing temporarily """ if input_file.upper().endswith(("MKV", "MP4", "WEBM")): # handle video / audio files here metadata = extractMetadata(createParser(input_file)) total_duration = 0 if metadata.has("duration"): total_duration = metadata.get('duration').seconds # proprietary logic to get the seconds to trim (at) LOGGER.info(total_duration) total_file_size = os.path.getsize(input_file) LOGGER.info(total_file_size) minimum_duration = (total_duration / total_file_size) * (MAX_TG_SPLIT_FILE_SIZE) # casting to int cuz float Time Stamp can cause errors minimum_duration = int(minimum_duration) LOGGER.info(minimum_duration) # END: proprietary start_time = 0 end_time = minimum_duration base_name = os.path.basename(input_file) input_extension = base_name.split(".")[-1] LOGGER.info(input_extension) i = 0 flag = False while end_time <= total_duration: LOGGER.info(i) # file name generate parted_file_name = "{}_PART_{}.{}".format(str(base_name), str(i).zfill(5), str(input_extension)) output_file = os.path.join(new_working_directory, parted_file_name) LOGGER.info(output_file) LOGGER.info(await cult_small_video(input_file, output_file, str(start_time), str(end_time))) LOGGER.info( f"Start time {start_time}, End time {end_time}, Itr {i}") # adding offset of 3 seconds to ensure smooth playback start_time = end_time - 3 end_time = end_time + minimum_duration i = i + 1 if (end_time > total_duration) and not flag: end_time = total_duration flag = True elif flag: break elif SP_LIT_ALGO_RITH_M.lower() == "hjs": # handle normal files here o_d_t = os.path.join(new_working_directory, os.path.basename(input_file)) o_d_t = o_d_t + "." file_genertor_command = [ "split", "--numeric-suffixes=1", "--suffix-length=5", f"--bytes={MAX_TG_SPLIT_FILE_SIZE}", input_file, o_d_t ] await run_comman_d(file_genertor_command) elif SP_LIT_ALGO_RITH_M.lower() == "rar": o_d_t = os.path.join( new_working_directory, os.path.basename(input_file), ) LOGGER.info(o_d_t) file_genertor_command = [ "rar", "a", f"-v{MAX_TG_SPLIT_FILE_SIZE}b", "-m0", o_d_t, input_file ] await run_comman_d(file_genertor_command) return new_working_directory
async def zee5_execute(bot, update): try: cb_data = update.data tg_send_type, youtube_dl_format, youtube_dl_ext = cb_data.split("|") thumb_image_path = Config.DOWNLOAD_LOCATION + \ "/" + str(update.from_user.id) + ".jpg" save_ytdl_json_path = Config.DOWNLOAD_LOCATION + \ "/" + str(update.from_user.id) + ".json" try: with open(save_ytdl_json_path, "r", encoding="utf8") as f: response_json = json.load(f) except (FileNotFoundError) as e: await bot.delete_messages( chat_id=update.message.chat.id, message_ids=update.message.message_id, revoke=True ) return False youtube_dl_url = zee5_capture.url linksplit = update.message.reply_to_message.text.split("/") videoname = linksplit[+5] logger.info(videoname) custom_file_name = videoname + ".mp4" await bot.edit_message_text( text=Translation.DOWNLOAD_START, chat_id=update.message.chat.id, message_id=update.message.message_id ) description = Translation.CUSTOM_CAPTION_UL_FILE.format(newname=custom_file_name) tmp_directory_for_each_user = Config.DOWNLOAD_LOCATION + "/" + 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 + "/" + custom_file_name command_to_exec = [] minus_f_format = youtube_dl_format + "+bestaudio" command_to_exec = [ "youtube-dl", "-c", "--max-filesize", str(Config.TG_MAX_FILE_SIZE), "-f", minus_f_format, "--hls-prefer-ffmpeg", youtube_dl_url, "-o", download_directory ] command_to_exec.append("--no-warnings") command_to_exec.append("--geo-bypass-country") command_to_exec.append("IN") start = datetime.now() process = await asyncio.create_subprocess_exec( *command_to_exec, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) stdout, stderr = await process.communicate() e_response = stderr.decode().strip() t_response = stdout.decode().strip() if os.path.isfile(download_directory): logger.info("no issues") else: logger.info("issues found, passing to sub process") command_to_exec.clear() minus_f_format = youtube_dl_format command_to_exec = [ "youtube-dl", "-c", "--max-filesize", str(Config.TG_MAX_FILE_SIZE), "-f", minus_f_format, "--hls-prefer-ffmpeg", youtube_dl_url, "-o", download_directory ] command_to_exec.append("--no-warnings") command_to_exec.append("--geo-bypass-country") command_to_exec.append("IN") start = datetime.now() process = await asyncio.create_subprocess_exec( *command_to_exec, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) stdout, stderr = await process.communicate() e_response = stderr.decode().strip() t_response = stdout.decode().strip() 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 bot.edit_message_text( chat_id=update.message.chat.id, message_id=update.message.message_id, text=error_message ) return False if t_response: os.remove(save_ytdl_json_path) end_one = datetime.now() time_taken_for_download = (end_one -start).seconds file_size = Config.TG_MAX_FILE_SIZE + 1 try: file_size = os.stat(download_directory).st_size except FileNotFoundError as exc: download_directory = os.path.splitext(download_directory)[0] + "." + "mp4" file_size = os.stat(download_directory).st_size if file_size > Config.TG_MAX_FILE_SIZE: await bot.edit_message_text( chat_id=update.message.chat.id, text=Translation.RCHD_TG_API_LIMIT.format(time_taken_for_download, humanbytes(file_size)), message_id=update.message.message_id ) else: await bot.edit_message_text( text=Translation.UPLOAD_START, chat_id=update.message.chat.id, message_id=update.message.message_id ) # get the correct width, height, and duration for videos greater than 10MB width = 0 height = 0 duration = 0 if tg_send_type != "file": metadata = extractMetadata(createParser(download_directory)) if metadata is not None: if metadata.has("duration"): duration = metadata.get('duration').seconds # get the correct width, height, and duration for videos greater than 10MB if not os.path.exists(thumb_image_path): mes = await thumb(update.from_user.id) if mes != None: m = await bot.get_messages(update.chat.id, mes.msg_id) await m.download(file_name=thumb_image_path) thumb_image_path = thumb_image_path else: try: thumb_image_path = await take_screen_shot( download_directory, os.path.dirname(download_directory), random.randint( 0, duration - 1 ) ) except: thumb_image_path = None pass else: width = 0 height = 0 metadata = extractMetadata(createParser(thumb_image_path)) if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") if tg_send_type == "vm": height = width Image.open(thumb_image_path).convert( "RGB").save(thumb_image_path) img = Image.open(thumb_image_path) img.thumbnail((90, 90)) if tg_send_type == "file": img.resize((320, height)) else: img.resize((90, height)) img.save(thumb_image_path, "JPEG") start_time = time.time() if tg_send_type == "file": await bot.send_document( chat_id=update.message.chat.id, document=download_directory, thumb=thumb_image_path, caption=description, parse_mode="HTML", # reply_markup=reply_markup, reply_to_message_id=update.message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=( Translation.UPLOAD_START, update.message, start_time ) ) elif tg_send_type == "video": await bot.send_video( chat_id=update.message.chat.id, video=download_directory, caption=description, parse_mode="HTML", duration=duration, width=width, height=height, supports_streaming=True, # reply_markup=reply_markup, thumb=thumb_image_path, reply_to_message_id=update.message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=( Translation.UPLOAD_START, update.message, start_time ) ) else: logger.info("Did this happen? :\\") try: shutil.rmtree(tmp_directory_for_each_user) except: pass try: os.remove(thumb_image_path) except: pass await bot.edit_message_text( text=Translation.AFTER_SUCCESSFUL_UPLOAD_MSG_WITH_TS, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="Support Channel", url="https://t.me/ARNextRobot")]]), chat_id=update.message.chat.id, message_id=update.message.message_id, disable_web_page_preview=True ) except: await update.reply_text("Couldn't download your video!", quote=True) logger.info('error in process')
async def rename_doc(bot, update): if update.from_user.id in Config.BANNED_USERS: await update.reply_text("You are B A N N E D") return TRChatBase(update.from_user.id, update.text, "rename") if (" " in update.text) and (update.reply_to_message is not None): cmd, file_name = update.text.split(" ", 1) if len(file_name) > 64: await update.reply_text( Translation.IFLONG_FILE_NAME.format(alimit="64", num=len(file_name))) return description = Translation.CUSTOM_CAPTION_UL_FILE download_location = Config.DOWNLOAD_LOCATION + "/" a = await bot.send_message(chat_id=update.chat.id, text=Translation.DOWNLOAD_START, reply_to_message_id=update.message_id) c_time = time.time() the_real_download_location = await bot.download_media( message=update.reply_to_message, file_name=download_location, progress=progress_for_pyrogram, progress_args=(Translation.DOWNLOAD_START, a, c_time)) if the_real_download_location is not None: try: await bot.edit_message_text( text=Translation.SAVED_RECVD_DOC_FILE, chat_id=update.chat.id, message_id=a.message_id) except: pass new_file_name = download_location + file_name os.rename(the_real_download_location, new_file_name) await bot.edit_message_text(text=Translation.UPLOAD_START, chat_id=update.chat.id, message_id=a.message_id) logger.info(the_real_download_location) thumb_image_path = Config.DOWNLOAD_LOCATION + "/" + str( update.from_user.id) + ".jpg" if not os.path.exists(thumb_image_path): mes = await get_thumb(update.from_user.id) if mes != None: m = await bot.get_messages(update.chat.id, mes.msg_id) await m.download(file_name=thumb_image_path) thumb_image_path = thumb_image_path else: thumb_image_path = None else: width = 0 height = 0 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.thumbnail((90, 90)) img.resize((320, height)) img.save(thumb_image_path, "JPEG") # https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#create-thumbnails c_time = time.time() await bot.send_document( chat_id=update.chat.id, document=new_file_name, thumb=thumb_image_path, caption=f"<b>{file_name}</b>", # reply_markup=reply_markup, reply_to_message_id=update.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=(Translation.UPLOAD_START, a, c_time)) try: os.remove(new_file_name) os.remove(thumb_image_path) except: pass await bot.edit_message_text( text=Translation.AFTER_SUCCESSFUL_UPLOAD_MSG, chat_id=update.chat.id, message_id=a.message_id, disable_web_page_preview=True) else: await bot.send_message(chat_id=update.chat.id, text=Translation.REPLY_TO_DOC_FOR_RENAME_FILE, reply_to_message_id=update.message_id)
async def upload(event): if event.fwd_from: return await event.edit("`Processing...`") input_str = event.pattern_match.group(1) if os.path.exists(input_str): if os.path.isfile(input_str): c_time = time.time() start_time = datetime.now() file_name = os.path.basename(input_str) thumb = None attributes = [] with open(input_str, "rb") as f: result = await upload_file( client=event.client, file=f, name=file_name, progress_callback=lambda d, t: asyncio.get_event_loop(). create_task( progress(d, t, event, c_time, "[FILE - UPLOAD]", input_str)), ) up_time = (datetime.now() - start_time).seconds if input_str.lower().endswith(("mp4", "mkv", "webm")): thumb = await get_video_thumb(input_str, "thumb_image.jpg") metadata = extractMetadata(createParser(input_str)) duration = 0 width = 0 height = 0 if metadata.has("duration"): duration = metadata.get("duration").seconds if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") attributes = [ DocumentAttributeVideo( duration=duration, w=width, h=height, round_message=False, supports_streaming=True, ) ] elif input_str.lower().endswith(("mp3", "flac", "wav")): metadata = extractMetadata(createParser(input_str)) 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") attributes = [ DocumentAttributeAudio( duration=duration, title=title, performer=artist, ) ] await event.client.send_file( event.chat_id, result, thumb=thumb, caption=file_name, force_document=False, allow_cache=False, reply_to=event.message.id, attributes=attributes, ) if thumb is not None: os.remove(thumb) await event.edit(f"Uploaded successfully in `{up_time}` seconds.") elif os.path.isdir(input_str): start_time = datetime.now() lst_files = [] for root, dirs, files in os.walk(input_str): for file in files: lst_files.append(os.path.join(root, file)) if len(lst_files) == 0: return await event.edit(f"`{input_str}` is empty.") await event.edit( f"Found `{len(lst_files)}` files. Now uploading...") for files in sorted(lst_files): file_name = os.path.basename(files) thumb = None attributes = [] msg = await event.reply(f"Uploading `{files}`") with open(files, "rb") as f: result = await upload_file( client=event.client, file=f, name=file_name, ) if file_name.lower().endswith(("mp4", "mkv", "webm")): thumb = await get_video_thumb(files, "thumb_image.jpg") metadata = extractMetadata(createParser(files)) duration = 0 width = 0 height = 0 if metadata.has("duration"): duration = metadata.get("duration").seconds if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") attributes = [ DocumentAttributeVideo( duration=duration, w=width, h=height, round_message=False, supports_streaming=True, ) ] elif file_name.lower().endswith(("mp3", "flac", "wav")): metadata = extractMetadata(createParser(files)) 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") attributes = [ DocumentAttributeAudio( duration=duration, title=title, performer=artist, ) ] await event.client.send_file( event.chat_id, result, thumb=thumb, caption=file_name, force_document=False, allow_cache=False, attributes=attributes, ) await msg.delete() if thumb is not None: os.remove(thumb) await event.delete() up_time = (datetime.now() - start_time).seconds await event.respond( f"Uploaded `{len(lst_files)}` files in `{input_str}` folder " f"in `{up_time}` seconds.") else: await event.edit("`404: File/Folder Not Found`")