async def start(self): await super().start() usr_bot_me = await self.get_me() LOGGER.info(f"Reddit-X Bot based on Pyrogram v{__version__} " f"(Layer {layer}) started on @{usr_bot_me.username}. " "Hi.")
async def new_message_event(client, message): try: #my_json_string=JSON.stringify(message) #to_python = JSON.loads(my_json_string) #print(to_python['sticker']) dicted = dict(message) with open(JSON.stringify(message)) as file: # data=json.load(file) #print(len(data["sticker"])) #print(data_dict["message"][0]["file_id"]) await message.reply_text( f"<code>{message}</code>", quote=True, disable_web_page_preview=True, disable_notification=True, ) except (PeerIdInvalid, UserIsBlocked): pass except Exception as e: LOGGER.info(str(e)) with BytesIO(str.encode(str(message))) as out_file: out_file.name = "json.text" await message.reply_document( document=out_file, caption=str(e), disable_notification=True, quote=True )
async def new_inline_query(client, inline_query): try: await client.send_message( chat_id=inline_query.from_user.id, text=f"<code>{inline_query}</code>", # parse_mode=, disable_web_page_preview=True, disable_notification=True, # reply_to_message_id=, ) except (PeerIdInvalid, UserIsBlocked): await inline_query.answer(results=[], cache_time=0, is_gallery=False, is_personal=True, next_offset="", switch_pm_text="please /start bot, first", switch_pm_parameter="bot_not_started") return False except Exception as e: LOGGER.info(str(e)) with BytesIO(str.encode(str(inline_query))) as out_file: out_file.name = "json.text" await client.send_document( chat_id=inline_query.from_user.id, document=out_file, caption=str(e), disable_notification=True, )
async def gDrive_upload_file(creds, file_path, message): service = build("drive", "v3", credentials=creds, cache_discovery=False) mime_type = guess_type(file_path)[0] mime_type = mime_type if mime_type else "text/plain" media_body = MediaFileUpload(file_path, mimetype=mime_type, chunksize=150 * 1024 * 1024, resumable=True) file_name = os.path.basename(file_path) body = { "name": file_name, "description": "Uploaded using TelePyroBot gDrive", "mimeType": mime_type, } u_file_obj = service.files().create(body=body, media_body=media_body) response = None display_message = "" while response is None: status, response = u_file_obj.next_chunk() if status: percentage = int(status.progress() * 100) progress_str = "[{0}{1}]\nProgress: {2}%\n".format( "".join(["●" for i in range(math.floor(percentage / 5))]), "".join(["○" for i in range(20 - math.floor(percentage / 5))]), round(percentage, 2)) current_message = f"uploading to gDrive\nFile Name: {file_name}\n{progress_str}" if display_message != current_message: try: await message.edit_text(current_message) display_message = current_message except Exception as e: LOGGER.info(str(e)) pass file_id = response.get("id") return file_id
async def covid(client, message): if len(message.text.split(" ")) == 1: await message.edit("`Enter a directory location`") elif len(message.text.split(" ",1)) == 2: temp_dir = message.text.split(" ", 1)[1] else: await message.edit(f"__Please check help by using__ `{COMMAND_HAND_LER}help batchup`") status_message = await message.reply_text("`Uploading Files...`") if os.path.exists(temp_dir): files = os.listdir(temp_dir) files.sort() await status_message.edit("`Uploading Files to Telegram...`") for file in files: c_time = time.time() required_file_name = temp_dir+"/"+file thumb_image_path = await is_thumb_image_exists(required_file_name) doc_caption = os.path.basename(required_file_name) LOGGER.info(f"Uploading {required_file_name} from {temp_dir} to Telegram.") await client.send_document( chat_id=message.chat.id, document=required_file_name, thumb=thumb_image_path, caption=doc_caption, parse_mode="html", disable_notification=True, progress=progress_for_pyrogram, progress_args=( "Trying to upload multiple files...", status_message, c_time) ) else: await message.edit("Directory Not Found.") return await status_message.edit(f"Uploaded all files from Directory `{temp_dir}`")
async def load_plugin(client, message): await message.edit("Processing ...") if message.reply_to_message is not None: down_loaded_plugin_name = await message.reply_to_message.download( file_name="./plugins/") if down_loaded_plugin_name is not None: # LOGGER.info(down_loaded_plugin_name) relative_path_for_dlpn = os.path.relpath(down_loaded_plugin_name, os.getcwd()) # LOGGER.info(relative_path_for_dlpn) lded_count = 0 path = Path(relative_path_for_dlpn) module_path = ".".join(path.parent.parts + (path.stem, )) # LOGGER.info(module_path) module = reload(import_module(module_path)) # https://git.io/JvlNL for name in vars(module).keys(): # noinspection PyBroadException try: handler, group = getattr(module, name).handler if isinstance(handler, Handler) and isinstance(group, int): client.add_handler(handler, group) LOGGER.info( '[{}] [LOAD] {}("{}") in group {} from "{}"'. format(client.session_name, type(handler).__name__, name, group, module_path)) lded_count += 1 except Exception as e: # LOGGER.info(str(e)) pass await message.edit(f"installed {lded_count} commands / plugins")
async def start(self): await super().start() usr_bot_me = await self.get_me() self.set_parse_mode("html") LOGGER.info(f"UserBot, hecho por Skueletor v{__version__} " f"(Layer {layer}) comenzó en @{usr_bot_me.username}. " "Hola.")
async def start(self): await super().start() me = await self.get_me() IS_BOT = me.is_bot LOGGER.info( f"PyroGramBot based on Pyrogram v{__version__} (Layer {layer}) started on @{me.username}. Hi." )
async def start(self): await super().start() usr_bot_me = await self.get_me() self.set_parse_mode("html") LOGGER.info(f"PyroGramBot based on Pyrogram v{__version__} " f"(Layer {layer}) started on @{usr_bot_me.username}. " "Hi.")
async def start(self): await super().start() result = load_cmds(ALL_PLUGINS) LOGGER.info(result) usr_bot_me = await self.get_me() LOGGER.info(f"PyroGramBot based on Pyrogram v{__version__} " f"(Layer {layer}) started..." f"Hey {usr_bot_me.first_name}")
async def stop(self, *args): await self.save_public_store(TG_IRU_S_M_ID, json.dumps(self.filterstore)) await self.save_public_store(WARN_DATA_ID, json.dumps(self.warndatastore)) await self.save_public_store(WARN_SETTINGS_ID, json.dumps(self.warnsettingsstore)) await super().stop() LOGGER.info("PyroGramBot stopped. Bye.")
async def start(self): await super().start() usr_bot_me = await self.get_me() self.set_parse_mode("html") self.filterstore = await self.load_public_store(TG_IRU_S_M_ID) self.warndatastore = await self.load_public_store(WARN_DATA_ID) self.warnsettingsstore = await self.load_public_store(WARN_SETTINGS_ID) LOGGER.info(f"PyroGramBot based on Pyrogram v{__version__} " f"(Layer {layer}) started on @{usr_bot_me.username}. " "Hi.")
async def gDrive_upload_file(creds, file_path, message): # Create Google Drive service instance service = build("drive", "v3", credentials=creds, cache_discovery=False) # getting the mime type of the file mime_type = guess_type(file_path)[0] mime_type = mime_type if mime_type else "text/plain" # File body description media_body = MediaFileUpload( file_path, mimetype=mime_type, chunksize=150 * 1024 * 1024, resumable=True ) file_name = os.path.basename(file_path) body = { "name": file_name, "description": "Uploaded using PyrogramUserBot gDrive v7", "mimeType": mime_type, } # Insert a file u_file_obj = service.files().create(body=body, media_body=media_body) response = None display_message = "" while response is None: status, response = u_file_obj.next_chunk() # await asyncio.sleep(5) if status: percentage = int(status.progress() * 100) progress_str = "[{0}{1}]\nProgress: {2}%\n".format( "".join(["â–ˆ" for i in range(math.floor(percentage / 5))]), "".join(["â–‘" for i in range(20 - math.floor(percentage / 5))]), round(percentage, 2), ) current_message = ( f"uploading to gDrive\nFile Name: {file_name}\n{progress_str}" ) if display_message != current_message: try: await message.edit_text(current_message) display_message = current_message except Exception as e: LOGGER.info(str(e)) pass # Permissions body description: anyone who has link can upload # Other permissions can be found at https://developers.google.com/drive/v3/reference/permissions # permissions = { # "role": "reader", # "type": "anyone", # "value": None, # "withLink": True # } # try: # # Insert new permissions # service.permissions().insert(fileId=file_id, body=permissions).execute() # except: # pass file_id = response.get("id") return file_id
async def start(self): await super().start() usr_bot_me = await self.get_me() self.filterstore = await self.load_public_store(TG_IRU_S_M_ID) self.warndatastore = await self.load_public_store(WARN_DATA_ID) self.warnsettingsstore = await self.load_public_store(WARN_SETTINGS_ID) if LAYER_UPDATE_INTERVAL: await check_feed(self) LOGGER.info(f"PyroGramBot based on Pyrogram v{__version__} " f"(Layer {layer}) started on @{usr_bot_me.username}. " "Hi.")
async def stop(self, *args): LOGGER.info(self.publicstore) try: await self.edit_message_text(chat_id=TG_URI, message_id=TG_IRU_S_M_ID, text=json.dumps(self.publicstore), disable_web_page_preview=True) except MessageNotModified: pass await super().stop() LOGGER.info("PyroGramBot stopped. Bye.")
async def take_screen_shot(video_file: str, duration: int, path: str = '') -> Optional[str]: """take a screenshot.""" ttl = duration // 2 thumb_image_path = path or os.path.join(screen_shot, f"{basename(video_file)}.jpg") command = f"ffmpeg -ss {ttl} -i '{video_file}' -vframes 1 '{thumb_image_path}'" err = (await run_cmd(command))[1] if err: LOGGER.info(err) return thumb_image_path if os.path.exists(thumb_image_path) else None
async def new_message_event(client, message): try: await message.reply_text( f"<code>{message}</code>", quote=True, disable_web_page_preview=True, disable_notification=True, ) except (PeerIdInvalid, UserIsBlocked): pass except Exception as e: LOGGER.info(str(e)) with BytesIO(str.encode(str(message))) as out_file: out_file.name = "json.text" await message.reply_document(document=out_file, caption=str(e), disable_notification=True, quote=True)
async def upload_as_document(client, message): text = message.command[1:] if not text: await message.edit("`Input not found`") return s_time = 0.1 typing_symbol = '|' old_text = '' await message.edit(typing_symbol) time.sleep(s_time) for character in text: s_t = s_time / random.randint(1, 100) old_text += character typing_text = old_text + typing_symbol try: await message.try_to_edit(typing_text, sudo=False) time.sleep(s_t) await message.try_to_edit(old_text, sudo=False) time.sleep(s_t) except FloodWait as ef: time.sleep(ef.x) LOGGER.info(str(ef))
async def start(self): await super().start() for oof in ALL_PLUGINS: if oof.lower() == "help": continue imported_module = importlib.import_module("pyrobot.plugins." + oof) if not hasattr(imported_module, "__PLUGIN__"): imported_module.__PLUGIN__ = imported_module.__name__ if not imported_module.__PLUGIN__.lower() in HELP_COMMANDS: HELP_COMMANDS[imported_module.__PLUGIN__.lower()] = imported_module else: raise Exception("Can't have two modules with the same name! Please change one") if hasattr(imported_module, "__help__") and imported_module.__help__: HELP_COMMANDS[imported_module.__PLUGIN__.lower()] = imported_module.__help__ usr_bot_me = await self.get_me() LOGGER.info( f"PyroGramBot based on Pyrogram v{__version__} " f"(Layer {layer}) started..." f"Hey {usr_bot_me.first_name}")
async def chosen_inline_result(client, inline_query): try: await client.send_message( chat_id=inline_query.from_user.id, text=f"<code>{inline_query}</code>", # parse_mode=, disable_web_page_preview=True, disable_notification=True, # reply_to_message_id=, ) except (PeerIdInvalid, UserIsBlocked): # this should ideally not happen, # but, who knows? :\ pass except Exception as e: LOGGER.info(str(e)) with BytesIO(str.encode(str(inline_query))) as out_file: out_file.name = "json.text" await client.send_document( chat_id=inline_query.from_user.id, document=out_file, caption=str(e), disable_notification=True, )
async def reinstall_bot(client, message): await message.edit("__Reinstalling!!__\n**Please Wait...**") if HEROKU_API_KEY is None or HEROKU_APP_NAME is None: await message.edit("__Please the Vars__ `HEROKU_API_KEY` __and__ `HEROKU_APP_NAME` __properly!__") return try: repo = git.Repo() except git.exc.InvalidGitRepositoryError as error_one: LOGGER.info(str(error_one)) repo = git.Repo.init() origin = repo.create_remote(REPO_REMOTE_NAME, OFFICIAL_UPSTREAM_REPO) origin.fetch() repo.create_head(IFFUCI_ACTIVE_BRANCH_NAME, origin.refs.master) repo.heads.master.checkout(True) active_branch_name = repo.active_branch.name LOGGER.info(active_branch_name) if active_branch_name != IFFUCI_ACTIVE_BRANCH_NAME: await message.edit(IS_SELECTED_DIFFERENT_BRANCH.format( branch_name=active_branch_name, COMMAND_HAND_LER=COMMAND_HAND_LER )) return False try: repo.create_remote(REPO_REMOTE_NAME, OFFICIAL_UPSTREAM_REPO) except Exception as error_two: LOGGER.info(str(error_two)) tmp_upstream_remote = repo.remote(REPO_REMOTE_NAME) tmp_upstream_remote.fetch(active_branch_name) await asyncio.sleep(3) tmp_upstream_remote.fetch(active_branch_name) repo.git.reset("--hard", "FETCH_HEAD") if HEROKU_API_KEY is not None: import heroku3 heroku = heroku3.from_key(HEROKU_API_KEY) heroku_app = heroku.apps()[HEROKU_APP_NAME] heroku_git_url = heroku_app.git_url.replace( "https://", "https://*****:*****@" ) if "heroku" in repo.remotes: remote = repo.remote("heroku") remote.set_url(heroku_git_url) else: remote = repo.create_remote("heroku", heroku_git_url) remote.push(refspec=HEROKU_GIT_REF_SPEC, force=True) else: await message.edit(NO_HEROKU_APP_CFGD)
async def updater(client, message): await message.edit("`Updating Please Wait...`") try: repo = git.Repo() except git.exc.InvalidGitRepositoryError as error_one: LOGGER.info(str(error_one)) repo = git.Repo.init() origin = repo.create_remote(REPO_REMOTE_NAME, OFFICIAL_UPSTREAM_REPO) origin.fetch() repo.create_head(IFFUCI_ACTIVE_BRANCH_NAME, origin.refs.master) repo.heads.master.checkout(True) active_branch_name = repo.active_branch.name LOGGER.info(active_branch_name) if active_branch_name != IFFUCI_ACTIVE_BRANCH_NAME: await message.edit( IS_SELECTED_DIFFERENT_BRANCH.format(branch_name=active_branch_name) ) return False try: repo.create_remote(REPO_REMOTE_NAME, OFFICIAL_UPSTREAM_REPO) except Exception as error_two: LOGGER.info(str(error_two)) tmp_upstream_remote = repo.remote(REPO_REMOTE_NAME) tmp_upstream_remote.fetch(active_branch_name) await asyncio.sleep(8) await message.edit(UPDATE_IN_PROGRESS) tmp_upstream_remote.fetch(active_branch_name) repo.git.reset("--hard", "FETCH_HEAD") if HEROKU_API_KEY is not None: import heroku3 heroku = heroku3.from_key(HEROKU_API_KEY) heroku_app = heroku.apps()[HEROKU_APP_NAME] heroku_git_url = heroku_app.git_url.replace( "https://", "https://*****:*****@") if "heroku" in repo.remotes: remote = repo.remote("heroku") remote.set_url(heroku_git_url) else: remote = repo.create_remote("heroku", heroku_git_url) remote.push(refspec=HEROKU_GIT_REF_SPEC) else: await message.edit(NO_HEROKU_APP_CFGD)
async def updater(client, message): if len(message.command) == 2 and message.command[1] == "force": force_update = True else: force_update = False umsg = await message.reply("`Checking for Update...`") if HEROKU_API_KEY is None or HEROKU_APP_NAME is None: await umsg.edit( "__Please the Vars__ `HEROKU_API_KEY` __and__ `HEROKU_APP_NAME` __properly!__" ) return if PRIVATE_GROUP_ID is None: await umsg.edit( "__**Please Set**__ `PRIVATE_GROUP_ID` **__to use updater!__**") try: repo = git.Repo() except git.exc.InvalidGitRepositoryError as error_one: LOGGER.info(str(error_one)) repo = git.Repo.init() origin = repo.create_remote(REPO_REMOTE_NAME, OFFICIAL_UPSTREAM_REPO) origin.fetch() repo.create_head(IFFUCI_ACTIVE_BRANCH_NAME, origin.refs.master) repo.heads.master.checkout(True) active_branch_name = repo.active_branch.name LOGGER.info(active_branch_name) if active_branch_name != IFFUCI_ACTIVE_BRANCH_NAME: await umsg.edit( IS_SELECTED_DIFFERENT_BRANCH.format( branch_name=active_branch_name, COMMAND_HAND_LER=COMMAND_HAND_LER)) return try: repo.create_remote(REPO_REMOTE_NAME, OFFICIAL_UPSTREAM_REPO) except Exception as error_two: LOGGER.info(str(error_two)) temp_remote = repo.remote(REPO_REMOTE_NAME) temp_remote.fetch(active_branch_name) changelog = generate_change_log( repo, DIFF_MARKER.format(remote_name=REPO_REMOTE_NAME, branch_name=active_branch_name)) LOGGER.info(changelog) try: remote_head_github = repo.head.reference commit_id = remote_head_github.commit.hexsha commit_link = f"<a href='https://github.com/SkuzzyxD/TelePyroBot/commit/{commit_id}'>{commit_id[:7]}</a>" except: commit_link = "None" message_one = NEW_BOT_UP_DATE_FOUND.format(branch_name=active_branch_name, changelog=changelog, commit_link=commit_link) message_two = NEW_UP_DATE_FOUND.format(branch_name=active_branch_name) if len(message_one) > MAX_MESSAGE_LENGTH: with open("change.log", "w+", encoding="utf8") as out_file: out_file.write(str(message_one)) await message.reply_document(document="change.log", caption=message_two, disable_notification=True, reply_to_message_id=message.message_id) os.remove("change.log") if not changelog and force_update == False: await umsg.edit("`Your userbot is already up-to-date!!`") return await umsg.edit(message_one, disable_web_page_preview=True) if force_update == True: await umsg.edit( "**Force-Update initiated**\n`Fetching latest version and installing it...`" ) changelog = "#ForceUpdate" temp_remote.fetch(active_branch_name) repo.git.reset("--hard", "FETCH_HEAD") heroku = heroku3.from_key(HEROKU_API_KEY) heroku_app = heroku.apps()[HEROKU_APP_NAME] heroku_git_url = heroku_app.git_url.replace( "https://", f"https://*****:*****@") if "heroku" in repo.remotes: remote = repo.remote("heroku") remote.set_url(heroku_git_url) else: remote = repo.create_remote("heroku", heroku_git_url) await umsg.reply( f"**Update Started**\n__**Type**__ `{COMMAND_HAND_LER}alive` **__to check if I'm alive__**\n\n**It would take upto 5 minutes to update!**" ) await client.send_message( PRIVATE_GROUP_ID, f"#UPDATE\n\n**__TelePyroBot Update__** {commit_link}\n\n**Changelog:**\n{changelog}", disable_web_page_preview=True) remote.push(refspec=HEROKU_GIT_REF_SPEC, force=True) asyncio.get_event_loop().create_task(deploy_start(client))
async def extract_youtube_dl_formats(url, user_working_dir): command_to_exec = [ "youtube-dl", "--no-warnings", "--youtube-skip-dash-manifest", "-j", url ] if "hotstar" in url: command_to_exec.append("--geo-bypass-country") command_to_exec.append("IN") LOGGER.info(command_to_exec) process = await asyncio.create_subprocess_exec( *command_to_exec, # stdout must a pipe to be accessible as process.stdout stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) # Wait for the subprocess to finish stdout, stderr = await process.communicate() e_response = stderr.decode().strip() LOGGER.info(e_response) t_response = stdout.decode().strip() LOGGER.info(t_response) # https://github.com/rg3/youtube-dl/issues/2630#issuecomment-38635239 if e_response: # logger.warn("Status : FAIL", exc.returncode, exc.output) error_message = e_response.replace( "please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see https://yt-dl.org/update on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output.", "" ) return None, error_message, None if t_response: # logger.info(t_response) x_reponse = t_response response_json = [] if "\n" in x_reponse: for yu_r in x_reponse.split("\n"): response_json.append(json.loads(yu_r)) else: response_json.append(json.loads(x_reponse)) # response_json = json.loads(x_reponse) save_ytdl_json_path = user_working_dir + \ "/" + str("ytdleech") + ".json" with open(save_ytdl_json_path, "w", encoding="utf8") as outfile: json.dump(response_json, outfile, ensure_ascii=False) # logger.info(response_json) inline_keyboard = [] # thumb_image = "https://placehold.it/90x90" # for current_r_json in response_json: # thumb_image = current_r_json.get("thumbnail", thumb_image) # duration = None if "duration" in current_r_json: duration = current_r_json["duration"] if "formats" in current_r_json: for formats in current_r_json["formats"]: format_id = formats.get("format_id") format_string = formats.get("format_note") if format_string is None: format_string = formats.get("format") format_ext = formats.get("ext") approx_file_size = "" if "filesize" in formats: approx_file_size = humanbytes(formats["filesize"]) dipslay_str_uon = " " + format_string + " (" + format_ext.upper() + ") " + approx_file_size + " " cb_string_video = "ytdl_{}|{}|{}".format( "video", format_id, format_ext) ikeyboard = [] if "drive.google.com" in url: if format_id == "source": ikeyboard = [ InlineKeyboardButton( dipslay_str_uon, callback_data=(cb_string_video).encode("UTF-8") ) ] else: if format_string is not None and not "audio only" in format_string: ikeyboard = [ InlineKeyboardButton( dipslay_str_uon, callback_data=(cb_string_video).encode("UTF-8") ) ] else: # special weird case :\ ikeyboard = [ InlineKeyboardButton( "SVideo [" + "] ( " + approx_file_size + " )", callback_data=(cb_string_video).encode("UTF-8") ) ] inline_keyboard.append(ikeyboard) if duration is not None: cb_string_64 = "ytdl_{}|{}|{}".format("audio", "64k", "mp3") cb_string_128 = "ytdl_{}|{}|{}".format("audio", "128k", "mp3") cb_string = "ytdl_{}|{}|{}".format("audio", "320k", "mp3") inline_keyboard.append([ InlineKeyboardButton( "MP3 " + "(" + "64 kbps" + ")", callback_data=cb_string_64.encode("UTF-8") ), InlineKeyboardButton( "MP3 " + "(" + "128 kbps" + ")", callback_data=cb_string_128.encode("UTF-8") ) ]) inline_keyboard.append([ InlineKeyboardButton( "MP3 " + "(" + "320 kbps" + ")", callback_data=cb_string.encode("UTF-8") ) ]) else: format_id = current_r_json["format_id"] format_ext = current_r_json["ext"] cb_string_video = "ytdl_{}|{}|{}".format( "video", format_id, format_ext) inline_keyboard.append([ InlineKeyboardButton( "SVideo", callback_data=(cb_string_video).encode("UTF-8") ) ]) break reply_markup = InlineKeyboardMarkup(inline_keyboard) # LOGGER.info(reply_markup) succss_mesg = """Select the desired format: 👇 <u>mentioned</u> <i>file size might be approximate</i>""" return thumb_image, succss_mesg, reply_markup
async def updater(client, message): status_message = await message.reply_text("🤔😳😳🙄") try: repo = git.Repo() except git.exc.InvalidGitRepositoryError as error_one: LOGGER.info(str(error_one)) repo = git.Repo.init() origin = repo.create_remote(REPO_REMOTE_NAME, OFFICIAL_UPSTREAM_REPO) origin.fetch() repo.create_head(IFFUCI_ACTIVE_BRANCH_NAME, origin.refs.master) repo.heads.master.checkout(True) active_branch_name = repo.active_branch.name LOGGER.info(active_branch_name) if active_branch_name != IFFUCI_ACTIVE_BRANCH_NAME: await status_message.edit( IS_SELECTED_DIFFERENT_BRANCH.format(branch_name=active_branch_name) ) return False try: repo.create_remote(REPO_REMOTE_NAME, OFFICIAL_UPSTREAM_REPO) except Exception as error_two: LOGGER.info(str(error_two)) tmp_upstream_remote = repo.remote(REPO_REMOTE_NAME) tmp_upstream_remote.fetch(active_branch_name) changelog = generate_change_log( repo, DIFF_MARKER.format(remote_name=REPO_REMOTE_NAME, branch_name=active_branch_name)) LOGGER.info(changelog) if not changelog: await status_message.edit(BOT_IS_UP_TO_DATE) return False message_one = NEW_BOT_UP_DATE_FOUND.format(branch_name=active_branch_name, changelog=changelog) message_two = NEW_UP_DATE_FOUND.format(branch_name=active_branch_name) if len(message_one) > MAX_MESSAGE_LENGTH: with open("change.log", "w+", encoding="utf8") as out_file: out_file.write(str(message_one)) await message.reply_document(document="change.log", caption=message_two, disable_notification=True, reply_to_message_id=message.message_id) os.remove("change.log") else: await message.reply(message_one) tmp_upstream_remote.fetch(active_branch_name) repo.git.reset("--hard", "FETCH_HEAD") if HEROKU_API_KEY is not None: import heroku3 heroku = heroku3.from_key(HEROKU_API_KEY) heroku_applications = heroku.apps() if len(heroku_applications) >= 1: # assuming there will be only one heroku application # created per account 🙃 # possibly, ignore premium Heroku users heroku_app = heroku_applications[0] heroku_git_url = heroku_app.git_url.replace( "https://", "https://*****:*****@") if "heroku" in repo.remotes: remote = repo.remote("heroku") remote.set_url(heroku_git_url) else: remote = repo.create_remote("heroku", heroku_git_url) remote.push(refspec=HEROKU_GIT_REF_SPEC) else: await message.reply(NO_HEROKU_APP_CFGD) await status_message.edit(RESTARTING_APP) # https://t.me/c/1387666944/94908 asyncio.get_event_loop().create_task(restart(client, status_message))
async def down_load_media(client, sms): message = await sms.reply_text("...", quote=True) if not os.path.isdir(TMP_DOWNLOAD_DIRECTORY): os.makedirs(TMP_DOWNLOAD_DIRECTORY) if sms.reply_to_message is not None: start_t = datetime.now() download_location = TMP_DOWNLOAD_DIRECTORY + "/" c_time = time.time() the_real_download_location = await client.download_media( message=sms.reply_to_message, file_name=download_location, progress=progress_for_pyrogram, progress_args=("trying to download", message, c_time)) end_t = datetime.now() ms = (end_t - start_t).seconds await message.edit( f"Downloaded to <code>{the_real_download_location}</code> in <u>{ms}</u> seconds", parse_mode="html") elif len(sms.command) > 1: start_t = datetime.now() the_url_parts = " ".join(sms.command[1:]) url = the_url_parts.strip() custom_file_name = os.path.basename(url) if "|" in the_url_parts: url, custom_file_name = the_url_parts.split("|") url = url.strip() custom_file_name = custom_file_name.strip() download_file_path = os.path.join(TMP_DOWNLOAD_DIRECTORY, custom_file_name) downloader = SmartDL(url, download_file_path, 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\n" current_message += f"URL: {url}\n" current_message += f"File Name: {custom_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 message.edit(disable_web_page_preview=True, text=current_message) display_message = current_message await asyncio.sleep(10) except Exception as e: LOGGER.info(str(e)) pass if os.path.exists(download_file_path): end_t = datetime.now() ms = (end_t - start_t).seconds await message.edit( f"Downloaded to <code>{download_file_path}</code> in <u>{ms}</u> seconds", parse_mode="html") else: await message.edit( "Reply to a Telegram Media, to download it to local server.")
async def stop(self, *args): await super().stop() LOGGER.info("PyroGramBot stopped. Bye.")
async def updater(client, message): await message.edit("`Checking for Update...`") if HEROKU_API_KEY is None or HEROKU_APP_NAME is None: await message.edit("__Please the Vars__ `HEROKU_API_KEY` __and__ `HEROKU_APP_NAME` __properly!__") return try: repo = git.Repo() except git.exc.InvalidGitRepositoryError as error_one: LOGGER.info(str(error_one)) repo = git.Repo.init() origin = repo.create_remote(REPO_REMOTE_NAME, OFFICIAL_UPSTREAM_REPO) origin.fetch() repo.create_head(IFFUCI_ACTIVE_BRANCH_NAME, origin.refs.master) repo.heads.master.checkout(True) active_branch_name = repo.active_branch.name LOGGER.info(active_branch_name) if active_branch_name != IFFUCI_ACTIVE_BRANCH_NAME: await message.edit(IS_SELECTED_DIFFERENT_BRANCH.format( branch_name=active_branch_name, COMMAND_HAND_LER=COMMAND_HAND_LER )) return False try: repo.create_remote(REPO_REMOTE_NAME, OFFICIAL_UPSTREAM_REPO) except Exception as error_two: LOGGER.info(str(error_two)) tmp_upstream_remote = repo.remote(REPO_REMOTE_NAME) tmp_upstream_remote.fetch(active_branch_name) try: changelog = generate_change_log( repo, DIFF_MARKER.format( remote_name=REPO_REMOTE_NAME, branch_name=active_branch_name ) ) LOGGER.info(changelog) except: pass message_one = NEW_BOT_UP_DATE_FOUND.format( branch_name=active_branch_name, changelog=changelog ) message_two = NEW_UP_DATE_FOUND.format( branch_name=active_branch_name ) if changelog: if len(message_one) > MAX_MESSAGE_LENGTH: with open("change.log", "w+", encoding="utf8") as out_file: out_file.write(str(message_one)) await message.reply_document( document="change.log", caption=message_two, disable_notification=True, reply_to_message_id=message.message_id ) os.remove("change.log") else: await message.reply(message_one) else: await message.edit(BOT_IS_UP_TO_DATE) return await asyncio.sleep(3) tmp_upstream_remote.fetch(active_branch_name) await message.reply(f"**Update Started!**\n__**Type**__ `{COMMAND_HAND_LER}alive` **__to check if I'm alive__**\n\n**It would take upto 5 minutes to update!**") repo.git.reset("--hard", "FETCH_HEAD") if HEROKU_API_KEY is not None: import heroku3 heroku = heroku3.from_key(HEROKU_API_KEY) heroku_app = heroku.apps()[HEROKU_APP_NAME] heroku_git_url = heroku_app.git_url.replace( "https://", "https://*****:*****@" ) if "heroku" in repo.remotes: remote = repo.remote("heroku") remote.set_url(heroku_git_url) else: remote = repo.create_remote("heroku", heroku_git_url) remote.push(refspec=HEROKU_GIT_REF_SPEC, force=True) else: await message.edit(NO_HEROKU_APP_CFGD)
async def youtube_dl_call_back(bot, update, cb_data): LOGGER.info(update) # youtube_dl extractors tg_send_type, youtube_dl_format, youtube_dl_ext = cb_data.split("|") # current_user_id = update.message.reply_to_message.from_user.id current_touched_user_id = update.from_user.id if current_user_id != current_touched_user_id: return False, None user_working_dir = os.path.join(TMP_DOWNLOAD_DIRECTORY, str(current_user_id)) # create download directory, if not exist if not os.path.isdir(user_working_dir): await bot.delete_messages( chat_id=update.message.chat.id, message_ids=[ update.message.message_id, update.message.reply_to_message.message_id, ], revoke=True) return save_ytdl_json_path = user_working_dir + \ "/" + str("ytdleech") + ".json" try: with open(save_ytdl_json_path, "r", encoding="utf8") as f_d: response_json = json.load(f_d) os.remove(save_ytdl_json_path) except FileNotFoundError: await bot.delete_messages( chat_id=update.message.chat.id, message_ids=[ update.message.message_id, update.message.reply_to_message.message_id, ], revoke=True) return False # response_json = response_json[0] # TODO: temporary limitations LOGGER.info(response_json) # youtube_dl_url = response_json.get("webpage_url") LOGGER.info(youtube_dl_url) # custom_file_name = "%(title)s.%(ext)s" # https://superuser.com/a/994060 LOGGER.info(custom_file_name) # await update.message.edit_caption(caption="trying to download") description = "@PyroGramBot" if "fulltitle" in response_json: description = response_json["fulltitle"][0:1021] # escape Markdown and special characters # tmp_directory_for_each_user = os.path.join(TMP_DOWNLOAD_DIRECTORY, str(update.from_user.id)) if not os.path.isdir(tmp_directory_for_each_user): os.makedirs(tmp_directory_for_each_user) download_directory = tmp_directory_for_each_user download_directory = os.path.join(tmp_directory_for_each_user, custom_file_name) command_to_exec = [] if tg_send_type == "audio": command_to_exec = [ "youtube-dl", "-c", "--prefer-ffmpeg", "--extract-audio", "--add-metadata", "--embed-thumbnail", "--audio-format", youtube_dl_ext, "--audio-quality", youtube_dl_format, youtube_dl_url, "-o", download_directory, # "--external-downloader", "aria2c" ] else: # command_to_exec = ["youtube-dl", "-f", youtube_dl_format, "--hls-prefer-ffmpeg", "--recode-video", "mp4", "-k", youtube_dl_url, "-o", download_directory] minus_f_format = youtube_dl_format if "youtu" in youtube_dl_url: for for_mat in response_json["formats"]: format_id = for_mat.get("format_id") if format_id == youtube_dl_format: acodec = for_mat.get("acodec") vcodec = for_mat.get("vcodec") if acodec == "none" or vcodec == "none": minus_f_format = youtube_dl_format + "+bestaudio" break command_to_exec = [ "youtube-dl", "-c", # "--embed-subs", "-f", minus_f_format, "--hls-prefer-ffmpeg", youtube_dl_url, "-o", download_directory, # "--external-downloader", "aria2c" ] # command_to_exec.append("--no-warnings") # command_to_exec.append("--quiet") command_to_exec.append("--restrict-filenames") # if "hotstar" in youtube_dl_url: command_to_exec.append("--geo-bypass-country") command_to_exec.append("IN") LOGGER.info(command_to_exec) start = datetime.now() t_response, e_response = await run_command(command_to_exec) # LOGGER.info(e_response) # LOGGER.info(t_response) ad_string_to_replace = "please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see https://yt-dl.org/update on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output." if e_response and ad_string_to_replace in e_response: error_message = e_response.replace(ad_string_to_replace, "") await update.message.edit_caption(caption=error_message) return False, None if t_response: # LOGGER.info(t_response) # os.remove(save_ytdl_json_path) end_one = datetime.now() time_taken_for_download = (end_one - start).seconds dir_contents = os.listdir(tmp_directory_for_each_user) # dir_contents.sort() await update.message.edit_caption( f"found {len(dir_contents)} files" f"\n Download took {time_taken_for_download} seconds" "\n Trying to Upload, now ...") LOGGER.info(dir_contents) # for single_file in dir_contents: local_file_name = os.path.join(tmp_directory_for_each_user, single_file) thumb = await is_thumb_image_exists(local_file_name) # caption_str = os.path.basename(local_file_name) metadata = extractMetadata(createParser(local_file_name)) 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") width, height = 0, 0 if thumb is not None: metadata = extractMetadata(createParser(thumb)) if metadata.has("height"): height = metadata.get("height") if metadata.has("width"): height = metadata.get("width") if local_file_name.upper().endswith(("MKV", "MP4", "WEBM")): await update.message.edit_media( media=InputMediaVideo(media=local_file_name, thumb=thumb, caption=description, parse_mode="html", width=width, height=height, duration=duration, supports_streaming=True)) elif local_file_name.upper().endswith( ("MP3", "M4A", "M4B", "FLAC", "WAV")): await update.message.edit_media(media=InputMediaAudio( media=local_file_name, thumb=thumb, caption=description, parse_mode="html", duration=duration, performer=artist, title=title) # quote=True, ) else: await update.message.edit_media(media=InputMediaDocument( media=local_file_name, thumb=thumb, caption=description, parse_mode="html") # quote=True, ) # try: shutil.rmtree(tmp_directory_for_each_user) except: pass
async def stop(self, *args): await super().stop() LOGGER.info("Reddit-X Bot stopped. Bye.")