async def upload_google_photos(event): if event.fwd_from: return input_str = event.pattern_match.group(2) logger.info(input_str) if not event.reply_to_msg_id and not input_str: await event.edit( "©️ <b>[DECHA]</b>\nTidak Ada Yang Akan Membantu Anda", parse_mode="html" ) return token_file = TOKEN_FILE_NAME is_cred_exists, creds = await check_creds(token_file, event) if not is_cred_exists: await event.edit("Pertama Jalankan <code>.gpsetup</code> Dulu", parse_mode="html") service = build("photoslibrary", "v1", http=creds.authorize(Http())) # create directory if not exists if not os.path.isdir(TEMP_DOWNLOAD_DIRECTORY): os.makedirs(TEMP_DOWNLOAD_DIRECTORY) file_path = None if input_str and os.path.exists(input_str): file_path = input_str elif not input_str: media_message = await event.client.get_messages( entity=event.chat_id, ids=event.reply_to_msg_id ) c_time = time.time() file_path = await media_message.download_media( file=TEMP_DOWNLOAD_DIRECTORY, progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress(d, t, event, c_time, "[DOWNLOADING]") ), ) logger.info(file_path) if not file_path: await event.edit("<b>[BERHENTI MELAKUKAN SPAM]</b>", parse_mode="html") return file_name, mime_type, file_size = file_ops(file_path) await event.edit("`File downloaded, " "`Sedang Mengumpulkan Informasi Unggahan`") async with aiohttp.ClientSession() as session: headers = { "Content-Length": "0", "Decha-Goog-Upload-Command": "start", "Decha-Goog-Upload-Content-Type": mime_type, "Decha-Goog-Upload-File-Name": file_name, "Decha-Goog-Upload-Protocol": "resumable", "Decha-Goog-Upload-Raw-Size": str(file_size), "Authorization": "Bearer " + creds.access_token, } # Step 1: Initiating an upload session step_one_response = await session.post( f"{PHOTOS_BASE_URI}/v1/uploads", headers=headers, ) if step_one_response.status != 200: await event.edit((await step_one_response.text())) return step_one_resp_headers = step_one_response.headers logger.info(step_one_resp_headers) # Step 2: Saving the session URL real_upload_url = step_one_resp_headers.get("Decha-Goog-Upload-URL") logger.info(real_upload_url) upload_granularity = int( step_one_resp_headers.get("Decha-Goog-Upload-Chunk-Granularity") ) logger.info(upload_granularity) number_of_req_s = int((file_size / upload_granularity)) logger.info(number_of_req_s) c_time = time.time() loop = asyncio.get_event_loop() async with aiofiles.open(file_path, mode="rb") as f_d: for i in range(number_of_req_s): current_chunk = await f_d.read(upload_granularity) offset = i * upload_granularity part_size = len(current_chunk) headers = { "Content-Length": str(part_size), "Decha-Goog-Upload-Command": "upload", "Decha-Goog-Upload-Offset": str(offset), "Authorization": "Bearer " + creds.access_token, } logger.info(i) logger.info(headers) response = await session.post( real_upload_url, headers=headers, data=current_chunk ) loop.create_task( progress( offset + part_size, file_size, event, c_time, "uploading(gphoto)🧐?", ) ) logger.info(response.headers) # await f_d.seek(i * upload_granularity) # await f_d.seek(upload_granularity) current_chunk = await f_d.read(upload_granularity) logger.info(number_of_req_s) headers = { "Content-Length": str(len(current_chunk)), "Decha-Goog-Upload-Command": "upload, finalize", "Decha-Goog-Upload-Offset": str(number_of_req_s * upload_granularity), "Authorization": "Bearer " + creds.access_token, } logger.info(headers) response = await session.post( real_upload_url, headers=headers, data=current_chunk ) logger.info(response.headers) final_response_text = await response.text() logger.info(final_response_text) await event.edit("`Mengunggah Foto Google, " "Mendapatkan FILE URI`") response_create_album = ( service.mediaItems() .batchCreate( body={ "newMediaItems": [ { "description": file_name, "simpleMediaItem": { "fileName": file_name, "uploadToken": final_response_text, }, } ] } ) .execute() ) logger.info(response_create_album) try: photo_url = ( response_create_album.get("newMediaItemResults")[0] .get("mediaItem") .get("productUrl") ) await event.edit(f"`[BERHASIL]`\n\nMengunggah Foto Ke Google [Lihat]({photo_url})") except Exception as e: await event.edit(str(e))
async def _(event): if event.fwd_from: return if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY): os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY) thumb = None if os.path.exists(thumb_image_path): thumb = thumb_image_path start = datetime.now() input_str = event.pattern_match.group(1) url = input_str file_name = os.path.basename(url) to_download_directory = Config.TMP_DOWNLOAD_DIRECTORY if "|" in input_str: url, file_name = input_str.split("|") url = url.strip() file_name = file_name.strip() downloaded_file_name = os.path.join(to_download_directory, file_name) downloader = SmartDL(url, downloaded_file_name, progress_bar=False) downloader.start(blocking=False) display_message = "" c_time = time.time() while not downloader.isFinished(): total_length = downloader.filesize if downloader.filesize else None downloaded = downloader.get_dl_size() now = time.time() diff = now - c_time percentage = downloader.get_progress() * 100 speed = downloader.get_speed() elapsed_time = round(diff) * 1000 progress_str = "[{0}{1}]\nProgress: {2}%".format( ''.join(["█" for i in range(math.floor(percentage / 5))]), ''.join(["░" for i in range(20 - math.floor(percentage / 5))]), round(percentage, 2)) estimated_total_time = downloader.get_eta(human=True) try: current_message = f"trying to download\n" current_message += f"URL: {url}\n" current_message += f"File Name: {file_name}\n" current_message += f"{progress_str}\n" current_message += f"{humanbytes(downloaded)} of {humanbytes(total_length)}\n" current_message += f"ETA: {estimated_total_time}" if round(diff % 10.00) == 0 and current_message != display_message: await event.edit(current_message) display_message = current_message except Exception as e: logger.info(str(e)) end = datetime.now() ms_dl = (end - start).seconds if downloader.isSuccessful(): await event.edit("Downloaded to `{}` in {} seconds.".format( downloaded_file_name, ms_dl)) if os.path.exists(downloaded_file_name): c_time = time.time() caat = await borg.send_file( event.chat_id, downloaded_file_name, force_document=True, supports_streaming=False, allow_cache=False, reply_to=event.message.id, thumb=thumb, progress_callback=lambda d, t: asyncio.get_event_loop(). create_task(progress(d, t, event, c_time, "trying to upload"))) end_two = datetime.now() os.remove(downloaded_file_name) ms_two = (end_two - end).seconds await event.delete() await caat.edit( f"__**➥ Downloaded in {ms_dl} seconds.**__\n__**➥ Uploaded in {ms_two} seconds.**__\n__**➥ Uploaded by :-**__ {DEFAULTUSER}" ) else: await event.edit("File Not Found {}".format(input_str)) else: await event.edit("Incorrect URL\n {}".format(input_str))
async def _(event): if event.fwd_from: return if not event.reply_to_msg_id: await event.edit("```Reply to any media file LOL.```") return reply_message = await event.get_reply_message() if not reply_message.media: await event.edit("reply to media file") return input_str = event.pattern_match.group(1) if input_str is None: await event.edit("`U DUMB DUDE`") return if input_str in ["mp3", "voice"]: await event.edit("`converting...`") else: await event.edit("try `.nfc voice` or`.nfc mp3`") return try: start = datetime.now() c_time = time.time() downloaded_file_name = await bot.download_media( reply_message, TEMP_DOWNLOAD_DIRECTORY, progress_callback=lambda d, t: asyncio.get_event_loop(). create_task(progress(d, t, event, c_time, "trying to download")), ) except Exception as e: # pylint:disable=C0103,W0703 await event.edit(str(e)) else: end = datetime.now() ms = (end - start).seconds await event.edit("Downloaded to `{}` in {} seconds.".format( downloaded_file_name, ms)) new_required_file_name = "" new_required_file_caption = "" command_to_run = [] voice_note = False supports_streaming = False if input_str == "voice": new_required_file_caption = "voice_" + str(round( time.time())) + ".opus" new_required_file_name = (TEMP_DOWNLOAD_DIRECTORY + "/" + new_required_file_caption) command_to_run = [ "ffmpeg", "-i", downloaded_file_name, "-map", "0:a", "-codec:a", "libopus", "-b:a", "100k", "-vbr", "on", new_required_file_name, ] voice_note = True supports_streaming = True elif input_str == "mp3": new_required_file_caption = "mp3_" + str(round( time.time())) + ".mp3" new_required_file_name = (TEMP_DOWNLOAD_DIRECTORY + "/" + new_required_file_caption) command_to_run = [ "ffmpeg", "-i", downloaded_file_name, "-vn", new_required_file_name, ] voice_note = False supports_streaming = True else: await event.edit("not supported") os.remove(downloaded_file_name) return logging.info(command_to_run) # TODO: re-write create_subprocess_exec 😉 process = await asyncio.create_subprocess_exec( *command_to_run, # 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() stderr.decode().strip() stdout.decode().strip() os.remove(downloaded_file_name) if os.path.exists(new_required_file_name): end_two = datetime.now() force_document = False await bot.send_file( entity=event.chat_id, file=new_required_file_name, allow_cache=False, silent=True, force_document=force_document, voice_note=voice_note, supports_streaming=supports_streaming, progress_callback=lambda d, t: asyncio.get_event_loop(). create_task(progress(d, t, event, c_time, "trying to upload")), ) (end_two - end).seconds os.remove(new_required_file_name) await event.delete()
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 download_video(v_url): url = v_url.pattern_match.group(2) type = v_url.pattern_match.group(1).lower() await v_url.edit("`Bersiap untuk mengunduh...`") if type == "aud": opts = { "format": "bestaudio", "addmetadata": True, "key": "FFmpegMetadata", "writethumbnail": True, "prefer_ffmpeg": True, "geo_bypass": True, "nocheckcertificate": True, "postprocessors": [{ "key": "FFmpegExtractAudio", "preferredcodec": "mp3", "preferredquality": "320", }], "outtmpl": "%(id)s.mp3", "quiet": True, "logtostderr": False, } video = False song = True elif type == "vid": opts = { "format": "best", "addmetadata": True, "key": "FFmpegMetadata", "prefer_ffmpeg": True, "geo_bypass": True, "nocheckcertificate": True, "postprocessors": [{ "key": "FFmpegVideoConvertor", "preferedformat": "mp4" }], "outtmpl": "%(id)s.mp4", "logtostderr": False, "quiet": True, } song = False video = True try: await v_url.edit("`Mengambil data, harap tunggu..`") with YoutubeDL(opts) as rip: rip_data = rip.extract_info(url) except DownloadError as DE: return await v_url.edit(f"`{str(DE)}`") except ContentTooShortError: return await v_url.edit("`The download content was too short.`") except GeoRestrictedError: return await v_url.edit( "`Video is not available from your geographic location " "due to geographic restrictions imposed by a website.`") except MaxDownloadsReached: return await v_url.edit("`Max-downloads limit has been reached.`") except PostProcessingError: return await v_url.edit("`There was an error during post processing.`") except UnavailableVideoError: return await v_url.edit( "`Media is not available in the requested format.`") except XAttrMetadataError as XAME: return await v_url.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`") except ExtractorError: return await v_url.edit("`There was an error during info extraction.`") except Exception as e: return await v_url.edit(f"{str(type(e)): {str(e)}}") c_time = time.time() if song: await v_url.edit(f"`Bersiap mengunggah lagu:`\n**{rip_data['title']}**" ) await v_url.client.send_file( v_url.chat_id, f"{rip_data['id']}.mp3", supports_streaming=True, attributes=[ DocumentAttributeAudio( duration=int(rip_data["duration"]), title=str(rip_data["title"]), performer=str(rip_data["uploader"]), ) ], progress_callback=lambda d, t: asyncio.get_event_loop(). create_task( progress(d, t, v_url, c_time, "Mengupload..", f"{rip_data['title']}.mp3")), ) os.remove(f"{rip_data['id']}.mp3") await v_url.delete() elif video: await v_url.edit( f"`Bersiap mengupload video:`\n**{rip_data['title']}**") await v_url.client.send_file( v_url.chat_id, f"{rip_data['id']}.mp4", supports_streaming=True, caption=rip_data["title"], progress_callback=lambda d, t: asyncio.get_event_loop(). create_task( progress(d, t, v_url, c_time, "Mengupload..", f"{rip_data['title']}.mp4")), ) os.remove(f"{rip_data['id']}.mp4") await v_url.delete()
async def uploadir(udir_event): input_str = udir_event.pattern_match.group(1) await borg.send_message(udir_event.chat_id, input_str) if os.path.exists(input_str): await udir_event.edit( f"Gathering file details in directory `{input_str}`") lst_of_files = [] lst_of_files = await catlst_of_files(input_str) 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, "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, "Uploading...", 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 _(event): if event.fwd_from: return mone = await event.reply("Processing ...") 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() 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 to `{}` in {} seconds.".format(downloaded_file_name, ms)) elif input_str: start = datetime.now() url = input_str file_name = os.path.basename(url) to_download_directory = Config.TMP_DOWNLOAD_DIRECTORY if "|" in input_str: url, file_name = input_str.split("|") url = url.strip() file_name = file_name.strip() downloaded_file_name = os.path.join(to_download_directory, file_name) downloader = SmartDL(url, downloaded_file_name, progress_bar=False) downloader.start(blocking=False) c_time = time.time() while not downloader.isFinished(): total_length = downloader.filesize if downloader.filesize else None downloaded = downloader.get_dl_size() display_message = "" now = time.time() diff = now - c_time percentage = downloader.get_progress() * 100 speed = downloader.get_speed() elapsed_time = round(diff) * 1000 progress_str = "{0}{1}\nProgress: {2}%".format( ''.join(["█" for i in range(math.floor(percentage / 5))]), ''.join(["░" for i in range(20 - math.floor(percentage / 5))]), round(percentage, 2)) estimated_total_time = downloader.get_eta(human=True) try: current_message = f"trying to download\nURL: {url}\nFile Name: {file_name}\n{progress_str}\n{humanbytes(downloaded)} of {humanbytes(total_length)}\nETA: {estimated_total_time}" if round(diff % 10.00) == 0 and current_message != display_message: await mone.edit(current_message) display_message = current_message except Exception as e: logger.info(str(e)) end = datetime.now() ms = (end - start).seconds if downloader.isSuccessful(): await mone.edit("Downloaded to `{}` in {} seconds.".format(downloaded_file_name, ms)) else: await mone.edit("Incorrect URL\n {}".format(input_str)) else: await mone.edit("Reply to a message to download to my local server.")
async def download(gdrive, service, uri=None): global is_cancelled reply = "" """ - Download files to local then upload - """ if not isdir(TEMP_DOWNLOAD_DIRECTORY): os.makedirs(TEMP_DOWNLOAD_DIRECTORY) required_file_name = None if uri: full_path = os.getcwd() + TEMP_DOWNLOAD_DIRECTORY.strip(".") if isfile(uri) and uri.endswith(".torrent"): downloads = aria2.add_torrent(uri, uris=None, options={"dir": full_path}, position=None) else: uri = [uri] downloads = aria2.add_uris(uri, options={"dir": full_path}, position=None) gid = downloads.gid await check_progress_for_dl(gdrive, gid, previous=None) file = aria2.get_download(gid) filename = file.name if file.followed_by_ids: new_gid = await check_metadata(gid) await check_progress_for_dl(gdrive, new_gid, previous=None) try: required_file_name = TEMP_DOWNLOAD_DIRECTORY + filenames except Exception: required_file_name = TEMP_DOWNLOAD_DIRECTORY + filename else: try: current_time = time.time() is_cancelled = False downloaded_file_name = await gdrive.client.download_media( await gdrive.get_reply_message(), TEMP_DOWNLOAD_DIRECTORY, progress_callback=lambda d, t: asyncio.get_event_loop(). create_task( progress( d, t, gdrive, current_time, "[FILE - DOWNLOAD]", is_cancelled=is_cancelled, )), ) except CancelProcess: reply += ("`[FILE - DIBATALKAN]`\n\n" "`Status` : **OK** - sinyal yang diterima dibatalkan.") return reply else: required_file_name = downloaded_file_name try: file_name = await get_raw_name(required_file_name) except AttributeError: reply += "`[MASUK- ERROR]`\n\n" "`Status` : **BAD**\n" return reply mimeType = await get_mimeType(required_file_name) try: status = "[FILE - UPLOAD]" if isfile(required_file_name): try: result = await upload(gdrive, service, required_file_name, file_name, mimeType) except CancelProcess: reply += ( "`[FILE - DIBATALKAN]`\n\n" "`Status` : **OK** - sinyal yang diterima dibatalkan.") return reply else: reply += (f"`{status}`\n\n" f"`Nama :` `{file_name}`\n" f"`Ukuran :` `{humanbytes(result[0])}`\n" f"`Link :` [{file_name}]({result[1]})\n" "`Status :` **OK** - Berhasil diunggah.\n\n") return reply else: status = status.replace("[FILE", "[FOLDER") global parent_Id folder = await create_dir(service, file_name) parent_Id = folder.get("id") webViewURL = "https://drive.google.com/drive/folders/" + parent_Id try: await task_directory(gdrive, service, required_file_name) except CancelProcess: reply += ( "`[FOLDER - DIBATALKAN]`\n\n" "`Status` : **OK** - sinyal yang diterima dibatalkan.") await reset_parentId() return reply except Exception: await reset_parentId() else: reply += (f"`{status}`\n\n" f"[{nama-file}]({webViewURL})\n" "`Status` : **OK** - Berhasil Diunggah.\n\n") await reset_parentId() return reply except Exception as e: status = status.replace("DOWNLOAD]", "ERROR]") reply += (f"`{status}`\n\n" "`Status` : **GAGAL**\n" f"`Alasan` : `{str(e)}`\n\n") return reply return
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("`𝕄𝕖𝕟𝕔𝕒𝕣𝕚 𝕄𝕦𝕤𝕚𝕜 𝕍𝕚𝕕𝕖𝕠..`") elif reply: query = str(reply.message) await event.edit("`𝕄𝕖𝕟𝕔𝕒𝕣𝕚 𝕄𝕦𝕤𝕚𝕜 𝕍𝕚𝕕𝕖𝕠..`") else: await event.edit("`ᴀᴘᴀ ʏᴀɴɢ ʜᴀʀᴜꜱ ꜱᴀʏᴀ ᴄᴀʀɪ?`") return await getmusicvideo(query) l = glob.glob(("*.mp4")) + glob.glob(("*.mkv")) + glob.glob(("*.webm")) if l: await event.edit("`𝕆𝕂, 𝕍𝕚𝕕𝕖𝕠 𝕄𝕦𝕤𝕚𝕜 𝕕𝕚 𝕋𝕖𝕞𝕦𝕜𝕒𝕟..`") else: await event.edit(f"`ᴍᴀᴀꜰ ꜱᴀʏᴀ ᴛɪᴅᴀᴋ ᴅᴀᴘᴀᴛ ᴍᴇɴᴇᴍᴜᴋᴀɴ` **{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}** `𝕌𝕡𝕝𝕠𝕒𝕕𝕖𝕕 𝕊𝕦𝕔𝕔𝕖𝕤𝕤𝕗𝕦𝕝𝕝𝕪..!`") 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 download(target_file): """For .download command, download files to the userbot's server.""" await target_file.edit("`Processing...`") input_str = target_file.pattern_match.group(1) replied = await target_file.get_reply_message() if not os.path.isdir(TEMP_DOWNLOAD_DIRECTORY): os.makedirs(TEMP_DOWNLOAD_DIRECTORY) if input_str: url = input_str file_name = unquote_plus(os.path.basename(url)) if "|" in input_str: url, file_name = input_str.split("|") url = url.strip() # https://stackoverflow.com/a/761825/4723940 file_name = file_name.strip() head, tail = os.path.split(file_name) if head: if not os.path.isdir( os.path.join(TEMP_DOWNLOAD_DIRECTORY, head)): os.makedirs(os.path.join(TEMP_DOWNLOAD_DIRECTORY, head)) file_name = os.path.join(head, tail) downloaded_file_name = TEMP_DOWNLOAD_DIRECTORY + "" + file_name downloader = SmartDL(url, downloaded_file_name, progress_bar=False) downloader.start(blocking=False) c_time = time.time() display_message = None while not downloader.isFinished(): status = downloader.get_status().capitalize() total_length = downloader.filesize if downloader.filesize else None downloaded = downloader.get_dl_size() now = time.time() diff = now - c_time percentage = downloader.get_progress() * 100 speed = downloader.get_speed() progress_str = "[{}{}] `{}%`".format( "".join(["●" for i in range(math.floor(percentage / 10))]), "".join(["○" for i in range(10 - math.floor(percentage / 10))]), round(percentage, 2), ) estimated_total_time = downloader.get_eta(human=True) try: current_message = ( f"`Name` : `{file_name}`\n" "Status" f"\n**{status}**... | {progress_str}" f"\n{humanbytes(downloaded)} of {humanbytes(total_length)}" f" @ {humanbytes(speed)}" f"\n`ETA` -> {estimated_total_time}") if round(diff % 15.00) == 0 and current_message != display_message: await target_file.edit(current_message) display_message = current_message except Exception as e: LOGS.info(str(e)) if downloader.isSuccessful(): await target_file.edit( f"Downloaded to `{downloaded_file_name}` successfully !!") else: await target_file.edit(f"Incorrect URL\n{url}") elif replied: if not replied.media: return await target_file.edit("`Reply to file or media `") try: media = replied.media if hasattr(media, "document"): file = media.document mime_type = file.mime_type filename = replied.file.name if not filename: if "audio" in mime_type: filename = ("audio_" + datetime.now().isoformat("_", "seconds") + ".ogg") elif "video" in mime_type: filename = ("video_" + datetime.now().isoformat("_", "seconds") + ".mp4") outdir = TEMP_DOWNLOAD_DIRECTORY + filename c_time = time.time() start_time = datetime.now() with open(outdir, "wb") as f: result = await download_file( client=target_file.client, location=file, out=f, progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task( progress(d, t, target_file, c_time, "[DOWNLOAD]", input_str)), ) else: start_time = datetime.now() result = await target_file.client.download_media( media, TEMP_DOWNLOAD_DIRECTORY) dl_time = (datetime.now() - start_time).seconds except Exception as e: # pylint:disable=C0103,W0703 await target_file.edit(str(e)) else: try: await target_file.edit( f"Downloaded to `{result.name}` in `{dl_time}` seconds.") except AttributeError: await target_file.edit( f"Downloaded to `{result}` in `{dl_time}` seconds.") else: await target_file.edit("See `.help download` for more info.")
async def _(event): if event.fwd_from: return mone = await event.reply("Processing ...") input_str = event.pattern_match.group(1) thumb = None file_name = input_str if os.path.exists(file_name): if not file_name.endswith((".mkv", ".mp4", ".mp3", ".flac")): await mone.edit("Sorry. But I don't think {} is a streamable file." .format(file_name) + " Please try again.\n" + "**Supported Formats**: MKV, MP4, MP3, FLAC") return False if os.path.exists(thumb_image_path): thumb = thumb_image_path else: thumb = get_video_thumb(file_name, thumb_image_path) start = datetime.now() metadata = extractMetadata(createParser(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, 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)) else: await mone.edit("404: File Not Found")
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, _, files in os.walk(input_str): for file in files: lst_files.append(os.path.join(root, file)) if not lst_files: return await event.edit(f"`{input_str}` is empty.") await event.edit( f"Found `{len(lst_files)}` files. Now uploading...") for files in os_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`")
async def _(event): if event.fwd_from: return mone = await event.edit("Processing ...") 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 = True supports_streaming = False 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 download_video(v_url): """ For .rip 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("`Persiapan untuk diunduh...`") if type == "audio": opts = { "format": "bestaudio", "addmetadata": True, "key": "FFmpegMetadata", "writethumbnail": True, "prefer_ffmpeg": True, "geo_bypass": True, "nocheckcertificate": True, "postprocessors": [ { "key": "FFmpegExtractAudio", "preferredcodec": "mp3", "preferredquality": "320", } ], "outtmpl": "%(id)s.mp3", "quiet": True, "logtostderr": False, } video = False song = True elif type == "video": opts = { "format": "best", "addmetadata": True, "key": "FFmpegMetadata", "prefer_ffmpeg": True, "geo_bypass": True, "nocheckcertificate": True, "postprocessors": [ {"key": "FFmpegVideoConvertor", "preferedformat": "mp4"} ], "outtmpl": "%(id)s.mp4", "logtostderr": False, "quiet": True, } song = False video = True try: await v_url.edit("`Mengambil data, harap tunggu..`") with YoutubeDL(opts) as rip: rip_data = rip.extract_info(url) except DownloadError as DE: return await v_url.edit(f"`{str(DE)}`") except ContentTooShortError: return await v_url.edit("`Konten unduhan terlalu pendek.`") except GeoRestrictedError: return await v_url.edit( "`Video tidak tersedia dari lokasi geografis Anda " "karena batasan geografis yang diberlakukan oleh situs web.`" ) except MaxDownloadsReached: return await v_url.edit("`Batas unduhan maksimal telah tercapai.`") except PostProcessingError: return await v_url.edit("`Ada kesalahan selama proses posting.`") except UnavailableVideoError: return await v_url.edit("`Media tidak tersedia dalam format yang diminta.`") except XAttrMetadataError as XAME: return await v_url.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`") except ExtractorError: return await v_url.edit("`Terjadi kesalahan selama ekstraksi info.`") except Exception as e: return await v_url.edit(f"{str(type(e)): {str(e)}}") c_time = time.time() if song: await v_url.edit(f"`Persiapan untuk upload lagu:`\n**{rip_data['title']}**") await v_url.client.send_file( v_url.chat_id, f"{rip_data['id']}.mp3", supports_streaming=True, attributes=[ DocumentAttributeAudio( duration=int(rip_data["duration"]), title=str(rip_data["title"]), performer=str(rip_data["uploader"]), ) ], progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress(d, t, v_url, c_time, "Uploading..", f"{rip_data['title']}.mp3") ), ) os.remove(f"{rip_data['id']}.mp3") await v_url.delete() elif video: await v_url.edit(f"`Persiapan untuk upload lagu:`\n**{rip_data['title']}**") await v_url.client.send_file( v_url.chat_id, f"{rip_data['id']}.mp4", supports_streaming=True, caption=rip_data["title"], progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress(d, t, v_url, c_time, "Uploading..", f"{rip_data['title']}.mp4") ), ) os.remove(f"{rip_data['id']}.mp4") await v_url.delete()
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("`Mohon Menunggu, Sedang Mencari Video Anda....`") elif reply.message: query = reply.message await event.edit("`Mohon Menunggu, Sedang Mencari Video Anda....`") else: await event.edit("`Apa Yang Harus Saya Temukan?`") return getmusicvideo(query) l = glob.glob(("*.mp4")) + glob.glob(("*.mkv")) + glob.glob(("*.webm")) if l: await event.edit("`Yaps.. Saya Menemukannya...`") else: await event.edit(f"Maaf..! Saya Tidak Menemukan Apapun Pencarian `{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("`Mengunggah Video.. Mohon Menunggu..`") 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 ff_mpeg_trim_cmd(event): if event.fwd_from: return if not os.path.exists(FF_MPEG_DOWN_LOAD_MEDIA_PATH): await edit_delete( event, f"a media file needs to be download, and save to the following path: `{FF_MPEG_DOWN_LOAD_MEDIA_PATH}`", ) return reply_to_id = await reply_id(event) webevent = await edit_or_reply(event, "`Triming the media......`") current_message_text = event.raw_text cmt = current_message_text.split(" ") start = datetime.now() if len(cmt) == 3: # output should be video cmd, start_time, end_time = cmt o = await cult_small_video( FF_MPEG_DOWN_LOAD_MEDIA_PATH, Config.TMP_DOWNLOAD_DIRECTORY, start_time, end_time, ) if o is None: return await edit_delete( webevent, f"**Error : **`Can't complete the process`" ) try: c_time = time.time() await event.client.send_file( event.chat_id, o, caption=" ".join(cmt[1:]), force_document=False, supports_streaming=True, allow_cache=False, reply_to=reply_to_id, progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress(d, t, webevent, c_time, "trying to upload") ), ) os.remove(o) except Exception as e: return await edit_delete(webevent, f"**Error : **`{e}`") elif len(cmt) == 2: # output should be image cmd, start_time = cmt o = await take_screen_shot( FF_MPEG_DOWN_LOAD_MEDIA_PATH, Config.TMP_DOWNLOAD_DIRECTORY, start_time ) if o is None: return await edit_delete( webevent, f"**Error : **`Can't complete the process`" ) try: c_time = time.time() await event.client.send_file( event.chat_id, o, caption=" ".join(cmt[1:]), force_document=True, supports_streaming=True, allow_cache=False, reply_to=event.message.id, progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress(d, t, webevent, c_time, "trying to upload") ), ) os.remove(o) except Exception as e: return await edit_delete(webevent, f"**Error : **`{e}`") else: await edit_delete(webevent, "RTFM") return end = datetime.now() ms = (end - start).seconds await edit_delete(webevent, f"`Completed Process in {ms} seconds`", 3)
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("`Mencari Musik Video..`") elif reply: query = str(reply.message) await event.edit("`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("`OK, 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}** `Uploaded Successfully..!`") 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 download_video(v_url): """ For .rip 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...`") if type == "audio": opts = { "format": "bestaudio", "addmetadata": True, "key": "FFmpegMetadata", "writethumbnail": True, "prefer_ffmpeg": True, "geo_bypass": True, "nocheckcertificate": True, "postprocessors": [ { "key": "FFmpegExtractAudio", "preferredcodec": "mp3", "preferredquality": "320", } ], "outtmpl": "%(id)s.mp3", "quiet": True, "logtostderr": False, "external_downloader": "aria2c", } video = False song = True elif type == "video": opts = { "format": "best", "addmetadata": True, "key": "FFmpegMetadata", "prefer_ffmpeg": True, "geo_bypass": True, "nocheckcertificate": True, "postprocessors": [ {"key": "FFmpegVideoConvertor", "preferedformat": "mp4"} ], "outtmpl": "%(id)s.mp4", "logtostderr": False, "quiet": True, "external_downloader": "aria2c", } song = False video = True try: await v_url.edit("`Fetching data, please wait..`") with YoutubeDL(opts) as rip: rip_data = rip.extract_info(url) except DownloadError as DE: return await v_url.edit(f"`{str(DE)}`") except ContentTooShortError: return await v_url.edit("`The download content was too short.`") except GeoRestrictedError: return await v_url.edit( "`Video is not available from your geographic location " "due to geographic restrictions imposed by a website.`" ) except MaxDownloadsReached: return await v_url.edit("`Max-downloads limit has been reached.`") except PostProcessingError: return await v_url.edit("`There was an error during post processing.`") except UnavailableVideoError: return await v_url.edit("`Media is not available in the requested format.`") except XAttrMetadataError as XAME: return await v_url.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`") except ExtractorError: return await v_url.edit("`There was an error during info extraction.`") except Exception as e: return await v_url.edit(f"{str(type(e)): {str(e)}}") c_time = time.time() if song: await v_url.edit( f"`Preparing to upload song:`\n**{rip_data['title']}**" f"\nby **{rip_data['uploader']}**" ) with open(rip_data["id"] + ".mp3", "rb") as f: result = await upload_file( client=v_url.client, file=f, name=f"{rip_data['id']}.mp3", progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress( d, t, v_url, c_time, "Uploading..", f"{rip_data['title']}.mp3" ) ), ) img_extensions = ["jpg", "jpeg", "webp"] img_filenames = [ fn_img for fn_img in os.listdir() if any(fn_img.endswith(ext_img) for ext_img in img_extensions) ] thumb_image = img_filenames[0] await v_url.client.send_file( v_url.chat_id, result, supports_streaming=True, attributes=[ DocumentAttributeAudio( duration=int(rip_data["duration"]), title=str(rip_data["title"]), performer=str(rip_data["uploader"]), ) ], thumb=thumb_image, ) os.remove(thumb_image) os.remove(f"{rip_data['id']}.mp3") await v_url.delete() elif video: await v_url.edit( f"`Preparing to upload video:`\n**{rip_data['title']}**" f"\nby **{rip_data['uploader']}**" ) thumb_image = await get_video_thumb(rip_data["id"] + ".mp4", "thumb.png") with open(rip_data["id"] + ".mp4", "rb") as f: result = await upload_file( client=v_url.client, file=f, name=f"{rip_data['id']}.mp4", progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress( d, t, v_url, c_time, "Uploading..", f"{rip_data['title']}.mp4" ) ), ) await v_url.client.send_file( v_url.chat_id, result, thumb=thumb_image, attributes=[ DocumentAttributeVideo( duration=rip_data["duration"], w=rip_data["width"], h=rip_data["height"], supports_streaming=True, ) ], caption=rip_data["title"], ) os.remove(f"{rip_data['id']}.mp4") os.remove(thumb_image) await v_url.delete()
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 bot.download_file(reply_message.media) await event.edit("`Downloading Media..`") if event.is_reply: data = await check_media(reply_message) if isinstance(data, bool): await event.edit("`Unsupported Files...`") return else: await event.edit("`Reply to Any Media Sur`") return 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) file_name = "glitch.png" to_download_directory = TEMP_DOWNLOAD_DIRECTORY downloaded_file_name = os.path.join(to_download_directory, file_name) downloaded_file_name = await bot.download_media( reply_message, downloaded_file_name, ) glitch_file = downloaded_file_name 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() os.remove(Glitched) 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)
async def _(event): if event.fwd_from: return input_str = event.pattern_match.group(1) reply_message = await event.get_reply_message() if reply_message is None: await event.edit( "reply to a media to use the `nfc` operation.\nInspired by @FileConverterBot" ) return await event.edit("trying to download media file, to my local") try: start = datetime.now() # c_time = time.ctime() 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, event, c_time, "trying to download")), ) except Exception as e: # pylint:disable=C0103,W0703 await event.edit(str(e)) else: end = datetime.now() ms = (end - start).seconds await event.edit("Downloaded to `{}` in {} seconds.".format( downloaded_file_name, ms)) new_required_file_name = "" new_required_file_caption = "" command_to_run = [] force_document = False voice_note = False supports_streaming = False if input_str == "voice": new_required_file_caption = "NLFC_" + str(round( time.time())) + ".opus" new_required_file_name = (Config.TMP_DOWNLOAD_DIRECTORY + "/" + new_required_file_caption) command_to_run = [ "ffmpeg", "-i", downloaded_file_name, "-map", "0:a", "-codec:a", "libopus", "-b:a", "100k", "-vbr", "on", new_required_file_name, ] voice_note = True supports_streaming = True elif input_str == "mp3": new_required_file_caption = "NLFC_" + str(round( time.time())) + ".mp3" new_required_file_name = (Config.TMP_DOWNLOAD_DIRECTORY + "/" + new_required_file_caption) command_to_run = [ "ffmpeg", "-i", downloaded_file_name, "-vn", new_required_file_name, ] voice_note = False supports_streaming = True else: await event.edit("not supported") os.remove(downloaded_file_name) return logger.info(command_to_run) # TODO: re-write create_subprocess_exec 😉 process = await asyncio.create_subprocess_exec( *command_to_run, # 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() stderr.decode().strip() stdout.decode().strip() os.remove(downloaded_file_name) if os.path.exists(new_required_file_name): end_two = datetime.now() await borg.send_file( entity=event.chat_id, file=new_required_file_name, caption=new_required_file_caption, allow_cache=False, silent=True, force_document=force_document, voice_note=voice_note, supports_streaming=supports_streaming, progress_callback=lambda d, t: asyncio.get_event_loop(). create_task(progress(d, t, event, c_time, "trying to upload")), ) ms_two = (end_two - end).seconds os.remove(new_required_file_name) await event.edit(f"converted in {ms_two} seconds")
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 _(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 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: caat = await borg.send_file(event.chat_id, downloaded_file_name, thumb=thumb, caption="reuploaded by cat", 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.delete() await caat.edit( f"__**➥ Downloaded in {ms_one} seconds.**__\n__**➥ Uploaded in {ms_two} seconds.**__\n__**➥ Uploaded by :-**__ {DEFAULTUSER}" ) 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 download(target_file): """ For .download command, download files to the userbot's server. """ await target_file.edit("Processing ...") input_str = target_file.pattern_match.group(1) if not os.path.isdir(TEMP_DOWNLOAD_DIRECTORY): os.makedirs(TEMP_DOWNLOAD_DIRECTORY) if "|" in input_str: url, file_name = input_str.split("|") url = url.strip() # https://stackoverflow.com/a/761825/4723940 file_name = file_name.strip() head, tail = os.path.split(file_name) if head: if not os.path.isdir(os.path.join(TEMP_DOWNLOAD_DIRECTORY, head)): os.makedirs(os.path.join(TEMP_DOWNLOAD_DIRECTORY, head)) file_name = os.path.join(head, tail) downloaded_file_name = TEMP_DOWNLOAD_DIRECTORY + "/" + file_name downloader = SmartDL(url, downloaded_file_name, progress_bar=False) downloader.start(blocking=False) c_time = time.time() display_message = None while not downloader.isFinished(): status = downloader.get_status().capitalize() total_length = downloader.filesize if downloader.filesize else None downloaded = downloader.get_dl_size() now = time.time() diff = now - c_time percentage = downloader.get_progress() * 100 speed = downloader.get_speed() progress_str = "[{0}{1}] `{2}%`".format( "".join(["■" for i in range(math.floor(percentage / 10))]), "".join(["▨" for i in range(10 - math.floor(percentage / 10))]), round(percentage, 2), ) estimated_total_time = downloader.get_eta(human=True) try: current_message = ( f"`Name` : `{file_name}`\n" "Status" f"\n**{status}**... | {progress_str}" f"\n{humanbytes(downloaded)} of {humanbytes(total_length)}" f" @ {speed}" f"\n`ETA` -> {estimated_total_time}") if round(diff % 10.00) == 0 and current_message != display_message: await target_file.edit(current_message) display_message = current_message except Exception as e: LOGS.info(str(e)) if downloader.isSuccessful(): await target_file.edit("Downloaded to `{}` successfully !!".format( downloaded_file_name)) else: await target_file.edit("Incorrect URL\n{}".format(url)) elif target_file.reply_to_msg_id: try: c_time = time.time() downloaded_file_name = await target_file.client.download_media( await target_file.get_reply_message(), TEMP_DOWNLOAD_DIRECTORY, progress_callback=lambda d, t: asyncio.get_event_loop(). create_task(progress(d, t, target_file, c_time, "[DOWNLOAD]")), ) except Exception as e: # pylint:disable=C0103,W0703 await target_file.edit(str(e)) else: await target_file.edit("Downloaded to `{}` successfully !!".format( downloaded_file_name)) else: await target_file.edit( "Reply to a message to download to my local server.")
async def youtube_play(message): query = message.pattern_match.group(2) type = message.pattern_match.group(1) if not query: await message.edit("`Enter query to download`") await message.edit("`Processing...`") try: results = json.loads(YoutubeSearch(query, max_results=7).to_json()) except KeyError: return await message.edit( "`Youtube Search gone retard.\nCan't search this query!`" ) url = f"https://www.youtube.com{results['videos'][0]['url_suffix']}" await message.edit('`Preparing to download...`') if type == "ytmusic" or type == "play": opts = { "format": "bestaudio", "addmetadata": True, "key": "FFmpegMetadata", "writethumbnail": True, "prefer_ffmpeg": True, "geo_bypass": True, "nocheckcertificate": True, "postprocessors": [ { "key": "FFmpegExtractAudio", "preferredcodec": "mp3", "preferredquality": "320", } ], "outtmpl": "%(id)s.mp3", "quiet": True, "logtostderr": False, } video = False song = True elif type == "ytvideo": opts = { "format": "best", "addmetadata": True, "key": "FFmpegMetadata", "prefer_ffmpeg": True, "geo_bypass": True, "nocheckcertificate": True, "postprocessors": [ {"key": "FFmpegVideoConvertor", "preferedformat": "mp4"} ], "outtmpl": "%(id)s.mp4", "logtostderr": False, "quiet": True, } song = False video = True try: await message.edit("`Fetching data, please wait..`") with YoutubeDL(opts) as rip: rip_data = rip.extract_info(url) except DownloadError as DE: return await message.edit(f"`{str(DE)}`") except ContentTooShortError: return await message.edit("`The download content was too short.`") except GeoRestrictedError: return await message.edit( "`Video is not available from your geographic location " "due to geographic restrictions imposed by a website.`" ) except MaxDownloadsReached: return await message.edit("`Max-downloads limit has been reached.`") except PostProcessingError: return await message.edit("`There was an error during post processing.`") except UnavailableVideoError: return await message.edit("`Media is not available in the requested format.`") except XAttrMetadataError as XAME: return await message.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`") except ExtractorError: return await message.edit("`There was an error during info extraction.`") except Exception as e: return await message.edit(f"{str(type(e)): {str(e)}}") c_time = time.time() if song: await message.edit(f"`Preparing to upload song:`\n**{rip_data['title']}**") await message.client.send_file( message.chat_id, f"{rip_data['id']}.mp3", supports_streaming=True, attributes=[ DocumentAttributeAudio( duration=int(rip_data["duration"]), title=str(rip_data["title"]), performer=str(rip_data["uploader"]), ) ], progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress(d, t, message, c_time, "Uploading..", f"{rip_data['title']}.mp3") ), ) os.remove(f"{rip_data['id']}.mp3") await message.delete() elif video: await message.edit(f"`Preparing to upload video:`\n**{rip_data['title']}**") await message.client.send_file( message.chat_id, f"{rip_data['id']}.mp4", supports_streaming=True, caption=rip_data["title"], progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress(d, t, message, c_time, "Uploading..", f"{rip_data['title']}.mp4") ), ) os.remove(f"{rip_data['id']}.mp4") await message.delete()