async def upload(u_event): """ For .upload command, allows you to upload a file from the userbot's server """ await u_event.reply("Processing ...") input_str = u_event.pattern_match.group(1) if input_str in ("userbot.session", "config.env"): await u_event.reply("`That's a dangerous operation! Not Permitted!`") return if os.path.exists(input_str): c_time = time.time() await u_event.client.send_file( u_event.chat_id, input_str, force_document=True, allow_cache=False, reply_to=u_event.message.id, progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task( progress(d, t, u_event, c_time, "Uploading...", input_str))) await u_event.reply("Uploaded successfully !!") else: await u_event.reply("404: File Not Found")
async def download(target_file): """ For .download command, download files to the userbot's server. """ await target_file.reply("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() elapsed_time = round(diff) * 1000 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"{status}..\ \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 target_file.reply(current_message) display_message = current_message except Exception as e: LOGS.info(str(e)) if downloader.isSuccessful(): await target_file.reply("Downloaded to `{}` successfully !!".format( downloaded_file_name)) else: await target_file.reply("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, "Downloading..."))) except Exception as e: # pylint:disable=C0103,W0703 await target_file.reply(str(e)) else: await target_file.reply("Downloaded to `{}` successfully !!".format( downloaded_file_name)) else: await target_file.reply( "Reply to a message to download to my local server.")
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.reply("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.reply( "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))) os.remove(single_file) uploaded = uploaded + 1 await udir_event.reply( "Uploaded {} files successfully !!".format(uploaded)) else: await udir_event.reply("404: Directory Not Found")
async def uploadas(uas_event): """ For .uploadas command, allows you to specify some arguments for upload. """ await uas_event.reply("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, "Uploading...", 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, "Uploading...", file_name))) elif spam_big_messages: await uas_event.reply("TBD: Not (yet) Implemented") return os.remove(thumb) await uas_event.reply("Uploaded successfully !!") except FileNotFoundError as err: await uas_event.reply(str(err)) else: await uas_event.reply("404: File Not Found")
async def download_video(v_url): lazy = v_url ; sender = await lazy.get_sender() ; me = await lazy.client.get_me() if not sender.id == me.id: rkp = await lazy.reply("`processing...`") else: rkp = await lazy.edit("`processing...`") url = v_url.pattern_match.group(1) if not url: return await rkp.edit("`Error \nusage song <song name>`") search = SearchVideos(url, offset = 1, mode = "json", max_results = 1) test = search.result() p = json.loads(test) q = p.get('search_result') try: url = q[0]['link'] except: return await rkp.edit("`failed to find`") type = "audio" await rkp.edit("`Preparing to download...`") if type == "audio": 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 rkp.edit("`Fetching data, please wait..`") with YoutubeDL(opts) as rip: rip_data = rip.extract_info(url) except DownloadError as DE: await rkp.edit(f"`{str(DE)}`") return except ContentTooShortError: await rkp.edit("`The download content was too short.`") return except GeoRestrictedError: await rkp.edit( "`Video is not available from your geographic location due to geographic restrictions imposed by a website.`" ) return except MaxDownloadsReached: await rkp.edit("`Max-downloads limit has been reached.`") return except PostProcessingError: await rkp.edit("`There was an error during post processing.`") return except UnavailableVideoError: await rkp.edit("`Media is not available in the requested format.`") return except XAttrMetadataError as XAME: await rkp.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`") return except ExtractorError: await rkp.edit("`There was an error during info extraction.`") return except Exception as e: await rkp.edit(f"{str(type(e)): {str(e)}}") return c_time = time.time() if song: await rkp.edit(f"`Preparing to upload song `\ \n**{rip_data['title']}**\ \nby *{rip_data['uploader']}*") 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 rkp.edit(f"`Preparing to upload video song :`\ \n**{rip_data['title']}**\ \nby *{rip_data['uploader']}*") 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 rkp.delete()
async def download_video(v_url): sender = await v_url.get_sender() ; me = await v_url.client.get_me() if not sender.id == me.id: rkp = await v_url.reply("`processing...`") else: rkp = await v_url.edit("`processing...`") url = v_url.pattern_match.group(2) type = v_url.pattern_match.group(1).lower() await rkp.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 } 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 rkp.edit("`Fetching data, please wait..`") with YoutubeDL(opts) as rip: rip_data = rip.extract_info(url) except DownloadError as DE: return await rkp.edit(f"`{str(DE)}`") except ContentTooShortError: return await rkp.edit("`The download content was too short.`") except GeoRestrictedError: return await rkp.edit( "`Video is not available from your geographic location " "due to geographic restrictions imposed by a website.`" ) except MaxDownloadsReached: return await rkp.edit("`Max-downloads limit has been reached.`") except PostProcessingError: return await rkp.edit("`There was an error during post processing....`") except UnavailableVideoError: return await rkp.edit("`Media is not available in the requested format.`") except XAttrMetadataError as XAME: return await rkp.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`") except ExtractorError: return await rkp.edit("`There was an error during info extraction.`") except Exception as e: return await rkp.edit(f"{str(type(e)): {str(e)}}") c_time = time.time() if song: await rkp.edit( f"`Preparing to upload audio:`\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 rkp.edit( f"`Preparing to upload 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, "Uploading..", f"{rip_data['title']}.mp4"))) os.remove(f"{rip_data['id']}.mp4") await v_url.delete()
async def gdrive_upload_function(dryb): """ For !gdrive command, upload files to google drive. """ await dryb.edit("Processing ...") input_str = dryb.pattern_match.group(1) if CLIENT_ID is None or CLIENT_SECRET is None: return if not os.path.isdir(TEMP_DOWNLOAD_DIRECTORY): os.makedirs(TEMP_DOWNLOAD_DIRECTORY) required_file_name = None 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() elapsed_time = round(diff) * 1000 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"{status}...\ \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 dryb.edit(current_message) display_message = current_message except Exception as e: LOGS.info(str(e)) pass if downloader.isSuccessful(): await dryb.edit( "Downloaded to `{}` successfully !!\nInitiating Upload to Google Drive.." .format(downloaded_file_name)) required_file_name = downloaded_file_name else: await dryb.edit("Incorrect URL\n{}".format(url)) elif input_str: input_str = input_str.strip() if os.path.exists(input_str): required_file_name = input_str await dryb.edit( "Found `{}` in local server, Initiating Upload to Google Drive.." .format(input_str)) else: await dryb.edit( "File not found in local server. Give me a valid file path !") return False elif dryb.reply_to_msg_id: try: c_time = time.time() downloaded_file_name = await dryb.client.download_media( await dryb.get_reply_message(), TEMP_DOWNLOAD_DIRECTORY, progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task(progress(d, t, dryb, c_time, "Downloading..."))) except Exception as e: await dryb.edit(str(e)) else: required_file_name = downloaded_file_name await dryb.edit( "Downloaded to `{}` Successfully !!\nInitiating Upload to Google Drive.." .format(downloaded_file_name)) if required_file_name: if G_DRIVE_AUTH_TOKEN_DATA is not None: with open(G_DRIVE_TOKEN_FILE, "w") as t_file: t_file.write(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, parent_id) await dryb.edit( f"File:`{required_file_name}`\nwas 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}`")