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) watermark_path = "./DOWNLOADS/watermark/" if not os.path.isdir(watermark_path): os.makedirs(watermark_path) 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 bot.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: await mone.edit(str(e)) else: end = datetime.now() ms = (end - start).seconds await mone.edit("Stored the pdf to `{}` in {} seconds.".format( downloaded_file_name, ms)) await mone.edit( "`Watermarking processing now, please wait for a while..`") watermark(inputpdf=Config.TMP_DOWNLOAD_DIRECTORY + reply_message.file.name, outputpdf=watermark_path + reply_message.file.name, watermarkpdf='./bin/watermark.pdf') # filename = sorted(get_lst_of_files(watermark_path + reply_message.file.name, [])) #filename = filename + "/" await event.edit("Uploading now") caption_rts = os.path.basename(watermark_path + reply_message.file.name) await bot.send_file( event.chat_id, watermark_path + reply_message.file.name, force_document=True, supports_streaming=False, allow_cache=False, caption=f'`{caption_rts}`', reply_to=event.message.id, progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task(progress(d, t, mone, c_time, "trying to upload"))) await asyncio.sleep(5) await event.delete() await asyncio.sleep(5) shutil.rmtree(watermark_path) await asyncio.sleep(5) os.remove(Config.TMP_DOWNLOAD_DIRECTORY + reply_message.file.name)
async def _(event): if event.fwd_from: return thumb = None if os.path.exists(thumb_image_path): thumb = thumb_image_path await event.edit( "Rename & Upload 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() to_download_directory = Config.TMP_DOWNLOAD_DIRECTORY downloaded_file_name = os.path.join(to_download_directory, file_name) c_time = time.time() downloaded_file_name = await event.client.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 = datetime.now() ms_one = (end - start).seconds if os.path.exists(downloaded_file_name): c_time = time.time() await event.client.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.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 // .rnupload file.name as reply to a Telegram media")
async def _(event): if event.fwd_from: return mone = await event.edit("Processing ...") input_str = event.pattern_match.group(1) thumb = None if os.path.exists(thumb_image_path): thumb = thumb_image_path if os.path.exists(input_str): start = datetime.now() c_time = time.time() await bot.send_file( event.chat_id, input_str, 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, mone, c_time, "trying to upload"))) end = datetime.now() # os.remove(input_str) ms = (end - start).seconds j = await mone.edit("Uploaded in {} seconds.".format(ms)) await asyncio.sleep(2) await j.delete() else: await mone.edit("404: File Not Found")
async def share_module(event): if event.fwd_from: return mone = await event.edit("Searching for required file..") input_str = event.pattern_match.group(1) module = f"modules/{input_str}.py" if os.path.exists(module): start = datetime.now() c_time = time.time() await client.send_file( event.chat_id, module, force_document=True, supports_streaming=False, allow_cache=False, reply_to=event.message.id, progress_callback=lambda d, t: asyncio.get_event_loop(). create_task(util.progress(d, t, mone, c_time, "Sharing module.."))) end = datetime.now() ms = (end - start).seconds await mone.edit(f"Uploaded {input_str} in {ms} seconds.") else: await mone.edit("404: Module not found") await asyncio.sleep(2) await mone.delete()
async def addzip(add): """ Add file to zip list """ #Prevent Channel Bug to use update if add.is_channel and not add.is_group: await event.edit("`compress Command isn't permitted on channels`") return if add.fwd_from: return if not add.is_reply: await add.edit("Reply to a file to compress it.") return directroy_zip = zip mone = await add.edit("Processing ...") if not os.path.isdir(ZIP_DOWNLOAD_DIRECTORY): os.makedirs(ZIP_DOWNLOAD_DIRECTORY) if add.reply_to_msg_id: reply_message = await add.get_reply_message() try: c_time = time.time() downloaded_file_name = await bot.download_media( reply_message, ZIP_DOWNLOAD_DIRECTORY, progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress(d, t, mone, c_time, "trying to download") ) ) directory_name = downloaded_file_name success = str(downloaded_file_name).replace(".zips", "") await add.edit(f"{success} Successfully added to list") except Exception as e: # pylint:disable=C0103,W0703 await mone.edit(str(e)) return
async def ff_mpeg_save_cmd(event): if event.fwd_from: return if not os.path.exists(FF_MPEG_DOWN_LOAD_MEDIA_PATH): if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY): os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY) if event.reply_to_msg_id: start = datetime.now() reply_message = await event.get_reply_message() try: c_time = time.time() downloaded_file_name = await bot.download_media( reply_message, FF_MPEG_DOWN_LOAD_MEDIA_PATH, 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.client.send_message(event.chat_id, str(e)) else: end = datetime.now() ms = (end - start).seconds h = await event.client.send_message(event.chat_id, "Downloaded to `{}` in {} seconds.".format(downloaded_file_name, ms)) await asyncio.sleep(4) await h.delete() else: f = await event.client.send_message(event.chat_id, "Reply to a Telegram media file") await asyncio.sleep(4) await f.delete() else: g = await event.client.send_message(event.chat_id, "a media file already exists in path. Please remove the media and try again! use `.exec rm -rf unibot.media.ffmpeg`") await asyncio.sleep(8) await g.delete()
async def _(event): if event.fwd_from: return mone = await event.edit("Processing ...") input_str = event.pattern_match.group(1) thumb = None file_name = input_str if os.path.exists(file_name): start = datetime.now() metadata = extractMetadata(createParser(file_name)) duration = 0 width = 0 height = 0 if metadata: 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") if os.path.exists(thumb_image_path): thumb = thumb_image_path else: thumb = await take_screen_shot(file_name, Config.TMP_DOWNLOAD_DIRECTORY, duration // 2) # 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 bot.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 gdriveupload(event): if event.fwd_from: return mone = await event.reply("Processing ...") if Config.G_DRIVE_CLIENT_ID is None or Config.G_DRIVE_CLIENT_SECRET is None: await mone.edit( "This module requires credentials from https://da.gd/so63O. Aborting!" ) return False input_str = event.pattern_match.group(1) if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY): os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY) required_file_name = None start = datetime.now() if event.reply_to_msg_id and not input_str: reply_message = await event.get_reply_message() try: c_time = time.time() downloaded_file_name = await bot.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)) return False else: end = datetime.now() ms = (end - start).seconds required_file_name = downloaded_file_name await mone.edit("Downloaded to `{}` in {} seconds.".format( downloaded_file_name, ms)) elif input_str: input_str = input_str.strip() if os.path.exists(input_str): end = datetime.now() ms = (end - start).seconds required_file_name = input_str await mone.edit("Found `{}` in {} seconds.".format( required_file_name, ms)) else: await mone.edit( "File Not found in local server. Give me a file path :((") return False if required_file_name: link = "" drive = GDriveHelper() await drive.authorize(event) task = drive.upload(required_file_name, mone) task2 = progressSpinner(drive, "UPLOAD PROGRESS", mone) result = await asyncio.gather(*[task, task2]) link = result[0] await mone.edit(f"Uploaded To GDrive: [{required_file_name}]({link})") else: await mone.edit( "File Not found in local server. Give me a file path :((")
async def pinterst_vid_img(event): x = await event.edit("`Progressing...`") url = event.pattern_match.group(1) get_url = get_download_url(url) j = download_video(get_url) thumb_image_path = Config.TMP_DOWNLOAD_DIRECTORY + "thumb_image.jpg" if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY): os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY) metadata = extractMetadata(createParser(j)) duration = 0 if metadata.has("duration"): duration = metadata.get('duration').seconds width = 0 height = 0 thumb = None if os.path.exists(thumb_image_path): thumb = thumb_image_path else: thumb = await take_screen_shot(j, os.path.dirname(os.path.abspath(j)), (duration / 2)) width = 0 height = 0 if os.path.exists(thumb_image_path): metadata = extractMetadata(createParser(thumb_image_path)) if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") c_time = time.time() await event.client.send_file( event.chat_id, j, thumb=thumb, caption="`pinterest video uploaded by` @By_Azade", 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"))) await event.delete() await x.delete() os.remove(Config.TMP_DOWNLOAD_DIRECTORY + 'pinterest_video.mp4') os.remove(thumb_image_path)
async def _(event): if event.fwd_from: return input_str = event.pattern_match.group(1) 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: reply_message = await event.get_reply_message() try: c_time = time.time() downloaded_file_name = await bot.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")) ) directory_name = downloaded_file_name await event.edit("Finish downloading to my local") to_upload_file = directory_name output = await create_archive(to_upload_file) is_zip = False if is_zip: check_if_file = await create_archive(to_upload_file) if check_if_file is not None: to_upload_file = check_if_file await bot.send_file( event.chat_id, output, caption="TAR By @By_Azade", force_document=True, allow_cache=False, reply_to=event.message.id, ) try: os.remove(output) os.remove(output) except: pass await event.edit("Task Completed") await asyncio.sleep(3) await event.delete() except Exception as e: # pylint:disable=C0103,W0703 await mone.edit(str(e)) elif input_str: directory_name = input_str await event.edit("Local file compressed to `{}`".format(output))
async def _(event): if event.fwd_from: return input_str = event.pattern_match.group(1) 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: reply_message = await event.get_reply_message() try: c_time = time.time() downloaded_file_name = await bot.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")) ) directory_name = downloaded_file_name await event.edit("creating 7z archive, please wait..") # patoolib.create_archive(directory_name + '.7z',directory_name) patoolib.create_archive( directory_name + ".7z", (directory_name, Config.TMP_DOWNLOAD_DIRECTORY)) # patoolib.create_archive("/content/21.yy Avrupa (1).pdf.zip",("/content/21.yy Avrupa (1).pdf","/content/")) await bot.send_file( event.chat_id, directory_name + ".7z", caption="7z archived By @By_Azade", force_document=True, allow_cache=False, reply_to=event.message.id, ) try: os.remove(directory_name + ".7z") os.remove(directory_name) except: pass await event.edit("Task Completed") await asyncio.sleep(3) await event.delete() except Exception as e: # pylint:disable=C0103,W0703 await mone.edit(str(e)) elif input_str: directory_name = input_str await event.edit( "Local file compressed to `{}`".format(directory_name + ".7z"))
async def _(event): if event.fwd_from: return mone = await event.edit("Processing ...") input_str = event.pattern_match.group(1) thumb = thumb_image_path if os.path.exists(thumb_image_path) else None if os.path.exists(input_str): start = datetime.now() c_time = time.time() with open(input_str, "rb") as out: res = await upload_file( event.client, out, progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task(progress(d, t, mone, c_time, "uploading"))) attributes, mime_type = utils.get_attributes(input_str, ) media = types.InputMediaUploadedDocument( file=res, mime_type=mime_type, attributes=attributes, thumb=thumb, ) await event.reply(file=media) # await bot.send_file( # event.chat_id, # input_str, # 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, mone, c_time, "trying to upload") # ) # ) end = datetime.now() os.remove(input_str) ms = (end - start).seconds j = await event.reply(f"Uploaded in {ms} seconds.") await asyncio.sleep(2) await j.delete() else: k = await event.reply("404: File Not Found") await asyncio.sleep(2) await k.delete()
async def convert_musicac(flac): if flac.fwd_from: return if not flac.is_reply: await flac.edit("Reply to a media to convert it.") return moneac = await flac.edit("Processing ...") if not os.path.isdir(TEMP_DOWNLOAD_DIRECTORY): os.makedirs(TEMP_DOWNLOAD_DIRECTORY) if flac.reply_to_msg_id: reply_message = await flac.get_reply_message() try: c_time = time.time() downloaded_file_nameac = await bot.download_media( reply_message, TEMP_DOWNLOAD_DIRECTORY, progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task( progress(d, t, moneac, c_time, "trying to download"))) directory_nameac = downloaded_file_nameac + ".flac" await flac.edit("`Converting your media....`") ff = ffmpy.FFmpeg(inputs={downloaded_file_nameac: None}, outputs={ directory_nameac: '-y -vn -acodec flac -ar 16000 -ac 1' }) ff.run() except Exception as e: # pylint:disable=C0103,W0703 await moneac.edit(str(e)) except ValueError as e: await moneac.edit(str(e)) await asyncio.sleep(7) await bot.send_file( flac.chat_id, directory_nameac, caption="`Enjoy your Music`", force_document=True, allow_cache=False, reply_to=flac.message.id, ) os.remove(directory_nameac) os.remove(downloaded_file_nameac) await flac.delete()
async def _(event): if event.fwd_from: return input_str = event.pattern_match.group(1) 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: reply_message = await event.get_reply_message() try: c_time = time.time() downloaded_file_name = await bot.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")) ) directory_name = downloaded_file_name await event.edit("Finish downloading to my local") command_to_exec = ["7z", "e", "-o" + extracted, directory_name] sp = subprocess.Popen(command_to_exec, stderr=subprocess.STDOUT, stdout=subprocess.PIPE) await bot.send_file( event.chat_id, directory_name + ".zip", caption="Zipped By @By_Azade", force_document=True, allow_cache=False, reply_to=event.message.id, ) try: os.remove(directory_name + ".zip") os.remove(directory_name) except: pass await event.edit("Task Completed") await asyncio.sleep(3) await event.delete() except Exception as e: # pylint:disable=C0103,W0703 await mone.edit(str(e)) elif input_str: directory_name = input_str await event.edit( "Local file compressed to `{}`".format(directory_name + ".zip"))
async def convert_video(mp4): if mp4.fwd_from: return if not mp4.is_reply: await mp4.edit("Reply to a media to convert it.") return mone4 = await mp4.edit("Processing ...") if not os.path.isdir(TEMP_DOWNLOAD_DIRECTORY): os.makedirs(TEMP_DOWNLOAD_DIRECTORY) if mp4.reply_to_msg_id: reply_message = await mp4.get_reply_message() try: c_time = time.time() downloaded_file_name4 = await bot.download_media( reply_message, TEMP_DOWNLOAD_DIRECTORY, progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress(d, t, mone4, c_time, "trying to download") ) ) directory_name4 = downloaded_file_name4 + ".mp4" await mp4.edit("`Converting your media....`") ff = ffmpy.FFmpeg( inputs = {downloaded_file_name4 : None}, outputs = {directory_name4 : None}) ff.run() except Exception as e: # pylint:disable=C0103,W0703 await mone4.edit(str(e)) except ValueError as e: await mone4.edit(str(e)) await asyncio.sleep(7) await bot.send_file( mp4.chat_id, directory_name4, caption="`Enjoy your Video`", force_document=False, allow_cache=False, reply_to=mp4.message.id, ) os.remove(directory_name4) os.remove(downloaded_file_name4) await mp4.delete()
async def pinterst_img_vid(event): x = await event.edit("`Progressing...`") url = event.pattern_match.group(1) get_url = get_download_url(url) j = download_image(get_url) if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY): os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY) c_time = time.time() await event.client.send_file( event.chat_id, j, caption="`pinterest image uploaded by` @By_Azade", force_document=False, allow_cache=False, reply_to=event.message.id, progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress(d, t, event, c_time, "trying to upload"))) await event.delete() await x.delete() os.remove(Config.TMP_DOWNLOAD_DIRECTORY + 'pinterest_iamge.jpg')
async def _(event): #Prevent Channel Bug to use update if event.is_channel and not event.is_group: await event.edit("`compress Commad isn't permitted on channels`") return if event.fwd_from: return if not event.is_reply: await event.edit("Reply to a file to compress it.") return mone = await event.edit("Processing ...") if not os.path.isdir(TEMP_DOWNLOAD_DIRECTORY): os.makedirs(TEMP_DOWNLOAD_DIRECTORY) if event.reply_to_msg_id: reply_message = await event.get_reply_message() try: 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, mone, c_time, "trying to download")) ) directory_name = downloaded_file_name await event.edit(downloaded_file_name) except Exception as e: # pylint:disable=C0103,W0703 await mone.edit(str(e)) zipfile.ZipFile(directory_name + '.zip', 'w', zipfile.ZIP_DEFLATED).write(directory_name) await bot.send_file( event.chat_id, directory_name + ".zip", caption="Zipped By EyePatch", force_document=True, allow_cache=False, reply_to=event.message.id, ) await event.edit("DONE!!!") await asyncio.sleep(7) await event.delete()
async def _(event): if event.fwd_from: return mone = await event.edit("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 event.client.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) display_message = "" c_time = time.time() while not downloader.isFinished(): total_length = downloader.filesize or 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 _ in range(math.floor(percentage / 5))), ''.join("â" for _ 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"\ f"URL: {url}\n"\ f"File Name: {file_name}\n" \ f"Speed: {speed}"\ f"{progress_str}\n"\ f"{ humanbytes(downloaded)} of { humanbytes(total_length)}\n"\ f"ETA: {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 os.path.exists(downloaded_file_name): 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_video(v_url): """ For .ytdl command, download media from YouTube and many other sites. """ url = v_url.pattern_match.group(2) type = v_url.pattern_match.group(1).lower() await v_url.edit("`Preparing to download...`") out_folder = Config.TMP_DOWNLOAD_DIRECTORY + "youtubedl/" thumb_image_path = Config.TMP_DOWNLOAD_DIRECTORY + "/thumb_image.jpg" if not os.path.isdir(out_folder): os.makedirs(out_folder) if type == "a": opts = { 'format': 'bestaudio', 'addmetadata': True, 'noplaylist': False, 'key': 'FFmpegMetadata', 'writethumbnail': True, 'embedthumbnail': True, 'prefer_ffmpeg': True, 'geo_bypass': True, 'nocheckcertificate': True, 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '320', }], 'outtmpl': out_folder + '%(title)s.%(ext)s', 'quiet': True, 'logtostderr': False } video = False song = True elif type == "v": opts = { 'format': 'best', 'addmetadata': True, 'noplaylist': False, 'getthumbnail': True, 'embedthumbnail': True, 'xattrs': True, 'writethumbnail': True, 'key': 'FFmpegMetadata', 'prefer_ffmpeg': True, 'geo_bypass': True, 'nocheckcertificate': True, 'postprocessors': [ { 'key': 'FFmpegVideoConvertor', 'preferedformat': 'mp4' }, ], 'outtmpl': out_folder + '%(title)s.%(ext)s', 'logtostderr': False, 'quiet': True } song = False video = True try: await v_url.edit("`Fetching playlist data, please wait..`") with YoutubeDL(opts) as ytdl: ytdl_data = ytdl.extract_info(url) # print(ytdl_data['thumbnail']) filename = sorted(get_lst_of_files(out_folder, [])) except DownloadError as DE: await v_url.edit(f"`{str(DE)}`") return except ContentTooShortError: await v_url.edit("`The download content was too short.`") return except GeoRestrictedError: await v_url.edit( "`Video is not available from your geographic location due to geographic restrictions imposed by a website.`" ) return except MaxDownloadsReached: await v_url.edit("`Max-downloads limit has been reached.`") return except PostProcessingError: await v_url.edit("`There was an error during post processing.`") return except UnavailableVideoError: await v_url.edit("`Media is not available in the requested format.`") return except XAttrMetadataError as XAME: await v_url.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`") return except ExtractorError: await v_url.edit("`There was an error during info extraction.`") return except Exception as e: await v_url.edit(f"{str(type(e)): {str(e)}}") return c_time = time.time() await v_url.edit( "`YouTube Playlist Downloading Processing Now.\nPlease Wait!`") if song: for single_file in filename: if os.path.exists(single_file): caption_rts = os.path.basename(single_file) force_document = True supports_streaming = False document_attributes = [] if single_file.endswith((".mp4", ".mp3", ".flac", ".webm")): metadata = extractMetadata(createParser(single_file)) duration = 0 width = 0 height = 180 if metadata.has("duration"): duration = metadata.get('duration').seconds document_attributes = [ DocumentAttributeVideo( duration=duration, w=width, h=height, round_message=False, supports_streaming=True, ) ] try: ytdl_data_name_audio = os.path.basename(single_file) thumb = out_folder + \ ytdl_data_name_audio[:( len(ytdl_data_name_audio)-4)] + ".jpg" print(ytdl_data_name_audio) file_path = single_file song_size = file_size(file_path) await v_url.client.send_file( v_url.chat_id, single_file, caption=f"`{ytdl_data_name_audio}`" + "\n" + f"{song_size}", force_document=force_document, supports_streaming=supports_streaming, allow_cache=False, thumb=thumb, reply_to=v_url.message.id, attributes=document_attributes, progress_callback=lambda d, : asyncio. get_event_loop().create_task( progress(d, v_url, c_time, "Uploading..", f"{ytdl_data_name_audio}"))) # os.remove(thumb) except Exception as e: await v_url.client.send_message( v_url.chat_id, "{} caused `{}`".format(caption_rts, str(e)), ) continue os.remove(single_file) await asyncio.sleep(DELETE_TIMEOUT) # await v_url.delete() shutil.rmtree(out_folder) if video: for single_file in filename: if os.path.exists(single_file): caption_rts = os.path.basename(single_file) force_document = False supports_streaming = True document_attributes = [] if single_file.endswith((".mp4", ".mp3", ".flac", ".webm")): metadata = extractMetadata(createParser(single_file)) duration = 0 width = 0 height = 0 if metadata.has("duration"): duration = metadata.get('duration').seconds document_attributes = [ DocumentAttributeVideo( duration=duration, w=width, h=height, round_message=False, supports_streaming=True, ) ] # print(ytdl_data) # for file in os.listdir("./DOWNLOADS/youtubedl/"): # if file.endswith(".jpg"): # thumb = "./DOWNLOADS/youtubedl/" + file # print(os.path.join("./DOWNLOADS/youtubedl/", file)) # image_link = ytdl_data['thumbnail'] # downloaded_image = wget.download(image_link,out_folder) # thumb = ytdl_data_name_video + ".jpg" file_path = single_file video_size = file_size(file_path) try: ytdl_data_name_video = os.path.basename(single_file) thumb = out_folder + \ ytdl_data_name_video[:( len(ytdl_data_name_video)-4)] + ".jpg" await v_url.client.send_file( v_url.chat_id, single_file, caption=f"`{ytdl_data_name_video}`" + "\n" + f"{video_size}", force_document=force_document, supports_streaming=supports_streaming, thumb=thumb, allow_cache=False, reply_to=v_url.message.id, attributes=document_attributes, progress_callback=lambda d, t: asyncio. get_event_loop().create_task( progress(d, t, v_url, c_time, "Uploading..", f"{ytdl_data_name_video}"))) # os.remove(thumb) except Exception as e: await v_url.client.send_message( v_url.chat_id, "{} caused `{}`".format(caption_rts, str(e)), ) continue os.remove(single_file) await asyncio.sleep(DELETE_TIMEOUT) # await v_url.delete() shutil.rmtree(out_folder)
async def ff_mpeg_trim_cmd(event): if event.fwd_from: return await event.delete() if not os.path.exists(FF_MPEG_DOWN_LOAD_MEDIA_PATH): k = await event.client.send_message(event.chat_id, f"a media file needs to be downloaded, and saved to the following path: `{FF_MPEG_DOWN_LOAD_MEDIA_PATH}`") await asyncio.sleep(4) await k.delete() return current_message_text = event.raw_text cmt = current_message_text.split(" ") logger.info(cmt) 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 ) logger.info(o) try: c_time = time.time() await bot.send_file( event.chat_id, o, caption=" ".join(cmt[1:]), force_document=False, 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, event, c_time, "trying to upload") ) ) os.remove(o) except Exception as e: logger.info(str(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 ) logger.info(o) try: c_time = time.time() await bot.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, event, c_time, "trying to upload") ) ) os.remove(o) except Exception as e: logger.info(str(e)) else: m = await event.client.send_message(event.chat_id, "RTFM") await asyncio.sleep(4) await m.delete() return end = datetime.now() ms = (end - start).seconds j = await event.client.send_message(event.chat_id, f"Completed Process in {ms} seconds") await asyncio.sleep(4) await j.delete()
async def _(event): if event.fwd_from: return mone = await event.reply("Processing ...") if Config.MIRROR_ACE_API_KEY is None or Config.MIRROR_ACE_API_TOKEN is None: await mone.edit( "This module requires API key from https://ouo.io/My1jdU. Aborting!" ) return False input_str = event.pattern_match.group(1) if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY): os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY) required_file_name = None start = datetime.now() if event.reply_to_msg_id and not input_str: reply_message = await event.get_reply_message() try: c_time = time.time() downloaded_file_name = await event.client.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)) return False else: end = datetime.now() ms = (end - start).seconds required_file_name = downloaded_file_name await mone.edit("Downloaded to `{}` in {} seconds.".format( required_file_name, ms)) elif input_str: input_str = input_str.strip() if os.path.exists(input_str): end = datetime.now() ms = (end - start).seconds required_file_name = input_str await mone.edit("Found `{}` in {} seconds.".format( required_file_name, ms)) else: await mone.edit( "File Not found in local server. Give me a file path :((") return False # logger.info(required_file_name) if required_file_name: # required_file_name will have the full path file_name = os.path.basename(required_file_name) file_size = os.stat(required_file_name).st_size step_one_auth_params = { "api_key": Config.MIRROR_ACE_API_KEY, "api_token": Config.MIRROR_ACE_API_TOKEN } async with aiohttp.ClientSession() as session: # /* STEP 1: get upload_key */ step_one_url = "https://mirrorace.com/api/v1/file/upload" resp = await session.post(step_one_url, data=step_one_auth_params) # logger.info(resp.status) if resp.status == 200: step_one_response_json = await resp.json() logger.info(step_one_response_json) if step_one_response_json["status"] == "success": await mone.edit("Received Upload URL from MirrorAce. ...") start = datetime.now() # /* STEP 2: Upload file */ # step one: response vars step_two_upload_url = step_one_response_json["result"][ "server_file"] cTracker = step_one_response_json["result"]["cTracker"] upload_key = step_one_response_json["result"]["upload_key"] default_mirrors = step_one_response_json["result"][ "default_mirrors"] max_chunk_size = step_one_response_json["result"][ "max_chunk_size"] max_file_size = step_one_response_json["result"][ "max_file_size"] max_mirrors = step_one_response_json["result"][ "max_mirrors"] # check file size limit if int(file_size) >= int(max_file_size): await mone.edit( f"File exceeds maximum file size allowed: {max_file_size}" ) return False # step two: setup mirrors = default_mirrors chunk_size = int(max_chunk_size) step_two_params = { "api_key": Config.MIRROR_ACE_API_KEY, "api_token": Config.MIRROR_ACE_API_TOKEN, "cTracker": cTracker, "upload_key": upload_key, "mirrors[]": mirrors, # //these required vars will be added by buildMultiPartRequest function # //'files' => $file, # //'mirrors[1]' => 1, # //'mirrors[2]' => 2, } # //range vars //for multi chunk upload response = False with open(required_file_name, "rb") as f_handle: # start chunk upload for chunk in iter((lambda: f_handle.read(chunk_size)), ""): # for chunk in f_handle.read(chunk_size): # print(chunk) # while (i < chunks) and not while_error: # chunk = f_handle.read(chunk_size) if not chunk: break headers = { "Content-Range": str(len(chunk)), "Content-Length": str(len(step_two_params) + len(chunk)), # "Content-Type": "multipart/form-data" } # https://github.com/aio-libs/aiohttp/issues/3571#issuecomment-456528924 response = requests.post( step_two_upload_url, files=[("files", (file_name, chunk))], data=step_two_params, # headers=headers ) logger.info(response.content) logger.info(response) final_response = response.json() if final_response["status"] == "success": end = datetime.now() ms = (end - start).seconds final_url = final_response["result"]["url"] await mone.edit(f"Added to {final_url} in {ms} seconds" ) else: await mone.edit( f"MirrorAce returned {final_response['status']} => {final_response['result']}" ) else: await mone.edit( f"MirrorAce returned {step_one_response_json['status']} => {step_one_response_json['result']}, after STEP TWO" ) else: await mone.edit( f"MirrorAce returned {resp['status']} => {resp['result']}, after STEP ONE" ) else: await mone.edit( "File Not found in local server. Give me a file path :((")
async def _(event): if event.fwd_from: return mone = await event.edit("Processing ...") if Config.VERY_STREAM_LOGIN is None or Config.VERY_STREAM_KEY is None: await mone.edit( "This module requires API key from https://verystream.com. Aborting!" ) return False input_str = event.pattern_match.group(1) if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY): os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY) required_file_name = None start = datetime.now() if event.reply_to_msg_id and not input_str: reply_message = await event.get_reply_message() try: c_time = time.time() downloaded_file_name = await bot.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)) return False else: end = datetime.now() ms = (end - start).seconds required_file_name = downloaded_file_name await mone.edit("Downloaded to `{}` in {} seconds.".format( downloaded_file_name, ms)) elif input_str: input_str = input_str.strip() if os.path.exists(input_str): end = datetime.now() ms = (end - start).seconds required_file_name = input_str await mone.edit("Found `{}` in {} seconds.".format( required_file_name, ms)) else: await mone.edit( "File Not found in local server. Give me a file path :((") return False # logger.info(required_file_name) if required_file_name: # required_file_name will have the full path file_name = os.path.basename(required_file_name) if "." in file_name: file_name = file_name.rsplit(".", maxsplit=1)[0] file_name = file_name + str(time.time()) file_size = os.stat(required_file_name).st_size # https://stackoverflow.com/a/22058673/4723940 sha_one_file_hash = get_sha_one_hash(required_file_name, 65536) # /* STEP 1: get upload_key */ login = Config.VERY_STREAM_LOGIN key = Config.VERY_STREAM_KEY sha1 = sha_one_file_hash mime = magic.Magic(mime=True) step_zero_url = f"https://api.verystream.com/file/createfolder?login={login}&key={key}&name={file_name}" async with aiohttp.ClientSession() as session: resp_zero = await session.get(step_zero_url) step_zero_response_text = json.loads(await resp_zero.text()) # logger.info(step_zero_response_text) if step_zero_response_text["status"] == 200: folder_id_e = step_zero_response_text["result"]["folderid"] await mone.edit(f"Created Folder with ID: {folder_id_e}") step_one_url = f"https://api.verystream.com/file/ul?login={login}&key={key}&sha1={sha1}&folder={folder_id_e}" resp = await session.get(step_one_url) # logger.info(resp.status) step_one_response_text = json.loads(await resp.text()) # logger.info(step_one_response_text) if step_one_response_text["status"] == 200: url = step_one_response_text["result"]["url"] await mone.edit(f"Start Uploading to {url}") start = datetime.now() files = { "file1": (file_name, open(required_file_name, "rb")) } resp = requests.post(url, files=files) step_two_response_text = resp.json() # logger.info(step_two_response_text) if step_two_response_text["status"] == 200: output_str = json.dumps( step_two_response_text["result"], sort_keys=True, indent=4) stream_url = step_two_response_text["result"]["url"] end = datetime.now() ms = (end - start).seconds await mone.edit( f"Obtained {stream_url} in {ms} seconds.\n{output_str}" ) # cleanup await event.delete() try: os.remove(required_file_name) except: pass else: await mone.edit( f"VeryStream returned {step_two_response_text['status']} => {step_two_response_text['msg']}, after STEP ONE" ) else: await mone.edit( f"VeryStream returned {step_one_response_text['status']} => {step_one_response_text['msg']}, after STEP ONE" ) else: await mone.edit( f"VeryStream returned {step_zero_response_text['status']} => {step_zero_response_text['msg']}, after STEP INIT" ) else: await mone.edit( "File Not found in local server. Give me a file path :((")
async def _(event): if event.fwd_from: return mone = await event.edit("Processing ...") extracted = Config.TMP_DOWNLOAD_DIRECTORY + "extracted/" thumb_image_path = Config.TMP_DOWNLOAD_DIRECTORY + "/thumb_image.jpg" if not os.path.isdir(extracted): os.makedirs(extracted) if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY): os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY) if event.reply_to_msg_id: start = datetime.now() reply_message = await event.get_reply_message() try: c_time = time.time() downloaded_file_name = await bot.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)) shutil.unpack_archive(downloaded_file_name, extracted) files = [f for f in glob("./DOWNLOADS/extracted/**", recursive=True) if os.path.isfile(f)] filename = set(list(files)) # NOTE no need this # with zipfile.ZipFile(downloaded_file_name, 'r') as zip_ref: # zip_ref.extractall(extracted) # filename = sorted(get_lst_of_files(extracted, [])) #filename = filename + "/" await event.edit("Unzipping now") # r=root, d=directories, f = files for single_file in filename: if os.path.exists(single_file): # https://stackoverflow.com/a/678242/4723940 caption_rts = os.path.basename(single_file) force_document = False supports_streaming = True document_attributes = [] if single_file.endswith((".mp4", ".mp3", ".flac", ".webm")): metadata = extractMetadata(createParser(single_file)) duration = 0 width = 0 height = 0 if metadata.has("duration"): duration = metadata.get('duration').seconds if os.path.exists(thumb_image_path): metadata = extractMetadata( createParser(thumb_image_path)) if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") document_attributes = [ DocumentAttributeVideo( duration=duration, w=width, h=height, round_message=False, supports_streaming=True ) ] try: await bot.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, "trying to upload") # ) ) except Exception as e: await bot.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) await asyncio.sleep(2) shutil.rmtree(Config.TMP_DOWNLOAD_DIRECTORY)
async def _(event): if event.fwd_from: return input_str = event.pattern_match.group(1) mone = await event.edit("Processing ...") if os.path.exists(input_str): start = datetime.now() # await event.edit("Processing ...") lst_of_files = sorted(get_lst_of_files(input_str, [])) logger.info(lst_of_files) u = 0 await event.edit("Found {} files. ".format(len(lst_of_files)) + "Uploading will start soon. " + "Please wait!") thumb = thumb_image_path if os.path.exists(thumb_image_path) else None 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) force_document = True supports_streaming = False document_attributes = [] width = 0 height = 0 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") if single_file.upper().endswith(Config.TL_VID_STREAM_TYPES): metadata = extractMetadata(createParser(single_file)) duration = 0 if metadata.has("duration"): duration = metadata.get('duration').seconds document_attributes = [ DocumentAttributeVideo(duration=duration, w=width, h=height, round_message=False, supports_streaming=True) ] supports_streaming = True force_document = False if single_file.upper().endswith(Config.TL_MUS_STREAM_TYPES): metadata = extractMetadata(createParser(single_file)) duration = metadata.get( 'duration').seconds if metadata.has("duration") else 0 title = metadata.get("title") if metadata.has( "title") else "" artist = metadata.get("artist") if metadata.has( "artist") else "" document_attributes = [ DocumentAttributeAudio(duration=duration, voice=False, title=title, performer=artist, waveform=None) ] supports_streaming = True force_document = False try: c_time = time.time() with open(single_file, "rb") as out: res = await upload_file( event.client, out, progress_callback=lambda d, t: asyncio. get_event_loop().create_task( progress(d, t, mone, c_time, "uploading"))) attributes, mime_type = utils.get_attributes( single_file, ) media = types.InputMediaUploadedDocument( file=res, mime_type=mime_type, attributes=document_attributes, thumb=thumb, force_file=force_document, supports_streaming=supports_streaming) await event.reply(file=media) # await bot.send_file( # event.chat_id, # single_file, # caption=caption_rts, # force_document=force_document, # supports_streaming=supports_streaming, # allow_cache=False, # reply_to=event.message.id, # thumb=thumb, # 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 bot.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) u += 1 # await event.edit("Uploaded {} / {} files.".format(u, len(lst_of_files))) # @ControllerBot was having issues, # if both edited_updates and update events come simultaneously. await asyncio.sleep(5) end = datetime.now() ms = (end - start).seconds await event.edit("Uploaded {} files in {} seconds.".format(u, ms)) else: await event.edit("404: Directory Not Found")
async def _(event): if event.fwd_from: return mone = await event.edit("Processing ...") input_str = event.pattern_match.group(1) thumb = None thumb_image_path = Config.TMP_DOWNLOAD_DIRECTORY + "thumb_image.jpg" logger.info(thumb_image_path) if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY): os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY) if event.reply_to_msg_id: start = datetime.now() reply_message = await event.get_reply_message() try: c_time = time.time() downloaded_file_name = await bot.download_media( reply_message, Config.TMP_DOWNLOAD_DIRECTORY, progress_callback=lambda d, t: asyncio.get_event_loop(). create_task(progress(d, t, mone, c_time, "trying to download")) ) except Exception as e: # pylint:disable=C0103,W0703 await mone.edit(str(e)) else: end = datetime.now() ms = (end - start).seconds await mone.edit("Downloaded now preparing to streaming upload") # if os.path.exists(input_str): if os.path.exists(Config.TMP_DOWNLOAD_DIRECTORY): if not downloaded_file_name.endswith( (".mkv", ".mp4", ".mp3", ".flac", ".webm", ".ts", ".mov")): await mone.edit( "**Supported Formats**: MKV, MP4, MP3, FLAC") return False if downloaded_file_name.upper().endswith( ("MKV", "MP4", "WEBM")): metadata = extractMetadata( createParser(downloaded_file_name)) duration = 0 if metadata.has("duration"): duration = metadata.get('duration').seconds width = 0 height = 0 thumb = None if os.path.exists(thumb_image_path): thumb = thumb_image_path else: thumb = await take_screen_shot( downloaded_file_name, os.path.dirname(os.path.abspath(downloaded_file_name)), (duration / 2)) start = datetime.now() metadata = extractMetadata(createParser(downloaded_file_name)) # duration = 0 width = 0 height = 0 # if metadata.has("duration"): # duration = metadata.get('duration').seconds if os.path.exists(thumb_image_path): metadata = extractMetadata(createParser(thumb_image_path)) if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") c_time = time.time() try: await bot.send_file( event.chat_id, downloaded_file_name, thumb=thumb, caption=input_str, force_document=False, allow_cache=False, reply_to=event.message.id, attributes=[ DocumentAttributeVideo(duration=duration, w=width, h=height, round_message=False, supports_streaming=True) ], progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task( progress(d, t, mone, c_time, "trying to upload"))) except Exception as e: await mone.edit(str(e)) else: end = datetime.now() # os.remove(input_str) ms = (end - start).seconds await mone.edit("Uploaded in {} seconds.".format(ms)) os.remove(thumb) await asyncio.sleep(5) os.remove(downloaded_file_name) else: await mone.edit("404: File Not Found")
async def 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>[Forwarded from utubebot]</b>\nno one gonna help you đ¤Ŗđ¤Ŗđ¤Ŗđ¤Ŗ", 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("đ <code>gphoto setup</code> first đĄđđ", parse_mode="html") service = build("photoslibrary", "v1", http=creds.authorize(Http())) # create directory if not exists if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY): os.makedirs(Config.TMP_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=Config.TMP_DOWNLOAD_DIRECTORY, progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task(progress(d, t, event, c_time, "trying to download"))) logger.info(file_path) if not file_path: await event.edit("<b>[stop spamming]</b>", parse_mode="html") return file_name, mime_type, file_size = file_ops(file_path) await event.edit("file downloaded, " "gathering upload informations ") async with aiohttp.ClientSession() as session: headers = { "Content-Length": "0", "X-Goog-Upload-Command": "start", "X-Goog-Upload-Content-Type": mime_type, "X-Goog-Upload-File-Name": file_name, "X-Goog-Upload-Protocol": "resumable", "X-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("X-Goog-Upload-URL") logger.info(real_upload_url) upload_granularity = int( step_one_resp_headers.get("X-Goog-Upload-Chunk-Granularity")) logger.info(upload_granularity) # https://t.me/c/1279877202/74 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), "X-Goog-Upload-Command": "upload", "X-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 to 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) # https://t.me/c/1279877202/74 logger.info(number_of_req_s) headers = { "Content-Length": str(len(current_chunk)), "X-Goog-Upload-Command": "upload, finalize", "X-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("uploaded to Google Photos, " "getting 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(photo_url) except Exception as e: await event.edit(str(e))
async def download(dryb): """ For .gdrive command, upload files to google drive. """ if not dryb.text[0].isalpha() and dryb.text[0] not in ("/", "#", "@", "!"): if dryb.fwd_from: return await dryb.edit("Processing ...") input_str = dryb.pattern_match.group(1) if CLIENT_ID is None or CLIENT_SECRET is None: return False if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY): os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY) required_file_name = None elif input_str: start = datetime.now() url = input_str file_name = os.path.basename(url) if "|" in input_str: url, file_name = input_str.split("|") url = url.strip() file_name = file_name.strip() downloaded_file_name = Config.TMP_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 or 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"{status}...\nURL: {url}\nFile Name: {file_name}\n{progress_str}\n{humanbytes(downloaded)} of {humanbytes(total_length)}\nETA: {estimated_total_time}" if current_message != display_message: await dryb.edit(current_message) display_message = current_message await asyncio.sleep(20) except Exception as e: logger.info(str(e)) end = datetime.now() ms = (end - start).seconds if downloader.isSuccessful(): await dryb.edit( "Downloaded to `{}` in {} seconds.\nNow Uploading to Google Drive..." .format(downloaded_file_name, ms)) required_file_name = downloaded_file_name else: await dryb.edit("Incorrect URL\n{}".format(url)) elif dryb.reply_to_msg_id: start = datetime.now() try: c_time = time.time() downloaded_file_name = await dryb.client.download_media( await dryb.get_reply_message(), Config.TMP_DOWNLOAD_DIRECTORY, progress_callback=lambda d, t: asyncio.get_event_loop(). create_task(progress(d, t, dryb, c_time, "Downloading...")) ) except Exception as e: # pylint:disable=C0103,W0703 await dryb.edit(str(e)) else: end = datetime.now() required_file_name = downloaded_file_name ms = (end - start).seconds await dryb.edit( "Downloaded to `{}` in {} seconds.\nNow Uploading to GDrive..." .format(required_file_name, ms)) if required_file_name: # if Config.G_DRIVE_AUTH_TOKEN_DATA is not None: with open(G_DRIVE_TOKEN_FILE, "w") as t_file: t_file.write(Config.G_DRIVE_AUTH_TOKEN_DATA) # Check if token file exists, if not create it by requesting authorization code if not os.path.isfile(G_DRIVE_TOKEN_FILE): storage = await create_token_file(G_DRIVE_TOKEN_FILE, dryb) http = authorize(G_DRIVE_TOKEN_FILE, storage) # Authorize, get file parameters, upload file and print out result URL for download http = authorize(G_DRIVE_TOKEN_FILE, None) file_name, mime_type = file_ops(required_file_name) # required_file_name will have the full path # Sometimes API fails to retrieve starting URI, we wrap it. try: g_drive_link = await upload_file(http, required_file_name, file_name, mime_type, dryb) await dryb.edit( f"File:`{required_file_name}`\nHas Successfully Uploaded to : [Google Drive]({g_drive_link})" ) except Exception as e: await dryb.edit( f"Error while uploading to Google Drive\nError Code:\n`{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 or 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 = "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() await event.client.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 a = await event.edit( "Downloaded in {} seconds. Uploaded in {} seconds.".format( ms_dl, ms_two)) await a.delete() await asyncio.sleep(5) else: await event.edit("File Not Found {}".format(input_str)) await asyncio.sleep(5) await event.delete() else: await event.edit("Incorrect URL\n {}".format(input_str))
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 event.client.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 event.client.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 _(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.time() downloaded_file_name = await bot.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 = [] 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) t_response, e_response = await run_command(command_to_run) 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") ) ) ms_two = (end_two - end).seconds os.remove(new_required_file_name) await event.edit(f"converted in {ms_two} seconds")