diff --git a/bin/cmrudl.py b/bin/cmrudl.py index dd5acea..5d1996a 100644 --- a/bin/cmrudl.py +++ b/bin/cmrudl.py @@ -227,9 +227,7 @@ def handle_data(self, data): self.jsobj = m.group(1) def result(self): - if not self.jsobj: - return None - return self.jsobj + return None if not self.jsobj else self.jsobj parser = TheHTMLParser() parser.feed(html) @@ -336,8 +334,7 @@ def create_file_name_temp(self, storage): return ".%s.%s" % (__prog__, urllib_quote(storage["hash"])) def create_file_name(self, storage): - opt_file = self.options.file - if opt_file: + if opt_file := self.options.file: return opt_file return storage["name"] if storage else None diff --git a/sample_config.py b/sample_config.py index 0cda945..2d240b5 100644 --- a/sample_config.py +++ b/sample_config.py @@ -64,7 +64,7 @@ class Config(object): "THUMB_IMAGE", "https://telegra.ph/file/6086da8c041f5de3227ed.jpg" ) # Specify NO_LOAD with plugin names for not loading in userbot - NO_LOAD = [x for x in os.environ.get("NO_LOAD", "").split()] + NO_LOAD = list(os.environ.get("NO_LOAD", "").split()) # Specify command handler that should be used for the plugins # This should be a valid "regex" pattern CMDSET = os.environ.get("CMDSET", r".") diff --git a/userbot/__init__.py b/userbot/__init__.py index 9b8aab4..e4a199e 100644 --- a/userbot/__init__.py +++ b/userbot/__init__.py @@ -18,7 +18,7 @@ __version__ = "1.0" __license__ = "GNU Affero General Public License v3.0" __author__ = "DogeUserBot < https://github.com/DOG-E/DogeUserBot >" -__copyright__ = "©️ Copyright 2021, " + __author__ +__copyright__ = f"©️ Copyright 2021, {__author__}" doge.version = __version__ if gvar("BOT_TOKEN"): @@ -59,7 +59,7 @@ else: Config.PM_LOGGER_GROUP_ID = int(gvar("PM_LOGGER_GROUP_ID")) elif str(Config.PM_LOGGER_GROUP_ID)[0] != "-": - Config.PM_LOGGER_GROUP_ID = int("-" + str(Config.PM_LOGGER_GROUP_ID)) + Config.PM_LOGGER_GROUP_ID = int(f"-{str(Config.PM_LOGGER_GROUP_ID)}") try: diff --git a/userbot/__main__.py b/userbot/__main__.py index 604b110..ab4807e 100644 --- a/userbot/__main__.py +++ b/userbot/__main__.py @@ -30,9 +30,9 @@ try: - LOGS.info(f"⏳ STARTING DOGE USERBOT 🐾") + LOGS.info("⏳ STARTING DOGE USERBOT 🐾") doge.loop.run_until_complete(setup_bot()) - LOGS.info(f"✅ STARTUP COMPLETED 🐾") + LOGS.info("✅ STARTUP COMPLETED 🐾") except Exception as e: LOGS.error(f"🚨 {e}") exit() @@ -71,7 +71,7 @@ async def startup_process(): await load_plugins("plugins") await load_plugins("assistant") LOGS.info(userbot.__copyright__) - LOGS.info("🔐 Licensed under the terms of the " + userbot.__license__) + LOGS.info(f"🔐 Licensed under the terms of the {userbot.__license__}") LOGS.info( f"\ \n➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\ diff --git a/userbot/assistant/bot_pms.py b/userbot/assistant/bot_pms.py index 811afbd..8c3b28c 100644 --- a/userbot/assistant/bot_pms.py +++ b/userbot/assistant/bot_pms.py @@ -95,12 +95,12 @@ async def bot_start(event): mention = f"[{chat.first_name}](tg://user?id={chat.id})" my_mention = f"[{user.first_name}](tg://user?id={user.id})" first = chat.first_name - last = chat.last_name if chat.last_name else "" + last = chat.last_name or "" fullname = f"{first} {last}" if last else first username = f"@{chat.username}" if chat.username else mention userid = chat.id my_first = user.first_name - my_last = user.last_name if user.last_name else "" + my_last = user.last_name or "" my_fullname = f"{my_first} {my_last}" if my_last else my_first my_username = f"@{user.username}" if user.username else my_mention if chat.id != OWNER_ID: @@ -129,21 +129,20 @@ async def bot_start(event): ) ) buttons = [ - (Button.url(f"📣 Kᴀɴᴀʟ ", "https://t.me/DogeUserBot"),), + (Button.url("📣 Kᴀɴᴀʟ ", "https://t.me/DogeUserBot"),), ( - Button.url(f"💬 Sᴜᴘᴘᴏʀᴛ ", "https://t.me/DogeSup"), - Button.url(f"🧩 Pʟᴜɢɪɴ ", "https://t.me/DogePlugin"), + Button.url("💬 Sᴜᴘᴘᴏʀᴛ ", "https://t.me/DogeSup"), + Button.url("🧩 Pʟᴜɢɪɴ ", "https://t.me/DogePlugin"), ), ] + else: start_msg = "**🐶 Wow!\ \n🐾 Merhaba {}!\n\ \n💬 Sana nasıl yardımcı olabilirim?**".format( my_mention ) - buttons = [ - (Button.inline(f"🐕‍🦺 ʏᴀʀᴅɪᴍ", data="mainmenu"),), - ] + buttons = [(Button.inline("🐕\u200d🦺 ʏᴀʀᴅɪᴍ", data="mainmenu"),)] try: await event.client.send_message( chat.id, @@ -239,12 +238,10 @@ async def bot_pms_edit(event): # sourcery no-metrics users = get_user_reply(event.id) if users is None: return - reply_msg = None - for user in users: - if user.chat_id == str(chat.id): - reply_msg = user.message_id - break - if reply_msg: + if reply_msg := next( + (user.message_id for user in users if user.chat_id == str(chat.id)), + None, + ): await event.client.send_message( OWNER_ID, "**⬆️ Bu mesaj şu kullanıcı tarafından düzenlendi.** {} :\n".format( @@ -303,11 +300,11 @@ async def handler(event): except Exception as e: LOGS.error(str(e)) if users_1 is not None: - reply_msg = None - for user in users_1: - if user.chat_id != OWNER_ID: - reply_msg = user.message_id - break + reply_msg = next( + (user.message_id for user in users_1 if user.chat_id != OWNER_ID), + None, + ) + try: if reply_msg: users = get_user_id(reply_msg) @@ -343,16 +340,18 @@ async def bot_start(event): users = get_user_id(reply_to) if users is None: return await info_msg.edit( - f"**🚨 Hᴀᴛᴀ:**\n🙁 'Üzgünüm! Bu kullanıcıyı veritabanımda bulamadım.`" + "**🚨 Hᴀᴛᴀ:**\\n🙁 'Üzgünüm! Bu kullanıcıyı veritabanımda bulamadım.`" ) + for usr in users: user_id = int(usr.chat_id) user_name = usr.first_name break if user_id is None: return await info_msg.edit( - f"**🚨 Hᴀᴛᴀ:**\n🙁 'Üzgünüm! Bu kullanıcıyı veritabanımda bulamadım.`" + "**🚨 Hᴀᴛᴀ:**\\n🙁 'Üzgünüm! Bu kullanıcıyı veritabanımda bulamadım.`" ) + uinfo = f"**👤 Bu mesaj şu kişi tarafından gönderildi:** {_format.mentionuser(user_name, user_id)}\ \n**ℹ️ Kullanıcı İsmi:** {user_name}\ \n**🆔 Kullanıcı ID'si:** `{user_id}`" @@ -363,13 +362,11 @@ async def send_flood_alert(user_) -> None: # sourcery no-metrics buttons = [ ( - Button.inline(f"🚫 Bᴀɴ", data=f"bot_pm_ban_{user_.id}"), - Button.inline( - f"➖ Boᴛ AɴᴛɪFʟooᴅ'ᴜ Kᴀᴘᴀᴛ", - data="toggle_bot-antiflood_off", - ), + Button.inline("🚫 Bᴀɴ", data=f"bot_pm_ban_{user_.id}"), + Button.inline("➖ Boᴛ AɴᴛɪFʟooᴅ'ᴜ Kᴀᴘᴀᴛ", data="toggle_bot-antiflood_off"), ) ] + found = False if FloodConfig.ALERT and (user_.id in FloodConfig.ALERT.keys()): found = True diff --git a/userbot/assistant/botcontrols.py b/userbot/assistant/botcontrols.py index e166d44..610899d 100644 --- a/userbot/assistant/botcontrols.py +++ b/userbot/assistant/botcontrols.py @@ -111,14 +111,16 @@ async def bot_broadcast(event): if count % 5 == 0: try: prog_ = ( - f"**🔊 Yayın Yapılıyor...**\n\n" - + progress_str( - total=bot_users_count, - current=count + len(blocked_users), + ( + "**🔊 Yayın Yapılıyor...**\\n\\n" + + progress_str( + total=bot_users_count, + current=count + len(blocked_users), + ) ) + f"\n\n• **✅ Başarılı:** `{count}`\n" - + f"• **❌ Hatalı** `{len(blocked_users)}`" - ) + ) + f"• **❌ Hatalı** `{len(blocked_users)}`" + await br_cast.edit(prog_) except FloodWaitError as e: await sleep(e.seconds) @@ -126,7 +128,7 @@ async def bot_broadcast(event): b_info = "🔊 ➡️ {} tane kullanıcı için mesajı başarıyla yayınladı.".format( count ) - if len(blocked_users) != 0: + if blocked_users: b_info += f"\n🚫 {len(blocked_users)} tane kullanıcı {BOT_USERNAME} botunu engellemiş ya da botla olan mesajları silmiş. Bu yüzden bot kullanıcıları listesinden silindi." b_info += "⏱ Tamamlanma Süresi: {}.".format( time_formatter((end_ - start_).seconds) @@ -187,8 +189,7 @@ async def ban_botpms(event): if user_id == OWNER_ID: return await event.reply("**🚨 Seni yasaklayamam.**") - check = check_is_black_list(user.id) - if check: + if check := check_is_black_list(user.id): return await event.client.send_message( event.chat_id, f"🛑 #ZATEN_BANLI\ diff --git a/userbot/assistant/botmanagers.py b/userbot/assistant/botmanagers.py index 8916e8d..c3ee6b0 100644 --- a/userbot/assistant/botmanagers.py +++ b/userbot/assistant/botmanagers.py @@ -50,9 +50,9 @@ def progress_str(total: int, current: int) -> str: return prog_arg.format( "Progress", percentage, - "".join((Config.FINISHED_PROGRESS_STR for i in range(floor(percentage / 5)))), + "".join(Config.FINISHED_PROGRESS_STR for _ in range(floor(percentage / 5))), "".join( - (Config.UNFINISHED_PROGRESS_STR for i in range(20 - floor(percentage / 5))) + Config.UNFINISHED_PROGRESS_STR for _ in range(20 - floor(percentage / 5)) ), ) @@ -81,8 +81,8 @@ async def unban_user_from_bot(user, reason, reply_to=None): rem_user_from_bl(user.id) except Exception as e: LOGS.error(str(e)) - banned_msg = f"**👀 Bu bottan yasaklanmıştınız.\ - /nℹ️ Şimdi sahibime mesaj göndermeye devam edebeilirsin!**" + banned_msg = "**👀 Bu bottan yasaklanmıştınız.\\\x1f /nℹ️ Şimdi sahibime mesaj göndermeye devam edebeilirsin!**" + if reason is not None: banned_msg += f"\n**⛓ Sebep:** `{reason}`" await doge.tgbot.send_message(user.id, banned_msg) diff --git a/userbot/assistant/buttonmaker.py b/userbot/assistant/buttonmaker.py index b37c757..05247b2 100644 --- a/userbot/assistant/buttonmaker.py +++ b/userbot/assistant/buttonmaker.py @@ -102,7 +102,7 @@ async def button(event): if not markdown_note: return await edl(event, "`🔲 Butonda hangi metni kullanmalıyım?`") - doginput = "Inline buttons " + markdown_note + doginput = f"Inline buttons {markdown_note}" results = await event.client.inline_query(BOT_USERNAME, doginput) await results[0].click(event.chat_id, reply_to=reply_to_id, hide_via=True) await event.delete() diff --git a/userbot/assistant/hide.py b/userbot/assistant/hide.py index 02f12d2..b0d3ac4 100644 --- a/userbot/assistant/hide.py +++ b/userbot/assistant/hide.py @@ -23,7 +23,7 @@ async def on_plug_in_callback_query_handler(event): try: reply_pop_up_alert = jsondata[f"{timestamp}"]["text"] except KeyError: - reply_pop_up_alert = f"🚨 Bu mesaj artık Doge sunucusunda yok." + reply_pop_up_alert = "🚨 Bu mesaj artık Doge sunucusunda yok." else: - reply_pop_up_alert = f"🚨 Bu mesaj artık Doge sunucusunda yok." + reply_pop_up_alert = "🚨 Bu mesaj artık Doge sunucusunda yok." await event.answer(reply_pop_up_alert, cache_time=0, alert=True) diff --git a/userbot/assistant/iyoutube.py b/userbot/assistant/iyoutube.py index fc50a0d..e7d1d59 100644 --- a/userbot/assistant/iyoutube.py +++ b/userbot/assistant/iyoutube.py @@ -75,7 +75,7 @@ async def yt_inline(event): input_url = (reply.text).strip() if not input_url: return await edl( - event, f"**📺 Geçerli bir YouTube URL'sine girin veya cevap verin!**" + event, "**📺 Geçerli bir YouTube URL'sine girin veya cevap verin!**" ) dogevent = await eor( @@ -97,7 +97,7 @@ async def yt_inline(event): await dogevent.delete() await results[0].click(event.chat_id, reply_to=reply_to_id, hide_via=True) else: - await dogevent.edit(f"**🚨 Üzgünüm! Hiçbir sonuç bulamadım.**") + await dogevent.edit("**🚨 Üzgünüm! Hiçbir sonuç bulamadım.**") @doge.tgbot.on( @@ -270,7 +270,7 @@ async def ytdl_callback(c_q: CallbackQuery): parse_mode="html", ) elif choosen_btn == "listall": - await c_q.answer(f"➡️ Görünüm olarak şu değiştirildi: 📜 Liste", alert=False) + await c_q.answer("➡️ Görünüm olarak şu değiştirildi: 📜 Liste", alert=False) list_res = "".join( search_data.get(vid_s).get("list_view") for vid_s in search_data ) @@ -284,23 +284,14 @@ async def ytdl_callback(c_q: CallbackQuery): await c_q.edit( file=await get_ytthumb(search_data.get("1").get("video_id")), buttons=[ - ( - Button.url( - f"↗️ Açᴍᴀᴋ Içɪɴ Tıᴋʟᴀʏıɴ", - url=telegraph, - ) - ), - ( - Button.inline( - f"📊 Dᴇᴛᴀʏʟᴀʀı Göʀ", - data=f"ytdl_detail_{data_key}_{page}", - ) - ), + Button.url("↗️ Açᴍᴀᴋ Içɪɴ Tıᴋʟᴀʏıɴ", url=telegraph), + Button.inline("📊 Dᴇᴛᴀʏʟᴀʀı Göʀ", data=f"ytdl_detail_{data_key}_{page}"), ], ) + else: # Detailed index = 1 - await c_q.answer(f"➡️ Görünüm şu olarak değiştirildi: 📊 Detaylı", alert=False) + await c_q.answer("➡️ Görünüm şu olarak değiştirildi: 📊 Detaylı", alert=False) first = search_data.get(str(index)) await c_q.edit( text=first.get("message"), diff --git a/userbot/assistant/secret.py b/userbot/assistant/secret.py index 86c99ea..cc5089b 100644 --- a/userbot/assistant/secret.py +++ b/userbot/assistant/secret.py @@ -33,7 +33,7 @@ async def on_plug_in_callback_query_handler(event): \n👀 Bu senin için değil!\ \n🤡 Git ve kendi işini yap." except KeyError: - reply_pop_up_alert = f"🚨 Bu mesaj artık Doge sunucusunda yok." + reply_pop_up_alert = "🚨 Bu mesaj artık Doge sunucusunda yok." else: - reply_pop_up_alert = f"🚨 Bu mesaj artık Doge sunucusunda yok." + reply_pop_up_alert = "🚨 Bu mesaj artık Doge sunucusunda yok." await event.answer(reply_pop_up_alert, cache_time=0, alert=True) diff --git a/userbot/assistant/sendbot.py b/userbot/assistant/sendbot.py index 15ff015..d783354 100644 --- a/userbot/assistant/sendbot.py +++ b/userbot/assistant/sendbot.py @@ -27,19 +27,18 @@ async def botmsg(event): reply_message = await event.get_reply_message() reply_to_id = await reply_id(event) if not text: - if reply_message.media: - media = await reply_message.download_media() - if reply_message.text: - await doge.tgbot.send_file(chat, media, caption=reply_message.text) - else: - await doge.tgbot.send_file(chat, media) - return await event.delete() - - else: + if not reply_message.media: return await edl( event, "__Bot üzerinden ne göndermeliyim? Bana bir metin verin ya da mesajı yanıtlayın.__", ) + media = await reply_message.download_media() + if reply_message.text: + await doge.tgbot.send_file(chat, media, caption=reply_message.text) + else: + await doge.tgbot.send_file(chat, media) + return await event.delete() + await doge.tgbot.send_message(chat, text, reply_to=reply_to_id) await event.delete() diff --git a/userbot/assistant/troll.py b/userbot/assistant/troll.py index bc7b6e7..177bc99 100644 --- a/userbot/assistant/troll.py +++ b/userbot/assistant/troll.py @@ -33,7 +33,7 @@ async def on_plug_in_callback_query_handler(event): encrypted_tcxt = message["text"] reply_pop_up_alert = encrypted_tcxt except KeyError: - reply_pop_up_alert = f"🚨 Bu mesaj artık Doge sunucusunda yok." + reply_pop_up_alert = "🚨 Bu mesaj artık Doge sunucusunda yok." else: - reply_pop_up_alert = f"🚨 Bu mesaj artık Doge sunucusunda yok." + reply_pop_up_alert = "🚨 Bu mesaj artık Doge sunucusunda yok." await event.answer(reply_pop_up_alert, cache_time=0, alert=True) diff --git a/userbot/core/client.py b/userbot/core/client.py index 84cb2b1..7fc0b96 100644 --- a/userbot/core/client.py +++ b/userbot/core/client.py @@ -209,11 +209,10 @@ async def wrapper(check): markdown=False, title="🐶 Doɢᴇ UsᴇʀBoᴛ Hᴀᴛᴀ Rᴀᴘᴏʀᴜ 🐾", ) - text = "**🐶 Doɢᴇ UsᴇʀBoᴛ Hᴀᴛᴀ Rᴀᴘᴏʀᴜ 🐾**" - text += "\n\n" + text = "**🐶 Doɢᴇ UsᴇʀBoᴛ Hᴀᴛᴀ Rᴀᴘᴏʀᴜ 🐾**" + "\n\n" text += f"**🚨 Hata Raporu:** [{new['error']}]({pastelink})" text += "\n\n" - link = f"[BURAYA](https://t.me/DogeSup)" + link = "[BURAYA](https://t.me/DogeSup)" text += "__💬 Eğer isterseniz buraya bildirebilirisiniz.__" text += "\n\n" text += "🐾 Bu mesajı {} ilet.".format(link) @@ -349,11 +348,10 @@ async def wrapper(check): markdown=False, title="🐶 Doɢᴇ Asɪsᴛᴀɴ Hᴀᴛᴀ Rᴀᴘᴏʀᴜ 🐾", ) - text = "**🐶 Doɢᴇ Asɪsᴛᴀɴ Hᴀᴛᴀ Rᴀᴘᴏʀᴜ 🐾**" - text += "\n\n" + text = "**🐶 Doɢᴇ Asɪsᴛᴀɴ Hᴀᴛᴀ Rᴀᴘᴏʀᴜ 🐾**" + "\n\n" text += f"**🚨 Hata Raporu:** [{new['error']}]({pastelink})" text += "\n\n" - link = f"[BURAYA](https://t.me/DogeSup)" + link = "[BURAYA](https://t.me/DogeSup)" text += "__💬 Eğer isterseniz buraya bildirebilirisiniz.__" text += "\n\n" text += "🐾 Bu mesajı {} ilet.".format(link) diff --git a/userbot/core/cmdinfo.py b/userbot/core/cmdinfo.py index c73c728..d87d74a 100644 --- a/userbot/core/cmdinfo.py +++ b/userbot/core/cmdinfo.py @@ -45,7 +45,7 @@ def _format_about( del about["d"] if "f" in about: - tmp_chelp += f"\n\n**🐾 Aʏᴀʀ:**" + tmp_chelp += "\\n\\n**🐾 Aʏᴀʀ:**" if isinstance(about["f"], dict): for f_n, f_d in about["f"].items(): tmp_chelp += f"\n ▫️ `{f_n}`: __{f_d.lower()}__" @@ -54,7 +54,7 @@ def _format_about( del about["f"] if "o" in about: - tmp_chelp += f"\n\n**🐾 Sᴇçᴇɴᴇᴋʟᴇʀ:**" + tmp_chelp += "\\n\\n**🐾 Sᴇçᴇɴᴇᴋʟᴇʀ:**" if isinstance(about["o"], dict): for o_n, o_d in about["o"].items(): tmp_chelp += f"\n ▫️ `{o_n}`: __{o_d.lower()}__" @@ -63,7 +63,7 @@ def _format_about( del about["o"] if "t" in about: - tmp_chelp += f"\n\n**🐾 Dᴇsᴛᴇᴋʟᴇɴᴇɴ Tüʀʟᴇʀ:**" + tmp_chelp += "\\n\\n**🐾 Dᴇsᴛᴇᴋʟᴇɴᴇɴ Tüʀʟᴇʀ:**" if isinstance(about["t"], list): for _opt in about["t"]: tmp_chelp += f"\n `{_opt}` ," @@ -72,7 +72,7 @@ def _format_about( del about["t"] if "u" in about: - tmp_chelp += f"\n\n**🐾 Kᴜʟʟᴀɴıᴍ:**" + tmp_chelp += "\\n\\n**🐾 Kᴜʟʟᴀɴıᴍ:**" if isinstance(about["u"], list): for ex_ in about["u"]: tmp_chelp += f"\n `{ex_}`" @@ -81,7 +81,7 @@ def _format_about( del about["u"] if "e" in about: - tmp_chelp += f"\n\n**🐾 Öʀɴᴇᴋ:**" + tmp_chelp += "\\n\\n**🐾 Öʀɴᴇᴋ:**" if isinstance(about["e"], list): for ex_ in about["e"]: tmp_chelp += f"\n `{ex_}`" diff --git a/userbot/core/events.py b/userbot/core/events.py index 8863b8a..54b299b 100644 --- a/userbot/core/events.py +++ b/userbot/core/events.py @@ -71,7 +71,7 @@ def filter(self, event): is_admin = event.chat.admin_rights if not is_creator and not is_admin: - text = f"**🚨 Bu komutu kullanabilmek için yönetici olmalıyım!**" + text = "**🚨 Bu komutu kullanabilmek için yönetici olmalıyım!**" event._client.loop.create_task(eor(event, text)) return @@ -379,16 +379,16 @@ async def edit_message( ): chatid = entity if isinstance(chatid, InputPeerChannel): - chat_id = int("-100" + str(chatid.channel_id)) + chat_id = int(f"-100{str(chatid.channel_id)}") elif isinstance(chatid, InputPeerChat): - chat_id = int("-" + str(chatid.chat_id)) + chat_id = int(f"-{str(chatid.chat_id)}") elif isinstance(chatid, InputPeerUser): chat_id = int(chatid.user_id) else: chat_id = chatid if str(chat_id) == str(Config.BOTLOG_CHATID): return await client.editmessage( - entity=entity, + entity=chatid, message=message, text=text, parse_mode=parse_mode, @@ -399,6 +399,7 @@ async def edit_message( buttons=buttons, schedule=schedule, ) + main_msg = text safecheck = await safe_check_text(main_msg) if safecheck: diff --git a/userbot/core/helpers.py b/userbot/core/helpers.py index 6e43155..e1aa38f 100644 --- a/userbot/core/helpers.py +++ b/userbot/core/helpers.py @@ -39,7 +39,7 @@ async def get_chat_link( extra = f"[{name}](tg://user?id={entity.id})" else: if hasattr(entity, "username") and entity.username is not None: - username = "@" + entity.username + username = f"@{entity.username}" else: username = entity.id if reply is not None: diff --git a/userbot/core/inlinebot.py b/userbot/core/inlinebot.py index 2835dfc..cf05949 100644 --- a/userbot/core/inlinebot.py +++ b/userbot/core/inlinebot.py @@ -50,12 +50,7 @@ def main_menu(): \n🐾 Yᴀʀᴅıᴍᴄı\n\ \n◽ Doɢᴇ oғ {mention}**" buttons = [ - ( - Button.inline( - f"ℹ️️ Bɪʟɢɪ", - data="check", - ), - ), + (Button.inline("ℹ️️ Bɪʟɢɪ", data="check"),), ( Button.inline( f"👮‍♂️ Aᴅᴍɪɴ ({len(GRP_INFO['admin'])})", @@ -86,12 +81,7 @@ def main_menu(): data="hub_menu", ), ), - ( - Button.inline( - f"⛔ KAPAT ⛔", - data="close", - ), - ), + (Button.inline("⛔ KAPAT ⛔", data="close"),), ] return text, buttons @@ -115,7 +105,7 @@ def ibuild_keyboard(buttons): def get_back_button(name): - return [Button.inline(f"⬅️️ Gᴇʀɪ", data=f"{name}")] + return [Button.inline("⬅️️ Gᴇʀɪ", data=f"{name}")] def command_in_category(cname): @@ -216,29 +206,21 @@ def paginate_help( "⏪", data=f"{prefix}_prev({modulo_page})_plugin", ), - Button.inline( - f"🐾 Mᴇɴᴜ", - data="mainmenu", - ), + Button.inline("🐾 Mᴇɴᴜ", data="mainmenu"), Button.inline( "⏩", data=f"{prefix}_next({modulo_page})_plugin", ), ), - ( - Button.inline( - f"⛔ Kᴀᴘᴀᴛ", - data="close", - ), - ), + (Button.inline("⛔ Kᴀᴘᴀᴛ", data="close"),), ] else: pairs = pairs + [ ( - Button.inline(f"🐾 Mᴇɴᴜ", data="mainmenu"), - Button.inline(f"⛔ Kᴀᴘᴀᴛ", data="close"), - ), + Button.inline("🐾 Mᴇɴᴜ", data="mainmenu"), + Button.inline("⛔ Kᴀᴘᴀᴛ", data="close"), + ) ] elif len(pairs) > number_of_rows: @@ -259,14 +241,11 @@ def paginate_help( ), ( Button.inline( - f"⬅️️ Gᴇʀɪ", + "⬅️️ Gᴇʀɪ", data=f"back_plugin_{category_plugins}_{category_pgno}", ), - Button.inline( - f"🐾 Mᴇɴᴜ", - data="mainmenu", - ), - Button.inline(f"⛔ Kᴀᴘᴀᴛ", data="close"), + Button.inline("🐾 Mᴇɴᴜ", data="mainmenu"), + Button.inline("⛔ Kᴀᴘᴀᴛ", data="close"), ), ] @@ -276,16 +255,14 @@ def paginate_help( pairs = pairs + [ ( Button.inline( - f"⬅️️ Gᴇʀɪ", + "⬅️️ Gᴇʀɪ", data=f"back_plugin_{category_plugins}_{category_pgno}", ), - Button.inline( - f"🐾 Mᴇɴᴜ", - data="mainmenu", - ), - Button.inline(f"⛔ Kᴀᴘᴀᴛ", data="close"), - ), + Button.inline("🐾 Mᴇɴᴜ", data="mainmenu"), + Button.inline("⛔ Kᴀᴘᴀᴛ", data="close"), + ) ] + return pairs diff --git a/userbot/core/managers.py b/userbot/core/managers.py index de4068e..479f0fa 100644 --- a/userbot/core/managers.py +++ b/userbot/core/managers.py @@ -57,7 +57,7 @@ async def eor( if aslink or deflink: linktext = linktext or "👀 Mesaj fazla uzun olduğu için yapıştırıldı!" response = await paste_message(text, pastetype="t") - text = linktext + f" [HERE]({response})" + text = f"{linktext} [HERE]({response})" if event.sender_id in sudo_users: if reply_to: return await reply_to.reply(text, link_preview=link_preview) diff --git a/userbot/helpers/functions/calculate.py b/userbot/helpers/functions/calculate.py index 01984a3..5924543 100644 --- a/userbot/helpers/functions/calculate.py +++ b/userbot/helpers/functions/calculate.py @@ -26,16 +26,14 @@ async def calcc(cmd, event, text=None): stderr = redirected_error.getvalue() sys.stdout = old_stdout sys.stderr = old_stderr - evaluation = "" if exc: - evaluation = exc + return exc elif stderr: - evaluation = stderr + return stderr elif stdout: - evaluation = stdout + return stdout else: - evaluation = text - return evaluation + return text async def aexecc(code, event): diff --git a/userbot/helpers/functions/functions.py b/userbot/helpers/functions/functions.py index d75a9a1..111aee4 100644 --- a/userbot/helpers/functions/functions.py +++ b/userbot/helpers/functions/functions.py @@ -64,7 +64,7 @@ async def get_cast(casttype, movie): if i < 1: mov_casttype += str(j) elif i < 5: - mov_casttype += ", " + str(j) + mov_casttype += f", {str(j)}" else: break i += 1 @@ -79,7 +79,7 @@ async def get_moviecollections(movie): for i in movie["box office"].keys(): result += f"\n• {i}: {movie['box office'][i]}" else: - result = f"Not data" + result = "Not data" return result @@ -87,13 +87,13 @@ async def get_moviecollections(movie): def getSimilarWords(wordx, limit=5): similars = [] if not path.exists("autocomplete.json"): - words = get(f"https://sozluk.gov.tr/autocomplete.json") + words = get("https://sozluk.gov.tr/autocomplete.json") open("autocomplete.json", "a+").write(words.text) words = words.json() else: words = loads(open("autocomplete.json", "r").read()) for word in words: - if word["madde"].startswith(wordx) and not word["madde"] == wordx: + if word["madde"].startswith(wordx) and word["madde"] != wordx: if len(similars) > limit: break similars.append(word["madde"]) @@ -120,7 +120,7 @@ async def getTranslate(text, **kwargs): # Credits: Robotlog - https://github.com/robotlog/SiriUserBot/blob/master/userbot/helps/forc.py#L5 async def fsmessage(event, text, forward=False, chat=None): - cHat = chat if chat else event.chat_id + cHat = chat or event.chat_id if not forward: try: e = await event.client.send_message(cHat, text) @@ -137,7 +137,7 @@ async def fsmessage(event, text, forward=False, chat=None): async def fsfile(event, file=None, chat=None): - cHat = chat if chat else event.chat_id + cHat = chat or event.chat_id try: e = await event.send_file(cHat, file) except YouBlockedUserError: @@ -147,13 +147,13 @@ async def fsfile(event, file=None, chat=None): async def newmsgres(conv, chat, timeout=None): - if timeout: - response = await conv.wait_event( + return ( + await conv.wait_event( NewMessage(incoming=True, from_users=chat), timeout=timeout ) - else: - response = await conv.wait_event(NewMessage(incoming=True, from_users=chat)) - return response + if timeout + else await conv.wait_event(NewMessage(incoming=True, from_users=chat)) + ) async def clippy(borg, msg, chat_id, reply_to_id): diff --git a/userbot/helpers/functions/imgtools.py b/userbot/helpers/functions/imgtools.py index af80fdf..c934e08 100644 --- a/userbot/helpers/functions/imgtools.py +++ b/userbot/helpers/functions/imgtools.py @@ -46,8 +46,8 @@ def get_warp_length(width): def random_color(): number_of_colors = 2 return [ - "#" + "".join(choice("0123456789ABCDEF") for j in range(6)) - for i in range(number_of_colors) + "#" + "".join(choice("0123456789ABCDEF") for _ in range(6)) + for _ in range(number_of_colors) ] @@ -125,7 +125,7 @@ async def crop_and_divide(img): (new_width, new_height) = (0, 0) media = [] for _ in range(1, rows + 1): - for o in range(1, columns + 1): + for _ in range(1, columns + 1): mimg = img.crop( ( new_width, @@ -303,7 +303,7 @@ async def dogememify_helper(CNG_FONTS, topString, bottomString, filename, endnam bottomTextPositionY = imageSize[1] - bottomTextSize[1] bottomTextPosition = (bottomTextPositionX, bottomTextPositionY) draw = Draw(img) - outlineRange = int(fontSize / 15) + outlineRange = fontSize // 15 for x in range(-outlineRange, outlineRange + 1): for y in range(-outlineRange, outlineRange + 1): draw.text( diff --git a/userbot/helpers/functions/jikan.py b/userbot/helpers/functions/jikan.py index 444cd62..7b3dfd4 100644 --- a/userbot/helpers/functions/jikan.py +++ b/userbot/helpers/functions/jikan.py @@ -223,9 +223,9 @@ async def formatJSON(outData): link = f"https://anilist.co/anime/{jsonData['id']}" msg += f"[{title}]({link})" msg += f"\n\n**Type:** {jsonData['format']}" - msg += f"\n**Genres:** " + msg += "\\n**Genres:** " for g in jsonData["genres"]: - msg += g + " " + msg += f"{g} " msg += f"\n**Status:** {jsonData['status']}" msg += f"\n**Episodes:** {jsonData['episodes']}" msg += f"\n**Year:** {jsonData['startDate']['year']}" @@ -241,7 +241,7 @@ async def formatJSON(outData): def shorten(description, info="anilist.co"): msg = "" if len(description) > 700: - description = description[0:200] + "....." + description = description[:200] + "....." msg += f"\n**Description:**\n{description} [Read More]({info})" else: msg += f"\n**Description:** \n {description}" @@ -258,8 +258,7 @@ async def anilist_user(input_str): "Fetch user details from anilist" username = {"search": input_str} result = post(anilisturl, json={"query": user_query, "variables": username}).json() - error = result.get("errors") - if error: + if error := result.get("errors"): error_sts = error[0].get("message") return [f"{error_sts}"] user_data = result["data"]["User"] @@ -327,10 +326,9 @@ def getBannerLink(mal, kitsu_search=True, anilistid=0): } """ data = {"query": query, "variables": {"idMal": int(mal)}} - image = post("https://graphql.anilist.co", json=data).json()["data"]["Media"][ + if image := post("https://graphql.anilist.co", json=data).json()["data"]["Media"][ "bannerImage" - ] - if image: + ]: return image return getPosterLink(mal) @@ -339,11 +337,10 @@ async def get_anime_manga(mal_id, search_type, _user_id): # sourcery no-metrics jikan = jikanpy.Jikan() if search_type == "anime_anime": result = jikan.anime(mal_id) - trailer = result["trailer_url"] - if trailer: + if trailer := result["trailer_url"]: TRAILER = f"🎬 Trailer" else: - TRAILER = f"🎬 No Trailer Available" + TRAILER = "🎬 No Trailer Available" studio_string = ", ".join( studio_info["name"] for studio_info in result["studios"] ) @@ -386,8 +383,7 @@ async def get_anime_manga(mal_id, search_type, _user_id): # sourcery no-metrics anime_data = anime_result["data"]["Media"] html_char = "" for character in anime_data["characters"]["nodes"]: - html_ = "" - html_ += "
" + html_ = "" + "
" html_ += f"""""" html_ += f"""""" html_ += "
" @@ -411,14 +407,14 @@ async def get_anime_manga(mal_id, search_type, _user_id): # sourcery no-metrics # Telegraph Post mejik html_pc = "" html_pc += f"

{native}

" - html_pc += f"

Synopsis:

" + html_pc += "

Synopsis:

" html_pc += result["synopsis"] or "Unknown" html_pc += "
" if html_char: - html_pc += f"

Main Characters:

" + html_pc += "

Main Characters:

" html_pc += html_char html_pc += "

" - html_pc += f"

More Info:

" + html_pc += "

More Info:

" html_pc += f"
Studios: {studios}
" html_pc += ( f"View on MAL" diff --git a/userbot/helpers/functions/nekos.py b/userbot/helpers/functions/nekos.py index 955a7ab..0f0c493 100644 --- a/userbot/helpers/functions/nekos.py +++ b/userbot/helpers/functions/nekos.py @@ -210,5 +210,4 @@ async def magik(photo): r = get( f"https://nekobot.xyz/api/imagegen?type=magik&image=https://telegra.ph{uphoto[0]}" ).json() - teledoge = r["message"] - return teledoge + return r["message"] diff --git a/userbot/helpers/functions/utils.py b/userbot/helpers/functions/utils.py index 1359218..8522b11 100644 --- a/userbot/helpers/functions/utils.py +++ b/userbot/helpers/functions/utils.py @@ -45,7 +45,7 @@ async def get_readable_time(seconds: int) -> str: for x in range(hmm): time_list[x] = str(time_list[x]) + time_suffix_list[x] if len(time_list) == 4: - up_time += time_list.pop() + ", " + up_time += f"{time_list.pop()}, " time_list.reverse() up_time += ":".join(time_list) return up_time diff --git a/userbot/helpers/functions/utube.py b/userbot/helpers/functions/utube.py index 54d3f68..e228686 100644 --- a/userbot/helpers/functions/utube.py +++ b/userbot/helpers/functions/utube.py @@ -44,7 +44,7 @@ async def yt_search(dog): try: dog = quote(dog) - html = urlopen("https://www.youtube.com/results?search_query=" + dog) + html = urlopen(f"https://www.youtube.com/results?search_query={dog}") user_data = findall(r"watch\?v=(\S{11})", html.read().decode()) video_link = [] k = 0 @@ -71,7 +71,7 @@ async def ytsearch(query, limit): f"**◽ Dᴇsᴄʀɪᴘᴛɪoɴ:** `{v['descriptionSnippet'][-1]['text']}`\n" ) except Exception: - textresult += f"**◽ Dᴇsᴄʀɪᴘᴛɪoɴ:** `None`\n" + textresult += "**◽ Dᴇsᴄʀɪᴘᴛɪoɴ:** `None`\\n" textresult += f"**⏱ Dᴜʀᴀᴛɪoɴ:** __{v['duration']}__ **◾ Vɪᴇᴡs:** __{v['viewCount']['short']}__\n" result += f"📺 {textresult}\n" return result @@ -101,7 +101,7 @@ async def yt_data(dog): params = {"format": "json", "url": dog} url = "https://www.youtube.com/oembed" # https://stackoverflow.com/questions/29069444/returning-the-urls-as-a-list-from-a-youtube-search-query query_string = urlencode(params) - url = url + "?" + query_string + url = f"{url}?{query_string}" with urlopen(url) as response: response_text = response.read() data = loads(response_text.decode()) @@ -126,9 +126,7 @@ async def get_ytthumb(videoid: str): def get_yt_video_id(url: str): - # https://regex101.com/r/c06cbV/1 - match = YOUTUBE_REGEX.search(url) - if match: + if match := YOUTUBE_REGEX.search(url): return match.group(1) @@ -137,16 +135,16 @@ def get_choice_by_id(choice_id, media_type: str): if choice_id == "mkv": choice_str = "bestvideo+bestaudio/best" disp_str = "best(video+audio)" - elif choice_id == "mp4": - choice_str = "bestvideo[ext=webm]+251/bestvideo[ext=mp4]+(258/256/140/bestaudio[ext=m4a])/bestvideo[ext=webm]+(250/249)/best" - disp_str = "best(video+audio)[webm/mp4]" elif choice_id == "mp3": choice_str = "320" disp_str = "320 Kbps" + elif choice_id == "mp4": + choice_str = "bestvideo[ext=webm]+251/bestvideo[ext=mp4]+(258/256/140/bestaudio[ext=m4a])/bestvideo[ext=webm]+(250/249)/best" + disp_str = "best(video+audio)[webm/mp4]" else: disp_str = str(choice_id) if media_type == "v": - choice_str = disp_str + "+(258/256/140/bestaudio[ext=m4a])/best" + choice_str = f"{disp_str}+(258/256/140/bestaudio[ext=m4a])/best" else: # Audio choice_str = disp_str return choice_str, disp_str @@ -169,7 +167,7 @@ async def result_formatter(results: list): out += views out += f'❯ Upload Date: {r.get("publishedTime")}\n' if upld: - out += f"❯ Uploader: " + out += "❯ Uploader: " out += f'{upld.get("name")}' output[index] = dict( @@ -187,26 +185,18 @@ def yt_search_btns( ): buttons = [ [ - Button.inline( - text=f"⬅️️ Bᴀcᴋ", - data=f"ytdl_back_{data_key}_{page}", - ), + Button.inline(text="⬅️️ Bᴀcᴋ", data=f"ytdl_back_{data_key}_{page}"), Button.inline( text=f"🔹 {page} - {total} 🔹", data=f"ytdl_next_{data_key}_{page}", ), ], [ - Button.inline( - text=f"📜 Lɪsᴛ Aʟʟ", - data=f"ytdl_listall_{data_key}_{page}", - ), - Button.inline( - text=f"📥 Doᴡɴʟoᴀᴅ", - data=f"ytdl_download_{vid}_0", - ), + Button.inline(text="📜 Lɪsᴛ Aʟʟ", data=f"ytdl_listall_{data_key}_{page}"), + Button.inline(text="📥 Doᴡɴʟoᴀᴅ", data=f"ytdl_download_{vid}_0"), ], ] + if del_back: buttons[0].pop(0) return buttons @@ -222,11 +212,8 @@ def download_button(vid: str, body: bool = False): # sourcery no-metrics vid_data = {"formats": []} buttons = [ [ - Button.inline(f"🌟 Bᴇsᴛ - 🎞 ᴍᴋᴠ", data=f"ytdl_download_{vid}_mkv_v"), - Button.inline( - f"🌟 Bᴇsᴛ - 🎞 ᴡᴇʙᴍ/ᴍᴘ4", - data=f"ytdl_download_{vid}_mp4_v", - ), + Button.inline("🌟 Bᴇsᴛ - 🎞 ᴍᴋᴠ", data=f"ytdl_download_{vid}_mkv_v"), + Button.inline("🌟 Bᴇsᴛ - 🎞 ᴡᴇʙᴍ/ᴍᴘ4", data=f"ytdl_download_{vid}_mp4_v"), ] ] @@ -239,7 +226,7 @@ def download_button(vid: str, body: bool = False): # sourcery no-metrics fr_size = video.get("filesize") if video.get("ext") == "mp4": for frmt_ in qual_list: - if fr_note in (frmt_, frmt_ + "60"): + if fr_note in (frmt_, f"{frmt_}60"): qual_dict[frmt_][fr_id] = fr_size if video.get("acodec") != "none": bitrrate = int(video.get("abr", 0)) @@ -262,13 +249,9 @@ def download_button(vid: str, body: bool = False): # sourcery no-metrics ) buttons += sublists(video_btns, width=2) buttons += [ - [ - Button.inline( - f"🌟 Bᴇsᴛ - 🎵 ᴍᴘ3 - 320ᴋʙᴘs", - data=f"ytdl_download_{vid}_mp3_a", - ) - ] + [Button.inline("🌟 Bᴇsᴛ - 🎵 ᴍᴘ3 - 320ᴋʙᴘs", data=f"ytdl_download_{vid}_mp3_a")] ] + buttons += sublists( [ Button.inline(audio_dict.get(key_), data=f"ytdl_download_{vid}_{key_}_a") @@ -309,8 +292,9 @@ def _tubeDl(url: str, starttime, uid: str): LOGS.error(e) except GeoRestrictedError: LOGS.error( - f"**🚨 Eʀʀoʀ:** The uploader hasn't made this video available in your country." + "**🚨 Eʀʀoʀ:** The uploader hasn't made this video available in your country." ) + else: return x diff --git a/userbot/helpers/google_image_download.py b/userbot/helpers/google_image_download.py index 6617e90..8b017f8 100644 --- a/userbot/helpers/google_image_download.py +++ b/userbot/helpers/google_image_download.py @@ -577,7 +577,7 @@ def download_extended_page(self, url, chromedriver): element = browser.find_element_by_tag_name("body") # Scroll down - for i in range(50): + for _ in range(50): element.send_keys(Keys.PAGE_DOWN) sleep(0.3) @@ -709,10 +709,10 @@ def single_image(self, image_url): image_name = image_name[: image_name.find("?")] # if ".jpg" in image_name or ".gif" in image_name or ".png" in image_name or ".bmp" in image_name or ".svg" in image_name or ".webp" in image_name or ".ico" in image_name: if any(map(lambda extension: extension in image_name, extensions)): - file_name = main_directory + "/" + image_name + file_name = f"{main_directory}/{image_name}" else: - file_name = main_directory + "/" + image_name + ".jpg" - image_name = image_name + ".jpg" + file_name = f"{main_directory}/{image_name}.jpg" + image_name = f"{image_name}.jpg" try: with open(file_name, "wb") as output_file: @@ -743,9 +743,7 @@ def similar_images(self, similar_images): l2 = content.find("&", l1) urll = content[l1:l2] - newurl = ( - "https://www.google.com/search?tbs=sbi:" + urll + "&site=search&sa=X" - ) + newurl = f"https://www.google.com/search?tbs=sbi:{urll}&site=search&sa=X" req2 = Request(newurl, headers=headers) urlopen(req2) l3 = content.find("/search?sa=X&q=") @@ -794,9 +792,7 @@ def build_url_parameters(self, arguments): 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]) - ) + exact_size = f",isz:ex,iszw:{str(size_array[0])},iszh:{str(size_array[1])}" else: exact_size = "" @@ -901,7 +897,7 @@ def build_url_parameters(self, arguments): }, ], } - for key, value in params.items(): + for value in params.values(): if value[0] is not None: ext_param = value[1][value[0]] # counter will tell if it is first param added or not @@ -909,7 +905,7 @@ def build_url_parameters(self, arguments): # add it to the built url built_url += ext_param else: - built_url = built_url + "," + ext_param + built_url = f"{built_url},{ext_param}" counter += 1 built_url = lang_url + built_url + exact_size return built_url @@ -974,9 +970,12 @@ def keywords_from_file(self, file_name): search_keyword = [] with codecopen(file_name, "r", encoding="utf-8-sig") as f: 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.extend( + line.replace("\n", "").replace("\r", "") + for line in f + if line not in ["\n", "\r\n"] + ) + else: print( "Invalid file type: Valid file types are either .txt or .csv \n" @@ -987,7 +986,7 @@ def keywords_from_file(self, file_name): # make directories def create_directories(self, main_directory, dir_name, thumbnail, thumbnail_only): - dir_name_thumbnail = dir_name + " - thumbnail" + dir_name_thumbnail = f"{dir_name} - thumbnail" # make a search keyword directory try: if not ospath.exists(main_directory): @@ -1025,7 +1024,7 @@ def download_image_thumbnail( ignore_urls, ): if print_urls or no_download: - print("Image URL: " + image_url) + print(f"Image URL: {image_url}") if no_download: return "success", "Printed url without downloading" try: @@ -1037,10 +1036,7 @@ def download_image_thumbnail( ) try: # timeout time to download an image - if socket_timeout: - timeout = float(socket_timeout) - else: - timeout = 10 + timeout = float(socket_timeout) if socket_timeout else 10 response = urlopen(req, None, timeout) data = response.read() response.close() @@ -1055,14 +1051,12 @@ def download_image_thumbnail( ) try: - output_file = open(path, "wb") - output_file.write(data) - output_file.close() + with open(path, "wb") as output_file: + output_file.write(data) if save_source: - list_path = main_directory + "/" + save_source + ".txt" - list_file = open(list_path, "a") - list_file.write(path + "\t" + img_src + "\n") - list_file.close() + list_path = f"{main_directory}/{save_source}.txt" + with open(list_path, "a") as list_file: + list_file.write(path + "\t" + img_src + "\n") except OSError as e: download_status = "fail" download_message = ( @@ -1076,12 +1070,12 @@ def download_image_thumbnail( download_status = "success" download_message = ( - "Completed Image Thumbnail ====> " + return_image_name + f"Completed Image Thumbnail ====> {return_image_name}" ) # image size parameter if print_size: - print("Image Size: " + str(self.file_size(path))) + print(f"Image Size: {str(self.file_size(path))}") except UnicodeEncodeError as e: download_status = "fail" @@ -1456,9 +1450,7 @@ def download(self, arguments): records = [] json_file = load(open(arguments["config_file"])) for record in range(len(json_file["Records"])): - arguments = {} - for i in args_list: - arguments[i] = None + arguments = {i: None for i in args_list} for key, value in json_file["Records"][record].items(): arguments[key] = value records.append(arguments) diff --git a/userbot/helpers/memeshelper.py b/userbot/helpers/memeshelper.py index d9d4c91..9a878cb 100644 --- a/userbot/helpers/memeshelper.py +++ b/userbot/helpers/memeshelper.py @@ -102,8 +102,7 @@ async def slap(replied_user, event, DEFAULTUSER): """Komik bir tokat gibi!""" user_id = replied_user.user.id first_name = replied_user.user.first_name - username = replied_user.user.username - if username: + if username := replied_user.user.username: slapped = "@{}".format(username) else: slapped = f"[{first_name}](tg://user?id={user_id})" diff --git a/userbot/helpers/nsfw.py b/userbot/helpers/nsfw.py index e1368e0..63809e9 100644 --- a/userbot/helpers/nsfw.py +++ b/userbot/helpers/nsfw.py @@ -116,7 +116,7 @@ def nsfw(category): category.sort(key=str.casefold) - horny = f"**Kategori:** " + horny = "**Kategori:** " for i in category: horny += f" `{i.lower()}` ||" return horny diff --git a/userbot/helpers/progress.py b/userbot/helpers/progress.py index cc2460d..fe60d9e 100644 --- a/userbot/helpers/progress.py +++ b/userbot/helpers/progress.py @@ -50,13 +50,13 @@ def humanbytes(size: int) -> str: if size is None or isinstance(size, str): return "" - power = 2 ** 10 + power = 2**10 raised_to_pow = 0 dict_power_n = {0: "", 1: "Ki", 2: "Mi", 3: "Gi", 4: "Ti"} while size > power: size /= power raised_to_pow += 1 - return str(round(size, 2)) + " " + dict_power_n[raised_to_pow] + "B" + return f"{str(round(size, 2))} {dict_power_n[raised_to_pow]}B" def time_formatter(seconds: int) -> str: @@ -65,11 +65,12 @@ def time_formatter(seconds: int) -> str: days, hours = divmod(hours, 24) seconds = round(seconds, 2) tmp = ( - ((str(days) + f" gün, ") if days else "") - + ((str(hours) + f" saat, ") if hours else "") - + ((str(minutes) + f" dakika, ") if minutes else "") - + ((str(seconds) + f" saniye, ") if seconds else "") + (f"{str(days)} gün, " if days else "") + + (f"{str(hours)} saat, " if hours else "") + + (f"{str(minutes)} dakika, " if minutes else "") + + (f"{str(seconds)} saniye, " if seconds else "") ) + return tmp[:-2] @@ -78,21 +79,21 @@ def readable_time(seconds: int) -> str: hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) return ( - ((str(int(days)) + f" gün, ") if days else "") - + ((str(int(hours)) + ":") if hours else "00:") - + ((str(int(minutes)) + ":") if minutes else "00:") + (f"{int(days)} gün, " if days else "") + + (f"{int(hours)}:" if hours else "00:") + + (f"{int(minutes)}:" if minutes else "00:") + (str(int(seconds)) if seconds else "00") ) def human_to_bytes(size: str) -> int: units = { - "M": 2 ** 20, - "MB": 2 ** 20, - "G": 2 ** 30, - "GB": 2 ** 30, - "T": 2 ** 40, - "TB": 2 ** 40, + "M": 2**20, + "MB": 2**20, + "G": 2**30, + "GB": 2**30, + "T": 2**40, + "TB": 2**40, } size = size.upper() @@ -146,13 +147,14 @@ async def progress( status = "Unknown" progress_str = "{0}\n`[{1}{2}] {3}%`".format( status, - "".join(Config.FINISHED_PROGRESS_STR for i in range(floor(percentage / 5))), + "".join(Config.FINISHED_PROGRESS_STR for _ in range(floor(percentage / 5))), "".join( Config.UNFINISHED_PROGRESS_STR - for i in range(20 - floor(percentage / 5)) + for _ in range(20 - floor(percentage / 5)) ), round(percentage, 2), ) + tmp = ( f"{progress_str}\n" f"`💾 {humanbytes(current)}/{humanbytes(total)}" diff --git a/userbot/helpers/qhelper.py b/userbot/helpers/qhelper.py index 02c925d..c1f6773 100644 --- a/userbot/helpers/qhelper.py +++ b/userbot/helpers/qhelper.py @@ -197,9 +197,9 @@ async def process(msg, user, client, reply, replied=None): elif reply.document.size < 1048576: docsize = str(round(reply.document.size / 1024, 2)) + " KB " elif reply.document.size < 1073741824: - docsize = str(round(reply.document.size / 1024 ** 2, 2)) + " MB " + docsize = str(round(reply.document.size / 1024**2, 2)) + " MB " else: - docsize = str(round(reply.document.size / 1024 ** 3, 2)) + " GB " + docsize = str(round(reply.document.size / 1024**3, 2)) + " GB " docbglen = ( font.getsize(docsize)[0] if font.getsize(docsize)[0] > font.getsize(docname)[0] diff --git a/userbot/helpers/utils/events.py b/userbot/helpers/utils/events.py index ebc605b..a256a17 100644 --- a/userbot/helpers/utils/events.py +++ b/userbot/helpers/utils/events.py @@ -177,6 +177,6 @@ async def get_chatinfo(event, dogevent): return None except (TypeError, ValueError) as err: LOGS.info(err) - await edl(dogevent, f"**🚨 Eʀʀoʀ:**\n`ℹ️ Couldn't fetch the chat!`") + await edl(dogevent, "**🚨 Eʀʀoʀ:**\\n`ℹ️ Couldn't fetch the chat!`") return None return chat_info diff --git a/userbot/helpers/utils/format.py b/userbot/helpers/utils/format.py index 455f390..f67bf82 100644 --- a/userbot/helpers/utils/format.py +++ b/userbot/helpers/utils/format.py @@ -28,7 +28,7 @@ async def paste_message(text, pastetype="p", extension=None, markdown=True, titl response = await pastetext(text, pastetype, extension) if "url" in response: return response["url"] - return f"**🚨 Eʀʀoʀ:** While pasting text to site" + return "**🚨 Eʀʀoʀ:** While pasting text to site" def md_to_text(md): @@ -87,12 +87,10 @@ def yaml_format(obj, indent=0, max_str_len=256, max_byte_len=64): # sourcery no formatted = yaml_format(v, indent) if not formatted.strip(): continue - result.append(" " * (indent if has_multiple_items else 1)) - result.append(f"{k}:") + result.extend((" " * (indent if has_multiple_items else 1), f"{k}:")) if not formatted[0].isspace(): result.append(" ") - result.append(f"{formatted}") - result.append("\n") + result.extend((f"{formatted}", "\n")) if has_items: result.pop() if has_multiple_items: diff --git a/userbot/helpers/utils/paste.py b/userbot/helpers/utils/paste.py index 035b813..8b8804e 100644 --- a/userbot/helpers/utils/paste.py +++ b/userbot/helpers/utils/paste.py @@ -32,7 +32,7 @@ async def t_paste(msg, title=None): """ To Paste the given message/text/code to Telegraph """ - c = title if title else "🐶 Doge UserBot 🐾" + c = title or "🐶 Doge UserBot 🐾" try: t = telegraph.create_page(title=c, content=[f"{msg}"]) response = t["url"] @@ -85,7 +85,7 @@ async def p_paste(message, extension=None): "raw": f"https://pasty.lus.pm/{response['id']}/raw", "bin": "Pasty", } - return {"error": f"`🚨 Unable to reach pasty.lus.pm!`"} + return {"error": "`🚨 Unable to reach pasty.lus.pm!`"} async def s_paste(message, extension="txt"): @@ -106,7 +106,7 @@ async def s_paste(message, extension="txt"): "raw": f"{siteurl}{response['payload']['id']}/raw", "bin": "Spacebin", } - return {"error": f"`🚨 Unable to reach spacebin!`"} + return {"error": "`🚨 Unable to reach spacebin!`"} def spaste(message, extension="txt"): @@ -152,7 +152,7 @@ async def n_paste(message, extension=None): "raw": f"nekobin.com/raw/{response['result']['key']}", "bin": "Neko", } - return {"error": f"`🚨 Unable to reach nekobin!`"} + return {"error": "`🚨 Unable to reach nekobin!`"} async def d_paste(message, extension=None): @@ -177,7 +177,7 @@ async def d_paste(message, extension=None): "raw": f"https://catbin.up.railway.app/raw/{response['key']}", "bin": "Dog", } - return {"error": f"`🚨 Unable to reach catbin!`"} + return {"error": "`🚨 Unable to reach catbin!`"} async def pastetext(text_to_print, pastetype=None, extension=None, title=None): diff --git a/userbot/plugins/admin.py b/userbot/plugins/admin.py index c5bd156..4c4e01a 100644 --- a/userbot/plugins/admin.py +++ b/userbot/plugins/admin.py @@ -556,7 +556,7 @@ async def endmute(event): try: await event.client.kick_participant(event.chat_id, user_id) except Exception as e: - return await dogevent.edit(NO_PERM + f"\n{e}") + return await dogevent.edit(f"{NO_PERM}\n{e}") if reason: await dogevent.edit( f"`Kicked` [{user.first_name}](tg://user?id={user_id})`!`\nReason: {reason}" diff --git a/userbot/plugins/afk.py b/userbot/plugins/afk.py index 1d31c9e..9782be8 100644 --- a/userbot/plugins/afk.py +++ b/userbot/plugins/afk.py @@ -112,7 +112,7 @@ async def afksetter(event): BOTLOG_CHATID, "#AFKTRUE \nSet AFK mode to True, and Reason is Not Mentioned", ) - elif media_t != "Sticker" and media_t: + else: if not BOTLOG: return await edl( event, diff --git a/userbot/plugins/alive.py b/userbot/plugins/alive.py index f4b1ee7..aa6dae0 100644 --- a/userbot/plugins/alive.py +++ b/userbot/plugins/alive.py @@ -94,7 +94,7 @@ async def thisalive(event): ping=ms, ) if DOG_IMG: - DOG = [x for x in DOG_IMG.split()] + DOG = list(DOG_IMG.split()) PIC = choice(DOG) try: await event.client.send_file( diff --git a/userbot/plugins/android.py b/userbot/plugins/android.py index 084038c..f6fb686 100644 --- a/userbot/plugins/android.py +++ b/userbot/plugins/android.py @@ -29,10 +29,11 @@ async def kakashi(event): "Get latest Magisk releases" magisk_repo = "https://raw.githubusercontent.com/topjohnwu/magisk-files/" magisk_dict = { - "⦁ **Stable**": magisk_repo + "master/stable.json", - "⦁ **Beta**": magisk_repo + "master/beta.json", - "⦁ **Canary**": magisk_repo + "master/canary.json", + "⦁ **Stable**": f"{magisk_repo}master/stable.json", + "⦁ **Beta**": f"{magisk_repo}master/beta.json", + "⦁ **Canary**": f"{magisk_repo}master/canary.json", } + releases = "**Latest Magisk Releases**\n\n" for name, release_url in magisk_dict.items(): data = get(release_url).json() @@ -67,8 +68,7 @@ async def device_info(event): "certified-android-devices/master/by_device.json" ).text ) - results = data.get(codename) - if results: + if results := data.get(codename): reply = f"**Search results for {codename}:**\n\n" for item in results: reply += ( @@ -113,12 +113,11 @@ async def codename_info(event): devices = devices_lower.get(brand) if not devices: return await eor(event, f"__I couldn't find {brand}.__") - results = [ + if results := [ i for i in devices if i["name"].lower() == device.lower() or i["model"].lower() == device.lower() - ] - if results: + ]: reply = f"**Search results for {brand} {device}:**\n\n" if len(results) > 8: results = results[:8] diff --git a/userbot/plugins/antispambot.py b/userbot/plugins/antispambot.py index beba1d0..a921f63 100644 --- a/userbot/plugins/antispambot.py +++ b/userbot/plugins/antispambot.py @@ -66,8 +66,7 @@ async def anti_spambot(event): # sourcery no-metrics except Exception as e: LOGS.info(e) if SPAMWATCH and not dogbanned: - ban = SPAMWATCH.get_ban(user.id) - if ban: + if ban := SPAMWATCH.get_ban(user.id): hmm = await event.reply( f"[{user.first_name}](tg://user?id={user.id}) was banned by spamwatch for the reason `{ban.reason}`" ) diff --git a/userbot/plugins/app.py b/userbot/plugins/app.py index 81e84b5..1785e77 100644 --- a/userbot/plugins/app.py +++ b/userbot/plugins/app.py @@ -32,7 +32,7 @@ async def app_search(event): try: remove_space = app_name.split(" ") final_name = "+".join(remove_space) - page = get("https://play.google.com/store/search?q=" + final_name + "&c=apps") + page = get(f"https://play.google.com/store/search?q={final_name}&c=apps") str(page.status_code) soup = BeautifulSoup(page.content, "lxml", from_encoding="utf-8") results = soup.findAll("div", "ZmHEEd") @@ -64,7 +64,7 @@ async def app_search(event): .img["data-src"] ) app_details = "📲​" - app_details += " " + app_name + "" + app_details += f" {app_name}" app_details += ( "\n\nDeveloper: Information of {name} diff --git a/userbot/plugins/custom.py b/userbot/plugins/custom.py index c78a94c..46a496b 100644 --- a/userbot/plugins/custom.py +++ b/userbot/plugins/custom.py @@ -170,13 +170,10 @@ async def dbsetter(event): # sourcery no-metrics username = reply.chat.username msg_id = reply.id vinfo = f"https://t.me/{username}/{msg_id}" - else: - if reply.media: - custom = await reply.forward_to(BOTLOG_CHATID) - vinfo = f"{custom.id}" - elif (type(reply.media) == MessageMediaDocument) or ( - type(reply.media) == MessageMediaPhoto - ): + elif reply.media: + custom = await reply.forward_to(BOTLOG_CHATID) + vinfo = f"{custom.id}" + elif type(reply.media) in [MessageMediaDocument, MessageMediaPhoto]: await eor(event, "`Creating link...`") downloaded_file_name = await event.client.download_media( reply, TEMP_DIR @@ -188,7 +185,7 @@ async def dbsetter(event): # sourcery no-metrics vinfo = f"https://telegra.ph{media_urls[0]}" except AttributeError: - return await eor(event, f"**🚨 Eʀʀoʀ:** `While making link.`") + return await eor(event, "**🚨 Eʀʀoʀ:** `While making link.`") except TelegraphException as exc: return await eor(event, f"**🚨 Eʀʀoʀ:**\n➡️ `{str(exc)}`") @@ -292,57 +289,56 @@ async def dbsetter(event): # sourcery no-metrics f"🔮 Value of **{apiname}** is now deleted & set to default.", time=20, ) - else: - if gvar("PERMISSION_TO_ALL_GLOBAL_DATA_VARIABLES") is True: - gvarname = vname - gvarinfo = vinfo - if cmd == "s": - if not gvarinfo: - return await edl( - event, - f"⚙️ Give some values which you want to save for **{gvarname}**", - ) - - sgvar(gvarname, gvarinfo) - if BOTLOG_CHATID: - await doge.tgbot.send_message( - BOTLOG_CHATID, - f"#SET_GLOBALDATAVAR\ - \n**⚙️ {gvarname}** is updated newly in database as below", - ) - await doge.tgbot.send_message(BOTLOG_CHATID, gvarinfo, silent=True) - await edl( + elif gvar("PERMISSION_TO_ALL_GLOBAL_DATA_VARIABLES") is True: + gvarname = vname + gvarinfo = vinfo + if cmd == "s": + if not gvarinfo: + return await edl( event, - f"⚙️ Value of **{gvarname}** is changed.", + f"⚙️ Give some values which you want to save for **{gvarname}**", ) - if cmd == "g": - gvardata = gvar(gvarname) - await edl(event, "**I sent global data var to BOTLOG.**") + + sgvar(gvarname, gvarinfo) + if BOTLOG_CHATID: await doge.tgbot.send_message( BOTLOG_CHATID, - f"⚙️ Value of **{gvarname}** is `{gvardata}`", + f"#SET_GLOBALDATAVAR\ + \n**⚙️ {gvarname}** is updated newly in database as below", ) - elif cmd == "d": - gvardata = gvar(gvarname) - dgvar(gvarname) - if BOTLOG_CHATID: - await doge.tgbot.send_message( - BOTLOG_CHATID, - f"#DEL_GLOBALDATAVAR\ + await doge.tgbot.send_message(BOTLOG_CHATID, gvarinfo, silent=True) + await edl( + event, + f"⚙️ Value of **{gvarname}** is changed.", + ) + if cmd == "g": + gvardata = gvar(gvarname) + await edl(event, "**I sent global data var to BOTLOG.**") + await doge.tgbot.send_message( + BOTLOG_CHATID, + f"⚙️ Value of **{gvarname}** is `{gvardata}`", + ) + elif cmd == "d": + gvardata = gvar(gvarname) + dgvar(gvarname) + if BOTLOG_CHATID: + await doge.tgbot.send_message( + BOTLOG_CHATID, + f"#DEL_GLOBALDATAVAR\ \n**{gvarname}** is deleted from database\ \n\ \n🚮 Deleted: `{gvardata}`", - ) - await edl( - event, - f"⚙️ Value of **{gvarname}** is now deleted & set to default.", - time=20, ) - else: - await eor( + await edl( event, - f"**🪀 Give correct VAR name from the list:\n\n**{vnlist}\n\n\n**🔮 Give correct API name from the list:\n\n**{apilist}", + f"⚙️ Value of **{gvarname}** is now deleted & set to default.", + time=20, ) + else: + await eor( + event, + f"**🪀 Give correct VAR name from the list:\n\n**{vnlist}\n\n\n**🔮 Give correct API name from the list:\n\n**{apilist}", + ) @doge.bot_cmd( diff --git a/userbot/plugins/dictionary.py b/userbot/plugins/dictionary.py index 590aa77..86ecfda 100644 --- a/userbot/plugins/dictionary.py +++ b/userbot/plugins/dictionary.py @@ -90,7 +90,7 @@ async def tdk(event): if "error" in response: await edl(dogevent, f"**I couldn't find ({inp}) in Turkish dictionary.**") words = getSimilarWords(inp) - if not words == "": + if words != "": return await edl( dogevent, f"__I couldn't find ({inp}) in Turkish dictionary.__\n\n**Similar Words:** {words}", @@ -100,29 +100,21 @@ async def tdk(event): meaningsStr = "" for mean in response[0]["anlamlarListe"]: meaningsStr += f"\n**{mean['anlam_sira']}.**" - if ("ozelliklerListe" in mean) and ( - (not mean["ozelliklerListe"][0]["tam_adi"] is None) - or (not mean["ozelliklerListe"][0]["tam_adi"] == "") + if "ozelliklerListe" in mean and ( + mean["ozelliklerListe"][0]["tam_adi"] is not None + or mean["ozelliklerListe"][0]["tam_adi"] != "" ): meaningsStr += f"__({mean['ozelliklerListe'][0]['tam_adi']})__" meaningsStr += f' ```{mean["anlam"]}```' - if response[0]["cogul_mu"] == "0": - cogul = "❌" - else: - cogul = "✅" - - if response[0]["ozel_mi"] == "0": - ozel = "❌" - else: - ozel = "✅" - + cogul = "❌" if response[0]["cogul_mu"] == "0" else "✅" + ozel = "❌" if response[0]["ozel_mi"] == "0" else "✅" await eor( dogevent, f"**Word:** `{inp}`\n\n**Is the plural?:** {cogul}\n**Is the word a proper noun?:** {ozel}\n\n**Meanings:** {meaningsStr}", ) words = getSimilarWords(inp) - if not words == "": + if words != "": return dogevent.edit( f"**Word:** `{inp}`\n\n**Is the plural?:** `{cogul}`\n**Is the word a proper noun?:** {ozel}\n\n**Meanings:** {meaningsStr}\n\n**Similar Words:** {words}", ) @@ -138,7 +130,7 @@ async def tdk(event): ) async def tureng(event): word = event.pattern_match.group(1) - url = "https://tureng.com/tr/turkce-ingilizce/" + word + url = f"https://tureng.com/tr/turkce-ingilizce/{word}" try: answer = get(url) except BaseException: @@ -148,7 +140,7 @@ async def tureng(event): try: table = soup.find("table") td = table.find_all("td", attrs={"lang": "en"}) - for val in td[0:5]: + for val in td[:5]: trlated = "{} 👉 {}\n".format(trlated, val.text) await eor(event, trlated) except BaseException: diff --git a/userbot/plugins/download.py b/userbot/plugins/download.py index b2b34e5..fb61a02 100644 --- a/userbot/plugins/download.py +++ b/userbot/plugins/download.py @@ -70,7 +70,7 @@ async def _(event): # sourcery no-metrics name += "_" + str(getattr(reply.document, "id", reply.id)) + ext if path and path.exists(): if path.is_file(): - newname = str(path.stem) + "_OLD" + newname = f"{str(path.stem)}_OLD" path.rename(path.with_name(newname).with_suffix(path.suffix)) file_name = path else: @@ -145,10 +145,11 @@ async def _(event): # sourcery no-metrics percentage = downloader.get_progress() * 100 dspeed = downloader.get_speed() progress_str = "`{0}{1} {2}`%".format( - "".join("▰" for i in range(floor(percentage / 5))), - "".join("▱" for i in range(20 - floor(percentage / 5))), + "".join("▰" for _ in range(floor(percentage / 5))), + "".join("▱" for _ in range(20 - floor(percentage / 5))), round(percentage, 2), ) + estimated_total_time = downloader.get_eta(human=True) current_message = f"Downloading the file\ \n\n**URL:** `{url}`\ @@ -223,7 +224,7 @@ async def _(event): # sourcery no-metrics name += "_" + str(getattr(reply.document, "id", reply.id)) + ext if path and path.exists(): if path.is_file(): - newname = str(path.stem) + "_OLD" + newname = f"{str(path.stem)}_OLD" path.rename(path.with_name(newname).with_suffix(path.suffix)) file_name = path else: diff --git a/userbot/plugins/evaluators.py b/userbot/plugins/evaluators.py index 2d51676..c97a3fb 100644 --- a/userbot/plugins/evaluators.py +++ b/userbot/plugins/evaluators.py @@ -48,8 +48,7 @@ async def _(event): ) if BOTLOG: await event.client.send_message( - BOTLOG_CHATID, - "Terminal command " + cmd + " was executed sucessfully.", + BOTLOG_CHATID, f"Terminal command {cmd} was executed sucessfully." ) @@ -106,8 +105,7 @@ async def _(event): ) if BOTLOG: await event.client.send_message( - BOTLOG_CHATID, - "eval command " + cmd + " was executed sucessfully.", + BOTLOG_CHATID, f"eval command {cmd} was executed sucessfully." ) diff --git a/userbot/plugins/feds.py b/userbot/plugins/feds.py index f7f2caf..8f7fb9b 100644 --- a/userbot/plugins/feds.py +++ b/userbot/plugins/feds.py @@ -274,9 +274,12 @@ async def quote_search(event): # sourcery no-metrics pass else: text_lines = response.text.split("`") - for fed_id in text_lines: - if len(fed_id) == 36 and fed_id.count("-") == 4: - fedidstoadd.append(fed_id) + fedidstoadd.extend( + fed_id + for fed_id in text_lines + if len(fed_id) == 36 and fed_id.count("-") == 4 + ) + except Exception as e: await edl( dogevent, @@ -477,10 +480,11 @@ async def fetch_fedinfo(event): await fsmessage(event, text=f"/fedadmins {input_str}", chat=rose) response = await newmsgres(conv, rose) await dogevent.edit( - f"**FedID:** ```{input_str}```\n\n" + response.text + f"**FedID:** ```{input_str}```\n\n{response.text}" if input_str else response.text ) + except Exception as e: await edl( dogevent, diff --git a/userbot/plugins/ffmpeg.py b/userbot/plugins/ffmpeg.py index 2c3db64..047b1c2 100644 --- a/userbot/plugins/ffmpeg.py +++ b/userbot/plugins/ffmpeg.py @@ -150,7 +150,7 @@ async def ff_mpeg_trim_cmd(event): end_time, ) if o is None: - return await edl(dogevent, f"**Error:** `Can't complete the process`") + return await edl(dogevent, "**Error:** `Can't complete the process`") try: c_time = time() await event.client.send_file( diff --git a/userbot/plugins/figlet.py b/userbot/plugins/figlet.py index acbaf37..d723e4e 100644 --- a/userbot/plugins/figlet.py +++ b/userbot/plugins/figlet.py @@ -81,8 +81,7 @@ async def figlet(event): event, f"**Invalid style selected!** __Check__ `{tr}doge figlet`." ) - result = figlet_format(deEmojify(text), font=font) else: font = choice(CMDFIG) - result = figlet_format(deEmojify(text), font=font) + result = figlet_format(deEmojify(text), font=font) await eor(event, f"ㅤ \n{result}", parse_mode=_format.parse_pre) diff --git a/userbot/plugins/fileconverts.py b/userbot/plugins/fileconverts.py index 261bd6b..15efc25 100644 --- a/userbot/plugins/fileconverts.py +++ b/userbot/plugins/fileconverts.py @@ -242,17 +242,13 @@ async def video_dogfile(event): # sourcery no-metrics else: remove(dogfile) return await edl(dogevent, "`No thumb found to make it video note`", 5) - if ( - mediatype - in [ - "Voice", - "Audio", - "Gif", - "Video", - "Sticker", - ] - and not dogfile.endswith((".webp")) - ): + if mediatype in [ + "Voice", + "Audio", + "Gif", + "Video", + "Sticker", + ] and not dogfile.endswith((".webp")): if osp.exists(PATH): c_time = time() attributes, mime_type = get_attributes(PATH) @@ -497,11 +493,7 @@ async def on_file_to_photo(event): ) async def _(event): # sourcery no-metrics "Converts Given animated sticker to gif" - input_str = event.pattern_match.group(1) - if not input_str: - quality = None - fps = None - else: + if input_str := event.pattern_match.group(1): loc = input_str.split(";") if len(loc) > 2: return await edl( @@ -537,6 +529,9 @@ async def _(event): # sourcery no-metrics quality = loc[0].strip() else: return await edl(event, "Use quality of range 0 to 721") + else: + quality = None + fps = None dogreply = await event.get_reply_message() doge_event = b64decode("eFZFRXlyUHY2Z2s1T0Rsaw==") if not dogreply or not dogreply.media or not dogreply.media.document: @@ -616,10 +611,11 @@ async def _(event): voice_note = False supports_streaming = False if input_str == "voice": - new_required_file_caption = "voice_" + str(round(time())) + ".opus" + new_required_file_caption = f"voice_{str(round(time()))}.opus" new_required_file_name = ( - TMP_DOWNLOAD_DIRECTORY + "/" + new_required_file_caption + f"{TMP_DOWNLOAD_DIRECTORY}/{new_required_file_caption}" ) + command_to_run = [ "ffmpeg", "-i", @@ -637,10 +633,11 @@ async def _(event): voice_note = True supports_streaming = True elif input_str == "mp3": - new_required_file_caption = "mp3_" + str(round(time())) + ".mp3" + new_required_file_caption = f"mp3_{str(round(time()))}.mp3" new_required_file_name = ( - TMP_DOWNLOAD_DIRECTORY + "/" + new_required_file_caption + f"{TMP_DOWNLOAD_DIRECTORY}/{new_required_file_caption}" ) + command_to_run = [ "ffmpeg", "-i", diff --git a/userbot/plugins/filesummary.py b/userbot/plugins/filesummary.py index 20f7e5d..7cbb8c5 100644 --- a/userbot/plugins/filesummary.py +++ b/userbot/plugins/filesummary.py @@ -45,8 +45,7 @@ def weird_division(n, d): async def _(event): # sourcery no-metrics "Shows you the complete media/file summary of the that group" entity = event.chat_id - input_str = event.pattern_match.group(1) - if input_str: + if input_str := event.pattern_match.group(1): try: entity = int(input_str) except ValueError: @@ -109,9 +108,9 @@ async def _(event): # sourcery no-metrics largest += f" • {mediax}: {humanbytes(media_dict[mediax]['max_size'])}\n" endtime = int(monotonic()) if endtime - starttime >= 120: - runtime = str(round(((endtime - starttime) / 60), 2)) + " minutes" + runtime = f"{str(round(((endtime - starttime) / 60), 2))} minutes" else: - runtime = str(endtime - starttime) + " seconds" + runtime = f"{str(endtime - starttime)} seconds" avghubytes = humanbytes(weird_division(totalsize, totalcount)) avgruntime = ( str(round((weird_division((endtime - starttime), totalcount)) * 1000, 2)) @@ -231,9 +230,9 @@ async def _(event): # sourcery no-metrics largest += f" • {mediax}: {humanbytes(media_dict[mediax]['max_size'])}\n" endtime = int(monotonic()) if endtime - starttime >= 120: - runtime = str(round(((endtime - starttime) / 60), 2)) + " minutes" + runtime = f"{str(round(((endtime - starttime) / 60), 2))} minutes" else: - runtime = str(endtime - starttime) + " seconds" + runtime = f"{str(endtime - starttime)} seconds" avghubytes = humanbytes(weird_division(totalsize, totalcount)) avgruntime = ( str(round((weird_division((endtime - starttime), totalcount)) * 1000, 2)) diff --git a/userbot/plugins/filters.py b/userbot/plugins/filters.py index 9924e03..f08a494 100644 --- a/userbot/plugins/filters.py +++ b/userbot/plugins/filters.py @@ -49,7 +49,7 @@ async def filter_incoming_handler(event): # sourcery no-metrics my_fullname = f"{my_first} {my_last}" if my_last else my_first my_username = f"@{me.username}" if me.username else my_mention for trigger in filters: - pattern = r"( |^|[^\w])" + escape(trigger.keyword) + r"( |$|[^\w])" + pattern = f"( |^|[^\\w]){escape(trigger.keyword)}( |$|[^\\w])" if search(pattern, name, flags=IGNORECASE): file_media = None filter_msg = None @@ -123,27 +123,26 @@ async def add_new_filter(event): msg = await event.get_reply_message() msg_id = None if msg and msg.media and not string: - if BOTLOG: - await event.client.send_message( - BOTLOG_CHATID, - f"#FILTER\ - \nCHAT ID: {event.chat_id}\ - \nTRIGGER: {keyword}\ - \n\nThe following message is saved as the filter's reply data for the chat, please DON'T delete it !!", - ) - msg_o = await event.client.forward_messages( - entity=BOTLOG_CHATID, - messages=msg, - from_peer=event.chat_id, - silent=True, - ) - msg_id = msg_o.id - else: + if not BOTLOG: return await eor( event, "__Saving media as reply to the filter requires the__ `PRIVATE_GROUP_BOT_API_ID` __to be set.__", ) + await event.client.send_message( + BOTLOG_CHATID, + f"#FILTER\ + \nCHAT ID: {event.chat_id}\ + \nTRIGGER: {keyword}\ + \n\nThe following message is saved as the filter's reply data for the chat, please DON'T delete it !!", + ) + msg_o = await event.client.forward_messages( + entity=BOTLOG_CHATID, + messages=msg, + from_peer=event.chat_id, + silent=True, + ) + msg_id = msg_o.id elif msg and msg.text and not string: string = msg.text elif not string: diff --git a/userbot/plugins/gdrive.py b/userbot/plugins/gdrive.py index e1b71ff..d14a091 100644 --- a/userbot/plugins/gdrive.py +++ b/userbot/plugins/gdrive.py @@ -286,7 +286,7 @@ async def download(event, gdrive, service, uri=None): # sourcery no-metrics status = status.replace("[FILE", "[FOLDER") folder = await create_dir(service, file_name, GDRIVE_.parent_Id) dir_id = folder.get("id") - webViewURL = "https://drive.google.com/drive/folders/" + dir_id + webViewURL = f"https://drive.google.com/drive/folders/{dir_id}" try: await task_directory(gdrive, service, required_file_name, dir_id) except CancelProcess: @@ -437,10 +437,11 @@ async def gdrive_download( speed = round(downloaded / diff, 2) eta = round((file_size - downloaded) / speed) prog_str = "`[{0}{1}] {2}%`".format( - "".join("▰" for i in range(floor(percentage / 10))), - "".join("▱" for i in range(10 - floor(percentage / 10))), + "".join("▰" for _ in range(floor(percentage / 10))), + "".join("▱" for _ in range(10 - floor(percentage / 10))), round(percentage, 2), ) + current_message = ( "**File downloading**\n\n" f"**Name:** `{file_name}`\n" @@ -492,14 +493,15 @@ async def gdrive_download( status, "".join( Config.FINISHED_PROGRESS_STR - for i in range(floor(percentage / 5)) + for _ in range(floor(percentage / 5)) ), "".join( Config.UNFINISHED_PROGRESS_STR - for i in range(20 - floor(percentage / 5)) + for _ in range(20 - floor(percentage / 5)) ), round(percentage, 2), ) + current_message = ( "**File Downloading**\n\n" f"**Name:** `{file_name}`\n" @@ -648,11 +650,11 @@ async def upload(gdrive, service, file_path, file_name, mimeType, dir_id=None): eta = round((file_size - uploaded) / speed) prog_str = "`Uploading:`\n`[{0}{1}] {2}`".format( "".join( - Config.FINISHED_PROGRESS_STR for i in range(floor(percentage / 10)) + Config.FINISHED_PROGRESS_STR for _ in range(floor(percentage / 10)) ), "".join( Config.UNFINISHED_PROGRESS_STR - for i in range(10 - floor(percentage / 10)) + for _ in range(10 - floor(percentage / 10)) ), round(percentage, 2), ) @@ -777,8 +779,8 @@ async def check_progress_for_dl(event, gid, previous): # sourcery no-metrics percentage = int(file.progress) downloaded = percentage * int(file.total_length) / 100 prog_str = "**Downloading:** `[{0}{1}] {2}`".format( - "".join("▰" for i in range(floor(percentage / 10))), - "".join("▱" for i in range(10 - floor(percentage / 10))), + "".join("▰" for _ in range(floor(percentage / 10))), + "".join("▱" for _ in range(10 - floor(percentage / 10))), file.progress_string(), ) diff --git a/userbot/plugins/git.py b/userbot/plugins/git.py index 32d38ec..45889a1 100644 --- a/userbot/plugins/git.py +++ b/userbot/plugins/git.py @@ -60,7 +60,7 @@ async def _(event): async with ClientSession() as session: async with session.get(URL) as request: if request.status == 404: - return await edl(event, "`" + username + " not found`") + return await edl(event, f"`{username} not found`") dogevent = await eor(event, "`fetching github info...`") result = await request.json() @@ -172,7 +172,7 @@ async def git_commit(file_name, mone): return await mone.edit("`File Already Exists`") if create_file: - file_name = "userbot/plugins/" + file_name + file_name = f"userbot/plugins/{file_name}" LOGS.info(file_name) try: repo.create_file( diff --git a/userbot/plugins/google.py b/userbot/plugins/google.py index c07d40d..a159858 100644 --- a/userbot/plugins/google.py +++ b/userbot/plugins/google.py @@ -101,13 +101,13 @@ async def gsearch(q_event): try: page = page[0] page = page.replace(".p", "") - match = match.replace(".p" + page, "") + match = match.replace(f".p{page}", "") except IndexError: page = 1 try: lim = lim[0] lim = lim.replace(".l", "") - match = match.replace(".l" + lim, "") + match = match.replace(f".l{lim}", "") lim = int(lim) if lim <= 0: lim = int(5) @@ -150,7 +150,7 @@ async def gsearch(q_event): if BOTLOG: await q_event.client.send_message( BOTLOG_CHATID, - "Google Search query `" + match + "` was executed successfully", + f"Google Search query `{match}` was executed successfully", ) @@ -332,7 +332,7 @@ async def google_search(event): event, "__Plox your search query exceeds 200 characters or you search query is empty.__", ) - query = "#12" + input + query = f"#12{input}" results = await event.client.inline_query("@StickerizerBot", query) await results[0].click(event.chat_id, reply_to=reply_to_id, hide_via=True) await event.delete() diff --git a/userbot/plugins/gps.py b/userbot/plugins/gps.py index 626f6e0..b94a42f 100644 --- a/userbot/plugins/gps.py +++ b/userbot/plugins/gps.py @@ -31,8 +31,7 @@ async def gps(event): input_str = event.pattern_match.group(1) dogevent = await eor(event, "`Finding...`") geolocator = Nominatim(user_agent="DogeUserBot") - geoloc = geolocator.geocode(input_str) - if geoloc: + if geoloc := geolocator.geocode(input_str): lon = geoloc.longitude lat = geoloc.latitude await event.client.send_file( diff --git a/userbot/plugins/groupactions.py b/userbot/plugins/groupactions.py index f97a416..bcac07a 100644 --- a/userbot/plugins/groupactions.py +++ b/userbot/plugins/groupactions.py @@ -304,8 +304,9 @@ async def rm_deletedacc(show): # sourcery no-metrics ) await sleep(e.seconds + 5) await event.edit( - f"__Ok the wait is over .I am cleaning all deleted accounts in this group__" + "__Ok the wait is over .I am cleaning all deleted accounts in this group__" ) + except UserAdminInvalidError: del_a += 1 except Exception as e: @@ -342,8 +343,9 @@ async def rm_deletedacc(show): # sourcery no-metrics ) await sleep(e.seconds + 5) await event.edit( - f"__Ok the wait is over .I am cleaning all deleted accounts in restricted or banned users list in this group__" + "__Ok the wait is over .I am cleaning all deleted accounts in restricted or banned users list in this group__" ) + except Exception as e: LOGS.error(str(e)) del_a += 1 diff --git a/userbot/plugins/speedtest.py b/userbot/plugins/speedtest.py index 594be3b..93adcbb 100644 --- a/userbot/plugins/speedtest.py +++ b/userbot/plugins/speedtest.py @@ -16,7 +16,7 @@ def convert_from_bytes(size): - power = 2 ** 10 + power = 2**10 n = 0 units = {0: "", 1: "Kbps", 2: "Mbps", 3: "Gbps", 4: "Tbps"} while size > power: