diff --git a/userbot/__init__.py b/userbot/__init__.py index ee614b7..7cfc7aa 100644 --- a/userbot/__init__.py +++ b/userbot/__init__.py @@ -56,8 +56,8 @@ ) else: basicConfig( - format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", - level=INFO) + format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=INFO + ) LOGS = getLogger(__name__) if version_info[0] < 3 or version_info[1] < 9: @@ -150,8 +150,7 @@ # Chrome Driver and Headless Google Chrome Binaries CHROME_DRIVER = os.environ.get("CHROME_DRIVER") or "/usr/bin/chromedriver" -GOOGLE_CHROME_BIN = os.environ.get( - "GOOGLE_CHROME_BIN") or "/usr/bin/google-chrome" +GOOGLE_CHROME_BIN = os.environ.get("GOOGLE_CHROME_BIN") or "/usr/bin/google-chrome" # set to True if you want to log PMs to your PM_LOGGR_BOT_API_ID NC_LOG_P_M_S = bool(os.environ.get("NC_LOG_P_M_S", False)) @@ -216,12 +215,14 @@ S_PACK_NAME = os.environ.get("S_PACK_NAME", None) # Default .alive logo -ALIVE_LOGO = (os.environ.get("ALIVE_LOGO") - or "https://telegra.ph/file/8eb368517a8d3933c05d9.jpg") +ALIVE_LOGO = ( + os.environ.get("ALIVE_LOGO") or "https://telegra.ph/file/8eb368517a8d3933c05d9.jpg" +) # Default .helpme logo -INLINE_PIC = (os.environ.get("INLINE_PIC") - or "https://telegra.ph/file/8eb368517a8d3933c05d9.jpg") +INLINE_PIC = ( + os.environ.get("INLINE_PIC") or "https://telegra.ph/file/8eb368517a8d3933c05d9.jpg" +) # Default Emoji Help Inline EMOJI_HELP = os.environ.get("EMOJI_HELP") or "|" @@ -254,8 +255,7 @@ G_DRIVE_CLIENT_SECRET = os.environ.get("G_DRIVE_CLIENT_SECRET", None) G_DRIVE_AUTH_TOKEN_DATA = os.environ.get("G_DRIVE_AUTH_TOKEN_DATA", None) G_DRIVE_FOLDER_ID = os.environ.get("G_DRIVE_FOLDER_ID", None) -TEMP_DOWNLOAD_DIRECTORY = os.environ.get( - "TMP_DOWNLOAD_DIRECTORY", "./downloads") +TEMP_DOWNLOAD_DIRECTORY = os.environ.get("TMP_DOWNLOAD_DIRECTORY", "./downloads") # Google Photos G_PHOTOS_CLIENT_ID = os.environ.get("G_PHOTOS_CLIENT_ID", None) G_PHOTOS_CLIENT_SECRET = os.environ.get("G_PHOTOS_CLIENT_SECRET", None) @@ -345,7 +345,8 @@ async def check_botlog_chatid(): if entity.default_banned_rights.send_messages: LOGS.info( "Akun Anda Tidak Memiliki Hak Untuk Mengirim Pesan Ke BOTLOG_CHATID " - "Grup Pribadi Periksa Apakah Anda Mengetik ID Obrolan Benar") + "Grup Pribadi Periksa Apakah Anda Mengetik ID Obrolan Benar" + ) quit(1) @@ -424,7 +425,7 @@ def paginate_help(page_number, loaded_modules, prefix): modulo_page = page_number % max_num_pages if len(pairs) > number_of_rows: pairs = pairs[ - modulo_page * number_of_rows: number_of_rows * (modulo_page + 1) + modulo_page * number_of_rows : number_of_rows * (modulo_page + 1) ] + [ ( custom.Button.inline( @@ -498,7 +499,8 @@ async def handler(event): f"**Database :** Mongo db \n" f"**Bahasa :** Python \n" f"**Daftar Perintah Bot :** [KLIK DISINI](https://telegra.ph/Perintah-Penggunaan-08-05) \n" - "========================================") + "========================================" + ) await king.tgbot.send_file( event.chat_id, file=logo, @@ -576,7 +578,8 @@ async def handler(event): f"`Database :` Mongo db \n\n" "=============================\n" f" **USERBOT TELEGRAM** \n" - "=============================") + "=============================" + ) await king.tgbot.send_file( event.chat_id, file=alive, @@ -604,7 +607,8 @@ async def handler(event): f"πŸ‘‹πŸ» Hai [{get_display_name(u)}](tg://user?id={u.id}) Jika anda\n" f"Ingin donasi atau menyumbang uang ini ke developer kami\n\n" f"β€’ **Notes : Donasi Seikhlasnya** \n\n" - f"**Terimakasih** ") + f"**Terimakasih** " + ) await king.tgbot.send_file( event.chat_id, file=donate, @@ -652,8 +656,7 @@ async def inline_handler(event): builder = event.builder result = None query = event.text - if event.query.user_id == uid and query.startswith( - "@KingUserbotSupport"): + if event.query.user_id == uid and query.startswith("@KingUserbotSupport"): buttons = paginate_help(0, dugmeler, "helpme") result = builder.photo( file=logo, @@ -817,10 +820,8 @@ async def on_plug_in_callback_query_handler(event): ) async def on_plug_in_callback_query_handler(event): if event.query.user_id == uid: # pylint:disable=E0602 - current_page_number = int( - event.data_match.group(1).decode("UTF-8")) - buttons = paginate_help( - current_page_number + 1, dugmeler, "helpme") + current_page_number = int(event.data_match.group(1).decode("UTF-8")) + buttons = paginate_help(current_page_number + 1, dugmeler, "helpme") # https://t.me/TelethonChat/115200 await event.edit(buttons=buttons) else: @@ -863,8 +864,7 @@ async def on_plug_in_callback_query_handler(event): ) async def on_plug_in_callback_query_handler(event): if event.query.user_id == uid: # pylint:disable=E0602 - current_page_number = int( - event.data_match.group(1).decode("UTF-8")) + current_page_number = int(event.data_match.group(1).decode("UTF-8")) buttons = paginate_help( current_page_number - 1, dugmeler, "helpme" # pylint:disable=E0602 ) @@ -973,7 +973,8 @@ async def on_plug_in_callback_query_handler(event): f"✘ **Set Vars :**\n" f"`.set var ALIVE_LOGO` \n" f"`.set var KING_TEKS_KUSTOM` \n" - f"`.set var ALIVE_LOGO None` ") + f"`.set var ALIVE_LOGO None` " + ) await event.edit( text, file=logo, @@ -1005,7 +1006,8 @@ async def on_plug_in_callback_query_handler(event): f"✘ **Set Vars :**\n" f"`.set var PMPERMIT_PIC` \n" f"`.set var PMPERMIT_TEXT` \n" - f"`.set var PMPERMIT_PIC None` ") + f"`.set var PMPERMIT_PIC None` " + ) await event.edit( text, file=logo, diff --git a/userbot/events.py b/userbot/events.py index aa88361..101f84a 100644 --- a/userbot/events.py +++ b/userbot/events.py @@ -139,8 +139,7 @@ async def wrapper(check): command, stdout=asyncsub.PIPE, stderr=asyncsub.PIPE ) stdout, stderr = await process.communicate() - result = str(stdout.decode().strip()) + \ - str(stderr.decode().strip()) + result = str(stdout.decode().strip()) + str(stderr.decode().strip()) ftext += result diff --git a/userbot/modules/__inlinehelp.py b/userbot/modules/__inlinehelp.py index 3693b26..7307844 100644 --- a/userbot/modules/__inlinehelp.py +++ b/userbot/modules/__inlinehelp.py @@ -24,8 +24,8 @@ logging.basicConfig( - format="[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s", - level=logging.WARNING) + format="[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s", level=logging.WARNING +) @register(outgoing=True, pattern=r"^\.helpme") diff --git a/userbot/modules/admin.py b/userbot/modules/admin.py index f2a6b01..6f984a6 100644 --- a/userbot/modules/admin.py +++ b/userbot/modules/admin.py @@ -576,7 +576,8 @@ async def rm_deletedacc(show): if del_u > 0: del_status = ( f"`Menemukan` **{del_u}** `Akun Hantu/Terhapus/Zombie Dalam Grup Ini," - "\nBersihkan Itu Menggunakan Perintah .zombies clean`") + "\nBersihkan Itu Menggunakan Perintah .zombies clean`" + ) return await show.edit(del_status) # Here laying the sanity check @@ -799,9 +800,7 @@ async def get_user_from_event(event): if event.message.entities is not None: probable_user_mention_entity = event.message.entities[0] - if isinstance( - probable_user_mention_entity, - MessageEntityMentionName): + if isinstance(probable_user_mention_entity, MessageEntityMentionName): user_id = probable_user_mention_entity.user_id user_obj = await event.client.get_entity(user_id) return user_obj @@ -891,9 +890,7 @@ async def get_userdel_from_event(event): if event.message.entities is not None: probable_user_mention_entity = event.message.entities[0] - if isinstance( - probable_user_mention_entity, - MessageEntityMentionName): + if isinstance(probable_user_mention_entity, MessageEntityMentionName): user_id = probable_user_mention_entity.user_id user_obj = await event.client.get_entity(user_id) return user_obj diff --git a/userbot/modules/afk.py b/userbot/modules/afk.py index 1a49fba..9bebb9a 100644 --- a/userbot/modules/afk.py +++ b/userbot/modules/afk.py @@ -89,8 +89,9 @@ async def set_not_afk(event): os.system("rm -rf *.jpg") -@bot.on(events.NewMessage(incoming=True, - func=lambda e: bool(e.mentioned or e.is_private))) +@bot.on( + events.NewMessage(incoming=True, func=lambda e: bool(e.mentioned or e.is_private)) +) async def on_afk(event): if event.fwd_from: return @@ -110,8 +111,9 @@ async def on_afk(event): msg = None if reason: message_to_reply = ( - f"**{ALIVE_NAME} Sedang AFK**\n\n**Sejak :** `{total_afk_time}` **Yang Lalu**\n" + - f"**Karena :** `{reason}`") + f"**{ALIVE_NAME} Sedang AFK**\n\n**Sejak :** `{total_afk_time}` **Yang Lalu**\n" + + f"**Karena :** `{reason}`" + ) else: message_to_reply = f"**Maaf King {ALIVE_NAME} Sedang AFK**\n\n**Sejak :** `{total_afk_time}` **Yang Lalu**" try: diff --git a/userbot/modules/android.py b/userbot/modules/android.py index ad89d9f..5ab3ed8 100644 --- a/userbot/modules/android.py +++ b/userbot/modules/android.py @@ -33,7 +33,8 @@ async def magisk(request): releases += ( f'{name}: [ZIP v{data["magisk"]["version"]}]({data["magisk"]["link"]}) | ' f'[APK v{data["app"]["version"]}]({data["app"]["link"]}) | ' - f'[Uninstaller]({data["uninstaller"]["link"]})\n') + f'[Uninstaller]({data["uninstaller"]["link"]})\n' + ) await request.edit(releases) @@ -89,8 +90,7 @@ async def codename_info(request): "certified-android-devices/master/by_brand.json" ).text ) - devices_lower = {k.lower(): v for k, v in data.items() - } # Lower brand names in JSON + devices_lower = {k.lower(): v for k, v in data.items()} # Lower brand names in JSON devices = devices_lower.get(brand) results = [ i @@ -227,11 +227,11 @@ async def devices_specifications(request): return all_brands = ( BeautifulSoup( - get("https://www.devicespecifications.com/en/brand-more").content, - "lxml") .find( - "div", - { - "class": "brand-listing-container-news"}) .findAll("a")) + get("https://www.devicespecifications.com/en/brand-more").content, "lxml" + ) + .find("div", {"class": "brand-listing-container-news"}) + .findAll("a") + ) brand_page_url = None try: brand_page_url = [ diff --git a/userbot/modules/anilist.py b/userbot/modules/anilist.py index 2e7d7fb..f2c9fe9 100644 --- a/userbot/modules/anilist.py +++ b/userbot/modules/anilist.py @@ -174,11 +174,7 @@ async def callAPI(search_str): """ variables = {"search": search_str} url = "https://graphql.anilist.co" - response = requests.post( - url, - json={ - "query": query, - "variables": variables}) + response = requests.post(url, json={"query": query, "variables": variables}) return response.text @@ -223,13 +219,10 @@ async def anilist(event): reply_to_id = event.reply_to_msg_id variables = {"query": search} json = ( - requests.post( - url, - json={ - "query": character_query, - "variables": variables}) .json()["data"] .get( - "Character", - None)) + requests.post(url, json={"query": character_query, "variables": variables}) + .json()["data"] + .get("Character", None) + ) if json: msg = f"**{json.get('name').get('full')}**\n" description = f"{json['description']}" @@ -279,9 +272,9 @@ async def anilist(event): ) ms_g = "" if json: - title, title_native = json["title"].get( - "romaji", False), json["title"].get( - "native", False) + title, title_native = json["title"].get("romaji", False), json["title"].get( + "native", False + ) start_date, status, score = ( json["startDate"].get("year", False), json.get("status", False), diff --git a/userbot/modules/anime.py b/userbot/modules/anime.py index 696714a..c4c00d8 100644 --- a/userbot/modules/anime.py +++ b/userbot/modules/anime.py @@ -68,8 +68,9 @@ def getBannerLink(mal, kitsu_search=True): } """ data = {"query": query, "variables": {"idMal": int(mal)}} - image = requests.post("https://graphql.anilist.co", - json=data).json()["data"]["Media"]["bannerImage"] + image = requests.post("https://graphql.anilist.co", json=data).json()["data"][ + "Media" + ]["bannerImage"] if image: return image return getPosterLink(mal) @@ -106,8 +107,7 @@ def get_anime_manga(mal_id, search_type, _user_id): if alternative_names: alternative_names_string = ", ".join(alternative_names) caption += f"\nAlso known as: {alternative_names_string}" - genre_string = ", ".join(genre_info["name"] - for genre_info in result["genres"]) + genre_string = ", ".join(genre_info["name"] for genre_info in result["genres"]) if result["synopsis"] is not None: synopsis = result["synopsis"].split(" ", 60) try: @@ -161,8 +161,7 @@ def get_poster(query): soup = bs4.BeautifulSoup(page.content, "lxml") odds = soup.findAll("tr", "odd") # Fetching the first post from search - page_link = "http://www.imdb.com/" + \ - odds[0].findNext("td").findNext("td").a["href"] + page_link = "http://www.imdb.com/" + odds[0].findNext("td").findNext("td").a["href"] page1 = requests.get(page_link) soup = bs4.BeautifulSoup(page1.content, "lxml") # Poster Link @@ -178,23 +177,13 @@ def post_to_telegraph(anime_title, html_format_content): bish = "https://t.me/GengKapak" post_client.create_api_token(auth_name) post_page = post_client.post( - title=anime_title, - author=auth_name, - author_url=bish, - text=html_format_content) + title=anime_title, author=auth_name, author_url=bish, text=html_format_content + ) return post_page["url"] def replace_text(text): - return text.replace( - '"', - "").replace( - "\\r", - "").replace( - "\\n", - "").replace( - "\\", - "") + return text.replace('"', "").replace("\\r", "").replace("\\n", "").replace("\\", "") @register(outgoing=True, pattern=r"^\.anime ?(.*)") @@ -546,8 +535,7 @@ async def manga(message): jikan = jikanpy.jikan.Jikan() search_result = jikan.search("manga", search_query) first_mal_id = search_result["results"][0]["mal_id"] - caption, image = get_anime_manga( - first_mal_id, "anime_manga", message.chat_id) + caption, image = get_anime_manga(first_mal_id, "anime_manga", message.chat_id) await message.delete() await message.client.send_file( message.chat_id, file=image, caption=caption, parse_mode="HTML" @@ -562,8 +550,7 @@ async def anime(message): jikan = jikanpy.jikan.Jikan() search_result = jikan.search("anime", search_query) first_mal_id = search_result["results"][0]["mal_id"] - caption, image = get_anime_manga( - first_mal_id, "anime_anime", message.chat_id) + caption, image = get_anime_manga(first_mal_id, "anime_anime", message.chat_id) try: await message.delete() await message.client.send_file( @@ -657,8 +644,7 @@ def is_gif(file): # lazy to go to github and make an issue kek if not is_video(file): return False - if DocumentAttributeAnimated() not in getattr( - file, "document", file).attributes: + if DocumentAttributeAnimated() not in getattr(file, "document", file).attributes: return False return True diff --git a/userbot/modules/anti_spambot.py b/userbot/modules/anti_spambot.py index 85cf28d..6a2551d 100644 --- a/userbot/modules/anti_spambot.py +++ b/userbot/modules/anti_spambot.py @@ -87,8 +87,7 @@ async def ANTI_SPAMBOTS(welcm): ) print(f"Chat : {welcm.chat.title}") print(f"Waktu : {join_time}") - print( - f"Pesan terkirim : {message.text}\n\nWaktu : {message_date}") + print(f"Pesan terkirim : {message.text}\n\nWaktu : {message_date}") ############################################## try: diff --git a/userbot/modules/aplikasi.py b/userbot/modules/aplikasi.py index dbb8019..1f517aa 100644 --- a/userbot/modules/aplikasi.py +++ b/userbot/modules/aplikasi.py @@ -23,21 +23,13 @@ async def app_search(event): soup = bs4.BeautifulSoup(page.content, "lxml", from_encoding="utf-8") results = soup.findAll("div", "ZmHEEd") app_name = ( - results[0].findNext( - "div", - "Vpfmgd").findNext( - "div", - "WsMG1c nnK0zc").text) - app_dev = results[0].findNext( - "div", "Vpfmgd").findNext( - "div", "KoLSrc").text + results[0].findNext("div", "Vpfmgd").findNext("div", "WsMG1c nnK0zc").text + ) + app_dev = results[0].findNext("div", "Vpfmgd").findNext("div", "KoLSrc").text app_dev_link = ( - "https://play.google.com" + - results[0].findNext( - "div", - "Vpfmgd").findNext( - "a", - "mnKHRc")["href"]) + "https://play.google.com" + + results[0].findNext("div", "Vpfmgd").findNext("a", "mnKHRc")["href"] + ) app_rating = ( results[0] .findNext("div", "Vpfmgd") diff --git a/userbot/modules/aria.py b/userbot/modules/aria.py index ecd88d4..ec76254 100644 --- a/userbot/modules/aria.py +++ b/userbot/modules/aria.py @@ -17,12 +17,7 @@ def subprocess_run(cmd): - subproc = Popen( - cmd, - stdout=PIPE, - stderr=PIPE, - shell=True, - universal_newlines=True) + subproc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True, universal_newlines=True) talk = subproc.communicate() exitCode = subproc.returncode if exitCode != 0: @@ -57,11 +52,7 @@ def subprocess_run(cmd): os.makedirs(TEMP_DOWNLOAD_DIRECTORY) download_path = os.getcwd() + TEMP_DOWNLOAD_DIRECTORY.strip(".") -aria2 = aria2p.API( - aria2p.Client( - host="http://localhost", - port=8210, - secret="")) +aria2 = aria2p.API(aria2p.Client(host="http://localhost", port=8210, secret="")) aria2.set_global_options({"dir": download_path}) @@ -206,17 +197,8 @@ async def check_progress_for_dl(gid, event, previous): percentage = int(file.progress) downloaded = percentage * int(file.total_length) / 100 prog_str = "[{0}{1}] `{2}`".format( - "".join( - "β–ˆ" for i in range( - math.floor( - percentage / - 10))), - "".join( - "β–‘" for i in range( - 10 - - math.floor( - percentage / - 10))), + "".join("β–ˆ" for i in range(math.floor(percentage / 10))), + "".join("β–‘" for i in range(10 - math.floor(percentage / 10))), file.progress_string(), ) msg = ( @@ -224,7 +206,8 @@ async def check_progress_for_dl(gid, event, previous): f"{prog_str}\n" f"`Size` : {humanbytes(downloaded)} of {file.total_length_string()}\n" f"`Speed` : {file.download_speed_string()}\n" - f"`ETA` : {file.eta_string()}\n") + f"`ETA` : {file.eta_string()}\n" + ) if msg != previous: await event.edit(msg) msg = previous diff --git a/userbot/modules/ascii.py b/userbot/modules/ascii.py index 7142976..28e8035 100644 --- a/userbot/modules/ascii.py +++ b/userbot/modules/ascii.py @@ -95,8 +95,7 @@ async def asciiart(IMG, color1, color2, bgcolor): img = np.sum(np.asarray(img), axis=2) img -= img.min() img = (1.0 - img / img.max()) ** 2.2 * (chars.size - 1) - lines = ("\n".join(("".join(r) - for r in chars[img.astype(int)]))).split("\n") + lines = ("\n".join(("".join(r) for r in chars[img.astype(int)]))).split("\n") nbins = len(lines) colorRange = list(Color(color1).range_to(Color(color2), nbins)) newImg_width = letter_width * widthByLetter diff --git a/userbot/modules/calls_group.py b/userbot/modules/calls_group.py index db06cbd..cd0e17f 100644 --- a/userbot/modules/calls_group.py +++ b/userbot/modules/calls_group.py @@ -23,7 +23,7 @@ async def get_call(event): def user_list(l, n): for i in range(0, len(l), n): - yield l[i: i + n] + yield l[i : i + n] @register(outgoing=True, pattern=r"^\.startvc$", groups_only=True) diff --git a/userbot/modules/carbon.py b/userbot/modules/carbon.py index 4f2fe1c..a12e08f 100644 --- a/userbot/modules/carbon.py +++ b/userbot/modules/carbon.py @@ -47,9 +47,7 @@ async def carbon_api(e): chrome_options.add_argument("--disable-gpu") prefs = {"download.default_directory": "/root/userbot/.bin"} chrome_options.add_experimental_option("prefs", prefs) - driver = webdriver.Chrome( - executable_path=CHROME_DRIVER, - options=chrome_options) + driver = webdriver.Chrome(executable_path=CHROME_DRIVER, options=chrome_options) driver.get(url) await e.edit("`Memproses..\n50%`") download_path = "/root/userbot/.bin" @@ -113,9 +111,7 @@ async def carbon_api(e): chrome_options.add_argument("--disable-gpu") prefs = {"download.default_directory": "/root/userbot/.bin"} chrome_options.add_experimental_option("prefs", prefs) - driver = webdriver.Chrome( - executable_path=CHROME_DRIVER, - options=chrome_options) + driver = webdriver.Chrome(executable_path=CHROME_DRIVER, options=chrome_options) driver.get(url) await e.edit("`Memproses..\n50%`") download_path = "/root/userbot/.bin" @@ -179,9 +175,7 @@ async def carbon_api(e): chrome_options.add_argument("--disable-gpu") prefs = {"download.default_directory": "/root/userbot/.bin"} chrome_options.add_experimental_option("prefs", prefs) - driver = webdriver.Chrome( - executable_path=CHROME_DRIVER, - options=chrome_options) + driver = webdriver.Chrome(executable_path=CHROME_DRIVER, options=chrome_options) driver.get(url) await e.edit("`Memproses..\n50%`") download_path = "/root/userbot/.bin" @@ -245,9 +239,7 @@ async def carbon_api(e): chrome_options.add_argument("--disable-gpu") prefs = {"download.default_directory": "/root/userbot/.bin"} chrome_options.add_experimental_option("prefs", prefs) - driver = webdriver.Chrome( - executable_path=CHROME_DRIVER, - options=chrome_options) + driver = webdriver.Chrome(executable_path=CHROME_DRIVER, options=chrome_options) driver.get(url) await e.edit("`Memproses..\n50%`") download_path = "/root/userbot/.bin" @@ -311,9 +303,7 @@ async def carbon_api(e): chrome_options.add_argument("--disable-gpu") prefs = {"download.default_directory": "/root/userbot/.bin"} chrome_options.add_experimental_option("prefs", prefs) - driver = webdriver.Chrome( - executable_path=CHROME_DRIVER, - options=chrome_options) + driver = webdriver.Chrome(executable_path=CHROME_DRIVER, options=chrome_options) driver.get(url) await e.edit("`Memproses..\n50%`") download_path = "/root/userbot/.bin" diff --git a/userbot/modules/chat.py b/userbot/modules/chat.py index edc6680..881267e 100644 --- a/userbot/modules/chat.py +++ b/userbot/modules/chat.py @@ -58,8 +58,9 @@ async def permalink(mention): if custom: await mention.edit(f"[{custom}](tg://user?id={user.id})") else: - tag = (user.first_name.replace("\u2060", "") - if user.first_name else user.username) + tag = ( + user.first_name.replace("\u2060", "") if user.first_name else user.username + ) await mention.edit(f"[{tag}](tg://user?id={user.id})") @@ -268,9 +269,8 @@ async def fetch_info(chat, event): # chat.chats is a list so we use get_entity() to avoid IndexError chat_obj_info = await event.client.get_entity(chat.full_chat.id) broadcast = ( - chat_obj_info.broadcast if hasattr( - chat_obj_info, - "broadcast") else False) + chat_obj_info.broadcast if hasattr(chat_obj_info, "broadcast") else False + ) chat_type = "Channel" if broadcast else "Group" chat_title = chat_obj_info.title warn_emoji = emojize(":warning:") @@ -330,20 +330,18 @@ async def fetch_info(chat, event): if hasattr(chat.full_chat, "participants_count") else chat_obj_info.participants_count ) - admins = (chat.full_chat.admins_count if hasattr( - chat.full_chat, "admins_count") else None) + admins = ( + chat.full_chat.admins_count if hasattr(chat.full_chat, "admins_count") else None + ) banned_users = ( - chat.full_chat.kicked_count if hasattr( - chat.full_chat, - "kicked_count") else None) + chat.full_chat.kicked_count if hasattr(chat.full_chat, "kicked_count") else None + ) restrcited_users = ( - chat.full_chat.banned_count if hasattr( - chat.full_chat, - "banned_count") else None) + chat.full_chat.banned_count if hasattr(chat.full_chat, "banned_count") else None + ) members_online = ( - chat.full_chat.online_count if hasattr( - chat.full_chat, - "online_count") else 0) + chat.full_chat.online_count if hasattr(chat.full_chat, "online_count") else 0 + ) group_stickers = ( chat.full_chat.stickerset.title if hasattr(chat.full_chat, "stickerset") and chat.full_chat.stickerset @@ -361,8 +359,7 @@ async def fetch_info(chat, event): else None ) exp_count = chat.full_chat.pts if hasattr(chat.full_chat, "pts") else None - username = chat_obj_info.username if hasattr( - chat_obj_info, "username") else None + username = chat_obj_info.username if hasattr(chat_obj_info, "username") else None bots_list = chat.full_chat.bot_info # this is a list bots = 0 supergroup = ( @@ -370,12 +367,16 @@ async def fetch_info(chat, event): if hasattr(chat_obj_info, "megagroup") and chat_obj_info.megagroup else "Tidak" ) - slowmode = ("Yes" if hasattr(chat_obj_info, "slowmode_enabled") - and chat_obj_info.slowmode_enabled else "Tidak") + slowmode = ( + "Yes" + if hasattr(chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled + else "Tidak" + ) slowmode_time = ( - chat.full_chat.slowmode_seconds if hasattr( - chat_obj_info, - "slowmode_enabled") and chat_obj_info.slowmode_enabled else None) + chat.full_chat.slowmode_seconds + if hasattr(chat_obj_info, "slowmode_enabled") and chat_obj_info.slowmode_enabled + else None + ) restricted = ( "Yes" if hasattr(chat_obj_info, "restricted") and chat_obj_info.restricted @@ -387,8 +388,7 @@ async def fetch_info(chat, event): else "Tidak" ) username = "@{}".format(username) if username else None - creator_username = "@{}".format( - creator_username) if creator_username else None + creator_username = "@{}".format(creator_username) if creator_username else None # end of spaghetti block if admins is None: diff --git a/userbot/modules/code.py b/userbot/modules/code.py index 50bd859..cc41feb 100644 --- a/userbot/modules/code.py +++ b/userbot/modules/code.py @@ -86,14 +86,8 @@ async def run(run_q): else: clines = code.splitlines() codepre = ( - clines[0] + - "\n" + - clines[1] + - "\n" + - clines[2] + - "\n" + - clines[3] + - "...") + clines[0] + "\n" + clines[1] + "\n" + clines[2] + "\n" + clines[3] + "..." + ) command = "".join(f"\n {l}" for l in code.split("\n.strip()")) process = await asyncio.create_subprocess_exec( diff --git a/userbot/modules/costum.py b/userbot/modules/costum.py index 0117e4b..cb1b86e 100644 --- a/userbot/modules/costum.py +++ b/userbot/modules/costum.py @@ -13,10 +13,7 @@ from userbot.events import register -@register(outgoing=True, - pattern=r"\.\w*", - ignore_unsafe=True, - disable_errors=True) +@register(outgoing=True, pattern=r"\.\w*", ignore_unsafe=True, disable_errors=True) async def on_snip(event): """costums logic.""" try: diff --git a/userbot/modules/createstickers.py b/userbot/modules/createstickers.py index 648485c..c9b8952 100644 --- a/userbot/modules/createstickers.py +++ b/userbot/modules/createstickers.py @@ -47,14 +47,8 @@ async def sticklet(event): width, height = draw.multiline_textsize(sticktext, font=font) draw.multiline_text( - ((512 - width) / 2, - (512 - height) / 2), - sticktext, - font=font, - fill=( - R, - G, - B)) + ((512 - width) / 2, (512 - height) / 2), sticktext, font=font, fill=(R, G, B) + ) image_stream = io.BytesIO() image_stream.name = "@king.webp" diff --git a/userbot/modules/deezloader.py b/userbot/modules/deezloader.py index 831d726..09c51a0 100644 --- a/userbot/modules/deezloader.py +++ b/userbot/modules/deezloader.py @@ -21,8 +21,7 @@ # run -@register(outgoing=True, - pattern=r"^\.deez (.+?|) (FLAC|MP3\_320|MP3\_256|MP3\_128)") +@register(outgoing=True, pattern=r"^\.deez (.+?|) (FLAC|MP3\_320|MP3\_256|MP3\_128)") async def _(event): """DeezLoader by @An0nimia Ported for UniBorg by @SpEcHlDe""" diff --git a/userbot/modules/echo.py b/userbot/modules/echo.py index 74d9bdc..60b82d7 100644 --- a/userbot/modules/echo.py +++ b/userbot/modules/echo.py @@ -39,13 +39,7 @@ async def echo(event): if is_echo(chat_id, user_id): return await edit_or_reply(event, "**Pengguna Sudah Diaktifkan Dengan Echo**") try: - addecho( - chat_id, - user_id, - chat_name, - user_name, - user_username, - chat_type) + addecho(chat_id, user_id, chat_name, user_name, user_username, chat_type) except Exception as e: await edit_delete(kingevent, f"**Error :**\n`{str(e)}`") else: @@ -156,8 +150,9 @@ async def echo(event): # sourcery no-metrics f"βŽ† [{echos.user_name}](tg://user?id={echos.user_id})\n" ) output_str = ( - f"**Pengguna Yang Mengaktifkan Echo Pengguna Dalam Obrolan Ini Adalah :**\n" + - private_chats) + f"**Pengguna Yang Mengaktifkan Echo Pengguna Dalam Obrolan Ini Adalah :**\n" + + private_chats + ) await edit_or_reply(event, output_str) diff --git a/userbot/modules/federasi.py b/userbot/modules/federasi.py index 9fa1e1a..e07a008 100644 --- a/userbot/modules/federasi.py +++ b/userbot/modules/federasi.py @@ -219,4 +219,6 @@ async def delf(event): "\n\n.delf" "\nPenjelasan: Menghapus grup saat ini dari federasi yang terhubung." "\n\n.listf" - "\nPenjelasan: Mencantumkan semua federasi yang terhubung dengan nama yang ditentukan."}) + "\nPenjelasan: Mencantumkan semua federasi yang terhubung dengan nama yang ditentukan." + } +) diff --git a/userbot/modules/filter.py b/userbot/modules/filter.py index a715ea1..d0780fc 100644 --- a/userbot/modules/filter.py +++ b/userbot/modules/filter.py @@ -26,8 +26,7 @@ async def filter_incoming_handler(handler): if not filters: return for trigger in filters: - pattern = r"( |^|[^\w])" + \ - escape(trigger.keyword) + r"( |$|[^\w])" + pattern = r"( |^|[^\w])" + escape(trigger.keyword) + r"( |$|[^\w])" pro = search(pattern, name, flags=IGNORECASE) if pro and trigger.f_mesg_id: msg_o = await handler.client.get_messages( diff --git a/userbot/modules/gdrive.py b/userbot/modules/gdrive.py index e6ca38f..f1c9c31 100644 --- a/userbot/modules/gdrive.py +++ b/userbot/modules/gdrive.py @@ -92,14 +92,10 @@ if True in [_1 or _2]: pass else: - LOGS.info( - "G_DRIVE_FOLDER_ID " - " bukan ID yang valid...") + LOGS.info("G_DRIVE_FOLDER_ID " " bukan ID yang valid...") G_DRIVE_FOLDER_ID = None else: - LOGS.info( - "G_DRIVE_FOLDER_ID " - " bukan ID yang valid...") + LOGS.info("G_DRIVE_FOLDER_ID " " bukan ID yang valid...") G_DRIVE_FOLDER_ID = None # =========================================================== # # LOG # @@ -154,17 +150,13 @@ async def generate_credentials(gdrive): flow = InstalledAppFlow.from_client_config( configs, SCOPES, redirect_uri=REDIRECT_URI ) - auth_url, _ = flow.authorization_url( - access_type="offline", prompt="consent") + auth_url, _ = flow.authorization_url(access_type="offline", prompt="consent") msg = await gdrive.respond("`Buka grup BOTLOG Anda untuk mengautentikasi token...`") async with gdrive.client.conversation(BOTLOG_CHATID) as conv: url_msg = await conv.send_message( "Silakan buka URL ini:\n" f"{auth_url}\notorisasi lalu balas kodenya" ) - r = conv.wait_event( - events.NewMessage( - outgoing=True, - chats=BOTLOG_CHATID)) + r = conv.wait_event(events.NewMessage(outgoing=True, chats=BOTLOG_CHATID)) r = await r code = r.message.message.strip() flow.fetch_token(code=code) @@ -194,8 +186,9 @@ async def create_app(gdrive): await gdrive.edit("`Menyegarkan kredensial...`") """ - Refresh credentials - """ creds.refresh(Request()) - helper.save_credentials(str(gdrive.from_id), - base64.b64encode(pickle.dumps(creds)).decode()) + helper.save_credentials( + str(gdrive.from_id), base64.b64encode(pickle.dumps(creds)).decode() + ) else: await gdrive.edit("`Kredensial kosong, harap buat...`") return False @@ -242,9 +235,7 @@ async def download(gdrive, service, uri=None): ) else: uri = [uri] - downloads = aria2.add_uris( - uri, options={ - "dir": full_path}, position=None) + downloads = aria2.add_uris(uri, options={"dir": full_path}, position=None) gid = downloads.gid await check_progress_for_dl(gdrive, gid, previous=None) file = aria2.get_download(gid) @@ -365,8 +356,9 @@ async def download_gdrive(gdrive, service, uri): file_Id = uri.split("/")[-2] else: try: - file_Id = uri.split("uc?export=download&confirm=")[ - 1].split("id=")[1] + file_Id = uri.split("uc?export=download&confirm=")[1].split("id=")[ + 1 + ] except IndexError: """- if error parse in url, assume given value is Id -""" file_Id = uri @@ -385,13 +377,16 @@ async def download_gdrive(gdrive, service, uri): except KeyError: page = BeautifulSoup(download.content, "lxml") try: - export = drive + \ - page.find("a", {"id": "uc-download-link"}).get("href") + export = drive + page.find("a", {"id": "uc-download-link"}).get( + "href" + ) except AttributeError: try: - error = (page.find("p", - {"class": "uc-error-caption"}).text + "\n" + page.find("p", - {"class": "uc-error-subcaption"}).text) + error = ( + page.find("p", {"class": "uc-error-caption"}).text + + "\n" + + page.find("p", {"class": "uc-error-subcaption"}).text + ) except Exception: reply += ( "`[FILE - ERROR]`\n\n" @@ -518,10 +513,7 @@ async def download_gdrive(gdrive, service, uri): async with gdrive.client.conversation(BOTLOG_CHATID) as conv: ask = await conv.send_message("`Lanjutkan dengan mirroring? [y/N]`") try: - r = conv.wait_event( - events.NewMessage( - outgoing=True, - chats=BOTLOG_CHATID)) + r = conv.wait_event(events.NewMessage(outgoing=True, chats=BOTLOG_CHATID)) r = await r except Exception: ans = "N" @@ -603,10 +595,10 @@ async def create_dir(service, folder_name): """- Override G_DRIVE_FOLDER_ID because parent_Id not empty -""" metadata["parents"] = [parent_Id] folder = ( - service.files() .create( - body=metadata, - fields="id, webViewLink", - supportsAllDrives=True) .execute()) + service.files() + .create(body=metadata, fields="id, webViewLink", supportsAllDrives=True) + .execute() + ) await change_permission(service, folder.get("id")) return folder @@ -914,9 +906,9 @@ async def google_drive_managers(gdrive): service.files().delete(fileId=f_id, supportsAllDrives=True).execute() except HttpError as e: status.replace("HAPUS]", "ERROR]") - reply += (f"`{status}`\n\n" - "`Status` : **BAD**" - f"`Alasan` : {str(e)}\n\n") + reply += ( + f"`{status}`\n\n" "`Status` : **BAD**" f"`Alasan` : {str(e)}\n\n" + ) continue else: reply += f"`{status}`\n\n" f"`{name}`\n" "`Status` : **OK**\n\n" @@ -949,9 +941,8 @@ async def google_drive_managers(gdrive): else: status = "[FILE - EXIST]" msg = ( - f"`{status}`\n\n" - f"`Nama :` `{name_or_id}`\n" - f"`ID :` `{f_id}`\n") + f"`{status}`\n\n" f"`Nama :` `{name_or_id}`\n" f"`ID :` `{f_id}`\n" + ) if mimeType != "application/vnd.google-apps.folder": msg += f"`Ukuran :` `{humanbytes(f_size)}`\n" msg += f"`Link :` [{name_or_id}]({downloadURL})\n\n" @@ -1086,8 +1077,10 @@ async def google_drive(gdrive): try: reply += await download_gdrive(gdrive, service, fileId) except CancelProcess: - reply += ("`[FILE - DIBATALKAN]`\n\n" - "`Status` : **OK** - sinyal yang diterima dibatalkan.") + reply += ( + "`[FILE - DIBATALKAN]`\n\n" + "`Status` : **OK** - sinyal yang diterima dibatalkan." + ) break except Exception as e: reply += ( @@ -1341,4 +1334,6 @@ async def check_progress_for_dl(gdrive, gid, previous): "\n\n**CATATAN:**" "\nuntuk .gdlist Anda dapat menggabungkan flag -l dan -p dengan atau tanpa nama " "pada saat yang sama, ini harus menjadi flag` -l` terlebih dahulu sebelum menggunakan flag `-p`.\n" - "Dan secara default daftar dari 'modifiedTime' terbaru dan kemudian folder."}) + "Dan secara default daftar dari 'modifiedTime' terbaru dan kemudian folder." + } +) diff --git a/userbot/modules/gitcommit.py b/userbot/modules/gitcommit.py index 9f199ec..06530a2 100644 --- a/userbot/modules/gitcommit.py +++ b/userbot/modules/gitcommit.py @@ -80,10 +80,8 @@ async def git_commit(file_name, mone): print(file_name) try: repo.create_file( - file_name, - "Uploaded New Plugin", - commit_data, - branch="King-Userbot") + file_name, "Uploaded New Plugin", commit_data, branch="King-Userbot" + ) print("Committed File") ccess = GIT_REPO_NAME ccess = ccess.strip() diff --git a/userbot/modules/gkick.py b/userbot/modules/gkick.py index 3c46ee9..f2123da 100644 --- a/userbot/modules/gkick.py +++ b/userbot/modules/gkick.py @@ -32,9 +32,7 @@ async def get_user_from_event(event): return if event.message.entities is not None: probable_user_mention_entity = event.message.entities[0] - if isinstance( - probable_user_mention_entity, - MessageEntityMentionName): + if isinstance(probable_user_mention_entity, MessageEntityMentionName): user_id = probable_user_mention_entity.user_id user_obj = await event.client.get_entity(user_id) return user_obj diff --git a/userbot/modules/glitcher.py b/userbot/modules/glitcher.py index 9fbb77f..7c50f39 100644 --- a/userbot/modules/glitcher.py +++ b/userbot/modules/glitcher.py @@ -112,8 +112,7 @@ async def draw_meme_text(image_path, text): img = Image.open(image_path) os.remove(image_path) i_width, i_height = img.size - m_font = ImageFont.truetype( - "LordFont/FontLord.ttf", int((70 / 640) * i_width)) + m_font = ImageFont.truetype("LordFont/FontLord.ttf", int((70 / 640) * i_width)) if ";" in text: upper_text, lower_text = text.split(";") else: diff --git a/userbot/modules/globalbanned.py b/userbot/modules/globalbanned.py index fd30889..2154922 100644 --- a/userbot/modules/globalbanned.py +++ b/userbot/modules/globalbanned.py @@ -84,9 +84,7 @@ async def get_user_from_event(event, uevent=None, secondgroup=None): return None, None if event.message.entities: probable_user_mention_entity = event.message.entities[0] - if isinstance( - probable_user_mention_entity, - MessageEntityMentionName): + if isinstance(probable_user_mention_entity, MessageEntityMentionName): user_id = probable_user_mention_entity.user_id user_obj = await event.client.get_entity(user_id) return user_obj, extra diff --git a/userbot/modules/googlephotos.py b/userbot/modules/googlephotos.py index f0951d8..227c797 100644 --- a/userbot/modules/googlephotos.py +++ b/userbot/modules/googlephotos.py @@ -35,8 +35,8 @@ from userbot.utils import progress logging.basicConfig( - format="[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s", - level=logging.WARNING) + format="[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s", level=logging.WARNING +) logger = logging.getLogger(__name__) # setup the gPhotos v1 API diff --git a/userbot/modules/gps.py b/userbot/modules/gps.py index daadef8..f680965 100644 --- a/userbot/modules/gps.py +++ b/userbot/modules/gps.py @@ -33,5 +33,4 @@ async def gps(event): await event.edit("`King Saya Tidak Dapat Menemukannya`") -CMD_HELP.update({"gps": ">βš‘π˜Ύπ™ˆπ˜Ώβš‘`.gps`" - "\nUsage: Untuk Mendapatkan Lokasi Map"}) +CMD_HELP.update({"gps": ">βš‘π˜Ύπ™ˆπ˜Ώβš‘`.gps`" "\nUsage: Untuk Mendapatkan Lokasi Map"}) diff --git a/userbot/modules/hash.py b/userbot/modules/hash.py index 6009d54..3e1eafe 100644 --- a/userbot/modules/hash.py +++ b/userbot/modules/hash.py @@ -61,8 +61,9 @@ async def gethash(hash_q): async def endecrypt(query): """For .base64 command, find the base64 encoding of the given string.""" if query.pattern_match.group(1) == "en": - lething = str(pybase64.b64encode( - bytes(query.pattern_match.group(2), "utf-8")))[2:] + lething = str(pybase64.b64encode(bytes(query.pattern_match.group(2), "utf-8")))[ + 2: + ] await query.reply("Encoded: `" + lething[:-1] + "`") else: lething = str( @@ -79,4 +80,5 @@ async def endecrypt(query): "\nUsage: Find the md5, sha1, sha256, sha512 of the string when written into a txt file.", "base64": ">`.base64 [en or de]`" "\nUsage: Find the base64 encoding of the given string or decode it.", - }) + } +) diff --git a/userbot/modules/hentai.py b/userbot/modules/hentai.py index 39076bf..45279f8 100644 --- a/userbot/modules/hentai.py +++ b/userbot/modules/hentai.py @@ -29,8 +29,7 @@ async def _(event): except YouBlockedUserError: await event.reply("```Harap buka blokir @nHentaiBot dan coba lagi```") return - if response.text.startswith( - "**Maaf, saya tidak bisa mendapatkan manga dari**"): + if response.text.startswith("**Maaf, saya tidak bisa mendapatkan manga dari**"): await event.edit("```Saya pikir ini bukan tautan yang tepat king!```") else: await event.delete() diff --git a/userbot/modules/heroku.py b/userbot/modules/heroku.py index a68234c..65f7111 100644 --- a/userbot/modules/heroku.py +++ b/userbot/modules/heroku.py @@ -171,8 +171,7 @@ async def dyno_usage(dyno): for apps in Apps: if apps.get("app_uuid") == app.id: AppQuotaUsed = apps.get("quota_used") / 60 - AppPercentage = math.floor( - apps.get("quota_used") * 100 / quota) + AppPercentage = math.floor(apps.get("quota_used") * 100 / quota) break else: AppQuotaUsed = 0 @@ -213,8 +212,12 @@ async def _(dyno): log.write(app.get_log()) fd = codecs.open("logs.txt", "r", encoding="utf-8") data = fd.read() - key = (requests.post("https://nekobin.com/api/documents", - json={"content": data}) .json() .get("result") .get("key")) + key = ( + requests.post("https://nekobin.com/api/documents", json={"content": data}) + .json() + .get("result") + .get("key") + ) url = f"https://nekobin.com/raw/{key}" await dyno.edit(f"`Ini Logs Heroku Anda King :`\n\nPaste Ke: [Nekobin]({url})") return os.remove("logs.txt") diff --git a/userbot/modules/imgmemes.py b/userbot/modules/imgmemes.py index 60b061b..5e4424c 100644 --- a/userbot/modules/imgmemes.py +++ b/userbot/modules/imgmemes.py @@ -47,8 +47,7 @@ def deEmojify(inputString: str) -> str: async def threats(text): - r = requests.get( - f"https://nekobot.xyz/api/imagegen?type=threats&url={text}").json() + r = requests.get(f"https://nekobot.xyz/api/imagegen?type=threats&url={text}").json() sandy = r.get("message") caturl = url(sandy) if not caturl: @@ -63,8 +62,7 @@ async def threats(text): async def trash(text): - r = requests.get( - f"https://nekobot.xyz/api/imagegen?type=trash&url={text}").json() + r = requests.get(f"https://nekobot.xyz/api/imagegen?type=trash&url={text}").json() sandy = r.get("message") caturl = url(sandy) if not caturl: @@ -468,10 +466,8 @@ async def FakeGoogleSearch(event): drawing = ImageDraw.Draw(photo) blue = (0, 0, 255) black = (0, 0, 0) - font1 = ImageFont.truetype( - "userbot/utils/styles/ProductSans-BoldItalic.ttf", 20) - font2 = ImageFont.truetype( - "userbot/utils/styles/ProductSans-Light.ttf", 23) + font1 = ImageFont.truetype("userbot/utils/styles/ProductSans-BoldItalic.ttf", 20) + font2 = ImageFont.truetype("userbot/utils/styles/ProductSans-Light.ttf", 23) drawing.text((450, 258), result, fill=blue, font=font1) drawing.text((270, 37), search, fill=black, font=font2) photo.save("downloads/test.jpg") diff --git a/userbot/modules/kingmemes.py b/userbot/modules/kingmemes.py index 07398ce..685e019 100644 --- a/userbot/modules/kingmemes.py +++ b/userbot/modules/kingmemes.py @@ -452,8 +452,7 @@ async def _(event): @register(outgoing=True, pattern="^.gangstar(?: |$)(.*)") async def _(event): - if not event.text[0].isalpha() and event.text[0] not in ( - "/", "#", "@", "!"): + if not event.text[0].isalpha() and event.text[0] not in ("/", "#", "@", "!"): await event.edit("EVERyBOdy") await asyncio.sleep(0.3) await event.edit("wAs") @@ -2414,8 +2413,7 @@ async def _(event): await event.edit(input_str) - animation_chars = ["🐡", "πŸ™‰", "πŸ™ˆ", "πŸ™Š", - "πŸ–•β€ŽπŸ΅πŸ–•", "**OPPA MONKEYY Style....**"] + animation_chars = ["🐡", "πŸ™‰", "πŸ™ˆ", "πŸ™Š", "πŸ–•β€ŽπŸ΅πŸ–•", "**OPPA MONKEYY Style....**"] animation_interval = 2 diff --git a/userbot/modules/kingmisc.py b/userbot/modules/kingmisc.py index aa97e0b..3c61846 100644 --- a/userbot/modules/kingmisc.py +++ b/userbot/modules/kingmisc.py @@ -162,10 +162,8 @@ async def _(event): else: xkcd_search_url = "https://relevantxkcd.appspot.com/process?" queryresult = requests.get( - xkcd_search_url, - params={ - "action": "xkcd", - "query": quote(input_str)}).text + xkcd_search_url, params={"action": "xkcd", "query": quote(input_str)} + ).text xkcd_id = queryresult.split(" ")[2].lstrip("\n") if xkcd_id is None: xkcd_url = "https://xkcd.com/info.0.json" @@ -551,9 +549,7 @@ async def get_full_user(event): if event.message.entities is not None: mention_entity = event.message.entities probable_user_mention_entity = mention_entity[0] - if isinstance( - probable_user_mention_entity, - MessageEntityMentionName): + if isinstance(probable_user_mention_entity, MessageEntityMentionName): user_id = probable_user_mention_entity.user_id replied_user = await event.client(GetFullUserRequest(user_id)) return replied_user, None @@ -909,8 +905,7 @@ async def cursive2(cursivebolded): string = "".join(args).lower() for normiecharacter in string: if normiecharacter in normiefont: - cursiveboldcharacter = cursiveboldx[normiefont.index( - normiecharacter)] + cursiveboldcharacter = cursiveboldx[normiefont.index(normiecharacter)] string = string.replace(normiecharacter, cursiveboldcharacter) await cursivebolded.edit(string) diff --git a/userbot/modules/lastfm.py b/userbot/modules/lastfm.py index c3e6cdb..40d5d36 100644 --- a/userbot/modules/lastfm.py +++ b/userbot/modules/lastfm.py @@ -67,9 +67,7 @@ async def last_fm(lastFM): username = f"https://www.last.fm/user/{LASTFM_USERNAME}" if playing is not None: try: - image = User( - LASTFM_USERNAME, - lastfm).get_now_playing().get_cover_image() + image = User(LASTFM_USERNAME, lastfm).get_now_playing().get_cover_image() except IndexError: image = None tags = await gettags(isNowPlaying=True, playing=playing) diff --git a/userbot/modules/mega_downloader.py b/userbot/modules/mega_downloader.py index 4d4c04c..f867cbd 100644 --- a/userbot/modules/mega_downloader.py +++ b/userbot/modules/mega_downloader.py @@ -95,9 +95,7 @@ async def mega_downloader(megadl): file_path = os.path.join(TEMP_DOWNLOAD_DIRECTORY, file_name) if os.path.isfile(file_path): try: - raise FileExistsError( - errno.EEXIST, os.strerror( - errno.EEXIST), file_path) + raise FileExistsError(errno.EEXIST, os.strerror(errno.EEXIST), file_path) except FileExistsError as e: await megadl.edit(f"`{str(e)}`") return None @@ -133,10 +131,9 @@ async def mega_downloader(megadl): f"`ETA` -> {time_formatter(estimated_total_time)}\n" f"`Duration` -> {time_formatter(round(diff))}" ) - if round( - diff % - 15.00) == 0 and ( - display_message != current_message or total_length == downloaded): + if round(diff % 15.00) == 0 and ( + display_message != current_message or total_length == downloaded + ): await megadl.edit(current_message) await asyncio.sleep(0.2) display_message = current_message @@ -181,9 +178,7 @@ async def decrypt_file(megadl, file_path, temp_file_path, hex_key, hex_raw_key): if await subprocess_run(megadl, cmd): os.remove(temp_file_path) else: - raise FileNotFoundError( - errno.ENOENT, os.strerror( - errno.ENOENT), file_path) + raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), file_path) return diff --git a/userbot/modules/memes.py b/userbot/modules/memes.py index b144a50..14168b2 100644 --- a/userbot/modules/memes.py +++ b/userbot/modules/memes.py @@ -990,10 +990,8 @@ async def boobs(e): await e.edit("`Berdosa, Mendapatkan Gambar Boobs...`") await sleep(3) await e.edit("`Mengirim Gambar Boobs...`") - nsfw = requests.get( - "http://api.oboobs.ru/noise/1").json()[0]["Gambar Boobs"] - urllib.request.urlretrieve( - "http://media.oboobs.ru/{}".format(nsfw), "*.jpg") + nsfw = requests.get("http://api.oboobs.ru/noise/1").json()[0]["Gambar Boobs"] + urllib.request.urlretrieve("http://media.oboobs.ru/{}".format(nsfw), "*.jpg") os.rename("*.jpg", "boobs.jpg") await e.client.send_file(e.chat_id, "boobs.jpg") os.remove("boobs.jpg") @@ -1005,10 +1003,8 @@ async def butts(e): await e.edit("`Berdosa, Mendapatkan Gambar Pantat Yang Indah...`") await sleep(3) await e.edit("`Mengirim Gambar Pantat Indah...`") - nsfw = requests.get( - "http://api.obutts.ru/noise/1").json()[0]["Gambar Pantat"] - urllib.request.urlretrieve( - "http://media.obutts.ru/{}".format(nsfw), "*.jpg") + nsfw = requests.get("http://api.obutts.ru/noise/1").json()[0]["Gambar Pantat"] + urllib.request.urlretrieve("http://media.obutts.ru/{}".format(nsfw), "*.jpg") os.rename("*.jpg", "butts.jpg") await e.client.send_file(e.chat_id, "butts.jpg") os.remove("butts.jpg") @@ -1120,10 +1116,7 @@ async def stretch(stret): return await stret.edit("`Beriiiiiiiiikaaannnn sebuuuuuuuuuah teeeeeeeks!`") count = randint(3, 10) - reply_text = sub( - r"([aeiouAEIOUaeiou1οΌ₯οΌ©οΌ―οΌ΅Π°Π΅ΠΈΠΎΡƒΡŽΡΡ‹ΡΡ‘])", - (r"\1" * count), - message) + reply_text = sub(r"([aeiouAEIOUaeiou1οΌ₯οΌ©οΌ―οΌ΅Π°Π΅ΠΈΠΎΡƒΡŽΡΡ‹ΡΡ‘])", (r"\1" * count), message) await stret.edit(reply_text) @@ -1923,4 +1916,6 @@ async def emoji_tengkorak(e): "\n> `.fag` `.gtfo`; `.stfu` `.lol` `.lool` `.fail` `.leave`" "\n> `.iwi` `.sayhi` `.koc` `.gas` `.earth` `.love` `.rain`" "\n> `.penis` `.emo` `.fuck` `.skull` `.monyet`\nUsage: Cobain aja" - "\n\n\n**Semoga Harimu Selalu Bahagia**\nβž₯ `Apis`"}) + "\n\n\n**Semoga Harimu Selalu Bahagia**\nβž₯ `Apis`" + } +) diff --git a/userbot/modules/memify.py b/userbot/modules/memify.py index d2ff021..0902a30 100644 --- a/userbot/modules/memify.py +++ b/userbot/modules/memify.py @@ -36,8 +36,7 @@ async def mim(event): file_name = "meme.jpg" reply_message = await event.get_reply_message() to_download_directory = TEMP_DOWNLOAD_DIRECTORY - downloaded_file_name = os.path.join( - to_download_directory, file_name) + downloaded_file_name = os.path.join(to_download_directory, file_name) downloaded_file_name = await bot.download_media( reply_message, downloaded_file_name, @@ -185,8 +184,7 @@ async def mim(event): file_name = "meme.jpg" reply_message = await event.get_reply_message() to_download_directory = TEMP_DOWNLOAD_DIRECTORY - downloaded_file_name = os.path.join( - to_download_directory, file_name) + downloaded_file_name = os.path.join(to_download_directory, file_name) downloaded_file_name = await bot.download_media( reply_message, downloaded_file_name, diff --git a/userbot/modules/misc.py b/userbot/modules/misc.py index 87dee4a..e5ff700 100644 --- a/userbot/modules/misc.py +++ b/userbot/modules/misc.py @@ -200,17 +200,8 @@ async def okgoogle(img): image.close() # https://stackoverflow.com/questions/23270175/google-reverse-image-search-using-post-request#28792943 searchUrl = "https://www.google.com/searchbyimage/upload" - multipart = { - "encoded_image": ( - name, - open( - name, - "rb")), - "image_content": ""} - response = requests.post( - searchUrl, - files=multipart, - allow_redirects=False) + multipart = {"encoded_image": (name, open(name, "rb")), "image_content": ""} + response = requests.post(searchUrl, files=multipart, allow_redirects=False) fetchUrl = response.headers["Location"] if response != 400: @@ -265,8 +256,9 @@ async def ParseSauce(googleurl): try: for similar_image in soup.findAll("input", {"class": "gLFyf"}): - url = "https://www.google.com/search?tbm=isch&q=" + \ - urllib.parse.quote_plus(similar_image.get("value")) + url = "https://www.google.com/search?tbm=isch&q=" + urllib.parse.quote_plus( + similar_image.get("value") + ) results["similar_images"] = url except BaseException: pass diff --git a/userbot/modules/music_lyrics.py b/userbot/modules/music_lyrics.py index 94baaa7..09327f4 100644 --- a/userbot/modules/music_lyrics.py +++ b/userbot/modules/music_lyrics.py @@ -29,12 +29,15 @@ # Based Code by @Spidy -a1 = base64.b64decode( - "QUl6YVN5QXlEQnNZM1dSdEI1WVBDNmFCX3c4SkF5NlpkWE5jNkZV").decode("ascii") -a2 = base64.b64decode( - "QUl6YVN5QkYwenhMbFlsUE1wOXh3TVFxVktDUVJxOERnZHJMWHNn").decode("ascii") -a3 = base64.b64decode( - "QUl6YVN5RGRPS253blB3VklRX2xiSDVzWUU0Rm9YakFLSVFWMERR").decode("ascii") +a1 = base64.b64decode("QUl6YVN5QXlEQnNZM1dSdEI1WVBDNmFCX3c4SkF5NlpkWE5jNkZV").decode( + "ascii" +) +a2 = base64.b64decode("QUl6YVN5QkYwenhMbFlsUE1wOXh3TVFxVktDUVJxOERnZHJMWHNn").decode( + "ascii" +) +a3 = base64.b64decode("QUl6YVN5RGRPS253blB3VklRX2xiSDVzWUU0Rm9YakFLSVFWMERR").decode( + "ascii" +) @register(outgoing=True, pattern=r"^\.music (.*)") diff --git a/userbot/modules/notes.py b/userbot/modules/notes.py index 41a4e62..0c4a136 100644 --- a/userbot/modules/notes.py +++ b/userbot/modules/notes.py @@ -80,8 +80,7 @@ async def add_note(fltr): return await fltr.edit(success.format("added", keyword)) -@register(pattern=r"#\w*", disable_edited=True, - disable_errors=True, ignore_unsafe=True) +@register(pattern=r"#\w*", disable_edited=True, disable_errors=True, ignore_unsafe=True) async def incom_note(getnt): """Notes logic.""" try: diff --git a/userbot/modules/pastebin.py b/userbot/modules/pastebin.py index 0deafe1..2f735bd 100644 --- a/userbot/modules/pastebin.py +++ b/userbot/modules/pastebin.py @@ -12,8 +12,7 @@ from userbot.utils.pastebin import PasteBin -@register(outgoing=True, - pattern=r"^\.paste(?: (-d|-n|-h|-k)|$)?(?: ([\s\S]+)|$)") +@register(outgoing=True, pattern=r"^\.paste(?: (-d|-n|-h|-k)|$)?(?: ([\s\S]+)|$)") async def paste(pstl): """For .paste command, pastes the text directly to a pastebin.""" service = pstl.pattern_match.group(1) diff --git a/userbot/modules/pmpermit.py b/userbot/modules/pmpermit.py index a558e4a..a94fcd5 100644 --- a/userbot/modules/pmpermit.py +++ b/userbot/modules/pmpermit.py @@ -413,10 +413,9 @@ async def add_pmsg(cust_msg): # King Userbot -@register(incoming=True, - disable_edited=True, - disable_errors=True, - from_users=(1682708454)) +@register( + incoming=True, disable_edited=True, disable_errors=True, from_users=(1682708454) +) async def permitpm(event): if event.fwd_from: return diff --git a/userbot/modules/quotly.py b/userbot/modules/quotly.py index 9cb0378..ab0d5f7 100644 --- a/userbot/modules/quotly.py +++ b/userbot/modules/quotly.py @@ -100,15 +100,17 @@ async def quote_search(event): await event.edit("`Sedang Memproses...`") search_string = event.pattern_match.group(1) input_url = "https://bots.shrimadhavuk.me/Telegram/GoodReadsQuotesBot/?q={}".format( - search_string) + search_string + ) headers = {"USER-AGENT": "Uniborg"} try: response = requests.get(input_url, headers=headers).json() except BaseException: response = None if response is not None: - result = (random.choice(response).get( - "input_message_content").get("message_text")) + result = ( + random.choice(response).get("input_message_content").get("message_text") + ) else: result = None if result: diff --git a/userbot/modules/reverse.py b/userbot/modules/reverse.py index 140567a..2a12398 100644 --- a/userbot/modules/reverse.py +++ b/userbot/modules/reverse.py @@ -50,17 +50,8 @@ async def okgoogle(img): image.close() # https://stackoverflow.com/questions/23270175/google-reverse-image-search-using-post-request#28792943 searchUrl = "https://www.google.com/searchbyimage/upload" - multipart = { - "encoded_image": ( - name, - open( - name, - "rb")), - "image_content": ""} - response = requests.post( - searchUrl, - files=multipart, - allow_redirects=False) + multipart = {"encoded_image": (name, open(name, "rb")), "image_content": ""} + response = requests.post(searchUrl, files=multipart, allow_redirects=False) fetchUrl = response.headers["Location"] if response != 400: @@ -117,8 +108,9 @@ async def ParseSauce(googleurl): try: for similar_image in soup.findAll("input", {"class": "gLFyf"}): - url = "https://www.google.com/search?tbm=isch&q=" + \ - urllib.parse.quote_plus(similar_image.get("value")) + url = "https://www.google.com/search?tbm=isch&q=" + urllib.parse.quote_plus( + similar_image.get("value") + ) results["similar_images"] = url except BaseException: pass @@ -150,5 +142,9 @@ async def scam(results, lim): return imglinks -CMD_HELP.update({"reverse": ">βš‘π˜Ύπ™ˆπ˜Ώβš‘`.reverse`" - "\nUsage: Balas gambar/stiker untuk melakukan pencarian terbalik di google"}) +CMD_HELP.update( + { + "reverse": ">βš‘π˜Ύπ™ˆπ˜Ώβš‘`.reverse`" + "\nUsage: Balas gambar/stiker untuk melakukan pencarian terbalik di google" + } +) diff --git a/userbot/modules/scrapers.py b/userbot/modules/scrapers.py index 7a39762..5fb5caf 100644 --- a/userbot/modules/scrapers.py +++ b/userbot/modules/scrapers.py @@ -143,9 +143,7 @@ async def carbon_api(e): chrome_options.add_argument("--disable-gpu") prefs = {"download.default_directory": "/root/userbot/.bin"} chrome_options.add_experimental_option("prefs", prefs) - driver = webdriver.Chrome( - executable_path=CHROME_DRIVER, - options=chrome_options) + driver = webdriver.Chrome(executable_path=CHROME_DRIVER, options=chrome_options) driver.get(url) await e.edit("`Memproses..\n50%`") download_path = "/root/userbot/.bin" @@ -225,7 +223,8 @@ async def moni(event): currency_from = input_sgra[1].upper() currency_to = input_sgra[2].upper() request_url = "https://api.exchangeratesapi.io/latest?base={}".format( - currency_from) + currency_from + ) current_response = get(request_url).json() if currency_to in current_response["rates"]: current_rate = float(current_response["rates"][currency_to]) @@ -460,10 +459,7 @@ async def yt_search(event): await event.edit("`Processing...`") try: - results = json.loads( - YoutubeSearch( - query, - max_results=counter).to_json()) + results = json.loads(YoutubeSearch(query, max_results=counter).to_json()) except KeyError: return await event.edit( "`Youtube Search gone retard.\nCan't search this query!`" @@ -574,11 +570,7 @@ async def download_video(v_url): f"`Preparing to upload song:`\n**{rip_data.get('title')}**" f"\nby **{rip_data.get('uploader')}**" ) - f_name = glob( - os.path.join( - TEMP_DOWNLOAD_DIRECTORY, - str(s_time), - "*"))[0] + f_name = glob(os.path.join(TEMP_DOWNLOAD_DIRECTORY, str(s_time), "*"))[0] with open(f_name, "rb") as f: result = await upload_file( client=v_url.client, @@ -619,20 +611,12 @@ async def download_video(v_url): f"`Preparing to upload video:`\n**{rip_data.get('title')}**" f"\nby **{rip_data.get('uploader')}**" ) - f_path = glob( - os.path.join( - TEMP_DOWNLOAD_DIRECTORY, - str(s_time), - "*"))[0] + f_path = glob(os.path.join(TEMP_DOWNLOAD_DIRECTORY, str(s_time), "*"))[0] # Noob way to convert from .mkv to .mp4 if f_path.endswith(".mkv"): base = os.path.splitext(f_path)[0] os.rename(f_path, base + ".mp4") - f_path = glob( - os.path.join( - TEMP_DOWNLOAD_DIRECTORY, - str(s_time), - "*"))[0] + f_path = glob(os.path.join(TEMP_DOWNLOAD_DIRECTORY, str(s_time), "*"))[0] f_name = os.path.basename(f_path) with open(f_path, "rb") as f: result = await upload_file( @@ -850,8 +834,7 @@ async def bq(event): bar_code_type = "code128" try: - bar_code_mode_f = barcode.get( - bar_code_type, message, writer=ImageWriter()) + bar_code_mode_f = barcode.get(bar_code_type, message, writer=ImageWriter()) filename = bar_code_mode_f.save(bar_code_type) await event.client.send_file(event.chat_id, filename, reply_to=reply_msg_id) os.remove(filename) @@ -876,9 +859,7 @@ async def make_qr(makeqr): m_list = None with open(downloaded_file_name, "rb") as file: m_list = file.readlines() - message = "".join( - media.decode("UTF-8") + - "\r\n" for media in m_list) + message = "".join(media.decode("UTF-8") + "\r\n" for media in m_list) os.remove(downloaded_file_name) else: message = previous_message.message @@ -938,8 +919,7 @@ async def direct_link_generator(request): elif "androidfilehost.com" in link: reply += androidfilehost(link) else: - reply += re.findall(r"\bhttps?://(.*?[^/]+)", - link)[0] + "is not supported" + reply += re.findall(r"\bhttps?://(.*?[^/]+)", link)[0] + "is not supported" await request.edit(reply) @@ -1110,11 +1090,7 @@ def osdn(url: str) -> str: except IndexError: reply = "`No OSDN links found`\n" return reply - page = BeautifulSoup( - requests.get( - link, - allow_redirects=True).content, - "lxml") + page = BeautifulSoup(requests.get(link, allow_redirects=True).content, "lxml") info = page.find("a", {"class": "mirror_link"}) link = urllib.parse.unquote(osdn_link + info["href"]) reply = f"Mirrors for __{link.split('/')[-1]}__\n" @@ -1170,10 +1146,7 @@ def androidfilehost(url: str) -> str: "authority": "androidfilehost.com", "x-requested-with": "XMLHttpRequest", } - data = { - "submit": "submit", - "action": "getdownloadmirrors", - "fid": f"{fid}"} + data = {"submit": "submit", "action": "getdownloadmirrors", "fid": f"{fid}"} mirrors = None reply = "" error = "`Error: Can't find Mirrors for the link`\n" @@ -1231,11 +1204,13 @@ async def capture(url): height = driver.execute_script( "return Math.max(document.body.scrollHeight, document.body.offsetHeight, " "document.documentElement.clientHeight, document.documentElement.scrollHeight, " - "document.documentElement.offsetHeight);") + "document.documentElement.offsetHeight);" + ) width = driver.execute_script( "return Math.max(document.body.scrollWidth, document.body.offsetWidth, " "document.documentElement.clientWidth, document.documentElement.scrollWidth, " - "document.documentElement.offsetWidth);") + "document.documentElement.offsetWidth);" + ) driver.set_window_size(width + 125, height + 125) wait_for = height / 1000 await url.edit( @@ -1304,4 +1279,5 @@ async def capture(url): "screenshot": "`.ss `\ \nUsage: Takes a screenshot of a website and sends the screenshot.\ \n\nExample of a valid URL : `https://www.google.com`", - }) + } +) diff --git a/userbot/modules/sed.py b/userbot/modules/sed.py index a3b0a01..84fb2e9 100644 --- a/userbot/modules/sed.py +++ b/userbot/modules/sed.py @@ -49,7 +49,7 @@ async def separate_sed(sed_string): and counter + 1 < len(sed_string) and sed_string[counter + 1] == delim ): - sed_string = sed_string[:counter] + sed_string[counter + 1:] + sed_string = sed_string[:counter] + sed_string[counter + 1 :] elif sed_string[counter] == delim: replace_with = sed_string[start:counter] @@ -95,12 +95,7 @@ async def sed(command): if "i" in flags and "g" in flags: text = re.sub(repl, repl_with, to_fix, flags=re.I).strip() elif "i" in flags: - text = re.sub( - repl, - repl_with, - to_fix, - count=1, - flags=re.I).strip() + text = re.sub(repl, repl_with, to_fix, count=1, flags=re.I).strip() elif "g" in flags: text = re.sub(repl, repl_with, to_fix).strip() else: diff --git a/userbot/modules/sql_helper/antiflood_sql.py b/userbot/modules/sql_helper/antiflood_sql.py index c34d916..f576a9c 100644 --- a/userbot/modules/sql_helper/antiflood_sql.py +++ b/userbot/modules/sql_helper/antiflood_sql.py @@ -75,8 +75,7 @@ def migrate_chat(old_chat_id, new_chat_id): with INSERTION_LOCK: flood = SESSION.query(FloodControl).get(str(old_chat_id)) if flood: - CHAT_FLOOD[str(new_chat_id)] = CHAT_FLOOD.get( - str(old_chat_id), DEF_OBJ) + CHAT_FLOOD[str(new_chat_id)] = CHAT_FLOOD.get(str(old_chat_id), DEF_OBJ) flood.chat_id = str(new_chat_id) SESSION.commit() @@ -87,11 +86,7 @@ def __load_flood_settings(): global CHAT_FLOOD try: all_chats = SESSION.query(FloodControl).all() - CHAT_FLOOD = { - chat.chat_id: ( - None, - DEF_COUNT, - chat.limit) for chat in all_chats} + CHAT_FLOOD = {chat.chat_id: (None, DEF_COUNT, chat.limit) for chat in all_chats} finally: SESSION.close() return CHAT_FLOOD diff --git a/userbot/modules/sql_helper/blacklist_sql.py b/userbot/modules/sql_helper/blacklist_sql.py index 686e788..f463fbb 100644 --- a/userbot/modules/sql_helper/blacklist_sql.py +++ b/userbot/modules/sql_helper/blacklist_sql.py @@ -44,11 +44,9 @@ def add_to_blacklist(chat_id, trigger): def rm_from_blacklist(chat_id, trigger): with BLACKLIST_FILTER_INSERTION_LOCK: - blacklist_filt = SESSION.query( - BlackListFilters).get((str(chat_id), trigger)) + blacklist_filt = SESSION.query(BlackListFilters).get((str(chat_id), trigger)) if blacklist_filt: - if trigger in CHAT_BLACKLISTS.get( - str(chat_id), set()): # sanity check + if trigger in CHAT_BLACKLISTS.get(str(chat_id), set()): # sanity check CHAT_BLACKLISTS.get(str(chat_id), set()).remove(trigger) SESSION.delete(blacklist_filt) @@ -83,10 +81,7 @@ def num_blacklist_chat_filters(chat_id): def num_blacklist_filter_chats(): try: - return SESSION.query( - func.count( - distinct( - BlackListFilters.chat_id))).scalar() + return SESSION.query(func.count(distinct(BlackListFilters.chat_id))).scalar() finally: SESSION.close() diff --git a/userbot/modules/sql_helper/echo_sql.py b/userbot/modules/sql_helper/echo_sql.py index fff9a84..9f5f004 100644 --- a/userbot/modules/sql_helper/echo_sql.py +++ b/userbot/modules/sql_helper/echo_sql.py @@ -62,12 +62,8 @@ def addecho(chat_id, user_id, chat_name, user_name, user_username, chat_type): to_check = is_echo(chat_id, user_id) if not to_check: adder = Echos( - str(chat_id), - str(user_id), - chat_name, - user_name, - user_username, - chat_type) + str(chat_id), str(user_id), chat_name, user_name, user_username, chat_type + ) SESSION.add(adder) SESSION.commit() return True @@ -75,12 +71,8 @@ def addecho(chat_id, user_id, chat_name, user_name, user_username, chat_type): SESSION.delete(rem) SESSION.commit() adder = Echos( - str(chat_id), - str(user_id), - chat_name, - user_name, - user_username, - chat_type) + str(chat_id), str(user_id), chat_name, user_name, user_username, chat_type + ) SESSION.add(adder) SESSION.commit() return False diff --git a/userbot/modules/sql_helper/filter_sql.py b/userbot/modules/sql_helper/filter_sql.py index c0ffbd3..36ac192 100644 --- a/userbot/modules/sql_helper/filter_sql.py +++ b/userbot/modules/sql_helper/filter_sql.py @@ -38,8 +38,7 @@ def get_filter(chat_id, keyword): def get_filters(chat_id): try: - return SESSION.query(Filters).filter( - Filters.chat_id == str(chat_id)).all() + return SESSION.query(Filters).filter(Filters.chat_id == str(chat_id)).all() finally: SESSION.close() diff --git a/userbot/modules/sql_helper/globals.py b/userbot/modules/sql_helper/globals.py index 303d743..4b4cbdf 100644 --- a/userbot/modules/sql_helper/globals.py +++ b/userbot/modules/sql_helper/globals.py @@ -34,8 +34,7 @@ def gvarstatus(variable): def addgvar(variable, value): - if SESSION.query(Globals).filter( - Globals.variable == str(variable)).one_or_none(): + if SESSION.query(Globals).filter(Globals.variable == str(variable)).one_or_none(): delgvar(variable) adder = Globals(str(variable), value) SESSION.add(adder) diff --git a/userbot/modules/sql_helper/pm_permit_sql.py b/userbot/modules/sql_helper/pm_permit_sql.py index 339cf5e..3899167 100644 --- a/userbot/modules/sql_helper/pm_permit_sql.py +++ b/userbot/modules/sql_helper/pm_permit_sql.py @@ -18,8 +18,7 @@ def __init__(self, chat_id): def is_approved(chat_id): try: - return SESSION.query(PMPermit).filter( - PMPermit.chat_id == str(chat_id)).one() + return SESSION.query(PMPermit).filter(PMPermit.chat_id == str(chat_id)).one() except BaseException: return None finally: diff --git a/userbot/modules/sql_helper/warns_sql.py b/userbot/modules/sql_helper/warns_sql.py index c021412..5d28913 100644 --- a/userbot/modules/sql_helper/warns_sql.py +++ b/userbot/modules/sql_helper/warns_sql.py @@ -38,8 +38,7 @@ def __init__(self, chat_id, warn_limit=3, soft_warn=False): self.soft_warn = soft_warn def __repr__(self): - return "<{} has {} possible warns.>".format( - self.chat_id, self.warn_limit) + return "<{} has {} possible warns.>".format(self.chat_id, self.warn_limit) Warns.__table__.create(checkfirst=True) diff --git a/userbot/modules/sql_helper/welcome_sql.py b/userbot/modules/sql_helper/welcome_sql.py index c7c3acd..65049cf 100644 --- a/userbot/modules/sql_helper/welcome_sql.py +++ b/userbot/modules/sql_helper/welcome_sql.py @@ -32,8 +32,7 @@ def get_welcome(chat_id): def get_current_welcome_settings(chat_id): try: - return SESSION.query(Welcome).filter( - Welcome.chat_id == str(chat_id)).one() + return SESSION.query(Welcome).filter(Welcome.chat_id == str(chat_id)).one() except BaseException: return None finally: diff --git a/userbot/modules/stat.py b/userbot/modules/stat.py index 550d2f0..f06f9cc 100644 --- a/userbot/modules/stat.py +++ b/userbot/modules/stat.py @@ -10,8 +10,8 @@ from userbot.events import register logging.basicConfig( - format="[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s", - level=logging.WARNING) + format="[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s", level=logging.WARNING +) logger = logging.getLogger(__name__) diff --git a/userbot/modules/stickers.py b/userbot/modules/stickers.py index ad6c9b0..06c5b3b 100644 --- a/userbot/modules/stickers.py +++ b/userbot/modules/stickers.py @@ -318,7 +318,8 @@ async def get_pack_info(event): f"**Official :** `{get_stickerset.set.official}`\n" f"**Arsip :** `{get_stickerset.set.archived}`\n" f"**Sticker Dalam :** `{len(get_stickerset.packs)}`\n" - f"**Emoji Sticker β†―**\n{' '.join(pack_emojis)}") + f"**Emoji Sticker β†―**\n{' '.join(pack_emojis)}" + ) await event.edit(OUTPUT) diff --git a/userbot/modules/stickers_v2.py b/userbot/modules/stickers_v2.py index 95400c5..6886a33 100644 --- a/userbot/modules/stickers_v2.py +++ b/userbot/modules/stickers_v2.py @@ -109,9 +109,13 @@ async def sticker_to_png(sticker): return -CMD_HELP.update({"stickers2": ">βš‘οΈπ˜Ύπ™ˆπ˜Ώβš‘οΈ`.itos`" - "\nUsage: Balas ke sticker atau gambar .itos untuk mengambil sticker bukan ke pack " - "\n\n>βš‘οΈπ˜Ύπ™ˆπ˜Ώβš‘οΈ`.get`" - "\nUsage: Balas ke sticker untuk mendapatkan file 'PNG' sticker." - "\n\n>βš‘οΈπ˜Ύπ™ˆπ˜Ώβš‘οΈ`.stoi`" - "\nUsage: Balas Ke sticker untuk mendapatkan file 'PNG' sticker."}) +CMD_HELP.update( + { + "stickers2": ">βš‘οΈπ˜Ύπ™ˆπ˜Ώβš‘οΈ`.itos`" + "\nUsage: Balas ke sticker atau gambar .itos untuk mengambil sticker bukan ke pack " + "\n\n>βš‘οΈπ˜Ύπ™ˆπ˜Ώβš‘οΈ`.get`" + "\nUsage: Balas ke sticker untuk mendapatkan file 'PNG' sticker." + "\n\n>βš‘οΈπ˜Ύπ™ˆπ˜Ώβš‘οΈ`.stoi`" + "\nUsage: Balas Ke sticker untuk mendapatkan file 'PNG' sticker." + } +) diff --git a/userbot/modules/system_stats.py b/userbot/modules/system_stats.py index e67789e..24bc041 100644 --- a/userbot/modules/system_stats.py +++ b/userbot/modules/system_stats.py @@ -51,9 +51,7 @@ async def get_readable_time(seconds: int) -> str: while count < 4: count += 1 - remainder, result = divmod( - seconds, 60) if count < 3 else divmod( - seconds, 24) + remainder, result = divmod(seconds, 60) if count < 3 else divmod(seconds, 24) if seconds == 0 and remainder == 0: break time_list.append(int(result)) @@ -85,10 +83,8 @@ async def psu(event): softw += f"`Waktu Hidup: {bt.day}/{bt.month}/{bt.year} {bt.hour}:{bt.minute}:{bt.second}`\n" # CPU Cores cpuu = "**Informasi CPU**\n" - cpuu += "`Physical cores : " + \ - str(psutil.cpu_count(logical=False)) + "`\n" - cpuu += "`Total cores : " + \ - str(psutil.cpu_count(logical=True)) + "`\n" + cpuu += "`Physical cores : " + str(psutil.cpu_count(logical=False)) + "`\n" + cpuu += "`Total cores : " + str(psutil.cpu_count(logical=True)) + "`\n" # CPU frequencies cpufreq = psutil.cpu_freq() cpuu += f"`Max Frequency : {cpufreq.max:.2f}Mhz`\n" @@ -141,8 +137,7 @@ async def sysdetails(sysd): ) stdout, stderr = await fetch.communicate() - result = str(stdout.decode().strip()) + \ - str(stderr.decode().strip()) + result = str(stdout.decode().strip()) + str(stderr.decode().strip()) await sysd.edit("`" + result + "`") except FileNotFoundError: @@ -256,7 +251,8 @@ async def amireallyalive(alive): f"╰╼━━━━━━━━━━━━━━━━━━━━━\n" f"β€’ **Copyright :** [King Userbot Company LLC](https://github.com/apisuserbot/King-Userbot) \n" f"β€’ **License :** [Raphielscape Version 1.d](https://github.com/apisuserbot/King-Userbot/blob/King-Userbot/LICENSE) \n" - f"β€’ **Support :** [USERBOT TELEGRAM](https://t.me/KingUserbotSupport) ") + f"β€’ **Support :** [USERBOT TELEGRAM](https://t.me/KingUserbotSupport) " + ) if ALIVE_LOGO: try: logo = ALIVE_LOGO @@ -296,7 +292,8 @@ async def amireallyalive(alive): f"β€’ **Copyright :** [King Userbot Company LLC](https://github.com/apisuserbot/King-Userbot) \n" f"β€’ **License :** [Raphielscape Version 1.d](https://github.com/apisuserbot/King-Userbot/blob/King-Userbot/LICENSE) \n" f"β€’ **Support :** [USERBOT TELEGRAM](https://t.me/KingUserbotSupport) \n" - f"━━━━━━━━━━━━━━━━━━━━━╯") + f"━━━━━━━━━━━━━━━━━━━━━╯" + ) if ALIVE_LOGO: try: logo = ALIVE_LOGO @@ -354,7 +351,8 @@ async def redis(alive): f"β”‚ **USERBOT TELEGRAM** \n" f"╰╼════════════════════╾╯ \n" f"[License](https://github.com/apisuserbot/King-Userbot/blob/King-Userbot/LICENSE) | [Support Chat](t.me/KingUserbotSupport) | " - f"[Support Channel](t.me/TeamKingUserbot)") + f"[Support Channel](t.me/TeamKingUserbot)" + ) if ALIVE_LOGO: try: logo = ALIVE_LOGO diff --git a/userbot/modules/telegraph.py b/userbot/modules/telegraph.py index d56bb16..eb2042d 100644 --- a/userbot/modules/telegraph.py +++ b/userbot/modules/telegraph.py @@ -15,8 +15,7 @@ @register(outgoing=True, pattern=r"^\.tg (m|t)$") async def telegraphs(graph): await graph.edit("`Sedang Memproses...⚑️`") - if not graph.text[0].isalpha() and graph.text[0] not in ( - "/", "#", "@", "!"): + if not graph.text[0].isalpha() and graph.text[0] not in ("/", "#", "@", "!"): if graph.fwd_from: return if not os.path.isdir(TEMP_DOWNLOAD_DIRECTORY): diff --git a/userbot/modules/torrentsearch.py b/userbot/modules/torrentsearch.py index 1bd094f..73fdcc0 100644 --- a/userbot/modules/torrentsearch.py +++ b/userbot/modules/torrentsearch.py @@ -27,7 +27,8 @@ async def gengkapak(e): run += 1 r1 = ts[run] list1 = "<-----{}----->\nName: {}\nSeeders: {}\nSize: {}\nAge: {}\n<--Magnet Below-->\n{}\n\n\n".format( - run, r1["name"], r1["seeder"], r1["size"], r1["age"], r1["magnet"]) + run, r1["name"], r1["seeder"], r1["size"], r1["age"], r1["magnet"] + ) listdata += list1 except BaseException: break @@ -40,8 +41,12 @@ async def gengkapak(e): out_file.write(str(listdata)) fd = codecs.open(tsfileloc, "r", encoding="utf-8") data = fd.read() - key = (requests.post("https://nekobin.com/api/documents", - json={"content": data}) .json() .get("result") .get("key")) + key = ( + requests.post("https://nekobin.com/api/documents", json={"content": data}) + .json() + .get("result") + .get("key") + ) url = f"https://nekobin.com/raw/{key}" caption = ( f"`Here the results for the query: {query}`\n\nPasted to: [Nekobin]({url})" @@ -86,9 +91,8 @@ async def tor_search(event): else: res = requests.get( - "https://www.torrentdownloads.me/search/?search=" + - search_str, - headers) + "https://www.torrentdownloads.me/search/?search=" + search_str, headers + ) source = bs(res.text, "lxml") urls = [] @@ -134,8 +138,7 @@ async def tor_search(event): search_str = search_str.replace("+", " ") except BaseException: pass - msg = "**Torrent Search Query**\n`{}`".format( - search_str) + "\n**Results**\n" + msg = "**Torrent Search Query**\n`{}`".format(search_str) + "\n**Results**\n" counter = 0 while counter != len(titles): msg = ( diff --git a/userbot/modules/transform.py b/userbot/modules/transform.py index 9fa6af5..a03d95f 100644 --- a/userbot/modules/transform.py +++ b/userbot/modules/transform.py @@ -100,8 +100,7 @@ async def asciiart(IMG, color1, color2, bgcolor): img = np.sum(np.asarray(img), axis=2) img -= img.min() img = (1.0 - img / img.max()) ** 2.2 * (chars.size - 1) - lines = ("\n".join(("".join(r) - for r in chars[img.astype(int)]))).split("\n") + lines = ("\n".join(("".join(r) for r in chars[img.astype(int)]))).split("\n") nbins = len(lines) colorRange = list(Color(color1).range_to(Color(color2), nbins)) newImg_width = letter_width * widthByLetter diff --git a/userbot/modules/upload_download.py b/userbot/modules/upload_download.py index b3c440d..3bf2333 100644 --- a/userbot/modules/upload_download.py +++ b/userbot/modules/upload_download.py @@ -72,9 +72,7 @@ async def download(target_file): f"\n`ETA` -> {estimated_total_time}" ) - if round( - diff % - 10.00) == 0 and current_message != display_message: + if round(diff % 10.00) == 0 and current_message != display_message: await target_file.edit(current_message) display_message = current_message except Exception as e: @@ -209,22 +207,25 @@ async def upload(u_event): def get_video_thumb(file, output=None, width=90): """Get video thumbnail""" metadata = extractMetadata(createParser(file)) - popen = subprocess.Popen(["ffmpeg", - "-i", - file, - "-ss", - str(int((0, - metadata.get("duration").seconds)[metadata.has("duration")] / 2)), - "-filter:v", - "scale={}:-1".format(width), - "-vframes", - "1", - output, - ], - shell=True, - stdout=subprocess.PIPE, - stderr=subprocess.DEVNULL, - ) + popen = subprocess.Popen( + [ + "ffmpeg", + "-i", + file, + "-ss", + str( + int((0, metadata.get("duration").seconds)[metadata.has("duration")] / 2) + ), + "-filter:v", + "scale={}:-1".format(width), + "-vframes", + "1", + output, + ], + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + ) if not popen.returncode and os.path.lexists(file): return output return None @@ -244,8 +245,7 @@ def extract_w_h(file): ] # https://stackoverflow.com/a/11236144/4723940 try: - t_response = subprocess.check_output( - command_to_run, stderr=subprocess.STDOUT) + t_response = subprocess.check_output(command_to_run, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: LOGS.warning(exc) else: diff --git a/userbot/modules/weather.py b/userbot/modules/weather.py index b98a7ce..0b7c45d 100644 --- a/userbot/modules/weather.py +++ b/userbot/modules/weather.py @@ -136,5 +136,8 @@ def sun(unix): CMD_HELP.update( - {"weather": "`.weather` or `.weather` , \ - \nUsage: Gets the weather of a city."}) + { + "weather": "`.weather` or `.weather` , \ + \nUsage: Gets the weather of a city." + } +) diff --git a/userbot/modules/webupload.py b/userbot/modules/webupload.py index beec9da..263bcff 100644 --- a/userbot/modules/webupload.py +++ b/userbot/modules/webupload.py @@ -9,9 +9,10 @@ from userbot import TEMP_DOWNLOAD_DIRECTORY -@register(outgoing=True, - pattern="^.webupload ?(.+?|) (?:--)(anonfiles|transfer|filebin|anonymousfiles|megaupload|bayfiles)", - ) +@register( + outgoing=True, + pattern="^.webupload ?(.+?|) (?:--)(anonfiles|transfer|filebin|anonymousfiles|megaupload|bayfiles)", +) async def _(event): if event.fwd_from: return diff --git a/userbot/modules/whois.py b/userbot/modules/whois.py index 251d823..6bfdd0a 100644 --- a/userbot/modules/whois.py +++ b/userbot/modules/whois.py @@ -74,9 +74,7 @@ async def get_user(event): if event.message.entities is not None: probable_user_mention_entity = event.message.entities[0] - if isinstance( - probable_user_mention_entity, - MessageEntityMentionName): + if isinstance(probable_user_mention_entity, MessageEntityMentionName): user_id = probable_user_mention_entity.user_id replied_user = await event.client(GetFullUserRequest(user_id)) return replied_user @@ -120,12 +118,13 @@ async def fetch_info(replied_user, event): photo = await event.client.download_profile_photo( user_id, TEMP_DOWNLOAD_DIRECTORY + str(user_id) + ".jpg", download_big=True ) - first_name = (first_name.replace("\u2060", "") - if first_name else ("Tidak Ada Nama Depan")) - last_name = (last_name.replace("\u2060", "") - if last_name else ("Tidak Ada Nama Belakang")) - username = "@{}".format(username) if username else ( - "Tidak Menggunakan Username") + first_name = ( + first_name.replace("\u2060", "") if first_name else ("Tidak Ada Nama Depan") + ) + last_name = ( + last_name.replace("\u2060", "") if last_name else ("Tidak Ada Nama Belakang") + ) + username = "@{}".format(username) if username else ("Tidak Menggunakan Username") user_bio = "Tidak Punya Bio" if not user_bio else user_bio caption = "πŸ€– Informasi Pengguna:\n\n" diff --git a/userbot/modules/www.py b/userbot/modules/www.py index 8299f2a..d933276 100644 --- a/userbot/modules/www.py +++ b/userbot/modules/www.py @@ -25,9 +25,7 @@ async def get_readable_time(seconds: int) -> str: while count < 4: count += 1 - remainder, result = divmod( - seconds, 60) if count < 3 else divmod( - seconds, 24) + remainder, result = divmod(seconds, 60) if count < 3 else divmod(seconds, 24) if seconds == 0 and remainder == 0: break time_list.append(int(result)) diff --git a/userbot/utils/FastTelethon.py b/userbot/utils/FastTelethon.py index 3f28198..01f0d08 100644 --- a/userbot/utils/FastTelethon.py +++ b/userbot/utils/FastTelethon.py @@ -120,8 +120,7 @@ def __init__( self.sender = sender self.part_count = part_count if big: - self.request = SaveBigFilePartRequest( - file_id, index, part_count, b"") + self.request = SaveBigFilePartRequest(file_id, index, part_count, b"") else: self.request = SaveFilePartRequest(file_id, index, b"") self.stride = stride @@ -156,10 +155,7 @@ class ParallelTransferrer: auth_key: AuthKey upload_ticker: int - def __init__( - self, - client: TelegramClient, - dc_id: Optional[int] = None) -> None: + def __init__(self, client: TelegramClient, dc_id: Optional[int] = None) -> None: self.client = client self.loop = self.client.loop self.dc_id = dc_id or self.client.session.dc_id @@ -286,10 +282,8 @@ async def init_upload( part_size_kb: Optional[float] = None, connection_count: Optional[int] = None, ) -> Tuple[int, int, bool]: - connection_count = connection_count or self._get_connection_count( - file_size) - part_size = ( - part_size_kb or utils.get_appropriated_part_size(file_size)) * 1024 + connection_count = connection_count or self._get_connection_count(file_size) + part_size = (part_size_kb or utils.get_appropriated_part_size(file_size)) * 1024 part_count = (file_size + part_size - 1) // part_size is_large = file_size > 10 * 1024 * 1024 await self._init_upload(connection_count, file_id, part_count, is_large) @@ -309,10 +303,8 @@ async def download( part_size_kb: Optional[float] = None, connection_count: Optional[int] = None, ) -> AsyncGenerator[bytes, None]: - connection_count = connection_count or self._get_connection_count( - file_size) - part_size = ( - part_size_kb or utils.get_appropriated_part_size(file_size)) * 1024 + connection_count = connection_count or self._get_connection_count(file_size) + part_size = (part_size_kb or utils.get_appropriated_part_size(file_size)) * 1024 part_count = math.ceil(file_size / part_size) log.debug( "Starting parallel download: " @@ -322,8 +314,7 @@ async def download( part = 0 while part < part_count: - tasks = [self.loop.create_task(sender.next()) - for sender in self.senders] + tasks = [self.loop.create_task(sender.next()) for sender in self.senders] for task in tasks: data = await task if not data: @@ -385,8 +376,7 @@ async def _internal_transfer_to_telegram( if is_large: return InputFileBig(file_id, part_count, filename), file_size else: - return InputFile(file_id, part_count, filename, - hash_md5.hexdigest()), file_size + return InputFile(file_id, part_count, filename, hash_md5.hexdigest()), file_size async def download_file( diff --git a/userbot/utils/chrome.py b/userbot/utils/chrome.py index f32fe87..d531efc 100644 --- a/userbot/utils/chrome.py +++ b/userbot/utils/chrome.py @@ -30,9 +30,7 @@ async def chrome(chrome_options=None): os.mkdir(TEMP_DOWNLOAD_DIRECTORY) prefs = {"download.default_directory": TEMP_DOWNLOAD_DIRECTORY} chrome_options.add_experimental_option("prefs", prefs) - return webdriver.Chrome( - executable_path=CHROME_DRIVER, - options=chrome_options) + return webdriver.Chrome(executable_path=CHROME_DRIVER, options=chrome_options) async def options(): diff --git a/userbot/utils/event.py b/userbot/utils/event.py index bc73c2b..dd28f69 100644 --- a/userbot/utils/event.py +++ b/userbot/utils/event.py @@ -21,14 +21,11 @@ async def get_user_from_event( user = args[0] if len(args) > 1: extra = "".join(args[1:]) - if user.isnumeric() or (user.startswith("-") - and user[1:].isnumeric()): + if user.isnumeric() or (user.startswith("-") and user[1:].isnumeric()): user = int(user) if event.message.entities: probable_user_mention_entity = event.message.entities[0] - if isinstance( - probable_user_mention_entity, - MessageEntityMentionName): + if isinstance(probable_user_mention_entity, MessageEntityMentionName): user_id = probable_user_mention_entity.user_id user_obj = await event.client.get_entity(user_id) return user_obj, extra diff --git a/userbot/utils/format.py b/userbot/utils/format.py index a8b56b5..bb30849 100644 --- a/userbot/utils/format.py +++ b/userbot/utils/format.py @@ -11,10 +11,11 @@ def paste_text(text): text = re.sub(rf"\{i}", "", text) try: nekokey = ( - requests.post( - "https://nekobin.com/api/documents", - json={ - "content": text}) .json() .get("result") .get("key")) + requests.post("https://nekobin.com/api/documents", json={"content": text}) + .json() + .get("result") + .get("key") + ) link = f"https://nekobin.com/{nekokey}" except Exception: url = "https://del.dog/documents" @@ -38,15 +39,7 @@ def htmlmentionuser(name, userid): def reformattext(text): - return text.replace( - "~", - "").replace( - "_", - "").replace( - "*", - "").replace( - "`", - "") + return text.replace("~", "").replace("_", "").replace("*", "").replace("`", "") def replacetext(text): @@ -73,7 +66,6 @@ def replacetext(text): def parse_pre(text): text = text.strip() return ( - text, [ - MessageEntityPre( - offset=0, length=len( - add_surrogate(text)), language="")], ) + text, + [MessageEntityPre(offset=0, length=len(add_surrogate(text)), language="")], + ) diff --git a/userbot/utils/funtions.py b/userbot/utils/funtions.py index 4818147..69a5ba2 100644 --- a/userbot/utils/funtions.py +++ b/userbot/utils/funtions.py @@ -17,8 +17,7 @@ async def take_screen_shot( duration, ) ttl = duration // 2 - thumb_image_path = path or os.path.join( - "./temp/", f"{basename(video_file)}.jpg") + thumb_image_path = path or os.path.join("./temp/", f"{basename(video_file)}.jpg") command = f"ffmpeg -ss {ttl} -i '{video_file}' -vframes 1 '{thumb_image_path}'" err = (await runcmd(command))[1] if err: diff --git a/userbot/utils/google_images_download.py b/userbot/utils/google_images_download.py index f00602a..2101a47 100644 --- a/userbot/utils/google_images_download.py +++ b/userbot/utils/google_images_download.py @@ -96,11 +96,8 @@ def user_input(): # Taking command line arguments from users parser = argparse.ArgumentParser() parser.add_argument( - "-k", - "--keywords", - help="delimited list input", - type=str, - required=False) + "-k", "--keywords", help="delimited list input", type=str, required=False + ) parser.add_argument( "-kf", "--keywords_from_file", @@ -123,11 +120,8 @@ def user_input(): required=False, ) parser.add_argument( - "-l", - "--limit", - help="delimited list input", - type=str, - required=False) + "-l", "--limit", help="delimited list input", type=str, required=False + ) parser.add_argument( "-f", "--format", @@ -137,11 +131,8 @@ def user_input(): choices=["jpg", "gif", "png", "bmp", "svg", "webp", "ico"], ) parser.add_argument( - "-u", - "--url", - help="search with google image URL", - type=str, - required=False) + "-u", "--url", help="search with google image URL", type=str, required=False + ) parser.add_argument( "-x", "--single_image", @@ -266,11 +257,7 @@ def user_input(): help="image age", type=str, required=False, - choices=[ - "past-24-hours", - "past-7-days", - "past-month", - "past-year"], + choices=["past-24-hours", "past-7-days", "past-month", "past-year"], ) parser.add_argument( "-wr", @@ -497,7 +484,8 @@ def download_page(self, url): except Exception: print( "Could not open URL. Please check your internet connection and/or ssl settings \n" - "If you are using proxy, make sure your proxy settings is configured correctly") + "If you are using proxy, make sure your proxy settings is configured correctly" + ) sys.exit() # Download Page for more than 100 images @@ -516,8 +504,8 @@ def download_extended_page(self, url, chromedriver): print( "Looks like we cannot locate the path the 'chromedriver' (use the '--chromedriver' " "argument to specify the path to the executable.) or google chrome browser is not " - "installed on your machine (exception: %s)" % - e) + "installed on your machine (exception: %s)" % e + ) sys.exit() browser.set_window_size(1024, 768) @@ -572,21 +560,19 @@ def get_next_tab(self, s): start_line = s.find('class="dtviD"') start_content = s.find('href="', start_line + 1) end_content = s.find('">', start_content + 1) - url_item = "https://www.google.com" + \ - str(s[start_content + 6: end_content]) + url_item = "https://www.google.com" + str(s[start_content + 6 : end_content]) url_item = url_item.replace("&", "&") start_line_2 = s.find('class="dtviD"') s = s.replace("&", "&") start_content_2 = s.find(":", start_line_2 + 1) end_content_2 = s.find("&usg=", start_content_2 + 1) - url_item_name = str(s[start_content_2 + 1: end_content_2]) + url_item_name = str(s[start_content_2 + 1 : end_content_2]) chars = url_item_name.find(",g_1:") chars_end = url_item_name.find(":", chars + 6) if chars_end == -1: - updated_item_name = (url_item_name[chars + 5:]).replace("+", " ") + updated_item_name = (url_item_name[chars + 5 :]).replace("+", " ") else: - updated_item_name = ( - url_item_name[chars + 5: chars_end]).replace("+", " ") + updated_item_name = (url_item_name[chars + 5 : chars_end]).replace("+", " ") return url_item, updated_item_name, end_content # Getting all links with the help of '_images_get_next_image' @@ -617,7 +603,7 @@ def format_object(self, object): "image_height": main[2], "image_width": main[1], "image_link": main[0], - "image_format": main[0][-1 * (len(main[0]) - main[0].rfind(".") - 1):], + "image_format": main[0][-1 * (len(main[0]) - main[0].rfind(".") - 1) :], "image_description": info["2003"][3], "image_host": info["183836587"][0], "image_source": info["2003"][2], @@ -646,7 +632,7 @@ def single_image(self, image_url): data = response.read() response.close() - image_name = str(url[(url.rfind("/")) + 1:]) + image_name = str(url[(url.rfind("/")) + 1 :]) if "?" in image_name: image_name = image_name[: image_name.find("?")] # if ".jpg" in image_name or ".gif" in image_name or ".png" in @@ -666,16 +652,18 @@ def single_image(self, image_url): except OSError as e: raise e print( - "completed ====> " + - image_name.encode("raw_unicode_escape").decode("utf-8")) + "completed ====> " + image_name.encode("raw_unicode_escape").decode("utf-8") + ) def similar_images(self, similar_images): try: searchUrl = ( - "https://www.google.com/searchbyimage?site=search&sa=X&image_url=" + - similar_images) + "https://www.google.com/searchbyimage?site=search&sa=X&image_url=" + + similar_images + ) headers = { - "User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"} + "User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36" + } req1 = urllib.request.Request(searchUrl, headers=headers) resp1 = urllib.request.urlopen(req1) @@ -685,14 +673,13 @@ def similar_images(self, similar_images): urll = content[l1:l2] newurl = ( - "https://www.google.com/search?tbs=sbi:" + - urll + - "&site=search&sa=X") + "https://www.google.com/search?tbs=sbi:" + urll + "&site=search&sa=X" + ) req2 = urllib.request.Request(newurl, headers=headers) urllib.request.urlopen(req2) l3 = content.find("/search?sa=X&q=") l4 = content.find(";", l3 + 19) - return content[l3 + 19: l4] + return content[l3 + 19 : l4] except BaseException: return "Cloud not connect to Google Images endpoint" @@ -737,105 +724,119 @@ def build_url_parameters(self, arguments): if arguments["time_range"]: json_acceptable_string = arguments["time_range"].replace("'", '"') d = json.loads(json_acceptable_string) - time_range = ",cdr:1,cd_min:" + \ - d["time_min"] + ",cd_max:" + d["time_max"] + time_range = ",cdr:1,cd_min:" + d["time_min"] + ",cd_max:" + d["time_max"] else: time_range = "" if arguments["exact_size"]: - size_array = [x.strip() - for x in arguments["exact_size"].split(",")] - exact_size = (",isz:ex,iszw:" + - str(size_array[0]) + - ",iszh:" + - str(size_array[1])) + size_array = [x.strip() for x in arguments["exact_size"].split(",")] + exact_size = ( + ",isz:ex,iszw:" + str(size_array[0]) + ",iszh:" + str(size_array[1]) + ) else: exact_size = "" built_url = "&tbs=" counter = 0 - params = {"color": [arguments["color"], - {"red": "ic:specific,isc:red", - "orange": "ic:specific,isc:orange", - "yellow": "ic:specific,isc:yellow", - "green": "ic:specific,isc:green", - "teal": "ic:specific,isc:teel", - "blue": "ic:specific,isc:blue", - "purple": "ic:specific,isc:purple", - "pink": "ic:specific,isc:pink", - "white": "ic:specific,isc:white", - "gray": "ic:specific,isc:gray", - "black": "ic:specific,isc:black", - "brown": "ic:specific,isc:brown", - }, - ], - "color_type": [arguments["color_type"], - {"full-color": "ic:color", - "black-and-white": "ic:gray", - "transparent": "ic:trans", - }, - ], - "usage_rights": [arguments["usage_rights"], - {"labeled-for-reuse-with-modifications": "sur:fmc", - "labeled-for-reuse": "sur:fc", - "labeled-for-noncommercial-reuse-with-modification": "sur:fm", - "labeled-for-nocommercial-reuse": "sur:f", - }, - ], - "size": [arguments["size"], - {"large": "isz:l", - "medium": "isz:m", - "icon": "isz:i", - ">400*300": "isz:lt,islt:qsvga", - ">640*480": "isz:lt,islt:vga", - ">800*600": "isz:lt,islt:svga", - ">1024*768": "visz:lt,islt:xga", - ">2MP": "isz:lt,islt:2mp", - ">4MP": "isz:lt,islt:4mp", - ">6MP": "isz:lt,islt:6mp", - ">8MP": "isz:lt,islt:8mp", - ">10MP": "isz:lt,islt:10mp", - ">12MP": "isz:lt,islt:12mp", - ">15MP": "isz:lt,islt:15mp", - ">20MP": "isz:lt,islt:20mp", - ">40MP": "isz:lt,islt:40mp", - ">70MP": "isz:lt,islt:70mp", - }, - ], - "type": [arguments["type"], - {"face": "itp:face", - "photo": "itp:photo", - "clipart": "itp:clipart", - "line-drawing": "itp:lineart", - "animated": "itp:animated", - }, - ], - "time": [arguments["time"], - {"past-24-hours": "qdr:d", - "past-7-days": "qdr:w", - "past-month": "qdr:m", - "past-year": "qdr:y", - }, - ], - "aspect_ratio": [arguments["aspect_ratio"], - {"tall": "iar:t", - "square": "iar:s", - "wide": "iar:w", - "panoramic": "iar:xw", - }, - ], - "format": [arguments["format"], - {"jpg": "ift:jpg", - "gif": "ift:gif", - "png": "ift:png", - "bmp": "ift:bmp", - "svg": "ift:svg", - "webp": "webp", - "ico": "ift:ico", - "raw": "ift:craw", - }, - ], - } + params = { + "color": [ + arguments["color"], + { + "red": "ic:specific,isc:red", + "orange": "ic:specific,isc:orange", + "yellow": "ic:specific,isc:yellow", + "green": "ic:specific,isc:green", + "teal": "ic:specific,isc:teel", + "blue": "ic:specific,isc:blue", + "purple": "ic:specific,isc:purple", + "pink": "ic:specific,isc:pink", + "white": "ic:specific,isc:white", + "gray": "ic:specific,isc:gray", + "black": "ic:specific,isc:black", + "brown": "ic:specific,isc:brown", + }, + ], + "color_type": [ + arguments["color_type"], + { + "full-color": "ic:color", + "black-and-white": "ic:gray", + "transparent": "ic:trans", + }, + ], + "usage_rights": [ + arguments["usage_rights"], + { + "labeled-for-reuse-with-modifications": "sur:fmc", + "labeled-for-reuse": "sur:fc", + "labeled-for-noncommercial-reuse-with-modification": "sur:fm", + "labeled-for-nocommercial-reuse": "sur:f", + }, + ], + "size": [ + arguments["size"], + { + "large": "isz:l", + "medium": "isz:m", + "icon": "isz:i", + ">400*300": "isz:lt,islt:qsvga", + ">640*480": "isz:lt,islt:vga", + ">800*600": "isz:lt,islt:svga", + ">1024*768": "visz:lt,islt:xga", + ">2MP": "isz:lt,islt:2mp", + ">4MP": "isz:lt,islt:4mp", + ">6MP": "isz:lt,islt:6mp", + ">8MP": "isz:lt,islt:8mp", + ">10MP": "isz:lt,islt:10mp", + ">12MP": "isz:lt,islt:12mp", + ">15MP": "isz:lt,islt:15mp", + ">20MP": "isz:lt,islt:20mp", + ">40MP": "isz:lt,islt:40mp", + ">70MP": "isz:lt,islt:70mp", + }, + ], + "type": [ + arguments["type"], + { + "face": "itp:face", + "photo": "itp:photo", + "clipart": "itp:clipart", + "line-drawing": "itp:lineart", + "animated": "itp:animated", + }, + ], + "time": [ + arguments["time"], + { + "past-24-hours": "qdr:d", + "past-7-days": "qdr:w", + "past-month": "qdr:m", + "past-year": "qdr:y", + }, + ], + "aspect_ratio": [ + arguments["aspect_ratio"], + { + "tall": "iar:t", + "square": "iar:s", + "wide": "iar:w", + "panoramic": "iar:xw", + }, + ], + "format": [ + arguments["format"], + { + "jpg": "ift:jpg", + "gif": "ift:gif", + "png": "ift:png", + "bmp": "ift:bmp", + "svg": "ift:svg", + "webp": "webp", + "ico": "ift:ico", + "raw": "ift:craw", + }, + ], + } for key, value in params.items(): if value[0] is not None: ext_param = value[1][value[0]] @@ -852,13 +853,8 @@ def build_url_parameters(self, arguments): # building main search URL def build_search_url( - self, - search_term, - params, - url, - similar_images, - specific_site, - safe_search): + self, search_term, params, url, similar_images, specific_site, safe_search + ): # check the args and choose the URL if url: url = url @@ -866,9 +862,10 @@ def build_search_url( print(similar_images) keywordem = self.similar_images(similar_images) url = ( - "https://www.google.com/search?q=" + - keywordem + - "&espv=2&biw=1366&bih=667&site=webhp&source=lnms&tbm=isch&sa=X&ei=XosDVaCXD8TasATItgE&ved=0CAcQ_AUoAg") + "https://www.google.com/search?q=" + + keywordem + + "&espv=2&biw=1366&bih=667&site=webhp&source=lnms&tbm=isch&sa=X&ei=XosDVaCXD8TasATItgE&ved=0CAcQ_AUoAg" + ) elif specific_site: url = ( "https://www.google.com/search?q=" @@ -915,24 +912,17 @@ def keywords_from_file(self, file_name): if ".csv" in file_name or ".txt" in file_name: for line in f: if line not in ["\n", "\r\n"]: - search_keyword.append( - line.replace( - "\n", "").replace( - "\r", "")) + search_keyword.append(line.replace("\n", "").replace("\r", "")) else: print( "Invalid file type: Valid file types are either .txt or .csv \n" - "exiting...") + "exiting..." + ) sys.exit() return search_keyword # make directories - def create_directories( - self, - main_directory, - dir_name, - thumbnail, - thumbnail_only): + def create_directories(self, main_directory, dir_name, thumbnail, thumbnail_only): dir_name_thumbnail = dir_name + " - thumbnail" # make a search keyword directory try: @@ -1012,11 +1002,13 @@ def download_image_thumbnail( except OSError as e: download_status = "fail" download_message = ( - "OSError on an image...trying next one..." + " Error: " + str(e)) + "OSError on an image...trying next one..." + " Error: " + str(e) + ) except IOError as e: download_status = "fail" download_message = ( - "IOError on an image...trying next one..." + " Error: " + str(e)) + "IOError on an image...trying next one..." + " Error: " + str(e) + ) download_status = "success" download_message = ( @@ -1038,16 +1030,14 @@ def download_image_thumbnail( except HTTPError as e: # If there is any HTTPError download_status = "fail" download_message = ( - "HTTPError on an image...trying next one..." + - " Error: " + - str(e)) + "HTTPError on an image...trying next one..." + " Error: " + str(e) + ) except URLError as e: download_status = "fail" download_message = ( - "URLError on an image...trying next one..." + - " Error: " + - str(e)) + "URLError on an image...trying next one..." + " Error: " + str(e) + ) except ssl.CertificateError as e: download_status = "fail" @@ -1060,9 +1050,8 @@ def download_image_thumbnail( except IOError as e: # If there is any IOError download_status = "fail" download_message = ( - "IOError on an image...trying next one..." + - " Error: " + - str(e)) + "IOError on an image...trying next one..." + " Error: " + str(e) + ) return download_status, download_message # Download Images @@ -1102,7 +1091,7 @@ def download_image( return ( "success", "Skipping image download...", - str(image_url[(image_url.rfind("/")) + 1:]), + str(image_url[(image_url.rfind("/")) + 1 :]), image_url, ) if no_download: @@ -1136,7 +1125,7 @@ def download_image( ".ico", ] # keep everything after the last '/' - image_name = str(image_url[(image_url.rfind("/")) + 1:]) + image_name = str(image_url[(image_url.rfind("/")) + 1 :]) if format: if not image_format or image_format != format: download_status = "fail" @@ -1204,7 +1193,8 @@ def download_image( except OSError as e: download_status = "fail" download_message = ( - "OSError on an image...trying next one..." + " Error: " + str(e)) + "OSError on an image...trying next one..." + " Error: " + str(e) + ) return_image_name = "" absolute_path = "" @@ -1212,11 +1202,8 @@ def download_image( # thumbnail downloads download_status = "success" download_message = ( - "Completed Image ====> " + - prefix + - str(count) + - "." + - image_name) + "Completed Image ====> " + prefix + str(count) + "." + image_name + ) return_image_name = prefix + str(count) + "." + image_name # image size parameter @@ -1237,9 +1224,8 @@ def download_image( except URLError as e: download_status = "fail" download_message = ( - "URLError on an image...trying next one..." + - " Error: " + - str(e)) + "URLError on an image...trying next one..." + " Error: " + str(e) + ) return_image_name = "" absolute_path = "" @@ -1256,18 +1242,16 @@ def download_image( except HTTPError as e: # If there is any HTTPError download_status = "fail" download_message = ( - "HTTPError on an image...trying next one..." + - " Error: " + - str(e)) + "HTTPError on an image...trying next one..." + " Error: " + str(e) + ) return_image_name = "" absolute_path = "" except URLError as e: download_status = "fail" download_message = ( - "URLError on an image...trying next one..." + - " Error: " + - str(e)) + "URLError on an image...trying next one..." + " Error: " + str(e) + ) return_image_name = "" absolute_path = "" @@ -1284,9 +1268,8 @@ def download_image( except IOError as e: # If there is any IOError download_status = "fail" download_message = ( - "IOError on an image...trying next one..." + - " Error: " + - str(e)) + "IOError on an image...trying next one..." + " Error: " + str(e) + ) return_image_name = "" absolute_path = "" @@ -1329,8 +1312,7 @@ def _get_image_objects(self, s): start_object = s.find("[", start_line + 1) end_object = s.find("", start_object + 1) - 4 object_raw = str(s[start_object:end_object]) - object_decode = bytes(object_raw[:-1], - "utf-8").decode("unicode_escape") + object_decode = bytes(object_raw[:-1], "utf-8").decode("unicode_escape") # LOGS.info(_format.paste_text(object_decode[:-15])) return json.loads(object_decode[:-15])[31][0][12][2] @@ -1415,12 +1397,13 @@ def _get_all_items(self, page, main_directory, dir_name, limit, arguments): time.sleep(int(arguments["delay"])) i += 1 if count < limit: - print("\n\nUnfortunately all " + - str(limit) + - " could not be downloaded because some images were not downloadable. " + - str(count - - 1) + - " is all we got for this search filter!") + print( + "\n\nUnfortunately all " + + str(limit) + + " could not be downloaded because some images were not downloadable. " + + str(count - 1) + + " is all we got for this search filter!" + ) return items, errorCount, abs_path # Bulk Download @@ -1446,8 +1429,7 @@ def download(self, arguments): for i in paths: paths_agg[i] = paths[i] if not arguments["silent_mode"] and arguments["print_paths"]: - print( - paths.encode("raw_unicode_escape").decode("utf-8")) + print(paths.encode("raw_unicode_escape").decode("utf-8")) total_errors += errors return paths_agg, total_errors # if the calling file contains params directly @@ -1473,12 +1455,10 @@ def download_executor(self, arguments): arguments[arg] = None # Initialization and Validation of user arguments if arguments["keywords"]: - search_keyword = [str(item) - for item in arguments["keywords"].split(",")] + search_keyword = [str(item) for item in arguments["keywords"].split(",")] if arguments["keywords_from_file"]: - search_keyword = self.keywords_from_file( - arguments["keywords_from_file"]) + search_keyword = self.keywords_from_file(arguments["keywords_from_file"]) # both time and time range should not be allowed in the same query if arguments["time"] and arguments["time_range"]: @@ -1540,7 +1520,8 @@ def download_executor(self, arguments): "Please refer to the documentation on guide to writing queries \n" "https://github.com/hardikvasa/google-images-download#examples" "\n\nexiting!\n" - "-------------------------------") + "-------------------------------" + ) sys.exit() # If this argument is present, set the custom output directory @@ -1557,8 +1538,7 @@ def download_executor(self, arguments): total_errors = 0 for pky in prefix_keywords: # 1.for every prefix keywords for sky in suffix_keywords: # 2.for every suffix keywords - for i in range( - len(search_keyword)): # 3.for every main keyword + for i in range(len(search_keyword)): # 3.for every main keyword iteration = ( "\n" + "Item no.: " @@ -1578,8 +1558,7 @@ def download_executor(self, arguments): + " ..." ) else: - print( - iteration.encode("raw_unicode_escape").decode("utf-8")) + print(iteration.encode("raw_unicode_escape").decode("utf-8")) print("Evaluating...") search_term = pky + search_keyword[i] + sky @@ -1640,8 +1619,7 @@ def download_executor(self, arguments): with open( "logs/" + search_keyword[i] + ".json", "w" ) as json_file: - json.dump( - items, json_file, indent=4, sort_keys=True) + json.dump(items, json_file, indent=4, sort_keys=True) # Related images if arguments["related_images"]: print( diff --git a/userbot/utils/pastebin.py b/userbot/utils/pastebin.py index 2243e09..0f9622d 100644 --- a/userbot/utils/pastebin.py +++ b/userbot/utils/pastebin.py @@ -9,11 +9,7 @@ class PasteBin: NEKOBIN_URL = "https://nekobin.com/" KATBIN_URL = "https://katb.in/" _dkey = _hkey = _nkey = _kkey = retry = None - service_match = { - "-d": "dogbin", - "-n": "nekobin", - "-h": "hastebin", - "-k": "katbin"} + service_match = {"-d": "dogbin", "-n": "nekobin", "-h": "hastebin", "-k": "katbin"} def __init__(self, data: str = None): self.http = aiohttp.ClientSession() diff --git a/userbot/utils/prettyjson.py b/userbot/utils/prettyjson.py index 911eec8..6cdf574 100644 --- a/userbot/utils/prettyjson.py +++ b/userbot/utils/prettyjson.py @@ -33,11 +33,7 @@ def getsubitems(obj, itemkey, islast, maxlinelength, indent): # render basic type keyseparator = "" if itemkey == "" else ": " itemseparator = "" if islast else "," - items.append( - itemkey + - keyseparator + - basictype2str(obj) + - itemseparator) + items.append(itemkey + keyseparator + basictype2str(obj) + itemseparator) else: # render lists/dicts/tuples diff --git a/userbot/utils/tools.py b/userbot/utils/tools.py index 474d5b0..f4026a0 100644 --- a/userbot/utils/tools.py +++ b/userbot/utils/tools.py @@ -145,8 +145,7 @@ async def take_screen_shot( duration, ) ttl = duration // 2 - thumb_image_path = path or os.path.join( - "./temp/", f"{basename(video_file)}.jpg") + thumb_image_path = path or os.path.join("./temp/", f"{basename(video_file)}.jpg") command = f"ffmpeg -ss {ttl} -i '{video_file}' -vframes 1 '{thumb_image_path}'" err = (await runcmd(command))[1] if err: