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)
async def convert_to_audio(bot, update): if update.from_user.id not in Config.AUTH_USERS: await bot.delete_messages( chat_id=update.chat.id, message_ids=update.message_id, revoke=True ) return TRChatBase(update.from_user.id, update.text, "converttoaudio") if (update.reply_to_message is not None) and (update.reply_to_message.media 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: await 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 # convert video to audio format audio_file_location_path = the_real_download_location 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 = None else: 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_audio( chat_id=update.chat.id, audio=audio_file_location_path, caption=description, duration=duration, # performer="", # title="", # reply_markup=reply_markup, thumb=thumb_image_path, 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(thumb_image_path) os.remove(the_real_download_location) os.remove(audio_file_location_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 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 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 = "© @TGBotsZ" 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 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")): # 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 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 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 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("Scaricando ...") 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( "Trovati {} files. L'upload inizierà presto. Vuoi un caffé?".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("Caricati {} files in {} secondi.".format(uploaded, duration)) else: await udir_event.edit("404: Cartella non trovata")
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 borg.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 borg.send_file( event.chat_id, downloaded_file_name, thumb=thumb, caption= "reuploaded by [GujjuBot](https://www.github.com/japarmar/GujjuBot", 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 uploadir(udir_event): """ .uploadir """ 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 upload_single_file(message, local_file_name, caption_str, from_user, client, edit_media, yt_thumb): await asyncio.sleep(EDIT_SLEEP_TIME_OUT) local_file_name = str(Path(local_file_name).resolve()) sent_message = None start_time = time.time() # thumbnail_location = os.path.join(DOWNLOAD_LOCATION, "thumbnails", str(from_user) + ".jpg") # LOGGER.info(thumbnail_location) if UPLOAD_AS_DOC.upper() == "TRUE": # todo thumb = None thumb_image_path = None if os.path.exists(thumbnail_location): thumb_image_path = await copy_file( thumbnail_location, os.path.dirname(os.path.abspath(local_file_name))) thumb = thumb_image_path message_for_progress_display = message if not edit_media: message_for_progress_display = await message.reply_text( "Memulai upload {}".format(os.path.basename(local_file_name))) prog = Progress(from_user, client, message_for_progress_display) sent_message = await message.reply_document( document=local_file_name, thumb=thumb, caption=caption_str, parse_mode="html", disable_notification=True, progress=prog.progress_for_pyrogram, progress_args=( f"{os.path.basename(local_file_name)}", start_time, ), ) if message.message_id != message_for_progress_display.message_id: try: await message_for_progress_display.delete() except FloodWait as gf: time.sleep(gf.x) except Exception as rr: LOGGER.warning(str(rr)) os.remove(local_file_name) if thumb is not None: os.remove(thumb) else: try: message_for_progress_display = message if not edit_media: message_for_progress_display = await message.reply_text( "Memulai upload {}".format( os.path.basename(local_file_name))) prog = Progress(from_user, client, message_for_progress_display) if local_file_name.upper().endswith(("MKV", "MP4", "WEBM")): duration = 0 try: metadata = extractMetadata(createParser(local_file_name)) if metadata.has("duration"): duration = metadata.get("duration").seconds except Exception as g_e: LOGGER.info(g_e) width = 0 height = 0 thumb_image_path = None if os.path.exists(thumbnail_location): thumb_image_path = await copy_file( thumbnail_location, os.path.dirname(os.path.abspath(local_file_name)), ) else: if not yt_thumb: thumb_image_path = await take_screen_shot( local_file_name, os.path.dirname(os.path.abspath(local_file_name)), (duration / 2), ) else: req = requests.get(yt_thumb) thumb_image_path = os.path.join( os.path.dirname(os.path.abspath(local_file_name)), str(time.time()) + ".jpg", ) with open(thumb_image_path, "wb") as thum: thum.write(req.content) img = Image.open(thumb_image_path).convert("RGB") img.save(thumb_image_path, format="jpeg") # get the correct width, height, and duration for videos greater than 10MB if os.path.exists(thumb_image_path): metadata = extractMetadata( createParser(thumb_image_path)) if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") # ref: https://t.me/PyrogramChat/44663 # https://stackoverflow.com/a/21669827/4723940 Image.open(thumb_image_path).convert("RGB").save( thumb_image_path) img = Image.open(thumb_image_path) # https://stackoverflow.com/a/37631799/4723940 img.resize((320, height)) img.save(thumb_image_path, "JPEG") # https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#create-thumbnails # thumb = None if thumb_image_path is not None and os.path.isfile( thumb_image_path): thumb = thumb_image_path # send video if edit_media and message.photo: await asyncio.sleep(EDIT_SLEEP_TIME_OUT) sent_message = await message.edit_media( media=InputMediaVideo( media=local_file_name, thumb=thumb, caption=caption_str, parse_mode="html", width=width, height=height, duration=duration, supports_streaming=True, ) # quote=True, ) else: sent_message = await message.reply_video( video=local_file_name, caption=caption_str, parse_mode="html", duration=duration, width=width, height=height, thumb=thumb, supports_streaming=True, disable_notification=True, progress=prog.progress_for_pyrogram, progress_args=( f"{os.path.basename(local_file_name)}", start_time, ), ) if thumb is not None: os.remove(thumb) elif local_file_name.upper().endswith( ("MP3", "M4A", "M4B", "FLAC", "WAV")): metadata = extractMetadata(createParser(local_file_name)) duration = 0 title = "" artist = "" if metadata.has("duration"): duration = metadata.get("duration").seconds if metadata.has("title"): title = metadata.get("title") if metadata.has("artist"): artist = metadata.get("artist") thumb_image_path = None if os.path.isfile(thumbnail_location): thumb_image_path = await copy_file( thumbnail_location, os.path.dirname(os.path.abspath(local_file_name)), ) thumb = None if thumb_image_path is not None and os.path.isfile( thumb_image_path): thumb = thumb_image_path # send audio if edit_media and message.photo: await asyncio.sleep(EDIT_SLEEP_TIME_OUT) sent_message = await message.edit_media( media=InputMediaAudio( media=local_file_name, thumb=thumb, caption=caption_str, parse_mode="html", duration=duration, performer=artist, title=title, )) else: sent_message = await message.reply_audio( audio=local_file_name, caption=caption_str, parse_mode="html", duration=duration, performer=artist, title=title, thumb=thumb, disable_notification=True, progress=prog.progress_for_pyrogram, progress_args=( f"{os.path.basename(local_file_name)}", start_time, ), ) if thumb is not None: os.remove(thumb) else: thumb_image_path = None if os.path.isfile(thumbnail_location): thumb_image_path = await copy_file( thumbnail_location, os.path.dirname(os.path.abspath(local_file_name)), ) # if a file, don't upload "thumb" # this "diff" is a major derp -_- 😔😭😭 thumb = None if thumb_image_path is not None and os.path.isfile( thumb_image_path): thumb = thumb_image_path # # send document if edit_media and message.photo: sent_message = await message.edit_media( media=InputMediaDocument( media=local_file_name, thumb=thumb, caption=caption_str, parse_mode="html", )) else: sent_message = await message.reply_document( document=local_file_name, thumb=thumb, caption=caption_str, parse_mode="html", disable_notification=True, progress=prog.progress_for_pyrogram, progress_args=( f"{os.path.basename(local_file_name)}", start_time, ), ) if thumb is not None: os.remove(thumb) except MessageNotModified as oY: LOGGER.info(oY) except FloodWait as g: LOGGER.info(g) time.sleep(g.x) except Exception as e: LOGGER.info(e) await message_for_progress_display.edit_text("**GAGAL**\n" + str(e)) else: if message.message_id != message_for_progress_display.message_id: try: if sent_message is not None: await message_for_progress_display.delete() except FloodWait as gf: time.sleep(gf.x) except Exception as rr: LOGGER.warning(str(rr)) await asyncio.sleep(5) os.remove(local_file_name) return sent_message
async def 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=f"<b>{file_name}</b>", # 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= "tg://msg?text=Hai%20Friend%20%E2%9D%A4%EF%B8%8F%2C%0AToday%20i%20just%20found%20out%20an%20intresting%20and%20Powerful%20%2A%2ARename%20Bot%2A%2A%20for%20Free%F0%9F%A5%B0.%20%0A%2A%2ABot%20Link%20%3A%2A%2A%20%40Turbo_Renamer_Bot%20%F0%9F%94%A5" ) ]]), 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 rename_doc(bot, update): update_channel = Config.UPDATE_CHANNEL if update_channel: try: user = await bot.get_chat_member(update_channel, update.chat.id) if user.status == "kicked": await update.reply_text(" Sorry, You are **B A N N E D**") return except UserNotParticipant: #await update.reply_text(f"Join @{update_channel} To Use Me") await update.reply_text( text="**Please Join My Update Channel Before Using Me..**", reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton(text="Join My Updates Channel", url=f"https://t.me/{update_channel}") ]])) 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 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 rename_video(bot, update): if update.from_user.id in Config.BANNED_USERS: await bot.delete_messages(chat_id=update.chat.id, message_ids=update.message_id, revoke=True) 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 = file_name + Translation.CUSTOM_CAPTION_UL_FILE download_location = Config.DOWNLOAD_LOCATION + "/" b = 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, b, 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=b.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=b.message_id) logger.info(the_real_download_location) width = 0 height = 0 duration = 0 metadata = extractMetadata(createParser(new_file_name)) 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( new_file_name, os.path.dirname(new_file_name), random.randint(0, duration - 1)) 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_video( chat_id=update.chat.id, video=new_file_name, duration=duration, 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, b, 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=b.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 _(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("`Sedang Mencari Musik Video`") elif reply: query = str(reply.message) await event.edit("`Sedang Mencari Musik Video`") else: await event.edit("`Apa yang harus saya cari?`") return await getmusicvideo(query) l = glob.glob(("*.mp4")) + glob.glob(("*.mkv")) + glob.glob(("*.webm")) if l: await event.edit("`Video Musik Di Temukan`") else: await event.edit(f"`Maaf Saya Tidak dapat Menemukan` **{query}**") return try: 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") 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.edit(f"**{query}** `Berhasil Diunggah`") os.remove(thumb_image) os.system("rm *.mkv *.mp4 *.webm") except BaseException: os.remove(thumb_image) os.system("rm *.mkv *.mp4 *.webm") return
async def ascii(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/video`") return await event.edit("`Downloading Media..`") if reply_message.photo: IMG = await bot.download_media( reply_message, "ascii.png", ) elif ( DocumentAttributeFilename(file_name="AnimatedSticker.tgs") in reply_message.media.document.attributes ): await bot.download_media( reply_message, "ASCII.tgs", ) os.system("lottie_convert.py ASCII.tgs ascii.png") IMG = "ascii.png" elif reply_message.video: video = await bot.download_media( reply_message, "ascii.mp4", ) extractMetadata(createParser(video)) os.system("ffmpeg -i ascii.mp4 -vframes 1 -an -s 480x360 -ss 1 ascii.png") IMG = "ascii.png" else: IMG = await bot.download_media( reply_message, "ascii.png", ) try: await event.edit("`Processing..`") list = await random_color() color1 = list[0] color2 = list[1] bgcolor = bground await asciiart(IMG, color1, color2, bgcolor) cmd = event.pattern_match.group(1) if cmd == "asciis": os.system("cp ascii.png ascii.webp") ascii_file = "ascii.webp" else: ascii_file = "ascii.png" await event.client.send_file( event.chat_id, ascii_file, force_document=False, reply_to=event.reply_to_msg_id, ) await event.delete() os.system("rm *.png") os.system("rm *.webp") os.system("rm *.mp4") os.system("rm *.tgs") except BaseException as e: os.system("rm *.png") os.system("rm *.webp") os.system("rm *.mp4") os.system("rm *.tgs") 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 rename_doc(bot, update): if update.from_user.id not in Config.AUTH_USERS: bot.delete_messages( chat_id=update.chat.id, message_ids=update.message_id, revoke=True ) 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) 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 ) if "IndianMovie" in the_real_download_location: bot.edit_message_text( text=Translation.RENAME_403_ERR, chat_id=update.chat.id, message_id=a.message_id ) return new_file_name = download_location + file_name os.rename(the_real_download_location, new_file_name) 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): 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=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(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 uploadas(uas_event): """ .uploadas """ 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, "Yüklənir...", 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, "Yüklənir...", file_name))) elif spam_big_messages: await uas_event.edit("TBD: Uğursuz oldu.") return os.remove(thumb) await uas_event.edit("Yüklənmə uğurlu oldu!!") except FileNotFoundError as err: await uas_event.edit(str(err)) else: await uas_event.edit("404: Fayl tapılmadı.")
async def uploadas(uas_event): """ For .uploadas command, allows you to specify some arguments for upload. """ if not uas_event.text[0].isalpha() and uas_event.text[0] not in ("/", "#", "@", "!"): if uas_event.fwd_from: return await uas_event.edit("Caricando ...") 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): 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 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=progress, ) elif round_message: 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=progress, ) elif spam_big_messages: await uas_event.edit("TBD: Non (ancora) Implementato") return end = datetime.now() duration = (end - start).seconds os.remove(thumb) await uas_event.edit("Caricato in {} secondi.".format(duration)) except FileNotFoundError as err: await uas_event.edit(str(err)) else: await uas_event.edit("404: File Non Trovato")
async def convert_to_video(bot, update): TRChatBase(update.from_user.id, update.text, "converttovideo") if update.reply_to_message is not None: description = Translation.CUSTOM_CAPTION_UL_FILE download_location = 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 = (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_video( chat_id=update.chat.id, video=the_real_download_location, caption=description, duration=duration, width=width, height=height, supports_streaming=True, # reply_markup=reply_markup, thumb=thumb_image_path, 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 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( "😉..let me start uploading.. of {}".format( os.path.basename(local_file_name))) if local_file_name.upper().endswith(("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 # Rename sent_message = await message.reply_video( video=local_file_name, # quote=True, caption=caption_str, parse_mode="html", thumb=thumb, disable_notification=True, reply_to_message_id=message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=( "patience💁♂️ ..while trying 🙇♂️🙇♂️ to upload", message_for_progress_display, start_time)) await message.reply_text("😃 File uploaded successfully") 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=("Patience...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 # Rename 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)) await message.reply_text("😃 File uploaded successfully") 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 rename_doc(bot, update): 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) > 128: await update.reply_text( Translation.IFLONG_FILE_NAME.format(alimit="128", num=len(file_name))) return caption_str = "" caption_str += "<b>" caption_str += file_name caption_str += "</b>" if Config.CHANNEL_URL is not None: caption_str += "\n\nJoin: " caption_str += "<a href='" caption_str += f"{Config.CHANNEL_URL}" caption_str += "'>" caption_str += f"{Config.CHANNEL_URL}" caption_str += "</a>" 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 if "IndianMovie" in the_real_download_location: await bot.edit_message_text(text=Translation.RENAME_403_ERR, chat_id=update.chat.id, message_id=a.message_id) return 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): logger.info('setting thumb.jpg as thumbnail') thumb_image_path = "thumb.jpg" 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=caption_str, # 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 _(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() c_time = time.time() to_download_directory = Config.TMP_DOWNLOAD_DIRECTORY downloaded_file_name = os.path.join(to_download_directory, file_name) downloaded_file_name = await borg.download_media( reply_message, downloaded_file_name, progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress(d, t, event, c_time, "trying to download") ) ) end_one = datetime.now() ms_one = (end_one - start).seconds if os.path.exists(downloaded_file_name): thumb = None if os.path.exists(thumb_image_path): thumb = 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 borg.send_file( event.chat_id, downloaded_file_name, thumb=thumb, caption=downloaded_file_name, 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, event, c_time, "trying to upload") ) ) 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 convert_to_video(bot, update): await bot.delete_messages(chat_id=update.message.chat.id, message_ids=message1[id]) thumb_image_path = os.getcwd() + "/" + "thumbnails" + "/" + str(update.from_user.id) + ".jpg" if not os.path.exists(thumb_image_path): thumb_image_path = None description = input_file_name[id].rsplit('.', 1)[0].upper() download_location = os.path.join(os.getcwd(), "downloads", str(update.message.chat.id)) if not os.path.isdir(download_location): os.makedirs(download_location) dl_folder = [f for f in os.listdir(download_location)] for f in dl_folder: try: os.remove(os.path.join(download_location, f)) except IndexError: pass saved_file_path = download_location + "/" + input_file_name[id].replace("_", " ") a = await bot.send_message( chat_id=update.message.chat.id, text=Translation.DOWNLOAD_START, ) c_time = time.time() try: await bot.download_media( message=replied_message[id], file_name=saved_file_path, progress=progress_for_pyrogram, progress_args=( Translation.DOWNLOAD_START, a, c_time ) ) except FloodWait as e: time.sleep(e.x) if saved_file_path is not None: metadata = extractMetadata(createParser(saved_file_path)) if metadata.has("duration"): duration = metadata.get('duration').seconds await bot.edit_message_text( text=Translation.SAVED_RECVD_DOC_FILE, chat_id=update.message.chat.id, message_id=a.message_id ) time.sleep(5) await bot.edit_message_text( chat_id=update.message.chat.id, text=Translation.UPLOAD_START, message_id=a.message_id ) c_time = time.time() try: await bot.send_video( chat_id=update.message.chat.id, video=saved_file_path, duration=duration, caption=Translation.CAPTION_TEXT.format(description), thumb=thumb_image_path, supports_streaming=True, progress=progress_for_pyrogram, progress_args=( Translation.UPLOAD_START, a, c_time ) ) except FloodWait as e: time.sleep(e.x) await a.delete() await bot.send_message( chat_id=update.message.chat.id, text=Translation.MAKE_A_COPY_TEXT, reply_markup=InlineKeyboardMarkup( [ [InlineKeyboardButton("📘 Document", callback_data="d_copy"), InlineKeyboardButton("🎞 Video", callback_data="v_copy")], [InlineKeyboardButton(" Close", callback_data="clear_med")] ]) )
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("`Bentar yaa asuu , agii nyari bokep neh....`") elif reply.message: query = reply.message await event.edit("`Sabar Kimak , orang sabar boolnya lebar....`") else: await event.edit("`Apa yang gua banting?`") return getmusicvideo(query) l = glob.glob(("*.mp4")) + glob.glob(("*.mkv")) + glob.glob(("*.webm")) if l: await event.edit("`Berhasil , Selamat Bergabut Ria...`") else: await event.edit(f"Cih, Tidak Menemukan Apapun `{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("`Proses Upload Video, Sabar Pantekkk..`") 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 upload_to_tg(message: Message, dirname: str, post: Post) -> None: # pylint: disable=R0912 """ uploads downloaded post from local to telegram servers """ pto = (".jpg", ".jpeg", ".png", ".bmp") vdo = (".mkv", ".mp4", ".webm") paths = [] if post.typename == 'GraphSidecar': # upload media group captioned = False media = [] for path in natsorted(os.listdir(dirname)): ab_path = dirname + '/' + path paths.append(ab_path) if str(path).endswith(pto): if captioned: media.append(InputMediaPhoto(media=ab_path)) else: media.append( InputMediaPhoto(media=ab_path, caption=get_caption(post)[:1023])) captioned = True elif str(path).endswith(vdo): if captioned: media.append(InputMediaVideo(media=ab_path)) else: media.append( InputMediaVideo(media=ab_path, caption=get_caption(post)[:1023])) captioned = True if media: await message.client.send_media_group(message.chat.id, media) await message.client.send_media_group(Config.LOG_CHANNEL_ID, media) if post.typename == 'GraphImage': # upload a photo for path in natsorted(os.listdir(dirname)): if str(path).endswith(pto): ab_path = dirname + '/' + path paths.append(ab_path) await message.client.send_photo( message.chat.id, ab_path, caption=get_caption(post)[:1023]) await message.client.send_photo( Config.LOG_CHANNEL_ID, ab_path, caption=get_caption(post)[:1023]) if post.typename == 'GraphVideo': # upload a video for path in natsorted(os.listdir(dirname)): if str(path).endswith(vdo): ab_path = dirname + '/' + path paths.append(ab_path) thumb = await get_thumb(ab_path) duration = 0 metadata = extractMetadata(createParser(ab_path)) if metadata and metadata.has("duration"): duration = metadata.get("duration").seconds await message.client.send_video( chat_id=message.chat.id, video=ab_path, duration=duration, thumb=thumb, caption=get_caption(post)[:1023]) await message.client.send_video( chat_id=Config.LOG_CHANNEL_ID, video=ab_path, duration=duration, thumb=thumb, caption=get_caption(post)[:1023]) await remove_thumb(thumb) for del_p in paths: if os.path.lexists(del_p): os.remove(del_p)
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 rename_doc(bot, update): update_channel = Config.UPDATE_CHANNEL if update_channel: try: user = await bot.get_chat_member(update_channel, update.chat.id) if user.status == "kicked": await update.reply_text(Scripted.ACCESS_DENIED) return except UserNotParticipant: await update.reply_text(text=Scripted.JOIN_NOW_TEXT, reply_markup=InlineKeyboardMarkup( [ [ InlineKeyboardButton(text="ᴊᴏɪɴ ɴᴏᴡ 🔓", url=f"https://t.me/{Config.UPDATE_CHANNEL}") ] ] ) ) return except Exception: await update.reply_text(Scripted.CONTACT_MY_DEVELOPER) return if (" " in update.text) and (update.reply_to_message is not None): cmd, file_name = update.text.split(" ", 1) new_file = file_name[:60] + file_name[-4:] description = Scripted.CUSTOM_CAPTION.format(file_name) download_location = Config.DOWNLOAD_LOCATION + "/" c = await bot.send_message( chat_id=update.chat.id, text=Scripted.TRYING_TO_DOWNLOAD, 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=(Scripted.DOWNLOAD_START, c, c_time) ) if the_real_download_location is not None: try: await bot.edit_message_text( text=Scripted.TRYING_TO_UPLOAD, chat_id=update.chat.id, message_id=c.message_id ) except: pass new_file_name = download_location + file_name os.rename(the_real_download_location, new_file_name) 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 sthumb(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") 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") c_time = time.time() await bot.send_document( chat_id=update.chat.id, document=new_file_name, thumb=thumb_image_path, caption=description, reply_to_message_id=update.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=(Scripted.UPLOAD_START, c, c_time)) try: os.remove(the_real_download_location) os.remove(thumb_image_path) except: pass await bot.edit_message_text( text=Scripted.UPLOAD_SUCCESS, chat_id=update.chat.id, message_id=c.message_id ) else: await bot.send_message( chat_id=update.chat.id, text=Scripted.REPLY_TO_FILE, reply_to_message_id=update.message_id)
def processFile(values, filename, display_filename=False, priority=None, human=True, display=True): charset = getTerminalCharset() # Create parser try: if values.force_parser: tags = [("id", values.force_parser), None] else: tags = None parser = createParser(filename, tags=tags) except InputStreamError as err: error(str(err)) return False if not parser: error("Unable to parse file: %s" % filename) return False with parser: # Extract metadata extract_metadata = not (values.mime or values.type) if extract_metadata: try: metadata = extractMetadata(parser, values.quality) except Exception as err: error(str(err)) metadata = None if not metadata: parser.error( "Hachoir can't extract metadata, but is able to parse: %s" % filename) return False else: if values.type: result = parser.description else: result = parser.mime_type if display: # Display metadatas on stdout if extract_metadata: text = metadata.exportPlaintext(priority=priority, human=human) if not text: text = ["(no metadata, priority may be too small)"] if display_filename: for line in text: line = "%s: %s" % (filename, line) print(makePrintable(line, charset)) else: for line in text: print(makePrintable(line, charset)) else: text = result if display_filename: text = "%s: %s" % (filename, text) print(text) return True
async def _(event): if not event.reply_to_msg_id: await event.edit("`Reply Ke Media`") return reply_message = await event.get_reply_message() if not reply_message.media: await event.edit("`Reply Ke Media/Sticker`") return await event.edit("`↺ Mendownload Media.....`") if reply_message.photo: await bot.download_media( reply_message, "wc.png", ) elif (DocumentAttributeFilename(file_name="AnimatedSticker.tgs") in reply_message.media.document.attributes): await bot.download_media( reply_message, "wc.tgs", ) os.system("lottie_convert.py wc.tgs wc.png") elif reply_message.video: video = await bot.download_media( reply_message, "wc.mp4", ) extractMetadata(createParser(video)) os.system("ffmpeg -i wc.mp4 -vframes 1 -an -s 480x360 -ss 1 wc.png") else: await bot.download_media( reply_message, "wc.png", ) try: await event.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() os.system("rm *.png *.mp4 *.tgs *.webp") except BaseException as e: os.system("rm *.png *.mp4 *.tgs *.webp") return await event.edit(str(e))