From 22b0e3ba355bba58be8b510221f0d32388af6fa0 Mon Sep 17 00:00:00 2001 From: "sourcery-ai[bot]" <58596630+sourcery-ai[bot]@users.noreply.github.com> Date: Fri, 16 Jun 2023 23:11:49 +0700 Subject: [PATCH] 'Refactored by Sourcery' (#62) Co-authored-by: Sourcery AI <> --- database/gban_db.py | 4 +-- database/karma_db.py | 4 +-- misskaty/helper/human_read.py | 11 +++--- misskaty/helper/kuso_utils.py | 28 ++++++++++----- misskaty/helper/mediainfo_paste.py | 10 ++---- misskaty/helper/subscene_helper.py | 14 ++++++-- misskaty/plugins/locks.py | 19 +++-------- misskaty/plugins/media_extractor.py | 52 +++++++++++++++------------- misskaty/plugins/ocr.py | 53 ++++++++++++++++------------- misskaty/plugins/web_scraper.py | 10 +++--- 10 files changed, 109 insertions(+), 96 deletions(-) diff --git a/database/gban_db.py b/database/gban_db.py index 9ef51e01..7c1b5abf 100644 --- a/database/gban_db.py +++ b/database/gban_db.py @@ -4,9 +4,7 @@ gbansdb = dbname.gban async def is_gbanned_user(user_id: int) -> bool: user = await gbansdb.find_one({"user_id": user_id}) - if not user: - return False - return True + return bool(user) async def add_gban_user(user_id: int): is_gbanned = await is_gbanned_user(user_id) diff --git a/database/karma_db.py b/database/karma_db.py index 2d6ff454..5b7b19a0 100644 --- a/database/karma_db.py +++ b/database/karma_db.py @@ -48,9 +48,7 @@ async def update_karma(chat_id: int, name: str, karma: dict): async def is_karma_on(chat_id: int) -> bool: chat = await karmadb.find_one({"chat_id_toggle": chat_id}) - if not chat: - return True - return False + return not chat async def karma_on(chat_id: int): diff --git a/misskaty/helper/human_read.py b/misskaty/helper/human_read.py index 0a7ddb44..79aad588 100644 --- a/misskaty/helper/human_read.py +++ b/misskaty/helper/human_read.py @@ -34,12 +34,11 @@ def get_readable_time(seconds: int) -> str: def get_readable_bitrate(bitrate_kbps): - if bitrate_kbps > 10000: - bitrate = str(round(bitrate_kbps / 1000, 2)) + " " + "Mb/s" - else: - bitrate = str(round(bitrate_kbps, 2)) + " " + "kb/s" - - return bitrate + return ( + f"{str(round(bitrate_kbps / 1000, 2))} Mb/s" + if bitrate_kbps > 10000 + else f"{str(round(bitrate_kbps, 2))} kb/s" + ) def get_readable_time2(seconds: int) -> str: diff --git a/misskaty/helper/kuso_utils.py b/misskaty/helper/kuso_utils.py index 0cf830d3..4223b900 100644 --- a/misskaty/helper/kuso_utils.py +++ b/misskaty/helper/kuso_utils.py @@ -38,12 +38,11 @@ async def kusonimeBypass(url: str, slug=None): e = traceback.format_exc() LOGGER.error(e) title, season, tipe, status_anime, ep, score, duration, rilis = "None", "None", "None", "None", 0, 0, 0, "None" - num = 1 genre = [] for _genre in soup.select("#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(2)"): gen = _genre.text.split(":").pop().strip().split(", ") genre = gen - for smokedl in soup.find("div", {"class": "dlbodz"}).find_all("div", {"class": "smokeddlrh"}): + for num, smokedl in enumerate(soup.find("div", {"class": "dlbodz"}).find_all("div", {"class": "smokeddlrh"}), start=1): mendata = {"name": title, "links": []} for smokeurl in smokedl.find_all("div", {"class": "smokeurlrh"}): quality = smokeurl.find("strong").text @@ -54,12 +53,25 @@ async def kusonimeBypass(url: str, slug=None): links.append({"client": client, "url": url}) mendata["links"].append({"quality": quality, "link_download": links}) data.append(mendata) - num += 1 - result.update({"error": False, "title": title, "thumb": thumb, "genre": genre, "genre_string": ", ".join(genre), "status_anime": status_anime, "season": season, "tipe": tipe, "ep": ep, "score": score, "duration": duration, "rilis": rilis, "data": data}) + result |= { + "error": False, + "title": title, + "thumb": thumb, + "genre": genre, + "genre_string": ", ".join(genre), + "status_anime": status_anime, + "season": season, + "tipe": tipe, + "ep": ep, + "score": score, + "duration": duration, + "rilis": rilis, + "data": data, + } except Exception: err = traceback.format_exc() LOGGER.error(err) - result.update({"error": True, "error_message": err}) + result |= {"error": True, "error_message": err} finally: await http.delete(_url) return result @@ -68,7 +80,8 @@ async def kusonimeBypass(url: str, slug=None): async def byPassPh(url: str, name: str): kusonime = await kusonimeBypass(url) results = {"error": True, "error_message": kusonime} - template = """ + if not kusonime["error"]: + template = """

Title : {{title}}

@@ -92,13 +105,12 @@ async def byPassPh(url: str, name: str):
{{/data}} """.strip() - if not kusonime["error"]: html = chevron.render(template, kusonime) telegraph = Telegraph() if not telegraph.get_access_token(): await telegraph.create_account(short_name=BOT_USERNAME) page = await telegraph.create_page(f"{kusonime.get('title')} By {escape(name)}", html_content=html) - results.update({"error": False, "url": "https://telegra.ph/{}".format(page["path"])}) + results |= {"error": False, "url": f'https://telegra.ph/{page["path"]}'} del results["error_message"] return results diff --git a/misskaty/helper/mediainfo_paste.py b/misskaty/helper/mediainfo_paste.py index 9613deb0..c565053b 100644 --- a/misskaty/helper/mediainfo_paste.py +++ b/misskaty/helper/mediainfo_paste.py @@ -161,7 +161,7 @@ def html_builder(title: str, text: str) -> str: infobox = "" subtitlebox = "" icon = "" - html_msg = "" + heading.format(content=title) + html_msg = f"{heading.format(content=title)}" for line in text.splitlines(): if ":" not in line and bool(line): @@ -194,14 +194,10 @@ def html_builder(title: str, text: str) -> str: html_msg += subtitlebox if "Text #" in line else infobox elif ":" in line: - if "Attachments" in line: - pass - elif "ErrorDetectionType" in line: - pass - else: + if "Attachments" not in line and "ErrorDetectionType" not in line: html_msg += f"
{line.strip()}
" - elif not bool(line): + else: html_msg += "
" html_msg += "
" diff --git a/misskaty/helper/subscene_helper.py b/misskaty/helper/subscene_helper.py index 1c058ba3..d438b2a2 100644 --- a/misskaty/helper/subscene_helper.py +++ b/misskaty/helper/subscene_helper.py @@ -34,9 +34,17 @@ async def down_page(url): releases = "" for i in range(2): r = release[i].text.strip() - releases = releases + f"\n{r}" + releases = f"{releases}\n{r}" except Exception: releases = "" - response = {"title": title, "imdb": imdb, "poster": poster, "author_name": author_name, "author_url": author_link, "download_url": download_url, "comments": comments, "releases": releases} - return response + return { + "title": title, + "imdb": imdb, + "poster": poster, + "author_name": author_name, + "author_url": author_link, + "download_url": download_url, + "comments": comments, + "releases": releases, + } diff --git a/misskaty/plugins/locks.py b/misskaty/plugins/locks.py index 377fb835..94720a7b 100644 --- a/misskaty/plugins/locks.py +++ b/misskaty/plugins/locks.py @@ -93,9 +93,9 @@ async def tg_lock(message, permissions: list, perm: str, lock: bool): if perm not in permissions: return await message.reply_text("Already locked.") permissions.remove(perm) + elif perm in permissions: + return await message.reply_text("Already Unlocked.") else: - if perm in permissions: - return await message.reply_text("Already Unlocked.") permissions.append(perm) permissions = {perm: True for perm in list(set(permissions))} @@ -126,12 +126,7 @@ async def locks_func(_, message): permissions = await current_chat_permissions(chat_id) if parameter in data: - await tg_lock( - message, - permissions, - data[parameter], - bool(state == "lock"), - ) + await tg_lock(message, permissions, data[parameter], state == "lock") elif parameter == "all" and state == "lock": await app.set_chat_permissions(chat_id, ChatPermissions()) await message.reply_text(f"Locked Everything in {message.chat.title}") @@ -161,10 +156,7 @@ async def locktypes(_, message): if not permissions: return await message.reply_text("No Permissions.") - perms = "" - for i in permissions: - perms += f"__**{i}**__\n" - + perms = "".join(f"__**{i}**__\n" for i in permissions) await message.reply_text(perms) @@ -180,8 +172,7 @@ async def url_detector(_, message): if user.id in mods or user.id in SUDO: return - check = get_urls_from_text(text) - if check: + if check := get_urls_from_text(text): permissions = await current_chat_permissions(chat_id) if "can_add_web_page_previews" not in permissions: try: diff --git a/misskaty/plugins/media_extractor.py b/misskaty/plugins/media_extractor.py index 00037e98..edf45450 100644 --- a/misskaty/plugins/media_extractor.py +++ b/misskaty/plugins/media_extractor.py @@ -120,31 +120,35 @@ async def ceksub(self: Client, ctx: Message, strings): @use_chat_lang() async def convertsrt(self: Client, ctx: Message, strings): reply = ctx.reply_to_message - if reply and reply.document and (reply.document.file_name and reply.document.file_name.endswith((".vtt", ".ass", ".srt"))): - msg = await ctx.reply_msg(strings("convert_str"), quote=True) - if not os.path.exists("downloads"): - os.makedirs("downloads") - dl = await reply.download(file_name="downloads/") - filename = dl.split("/", 3)[3] - LOGGER.info(f"ConvertSub: {filename} by {ctx.from_user.first_name if ctx.from_user else ctx.sender_chat.title} [{ctx.from_user.id if ctx.from_user else ctx.sender_chat.id}]") - suffix = "srt" if ctx.command[0] == "converttosrt" else "ass" - (await shell_exec(f"{FF_MPEG_NAME} -i '{dl}' 'downloads/{filename}.{suffix}'"))[0] - c_time = time() - await ctx.reply_document( - f"downloads/{filename}.{suffix}", - caption=strings("capt_conv_sub").format(nf=filename, bot=self.me.username), - thumb="assets/thumb.jpg", - progress=progress_for_pyrogram, - progress_args=(strings("up_str"), msg, c_time, self.me.dc_id), - ) - await msg.delete_msg() - try: - os.remove(dl) - os.remove(f"downloads/{filename}.{suffix}") - except: - pass - else: + if ( + not reply + or not reply.document + or not reply.document.file_name + or not reply.document.file_name.endswith((".vtt", ".ass", ".srt")) + ): return await ctx.reply_msg(strings("conv_sub_help").format(cmd=ctx.command[0]), del_in=6) + msg = await ctx.reply_msg(strings("convert_str"), quote=True) + if not os.path.exists("downloads"): + os.makedirs("downloads") + dl = await reply.download(file_name="downloads/") + filename = dl.split("/", 3)[3] + LOGGER.info(f"ConvertSub: {filename} by {ctx.from_user.first_name if ctx.from_user else ctx.sender_chat.title} [{ctx.from_user.id if ctx.from_user else ctx.sender_chat.id}]") + suffix = "srt" if ctx.command[0] == "converttosrt" else "ass" + (await shell_exec(f"{FF_MPEG_NAME} -i '{dl}' 'downloads/{filename}.{suffix}'"))[0] + c_time = time() + await ctx.reply_document( + f"downloads/{filename}.{suffix}", + caption=strings("capt_conv_sub").format(nf=filename, bot=self.me.username), + thumb="assets/thumb.jpg", + progress=progress_for_pyrogram, + progress_args=(strings("up_str"), msg, c_time, self.me.dc_id), + ) + await msg.delete_msg() + try: + os.remove(dl) + os.remove(f"downloads/{filename}.{suffix}") + except: + pass @app.on_callback_query(filters.regex(r"^streamextract#")) diff --git a/misskaty/plugins/ocr.py b/misskaty/plugins/ocr.py index 6397b5d0..f3e7fefd 100644 --- a/misskaty/plugins/ocr.py +++ b/misskaty/plugins/ocr.py @@ -30,26 +30,33 @@ __HELP__ = "/ocr [reply to photo] - Read Text From Image" @use_chat_lang() async def ocr(self: Client, ctx: Message, strings): reply = ctx.reply_to_message - if reply and (reply.sticker or reply.photo or reply.document and reply.document.mime_type.startswith("image")): - msg = await ctx.reply_msg(strings("read_ocr"), quote=True) - try: - file_path = await reply.download() - if reply.sticker: - file_path = await reply.download(f"ocr_{ctx.from_user.id if ctx.from_user else ctx.sender_chat.id}.jpg") - response = await Telegraph().upload_file(file_path) - url = f"https://telegra.ph{response[0]['src']}" - req = ( - await http.get( - f"https://script.google.com/macros/s/AKfycbwURISN0wjazeJTMHTPAtxkrZTWTpsWIef5kxqVGoXqnrzdLdIQIfLO7jsR5OQ5GO16/exec?url={url}", - follow_redirects=True, - ) - ).json() - await msg.edit_msg(strings("result_ocr").format(result=req["text"])) - if os.path.exists(file_path): - os.remove(file_path) - except Exception as e: - await msg.edit_msg(str(e)) - if os.path.exists(file_path): - os.remove(file_path) - else: - return await ctx.reply_msg(strings("no_photo").format(cmd=ctx.command[0]), quote=True) \ No newline at end of file + if ( + not reply + or not reply.sticker + and not reply.photo + and ( + not reply.document + or not reply.document.mime_type.startswith("image") + ) + ): + return await ctx.reply_msg(strings("no_photo").format(cmd=ctx.command[0]), quote=True) + msg = await ctx.reply_msg(strings("read_ocr"), quote=True) + try: + file_path = await reply.download() + if reply.sticker: + file_path = await reply.download(f"ocr_{ctx.from_user.id if ctx.from_user else ctx.sender_chat.id}.jpg") + response = await Telegraph().upload_file(file_path) + url = f"https://telegra.ph{response[0]['src']}" + req = ( + await http.get( + f"https://script.google.com/macros/s/AKfycbwURISN0wjazeJTMHTPAtxkrZTWTpsWIef5kxqVGoXqnrzdLdIQIfLO7jsR5OQ5GO16/exec?url={url}", + follow_redirects=True, + ) + ).json() + await msg.edit_msg(strings("result_ocr").format(result=req["text"])) + if os.path.exists(file_path): + os.remove(file_path) + except Exception as e: + await msg.edit_msg(str(e)) + if os.path.exists(file_path): + os.remove(file_path) \ No newline at end of file diff --git a/misskaty/plugins/web_scraper.py b/misskaty/plugins/web_scraper.py index 08403412..2d1aae52 100644 --- a/misskaty/plugins/web_scraper.py +++ b/misskaty/plugins/web_scraper.py @@ -411,11 +411,11 @@ async def getSame(msg, query, current_page, strings): try: index = int(current_page - 1) PageLen = len(SCRAP_DICT[msg.id][0]) - sameresult = "" - for c, i in enumerate(SCRAP_DICT[msg.id][0][index], start=1): - sameresult += f"{index*6+c}. {i['title']}\nStatus: {i['sta']}\nRating: {i['rate']}\n\n" - IGNORE_CHAR = "[]" - sameresult = "".join(i for i in sameresult if not i in IGNORE_CHAR) + sameresult = "".join( + f"{index * 6 + c}. {i['title']}\nStatus: {i['sta']}\nRating: {i['rate']}\n\n" + for c, i in enumerate(SCRAP_DICT[msg.id][0][index], start=1) + ) + sameresult = "".join(i for i in sameresult if i not in "[]") return sameresult, PageLen except (IndexError, KeyError): await msg.edit_msg(strings("no_result"), del_in=5)