From 72c7d3b221a4dd3f187ea776512e0098c624a085 Mon Sep 17 00:00:00 2001 From: Sourcery AI <> Date: Sun, 27 Feb 2022 22:51:55 +0000 Subject: [PATCH 1/2] 'Refactored by Sourcery' --- bin/cmrudl.py | 7 +- sample_config.py | 5 +- userbot/__init__.py | 11 +- userbot/__main__.py | 2 +- userbot/assistant/botcontrols.py | 19 +- userbot/assistant/botmanagers.py | 16 +- userbot/assistant/botpm.py | 298 ++++++++++++----------- userbot/assistant/buttonmaker.py | 2 +- userbot/assistant/iyoutube.py | 24 +- userbot/assistant/sendbot.py | 17 +- userbot/assistant/settings.py | 103 ++++---- userbot/core/client.py | 10 +- userbot/core/cmdinfo.py | 10 +- userbot/core/decorators.py | 20 +- userbot/core/events.py | 9 +- userbot/core/inlinebot.py | 94 ++----- userbot/core/managers.py | 2 +- userbot/helpers/functions/calculate.py | 9 +- userbot/helpers/functions/functions.py | 22 +- userbot/helpers/functions/imgtools.py | 8 +- userbot/helpers/functions/jikan.py | 30 +-- userbot/helpers/functions/nekos.py | 3 +- userbot/helpers/functions/utils.py | 2 +- userbot/helpers/functions/utube.py | 46 ++-- userbot/helpers/google_image_download.py | 60 ++--- userbot/helpers/memeshelper.py | 3 +- userbot/helpers/nsfw.py | 2 +- userbot/helpers/progress.py | 24 +- userbot/helpers/utils/events.py | 8 +- userbot/helpers/utils/format.py | 8 +- userbot/helpers/utils/paste.py | 10 +- userbot/plugins/admin.py | 5 +- userbot/plugins/afk.py | 20 +- userbot/plugins/alive.py | 2 +- userbot/plugins/android.py | 18 +- userbot/plugins/antispambot.py | 3 +- userbot/plugins/app.py | 6 +- userbot/plugins/archive.py | 10 +- userbot/plugins/autoprofile.py | 12 +- userbot/plugins/blacklistwords.py | 2 +- userbot/plugins/carbon.py | 2 +- userbot/plugins/climate.py | 10 +- userbot/plugins/contacts.py | 7 +- userbot/plugins/corecmds.py | 276 ++++++++++----------- userbot/plugins/countries.py | 30 +-- userbot/plugins/custom.py | 150 ++++++------ userbot/plugins/dictionary.py | 26 +- userbot/plugins/download.py | 11 +- userbot/plugins/evaluators.py | 6 +- userbot/plugins/feds.py | 45 ++-- userbot/plugins/ffmpeg.py | 2 +- userbot/plugins/figlet.py | 3 +- userbot/plugins/fileconverts.py | 21 +- userbot/plugins/filesummary.py | 15 +- userbot/plugins/filters.py | 33 ++- userbot/plugins/gdrive.py | 28 ++- 56 files changed, 774 insertions(+), 853 deletions(-) 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 30a9ead..9ad9086 100644 --- a/sample_config.py +++ b/sample_config.py @@ -19,6 +19,8 @@ from telethon.tl.types import ChatBannedRights + + class Config(object): LOGGER = True @@ -56,7 +58,7 @@ class Config(object): DOGEPLUGIN = os.environ.get("DOGEPLUGIN", False) DOGEHUB = os.environ.get("DOGEHUB", False) # 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".") @@ -101,6 +103,7 @@ class Config(object): BOTLOG_CHATID = 0 + class Production(Config): LOGGER = False diff --git a/userbot/__init__.py b/userbot/__init__.py index 0fd3ae5..a49d433 100644 --- a/userbot/__init__.py +++ b/userbot/__init__.py @@ -21,7 +21,7 @@ __version__ = "1.0" __license__ = "🔐 GNU Affero Genel Kamu Lisansı v3.0" __author__ = "DOG-E < https://github.com/DOG-E/DogeUserBot >" -__copyright__ = "©️ Copyright 2021, " + __author__ +__copyright__ = f"©️ Copyright 2021, {__author__}" doge.version = __version__ if gvar("BOT_TOKEN"): @@ -61,15 +61,10 @@ 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)) - - -if gvar("TAG_LOGGER_GROUP_ID"): - TAG_LOGGER_GROUP = gvar("TAG_LOGGER_GROUP_ID") -else: - TAG_LOGGER_GROUP = Config.PM_LOGGER_GROUP_ID + Config.PM_LOGGER_GROUP_ID = int(f"-{str(Config.PM_LOGGER_GROUP_ID)}") +TAG_LOGGER_GROUP = gvar("TAG_LOGGER_GROUP_ID") or Config.PM_LOGGER_GROUP_ID # HEROKU: try: if Config.HEROKU_API_KEY is not None or Config.HEROKU_APP_NAME is not None: diff --git a/userbot/__main__.py b/userbot/__main__.py index b67902b..56434f5 100644 --- a/userbot/__main__.py +++ b/userbot/__main__.py @@ -87,7 +87,7 @@ async def startup_process(): LOGS.info("🐶 %100 ~ DOGE USERBOT HAZIR!\n\n\n\n\n\n\n") LOGS.info(userbot.__copyright__) - LOGS.info(userbot.__license__ + " ile korunmaktadır.") + LOGS.info(f'{userbot.__license__} ile korunmaktadır.') LOGS.info( f"\ \n➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\ diff --git a/userbot/assistant/botcontrols.py b/userbot/assistant/botcontrols.py index 4a823af..8b9d8ea 100644 --- a/userbot/assistant/botcontrols.py +++ b/userbot/assistant/botcontrols.py @@ -200,14 +200,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) @@ -215,7 +217,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ı {gvar('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) @@ -252,8 +254,7 @@ async def ban_botpms(event): if user_id == int(gvar("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 93596c6..643fc49 100644 --- a/userbot/assistant/botmanagers.py +++ b/userbot/assistant/botmanagers.py @@ -50,16 +50,12 @@ def progress_str(total: int, current: int) -> str: "Progress", percentage, "".join( - ( - (gvar("FINISHED_PROGRESS_STR") or "▰") - for i in range(floor(percentage / 5)) - ) + (gvar("FINISHED_PROGRESS_STR") or "▰") + for _ in range(floor(percentage / 5)) ), "".join( - ( - (gvar("UNFINISHED_PROGRESS_STR") or "▱") - for i in range(20 - floor(percentage / 5)) - ) + (gvar("UNFINISHED_PROGRESS_STR") or "▱") + for _ in range(20 - floor(percentage / 5)) ), ) @@ -88,8 +84,8 @@ async def unban_user_from_bot(user, reason, reply_to=None): rem_user_from_bl(user.id) except Exception as e: LOGS.error(f"🚨 {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.bot.send_message(user.id, banned_msg) diff --git a/userbot/assistant/botpm.py b/userbot/assistant/botpm.py index ac43fab..f897d8a 100644 --- a/userbot/assistant/botpm.py +++ b/userbot/assistant/botpm.py @@ -292,11 +292,11 @@ async def bot_start(event): mention = f"[{chat.first_name}](tg://user?id={userid})" my_mention = gvar("mention") 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 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 customstrmsg = gvar("START_TEXT") or None @@ -455,172 +455,181 @@ async def bot_start(event): @doge.shiba_cmd(incoming=True, func=lambda e: e.is_private) async def bot_pms(event): # sourcery no-metrics - if gvar("BOT_PM") != "False": - chat = await event.get_chat() - if check_is_black_list(chat.id): + if gvar("BOT_PM") == "False": + return + chat = await event.get_chat() + if check_is_black_list(chat.id): + return + if chat.id != int(gvar("OWNER_ID")): + msg = await event.forward_to(int(gvar("OWNER_ID"))) + try: + add_user_to_db(msg.id, get_display_name(chat), chat.id, event.id, 0, 0) + except Exception as e: + LOGS.error(f"🚨 {str(e)}") + if BOTLOG: + await doge.bot.send_message( + BOTLOG_CHATID, + f"**🚨 Hᴀᴛᴀ:**\n`ℹ️ Mesaj detaylarını veritabanında saklarken bir hata oluştu.`\ + \n➡️ `{str(e)}`", + ) + else: + if event.text.startswith("/"): return - if chat.id != int(gvar("OWNER_ID")): - msg = await event.forward_to(int(gvar("OWNER_ID"))) + reply_to = await reply_id(event) + if reply_to is None: + return + users = get_user_id(reply_to) + if users is None: + return + for usr in users: + user_id = int(usr.chat_id) + reply_msg = usr.reply_id + user_name = usr.first_name + break + if user_id is not None: try: - add_user_to_db(msg.id, get_display_name(chat), chat.id, event.id, 0, 0) + if event.media: + msg = await event.client.send_file( + user_id, event.media, caption=event.text, reply_to=reply_msg + ) + else: + msg = await event.client.send_message( + user_id, event.text, reply_to=reply_msg, link_preview=False + ) + except UserIsBlockedError: + await doge(UnblockRequest(gvar("BOT_USERNAME"))) + if event.media: + msg = await event.client.send_file( + user_id, event.media, caption=event.text, reply_to=reply_msg + ) + else: + msg = await event.client.send_message( + user_id, event.text, reply_to=reply_msg, link_preview=False + ) + except Exception as e: + return await event.reply(f"**🚨 Hᴀᴛᴀ:**\n➡️ `{e}`") + try: + add_user_to_db( + reply_to, user_name, user_id, reply_msg, event.id, msg.id + ) except Exception as e: LOGS.error(f"🚨 {str(e)}") if BOTLOG: await doge.bot.send_message( BOTLOG_CHATID, f"**🚨 Hᴀᴛᴀ:**\n`ℹ️ Mesaj detaylarını veritabanında saklarken bir hata oluştu.`\ - \n➡️ `{str(e)}`", - ) - else: - if event.text.startswith("/"): - return - reply_to = await reply_id(event) - if reply_to is None: - return - users = get_user_id(reply_to) - if users is None: - return - for usr in users: - user_id = int(usr.chat_id) - reply_msg = usr.reply_id - user_name = usr.first_name - break - if user_id is not None: - try: - if event.media: - msg = await event.client.send_file( - user_id, event.media, caption=event.text, reply_to=reply_msg - ) - else: - msg = await event.client.send_message( - user_id, event.text, reply_to=reply_msg, link_preview=False - ) - except UserIsBlockedError: - await doge(UnblockRequest(gvar("BOT_USERNAME"))) - if event.media: - msg = await event.client.send_file( - user_id, event.media, caption=event.text, reply_to=reply_msg - ) - else: - msg = await event.client.send_message( - user_id, event.text, reply_to=reply_msg, link_preview=False - ) - except Exception as e: - return await event.reply(f"**🚨 Hᴀᴛᴀ:**\n➡️ `{e}`") - try: - add_user_to_db( - reply_to, user_name, user_id, reply_msg, event.id, msg.id - ) - except Exception as e: - LOGS.error(f"🚨 {str(e)}") - if BOTLOG: - await doge.bot.send_message( - BOTLOG_CHATID, - f"**🚨 Hᴀᴛᴀ:**\n`ℹ️ Mesaj detaylarını veritabanında saklarken bir hata oluştu.`\ \n➡️ `{e}`", - ) + ) @doge.shiba_cmd(edited=True) async def bot_pms_edit(event): # sourcery no-metrics - if gvar("BOT_PM") != "False": - chat = await event.get_chat() - if check_is_black_list(chat.id): + if gvar("BOT_PM") == "False": + return + chat = await event.get_chat() + if check_is_black_list(chat.id): + return + if chat.id != int(gvar("OWNER_ID")): + users = get_user_reply(event.id) + if users is None: return - if chat.id != int(gvar("OWNER_ID")): - users = get_user_reply(event.id) + if reply_msg := next( + ( + user.message_id + for user in users + if user.chat_id == str(chat.id) + ), + None, + ): + await event.client.send_message( + int(gvar("OWNER_ID")), + "**⬆️ Bu mesaj şu kullanıcı tarafından düzenlendi.** {} :\n".format( + _format.mentionuser(get_display_name(chat), chat.id) + ), + reply_to=reply_msg, + ) + msg = await event.forward_to(int(gvar("OWNER_ID"))) + try: + add_user_to_db( + msg.id, get_display_name(chat), chat.id, event.id, 0, 0 + ) + except Exception as e: + LOGS.error(f"🚨 {str(e)}") + if BOTLOG: + await doge.bot.send_message( + BOTLOG_CHATID, + f"**🚨 Hᴀᴛᴀ:**\n__ℹ️ Mesaj detaylarını veritabanında saklarken bir hata oluştu.__\ + \n➡️ `{e}`", + ) + else: + reply_to = await reply_id(event) + if reply_to is not None: + users = get_user_id(reply_to) + result_id = 0 if users is None: return - reply_msg = None - for user in users: - if user.chat_id == str(chat.id): - reply_msg = user.message_id + for usr in users: + if event.id == usr.logger_id: + user_id = int(usr.chat_id) + reply_msg = usr.reply_id + result_id = usr.result_id break - if reply_msg: - await event.client.send_message( - int(gvar("OWNER_ID")), - "**⬆️ Bu mesaj şu kullanıcı tarafından düzenlendi.** {} :\n".format( - _format.mentionuser(get_display_name(chat), chat.id) - ), - reply_to=reply_msg, - ) - msg = await event.forward_to(int(gvar("OWNER_ID"))) + if result_id != 0: try: - add_user_to_db( - msg.id, get_display_name(chat), chat.id, event.id, 0, 0 + await event.client.edit_message( + user_id, result_id, event.text, file=event.media ) except Exception as e: LOGS.error(f"🚨 {str(e)}") - if BOTLOG: - await doge.bot.send_message( - BOTLOG_CHATID, - f"**🚨 Hᴀᴛᴀ:**\n__ℹ️ Mesaj detaylarını veritabanında saklarken bir hata oluştu.__\ - \n➡️ `{e}`", - ) - else: - reply_to = await reply_id(event) - if reply_to is not None: - users = get_user_id(reply_to) - result_id = 0 - if users is None: - return - for usr in users: - if event.id == usr.logger_id: - user_id = int(usr.chat_id) - reply_msg = usr.reply_id - result_id = usr.result_id - break - if result_id != 0: - try: - await event.client.edit_message( - user_id, result_id, event.text, file=event.media - ) - except Exception as e: - LOGS.error(f"🚨 {str(e)}") @doge.bot.on(MessageDeleted) async def handler(event): - if gvar("BOT_PM") != "False": - for msg_id in event.deleted_ids: - users_1 = get_user_reply(msg_id) - users_2 = get_user_logging(msg_id) - if users_2 is not None: - result_id = 0 - for usr in users_2: - if msg_id == usr.logger_id: - user_id = int(usr.chat_id) - result_id = usr.result_id - break - if result_id != 0: - try: - await event.client.delete_messages(user_id, result_id) - except Exception as e: - LOGS.error(f"🚨 {str(e)}") - if users_1 is not None: - reply_msg = None - for user in users_1: - if user.chat_id != int(gvar("OWNER_ID")): - reply_msg = user.message_id - break + if gvar("BOT_PM") == "False": + return + for msg_id in event.deleted_ids: + users_1 = get_user_reply(msg_id) + users_2 = get_user_logging(msg_id) + if users_2 is not None: + result_id = 0 + for usr in users_2: + if msg_id == usr.logger_id: + user_id = int(usr.chat_id) + result_id = usr.result_id + break + if result_id != 0: try: - if reply_msg: - users = get_user_id(reply_msg) - for usr in users: - user_id = int(usr.chat_id) - user_name = usr.first_name - break - if check_is_black_list(user_id): - return - await event.client.send_message( - int(gvar("OWNER_ID")), - "**⬆️ Bu mesaj, {} tarafından asistan botun sohbetinden silindi!**".format( - _format.mentionuser(user_name, user_id) - ), - reply_to=reply_msg, - ) + await event.client.delete_messages(user_id, result_id) except Exception as e: LOGS.error(f"🚨 {str(e)}") + if users_1 is not None: + reply_msg = next( + ( + user.message_id + for user in users_1 + if user.chat_id != int(gvar("OWNER_ID")) + ), + None, + ) + + try: + if reply_msg: + users = get_user_id(reply_msg) + for usr in users: + user_id = int(usr.chat_id) + user_name = usr.first_name + break + if check_is_black_list(user_id): + return + await event.client.send_message( + int(gvar("OWNER_ID")), + "**⬆️ Bu mesaj, {} tarafından asistan botun sohbetinden silindi!**".format( + _format.mentionuser(user_name, user_id) + ), + reply_to=reply_msg, + ) + except Exception as e: + LOGS.error(f"🚨 {str(e)}") @doge.shiba_cmd(pattern="^/uinfo$", from_users=int(gvar("OWNER_ID"))) @@ -638,16 +647,18 @@ async def uinfo(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}`" @@ -658,13 +669,14 @@ async def send_flood_alert(user_) -> None: # sourcery no-metrics buttons = [ ( - Button.inline(f"🚫 Bᴀɴ", data=f"bot_pm_ban_{user_.id}"), + 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/buttonmaker.py b/userbot/assistant/buttonmaker.py index 1786765..2e72763 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(gvar("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/iyoutube.py b/userbot/assistant/iyoutube.py index 3e0a5ac..36f175b 100644 --- a/userbot/assistant/iyoutube.py +++ b/userbot/assistant/iyoutube.py @@ -75,9 +75,10 @@ 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( event, "**🔎 Şunun için YouTube'da arama yapıyorm:** `{}`...".format(input_url) ) @@ -99,7 +100,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.bot.on( @@ -272,7 +273,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 ) @@ -286,23 +287,16 @@ 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/sendbot.py b/userbot/assistant/sendbot.py index d0feee0..042dbc8 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.bot.send_file(chat, media, caption=reply_message.text) - else: - await doge.bot.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.bot.send_file(chat, media, caption=reply_message.text) + else: + await doge.bot.send_file(chat, media) + return await event.delete() + await doge.bot.send_message(chat, text, reply_to=reply_to_id) await event.delete() diff --git a/userbot/assistant/settings.py b/userbot/assistant/settings.py index 6468012..3c5e373 100644 --- a/userbot/assistant/settings.py +++ b/userbot/assistant/settings.py @@ -63,8 +63,9 @@ async def settings(event: CallbackQuery): ] if not event.is_private and event.chat_id == BOTLOG_CHATID: return await event.answer( - f"Bu ayarları yapabilmek için bana özelden yazmalısın!", alert=True + "Bu ayarları yapabilmek için bana özelden yazmalısın!", alert=True ) + elif not event.is_private: return else: @@ -335,7 +336,7 @@ async def TAG_LOGGER_OFF(event: CallbackQuery): elif gvar("GRPLOG") == "True": sgvar("GRPLOG", "False") return await event.answer( - f"🐶 Doɢᴇ UsᴇʀBoᴛ\n\n TAG loggerözelliğiniz başarıyla kapatıldı", + "🐶 Doɢᴇ UsᴇʀBoᴛ\\n\\n TAG loggerözelliğiniz başarıyla kapatıldı", alert=True, ) @@ -355,16 +356,20 @@ async def TAG_LOGGER_ON(event: CallbackQuery): ] if gvar("GRPLOG") == "True": return await event.answer( - f"🐶 Doɢᴇ UsᴇʀBoᴛ\n\n TAG Logger özelliğiniz zaten açık!", alert=True + "🐶 Doɢᴇ UsᴇʀBoᴛ\\n\\n TAG Logger özelliğiniz zaten açık!", + alert=True, ) + elif gvar("PM_LOGGER_GROUP_ID") is None and gvar("TAG_LOGGER_GROUP_ID") is None: await event.answer( - f"🐶 Doɢᴇ UsᴇʀBoᴛ\n\n TAG Logger özelliğini açmak için öncelikle bir grup ayarlamanız gerekir. Sizi grup ayarlama ekranına yönlendiriyorum..." + "🐶 Doɢᴇ UsᴇʀBoᴛ\\n\\n TAG Logger özelliğini açmak için öncelikle bir grup ayarlamanız gerekir. Sizi grup ayarlama ekranına yönlendiriyorum..." ) + await event.edit( - f"""🔔 **Etiketleri kaydetme grubunuzun Doge UserBot tarafından oluşturulmasını istiyorsanız** "`🕹 Otomatik`", **kendiniz ayarlamak istiyorsanız** "`🥏 Manüel`" **yazan butona tıklayın.**""", + """🔔 **Etiketleri kaydetme grubunuzun Doge UserBot tarafından oluşturulmasını istiyorsanız** "`🕹 Otomatik`", **kendiniz ayarlamak istiyorsanız** "`🥏 Manüel`" **yazan butona tıklayın.**""", buttons=buttons, ) + elif ( gvar("PM_LOGGER_GROUP_ID") is not None or gvar("TAG_LOGGER_GROUP_ID") is not None @@ -385,13 +390,16 @@ async def TAG_LOGGER_GROUP_AUTO(event: CallbackQuery): elif gvar("TAG_LOGGER_GROUP_ID") is not None: try: a = await doge.bot.send_message( - int(gvar("TAG_LOGGER_GROUP_ID")), f"Tag Logger Grubu Test Mesajı!" + int(gvar("TAG_LOGGER_GROUP_ID")), + "Tag Logger Grubu Test Mesajı!", ) + await a.delete() return await event.edit( - f"Tag Logger için zaten kayıtlı bir grubunuz var! Grup oluşturma işlemini iptal ediyorum", + "Tag Logger için zaten kayıtlı bir grubunuz var! Grup oluşturma işlemini iptal ediyorum", buttons=get_back_button("TAG_LOGGER_GROUP"), ) + except Exception as e: LOGS.warning( f"Tag Logger grubuna ulaşılamadı yeni grup açılıyor... Hata Raporu: {e}" @@ -457,7 +465,7 @@ async def PM_LOGGER_OFF(event): elif gvar("pmpermit") == "True": sgvar("HEROKULOGGER", "False") return await event.answer( - f"🐶 Doɢᴇ UsᴇʀBoᴛ\n\ PM Permit özelliğiniz başarıyla kapatıldı", + "🐶 Doɢᴇ UsᴇʀBoᴛ\\n\\ PM Permit özelliğiniz başarıyla kapatıldı", alert=True, ) @@ -477,17 +485,20 @@ async def PM_LOGGER_ON(event: CallbackQuery): ] if gvar("pmpermit") == "True": return await event.answer( - f"🐶 Doɢᴇ UsᴇʀBoᴛ\n\n PM Logger özelliğiniz zaten açık!", alert=True + "🐶 Doɢᴇ UsᴇʀBoᴛ\\n\\n PM Logger özelliğiniz zaten açık!", + alert=True, ) + elif gvar("PM_LOGGER_GROUP_ID") is not None and gvar("pmpermit") != "True": sgvar("pmpermit", True) return await event.answer("🐶 PM LOGGER değeriniz açıldı!", alert=True) elif gvar("PM_LOGGER_GROUP_ID") is None: await event.answer( - f"🐶 Doɢᴇ UsᴇʀBoᴛ\n\n PM Logger özelliğini açmak için öncelikle bir grup ayarlamanız gerekir. Sizi grup ayarlama ekranına yönlendiriyorum..." + "🐶 Doɢᴇ UsᴇʀBoᴛ\\n\\n PM Logger özelliğini açmak için öncelikle bir grup ayarlamanız gerekir. Sizi grup ayarlama ekranına yönlendiriyorum..." ) + await event.edit( - f"""💬 **PM için log grubunuzun Doge UserBot tarafından oluşturulmasını istiyorsanız** "`🕹 Otomatik`", **kendiniz ayarlamak istiyorsanız** "`🥏 Manüel`" **yazan butona tıklayın.**""", + """💬 **PM için log grubunuzun Doge UserBot tarafından oluşturulmasını istiyorsanız** "`🕹 Otomatik`", **kendiniz ayarlamak istiyorsanız** "`🥏 Manüel`" **yazan butona tıklayın.**""", buttons=buttons, ) @@ -504,13 +515,15 @@ async def PM_LOGGER_GROUP_AUTO(event: CallbackQuery): elif gvar("PM_LOGGER_GROUP_ID") is not None: try: a = await doge.bot.send_message( - int(gvar("PM_LOGGER_GROUP_ID")), f"PM Logger Grubu Test Mesajı!" + int(gvar("PM_LOGGER_GROUP_ID")), "PM Logger Grubu Test Mesajı!" ) + await a.delete() return await event.edit( - f"PM Logger için zaten kayıtlı bir grubunuz var! Grup oluşturma işlemini iptal ediyorum", + "PM Logger için zaten kayıtlı bir grubunuz var! Grup oluşturma işlemini iptal ediyorum", buttons=get_back_button("PM_LOGGER_GROUP"), ) + except Exception as e: LOGS.warning( f"PM Logger grubuna ulaşılamadı yeni grup açılıyor... Hata Raporu: {e}" @@ -735,7 +748,9 @@ async def hlogger(event): ], ] buttons.append(get_back_button("sscg")) - await event.edit(f"Heroku Logger özelliği menünüzü özelleştirin.", buttons=buttons) + await event.edit( + "Heroku Logger özelliği menünüzü özelleştirin.", buttons=buttons + ) # heroku logger özelliğini kapatma işlemi @@ -748,7 +763,7 @@ async def hgloggeroff(event): if gvar("HEROKULOOGER") == "True": sgvar("HEROKULOGGER", "False") return await event.answer( - f"🐶 Doɢᴇ UsᴇʀBoᴛ\n\ Heroku Logger özelliğiniz başarıyla kapatıldı", + "🐶 Doɢᴇ UsᴇʀBoᴛ\\n\\ Heroku Logger özelliğiniz başarıyla kapatıldı", alert=True, ) @@ -770,20 +785,24 @@ async def hgloggeron(event: CallbackQuery): # return await event.answer("Bir geliştirici değilsiniz.", alert=True) if gvar("HEROKULOGGER") == "True": return await event.answer( - f"🐶 Doɢᴇ UsᴇʀBoᴛ\n\n Heroku Logger özelliğiniz zaten açık!", alert=True + "🐶 Doɢᴇ UsᴇʀBoᴛ\\n\\n Heroku Logger özelliğiniz zaten açık!", + alert=True, ) + if gvar("HLOGGER_ID") is None and gvar("HEROKULOGGER") == "False": await event.answer( - f"🐶 Doɢᴇ UsᴇʀBoᴛ\n\n Heroku Logger özelliğini açmak için öncelikle bir grup ayarlamanız gerekir. Sizi grup ayarlama ekranına yönlendiriyorum..." + "🐶 Doɢᴇ UsᴇʀBoᴛ\\n\\n Heroku Logger özelliğini açmak için öncelikle bir grup ayarlamanız gerekir. Sizi grup ayarlama ekranına yönlendiriyorum..." ) + await event.edit( - f'📑 **Heroku log grubunuzun Doge UserBot tarafından oluşturulmasını istiyorsanız** "`🕹 Otomatik`", **kendiniz ayarlamak istiyorsanız** "`🥏 Manüel`" **yazan butona tıklayın.**', + '📑 **Heroku log grubunuzun Doge UserBot tarafından oluşturulmasını istiyorsanız** "`🕹 Otomatik`", **kendiniz ayarlamak istiyorsanız** "`🥏 Manüel`" **yazan butona tıklayın.**', buttons=buttons, ) + if gvar("HEROKULOGGER") == "False" and gvar("HLOOGER_ID") is not None: sgvar("HEROKLOGGER", "True") await event.answer( - f"🐶 Doɢᴇ UsᴇʀBoᴛ\n\n Heroku Logger özelliğiniz başarıyla etkinleştirildi! Veritabanına kayıtlı gruba Heroku Log eylemi başlatılacaktır." + "🐶 Doɢᴇ UsᴇʀBoᴛ\\n\\n Heroku Logger özelliğiniz başarıyla etkinleştirildi! Veritabanına kayıtlı gruba Heroku Log eylemi başlatılacaktır." ) @@ -801,7 +820,7 @@ async def hgloggrpc(event: CallbackQuery): ], ] await event.edit( - f'📑 **Heroku log grubunuzun Doge UserBot tarafından oluşturulmasını istiyorsanız** "`🕹 Otomatik`", **kendiniz ayarlamak istiyorsanız** "`🥏 Manüel`" **yazan butona tıklayın.**', + '📑 **Heroku log grubunuzun Doge UserBot tarafından oluşturulmasını istiyorsanız** "`🕹 Otomatik`", **kendiniz ayarlamak istiyorsanız** "`🥏 Manüel`" **yazan butona tıklayın.**', buttons=buttons, ) @@ -820,13 +839,15 @@ async def hgloggerautocreate(event: CallbackQuery): elif gvar("HLOGGER_ID") is not None: try: a = await doge.bot.send_message( - int(gvar("HLOGGER_ID")), f"Heroku Logger Grubu Test Mesajı!" + int(gvar("HLOGGER_ID")), "Heroku Logger Grubu Test Mesajı!" ) + await a.delete() return await event.edit( - f"Heroku Logger için zaten kayıtlı bir grubunuz var! Grup oluşturma işlemini iptal ediyorum", + "Heroku Logger için zaten kayıtlı bir grubunuz var! Grup oluşturma işlemini iptal ediyorum", buttons=get_back_button("hgloggrpc"), ) + except Exception as e: LOGS.warning( f"Heroku Logger grubuna ulaşılamadı yeni grup açılıyor... Hata Raporu: {e}" @@ -851,9 +872,7 @@ async def fggroup(event: CallbackQuery): ], ] await event.edit( - f"""✅ **Rose için Fban grup ayarları!** - -**Fban grubunuzun Doge UserBot tarafından oluşturulmasını istiyorsanız** "`c`", **kendiniz ayarlamak istiyorsanız** "`🥏 Manüel`" **yazan butona tıklayın.**""", + """✅ **Rose için Fban grup ayarları!**\x1f\x1f**Fban grubunuzun Doge UserBot tarafından oluşturulmasını istiyorsanız** "`c`", **kendiniz ayarlamak istiyorsanız** "`🥏 Manüel`" **yazan butona tıklayın.**""", buttons=buttons, link_preview=False, ) @@ -875,9 +894,10 @@ async def fggrupcreate(event: CallbackQuery): ) await a.delete() return await event.edit( - f"FBan için zaten bir grubunuz var! Grup oluşturma işlemini iptal ediyorum...", + "FBan için zaten bir grubunuz var! Grup oluşturma işlemini iptal ediyorum...", buttons=get_back_button("fgroup"), ) + except Exception: await event.edit( f"{gvar('mention')} Veritabanına kayıtlı grubunuza erişiminiz yok. Sizin için bir FBan grubu oluşturuyorum! Lütfen bekleyin..." @@ -899,7 +919,7 @@ async def pccreate(event: CallbackQuery): ], ] await event.edit( - f"__Gizli kanalınız için DogeUserBot tarafından oluştulurulmasını isterseniz__ '✅ Evet' __düğmesine, kendiniz oluşturduğunuz bir grubu ayarlamak için__ '❎ Hayır' __düğmesine basınız.__", + "__Gizli kanalınız için DogeUserBot tarafından oluştulurulmasını isterseniz__ '✅ Evet' __düğmesine, kendiniz oluşturduğunuz bir grubu ayarlamak için__ '❎ Hayır' __düğmesine basınız.__", buttons=buttons, ) @@ -911,13 +931,15 @@ async def pcmanuel(event: CallbackQuery): if gvar("PRIVATE_CHANNEL_ID") is not None: try: a = await doge.send_message( - int(gvar("PRIVATE_CHANNEL_ID")), f"Gizli kanal Deneme mesajı!" + int(gvar("PRIVATE_CHANNEL_ID")), "Gizli kanal Deneme mesajı!" ) + await a.delete() return await event.edit( - f"Gizli Kanal özelliği için zaten hazırda bi kanalınız var! Yeni kanal açma işlemini iptal ediyorum.", + "Gizli Kanal özelliği için zaten hazırda bi kanalınız var! Yeni kanal açma işlemini iptal ediyorum.", buttons=get_back_button("pccreate"), ) + except Exception as e: LOGS.warning( f"Gizli kanala erişim sağlanamadı yeni kanal açılıyor... Hata Raporu: {e}" @@ -933,7 +955,7 @@ async def pcmanuel(event: CallbackQuery): ) if gvar("PRIVATE_CHANNEL_ID") is None: await event.edit( - f"Veritabanında kayıtlı bir Gizli Kanal değeri bulunamadı! Sizin için yeni bir Gizli Kanal oluşturuyoruM! Lütfen bekleyin..." + "Veritabanında kayıtlı bir Gizli Kanal değeri bulunamadı! Sizin için yeni bir Gizli Kanal oluşturuyoruM! Lütfen bekleyin..." ) @@ -1638,20 +1660,14 @@ async def herokuloggergroupcreate(event: CallbackQuery): # GİZLİ KANAL İÇİN OTOMATİK KANAL AÇMA İŞLEMİ async def privatechannel(event: CallbackQuery): - descript = f"🚧 BU KANALI SİLMEYİN!\n\ - \n🗑 Eğer bu kanalı silerseniz,\ - \n🐾 Kaydederek iletme özelliği çalışmayacaktır.\n\ - \n🧡 @DogeUserBot" + descript = "🚧 BU KANALI SİLMEYİN!\\n\\\x1f \\n🗑 Eğer bu kanalı silerseniz,\\\x1f \\n🐾 Kaydederek iletme özelliği çalışmayacaktır.\\n\\\x1f \\n🧡 @DogeUserBot" + gphoto = await doge.upload_file(file="userbot/helpers/resources/DogeBotLog.jpg") await sleep(0.75) _, channelid = await create_channel("🐾 Doɢᴇ Gɪzʟɪ Kᴀɴᴀʟ", doge, descript, gphoto) await sleep(0.75) - descmsg = f"**🚧 BU KANALI SİLMEYİN!\ - \n🚧 BU KANALDAN AYRILMAYIN!\ - \n🚧 BU KANALI DEĞİŞTİRMEYİN!**\n\ - \n🗑 Eğer bu kanalı silerseniz,\ - \n🐾 Kaydederek iletme özelliği çalışmayacaktır!\n\ - \n**🧡 @DogeUserBot**" + descmsg = "**🚧 BU KANALI SİLMEYİN!\\\x1f \\n🚧 BU KANALDAN AYRILMAYIN!\\\x1f \\n🚧 BU KANALI DEĞİŞTİRMEYİN!**\\n\\\x1f \\n🗑 Eğer bu kanalı silerseniz,\\\x1f \\n🐾 Kaydederek iletme özelliği çalışmayacaktır!\\n\\\x1f \\n**🧡 @DogeUserBot**" + msg = await doge.send_message(channelid, descmsg) await sleep(0.25) await msg.pin() @@ -1832,9 +1848,10 @@ async def ss(event: CallbackQuery, x, y, z=None): if "PIC" in y: rpic = response.message try: - if (type(rpic.media) == MessageMediaDocument) or ( - type(rpic.media) == MessageMediaPhoto - ): + if type(rpic.media) in [ + MessageMediaDocument, + MessageMediaPhoto, + ]: downloaded_file_name = await event.client.download_media( rpic, TEMP_DIR ) diff --git a/userbot/core/client.py b/userbot/core/client.py index f75045e..22518df 100644 --- a/userbot/core/client.py +++ b/userbot/core/client.py @@ -211,11 +211,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 bunu bildirebilirisiniz.__" text += "\n\n" text += "🐾 Bu mesajı {} iletin.".format(link) @@ -351,11 +350,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 bunu bildirebilirisiniz.__" text += "\n\n" text += "🐾 Bu mesajı {} iletin.".format(link) diff --git a/userbot/core/cmdinfo.py b/userbot/core/cmdinfo.py index d63dcbd..6f28768 100644 --- a/userbot/core/cmdinfo.py +++ b/userbot/core/cmdinfo.py @@ -44,7 +44,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()}__" @@ -53,7 +53,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()}__" @@ -62,7 +62,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}` ," @@ -71,7 +71,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_}`" @@ -80,7 +80,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/decorators.py b/userbot/core/decorators.py index 6451884..492a55d 100644 --- a/userbot/core/decorators.py +++ b/userbot/core/decorators.py @@ -42,17 +42,17 @@ async def wrapper(c_q: CallbackQuery): def sudo_owner(func): async def wrapper(event): - if event.sender_id and ( - event.sender_id == int(gvar("OWNER_ID")) - or event.sender_id in Config.SUDO_USERS + if ( + not event.sender_id + or event.sender_id != int(gvar("OWNER_ID")) + and event.sender_id not in Config.SUDO_USERS ): - try: - await func(event) - except FloodWaitError as e: - await sleep(e.seconds + 5) - except MessageNotModifiedError: - pass - else: return + try: + await func(event) + except FloodWaitError as e: + await sleep(e.seconds + 5) + except MessageNotModifiedError: + pass return wrapper diff --git a/userbot/core/events.py b/userbot/core/events.py index 5cef0be..88827a1 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 @@ -377,16 +377,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, @@ -397,6 +397,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/inlinebot.py b/userbot/core/inlinebot.py index 176eb56..0e4c71c 100644 --- a/userbot/core/inlinebot.py +++ b/userbot/core/inlinebot.py @@ -48,14 +48,7 @@ def back_menu(back): text = f"**🐶 Doɢᴇ UsᴇʀBoᴛ\ \n🐾 Yᴀʀᴅıᴍᴄı\n\ \n◽ Doɢᴇ oғ {gvar('mention')}**" - buttons = [ - ( - Button.inline( - f"ℹ️️ Bɪʟɢɪ", - data="check", - ), - ), - ( + buttons = [(Button.inline("ℹ️️ Bɪʟɢɪ", data="check"), ), ( Button.inline( f"👮‍♂️ Aᴅᴍɪɴ ({len(GRP_INFO['admin'])})", data="admin_menu", @@ -64,8 +57,7 @@ def back_menu(back): f"🐶 Doɢᴇ ({len(GRP_INFO['bot'])})", data="bot_menu", ), - ), - ( + ), ( Button.inline( f"🎈 Eɢ̆ʟᴇɴᴄᴇ ({len(GRP_INFO['fun'])})", data="fun_menu", @@ -74,8 +66,7 @@ def back_menu(back): f"🪀 Çᴇşɪᴛʟɪ ({len(GRP_INFO['misc'])})", data="misc_menu", ), - ), - ( + ), ( Button.inline( f"🧰 Aʀᴀç ({len(GRP_INFO['tool'])})", data="tool_menu", @@ -84,8 +75,7 @@ def back_menu(back): f"🍑 Hᴜʙ ({len(GRP_INFO['hub'])})", data="hub_menu", ), - ), - ] + )] buttons.append(get_back_button(back)) return text, buttons @@ -94,14 +84,7 @@ def main_menu(): text = f"**🐶 Doɢᴇ UsᴇʀBoᴛ\ \n🐾 Yᴀʀᴅıᴍᴄı\n\ \n◽ Doɢᴇ oғ {gvar('mention')}**" - buttons = [ - ( - Button.inline( - f"ℹ️️ Bɪʟɢɪ", - data="check", - ), - ), - ( + buttons = [(Button.inline("ℹ️️ Bɪʟɢɪ", data="check"), ), ( Button.inline( f"👮‍♂️ Aᴅᴍɪɴ ({len(GRP_INFO['admin'])})", data="admin_menu", @@ -110,8 +93,7 @@ def main_menu(): f"🐶 Doɢᴇ ({len(GRP_INFO['bot'])})", data="bot_menu", ), - ), - ( + ), ( Button.inline( f"🎈 Eɢ̆ʟᴇɴᴄᴇ ({len(GRP_INFO['fun'])})", data="fun_menu", @@ -120,8 +102,7 @@ def main_menu(): f"🪀 Çᴇşɪᴛʟɪ ({len(GRP_INFO['misc'])})", data="misc_menu", ), - ), - ( + ), ( Button.inline( f"🧰 Aʀᴀç ({len(GRP_INFO['tool'])})", data="tool_menu", @@ -130,14 +111,7 @@ def main_menu(): f"🍑 Hᴜʙ ({len(GRP_INFO['hub'])})", data="hub_menu", ), - ), - ( - Button.inline( - f"⛔ KAPAT ⛔", - data="close", - ), - ), - ] + ), (Button.inline("⛔ KAPAT ⛔", data="close"), )] return text, buttons @@ -253,39 +227,25 @@ def paginate_help( modulo_page = page_number % max_num_pages if plugins: if len(pairs) > number_of_rows: - pairs = pairs[ + pairs = (pairs[ modulo_page * number_of_rows : number_of_rows * (modulo_page + 1) - ] + [ - ( - Button.inline( + ] + [(Button.inline( "⏪", data=f"{prefix}_prev({modulo_page})_plugin", - ), - Button.inline( - f"🐾 Mᴇɴᴜ", - data="mainmenu", - ), - Button.inline( + ), 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: if category_pgno < 0: category_pgno = len(pairs) + category_pgno @@ -304,33 +264,29 @@ 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"), ), ] + else: if category_pgno < 0: category_pgno = len(pairs) + category_pgno 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 d7de6c7..2c0834f 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..4387105 100644 --- a/userbot/helpers/functions/calculate.py +++ b/userbot/helpers/functions/calculate.py @@ -28,14 +28,13 @@ async def calcc(cmd, event, text=None): 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 3264506..fc8a475 100644 --- a/userbot/helpers/functions/functions.py +++ b/userbot/helpers/functions/functions.py @@ -63,7 +63,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 @@ -78,7 +78,7 @@ async def get_moviecollections(movie): for i in movie["box office"].keys(): result += f"\n• {i}: {movie['box office'][i]}" else: - result = f"Veri Yok!" + result = "Veri Yok!" return result @@ -86,13 +86,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"]) @@ -119,7 +119,7 @@ def getSimilarWords(wordx, limit=5): # 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) @@ -136,7 +136,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: @@ -146,13 +146,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 a99cdd3..5a2e3f0 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**Tip:** {jsonData['format']}" - msg += f"\n**Çeşitler:** " + msg += "\\n**Çeşitler:** " for g in jsonData["genres"]: - msg += g + " " + msg += f'{g} ' msg += f"\n**Durum:** {jsonData['status']}" msg += f"\n**Bölümler:** {jsonData['episodes']}" msg += f"\n**Yıl:** {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**Açıklama:**\n{description} [Devamını Oku]({info})" else: msg += f"\n**Açıklama:** \n {description}" @@ -258,8 +258,7 @@ async def anilist_user(input_str): "Kullanıcı Detaylarını Anilist'den Alın" 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"][ - "bannerImage" - ] - if image: + if image := post("https://graphql.anilist.co", json=data).json()["data"][ + "Media" + ]["bannerImage"]: 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"🎬 Fragman" else: - TRAILER = f"🎬 Fragman Yok" + TRAILER = "🎬 Fragman Yok" 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"

Özet:

" + html_pc += "

Özet:

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

Ana karakterler:

" + html_pc += "

Ana karakterler:

" html_pc += html_char html_pc += "

" - html_pc += f"

Daha fazla bilgi:

" + html_pc += "

Daha fazla bilgi:

" html_pc += f"
Stüdyolar: {studios}
" html_pc += f"MAL'da görüntüle" html_pc += f"anilist.com'da göster" 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 dd69d5f..6be2449 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 9a3fa25..2f66af4 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 @@ -69,7 +69,7 @@ async def ytsearch(query, limit): try: textresult += f"**◽ Açıᴋʟᴀᴍᴀ:** `{v['descriptionSnippet'][-1]['text']}`\n" except Exception: - textresult += f"**◽ Açıᴋʟᴀᴍᴀ:** `None`\n" + textresult += "**◽ Açıᴋʟᴀᴍᴀ:** `None`\\n" textresult += f"**⏱ Süʀᴇ:** __{v['duration']}__ **◾ İzʟᴇɴᴍᴇ:** __{v['viewCount']['short']}__\n" result += f"📺 {textresult}\n" return result @@ -99,7 +99,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()) @@ -124,9 +124,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) @@ -135,16 +133,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 @@ -167,7 +165,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( @@ -186,8 +184,7 @@ def yt_search_btns( buttons = [ [ Button.inline( - text=f"⬅️️ Gᴇʀɪ", - data=f"ytdl_back_{data_key}_{page}", + text="⬅️️ Gᴇʀɪ", data=f"ytdl_back_{data_key}_{page}" ), Button.inline( text=f"🔹 {page} - {total} 🔹", @@ -196,15 +193,13 @@ def yt_search_btns( ], [ Button.inline( - text=f"📜 Hᴇᴘsɪɴɪ Lɪsᴛᴇʟᴇ", + text="📜 Hᴇᴘsɪɴɪ Lɪsᴛᴇʟᴇ", data=f"ytdl_listall_{data_key}_{page}", ), - Button.inline( - text=f"📥 İɴᴅɪʀ", - data=f"ytdl_download_{vid}_0", - ), + Button.inline(text="📥 İɴᴅɪʀ", data=f"ytdl_download_{vid}_0"), ], ] + if del_back: buttons[0].pop(0) return buttons @@ -220,14 +215,16 @@ def download_button(vid: str, body: bool = False): # sourcery no-metrics vid_data = {"formats": []} buttons = [ [ - Button.inline(f"🌟 Eɴ İʏɪsɪ - 🎞 ᴍᴋᴠ", data=f"ytdl_download_{vid}_mkv_v"), Button.inline( - f"🌟 Eɴ İʏɪsɪ - 🎞 ᴡᴇʙᴍ/ᴍᴘ4", - data=f"ytdl_download_{vid}_mp4_v", + "🌟 Eɴ İʏɪsɪ - 🎞 ᴍᴋᴠ", data=f"ytdl_download_{vid}_mkv_v" + ), + Button.inline( + "🌟 Eɴ İʏɪsɪ - 🎞 ᴡᴇʙᴍ/ᴍᴘ4", data=f"ytdl_download_{vid}_mp4_v" ), ] ] + qual_dict = defaultdict(lambda: defaultdict(int)) qual_list = ["144p", "240p", "360p", "480p", "720p", "1080p", "1440p"] audio_dict = {} @@ -237,7 +234,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,11 +259,12 @@ def download_button(vid: str, body: bool = False): # sourcery no-metrics buttons += [ [ Button.inline( - f"🌟 Eɴ İʏɪsɪ - 🎵 ᴍᴘ3 - 320ᴋʙᴘs", + "🌟 Eɴ İʏɪ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") @@ -306,7 +304,7 @@ def _tubeDl(url: str, starttime, uid: str): except DownloadError as e: LOGS.error(f"🚨 {e}") except GeoRestrictedError: - LOGS.error(f"**🚨 Hᴀᴛᴀ:** Bu video ülkenizde mevcut değil.") + LOGS.error("**🚨 Hᴀᴛᴀ:** Bu video ülkenizde mevcut değil.") else: return x diff --git a/userbot/helpers/google_image_download.py b/userbot/helpers/google_image_download.py index 6617e90..c746017 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 = ( @@ -1075,13 +1069,11 @@ def download_image_thumbnail( ) download_status = "success" - download_message = ( - "Completed Image Thumbnail ====> " + return_image_name - ) + download_message = 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 +1448,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 8693b55..7091530 100644 --- a/userbot/helpers/progress.py +++ b/userbot/helpers/progress.py @@ -56,7 +56,7 @@ def humanbytes(size: int) -> str: 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] @@ -84,7 +85,7 @@ def afk_time(seconds, short=True): + ((str(minutes) + (" dakika, " if not short else "dk, ")) if minutes else "") + ((str(seconds) + (" saniye, " if not short else "s, ")) if seconds else "") ) - return tmp[:-2] + " önce" + return f'{tmp[:-2]} önce' def readable_time(seconds: int) -> str: @@ -92,9 +93,9 @@ 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") ) @@ -162,14 +163,15 @@ async def progress( status, "".join( (gvar("FINISHED_PROGRESS_STR") or "▰") - for i in range(floor(percentage / 5)) + for _ in range(floor(percentage / 5)) ), "".join( (gvar("UNFINISHED_PROGRESS_STR") or "▱") - 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/utils/events.py b/userbot/helpers/utils/events.py index c45923f..8ac09e8 100644 --- a/userbot/helpers/utils/events.py +++ b/userbot/helpers/utils/events.py @@ -124,7 +124,7 @@ async def get_chatinfo(event, dogevent): LOGS.info( f"Yürütülen işlem için kanal veya grup ID mevcut değil! HATA: {err}" ) - await edl(dogevent, f"**🚨 HATA:**\n`ℹ️ Sohbeti alamadım!`") + await edl(dogevent, "**🚨 HATA:**\\n`ℹ️ Sohbeti alamadım!`") return None return chat_info @@ -145,7 +145,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: @@ -192,9 +192,7 @@ async def checking(doge): def only_botlog(event): - if str(event.chat_id) == gvar("PRIVATE_GROUP_BOT_API_ID"): - return True - return False + return str(event.chat_id) == gvar("PRIVATE_GROUP_BOT_API_ID") async def wowmygroup(event, msg): diff --git a/userbot/helpers/utils/format.py b/userbot/helpers/utils/format.py index bbd4be1..c9d62c5 100644 --- a/userbot/helpers/utils/format.py +++ b/userbot/helpers/utils/format.py @@ -71,7 +71,7 @@ def parse_pre(text): # Based on TLObject.pretty_format -def yaml_format(obj, indent=0, max_str_len=256, max_byte_len=64): # sourcery no-metrics +def yaml_format(obj, indent=0, max_str_len=256, max_byte_len=64): # sourcery no-metrics """ Pretty formats the given object as a YAML string which is returned. """ @@ -95,12 +95,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 3a1bfc9..231dd0e 100644 --- a/userbot/helpers/utils/paste.py +++ b/userbot/helpers/utils/paste.py @@ -34,7 +34,7 @@ async def t_paste(msg, title=None): """ Verilen mesajı / metin / kodu telgrafa yapıştırmak için """ - 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"] @@ -86,7 +86,7 @@ async def p_paste(message, extension=None): "raw": f"https://pasty.lus.pm/{response['id']}/raw", "bin": "Pasty", } - return {"error": f"`🚨 Pasty.lus.pm'e ulaşılamıyor!`"} + return {"error": "`🚨 Pasty.lus.pm'e ulaşılamıyor!`"} async def s_paste(message, extension="txt"): @@ -107,7 +107,7 @@ async def s_paste(message, extension="txt"): "raw": f"{siteurl}{response['payload']['id']}/raw", "bin": "Spacebin", } - return {"error": f"`🚨 SpaceBin'e ulaşılamıyor!`"} + return {"error": "`🚨 SpaceBin'e ulaşılamıyor!`"} def spaste(message, extension="txt"): @@ -153,7 +153,7 @@ async def n_paste(message, extension=None): "raw": f"nekobin.com/raw/{response['result']['key']}", "bin": "Neko", } - return {"error": f"`🚨 Nekobin'e ulaşılamıyor!`"} + return {"error": "`🚨 Nekobin'e ulaşılamıyor!`"} async def d_paste(message, extension=None): @@ -178,7 +178,7 @@ async def d_paste(message, extension=None): "raw": f"https://catbin.up.railway.app/raw/{response['key']}", "bin": "Dog", } - return {"error": f"`🚨 CatBin'e ulaşılamıyor!`"} + return {"error": "`🚨 CatBin'e ulaşılamıyor!`"} 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 2912b17..dde115b 100644 --- a/userbot/plugins/admin.py +++ b/userbot/plugins/admin.py @@ -657,10 +657,7 @@ async def pin(event): event, f"**Beklenmeyen bir hatayla karşılaşıldı! Hata Raporu:** {e}" ) await edl(event, "**Başarıyla sabitlendi!**", 5) - if is_silent == True: - a = "Evet" - elif is_silent == False: - a = "Hayır" + a = "Hayır" if not is_silent else "Evet" if BOTLOG and not event.is_private: await doge.bot.send_message( BOTLOG_CHATID, diff --git a/userbot/plugins/afk.py b/userbot/plugins/afk.py index 9b36540..16514d2 100644 --- a/userbot/plugins/afk.py +++ b/userbot/plugins/afk.py @@ -85,7 +85,7 @@ async def set_afk(event): global AFKMEDIA if not media_t: AFKMEDIA = None - elif media_t != "Sticker" and media_t: + elif media_t != "Sticker": if not BOTLOG: return await edl( event, @@ -102,19 +102,15 @@ async def set_afk(event): try: full = await event.client(GetFullUserRequest(int(gvar("OWNER_ID")))) bio = full.about - CACHE_AFK = "🐶 @DogeUserBot Sahibim şu an AFK! 🐾" - if bio is not None: - if len(bio) > 55: - await event.client(UpdateProfileRequest(about=CACHE_AFK)) - sgvar("CACHE_AFKBIO", CACHE_AFK) - elif len(bio) < 55: - await event.client( - UpdateProfileRequest(about=f"{gvar('AFKBIO')} | @DogeUserBot") - ) - sgvar("AFKBIO", bio) - elif bio is None: + if bio is not None and len(bio) > 55 or bio is None: + CACHE_AFK = "🐶 @DogeUserBot Sahibim şu an AFK! 🐾" await event.client(UpdateProfileRequest(about=CACHE_AFK)) sgvar("CACHE_AFKBIO", CACHE_AFK) + elif len(bio) < 55: + await event.client( + UpdateProfileRequest(about=f"{gvar('AFKBIO')} | @DogeUserBot") + ) + sgvar("AFKBIO", bio) except BaseException: pass if BOTLOG: diff --git a/userbot/plugins/alive.py b/userbot/plugins/alive.py index 23b1f43..dfd1977 100644 --- a/userbot/plugins/alive.py +++ b/userbot/plugins/alive.py @@ -88,7 +88,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 77942b4..4a9fbe4 100644 --- a/userbot/plugins/android.py +++ b/userbot/plugins/android.py @@ -29,10 +29,11 @@ async def kakashi(event): "En son Magisk sürümlerini alır." magisk_repo = "https://raw.githubusercontent.com/topjohnwu/magisk-files/" magisk_dict = { - "⦁ Stabil": magisk_repo + "master/stable.json", - "⦁ Beta": magisk_repo + "master/beta.json", - "⦁ Canary": magisk_repo + "master/canary.json", + "⦁ Stabil": f'{magisk_repo}master/stable.json', + "⦁ Beta": f'{magisk_repo}master/beta.json', + "⦁ Canary": f'{magisk_repo}master/canary.json', } + releases = "**En son magisk sürümleri**\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"**{codename} için arama sonucu:**\n\n" for item in results: reply += ( @@ -114,12 +114,12 @@ async def codename_info(event): devices = devices_lower.get(brand) if not devices: return await eor(event, f"`{brand}` `adında bir cihaz bulamadım.`") - results = [ + if results := [ i for i in devices - if i["name"].lower() == device.lower() or i["model"].lower() == device.lower() - ] - if results: + if i["name"].lower() == device.lower() + or i["model"].lower() == device.lower() + ]: reply = f"**{brand} {device} için arama sonucu:**\n\n" if len(results) > 8: results = results[:8] diff --git a/userbot/plugins/antispambot.py b/userbot/plugins/antispambot.py index 6c11e21..bb86238 100644 --- a/userbot/plugins/antispambot.py +++ b/userbot/plugins/antispambot.py @@ -68,8 +68,7 @@ async def anti_spambot(event): # sourcery no-metrics LOGS.info(e) SPAMWATCH = Client(gvar("SPAMWATCH_API")) 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}) `{ban.reason}` nedeniyle SpamWatch tarafından yasaklandı." ) diff --git a/userbot/plugins/app.py b/userbot/plugins/app.py index 4deae12..bdea7b8 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\nGeliştirici: {plugin.file.name.split('.')[0]}\n" - await eor(event, installed, parse_mode="html") - else: - await edl( - event, - f"**🚨 Eʀʀoʀ:**\ + if shortname == "py": + installed += f"🐾 {plugin.file.name.split('.')[0]}\n" + await eor(event, installed, parse_mode="html") + else: + await edl( + event, + f"**🚨 Eʀʀoʀ:**\ \n**➡️ To list externally installed plugins, you must first set a PLUGIN_CHANNEL.\ \n\ \n🔮 If you want PLUGIN_CHANNEL to be set automatically;\ \n🦴 Write** `{tr}sdog PLUGINS True`", - ) + ) @doge.bot_cmd( diff --git a/userbot/plugins/countries.py b/userbot/plugins/countries.py index e7decb4..2f2eb40 100644 --- a/userbot/plugins/countries.py +++ b/userbot/plugins/countries.py @@ -41,23 +41,15 @@ async def country_(message): name = a.get("name") bb = a.get("altSpellings") - hu = "" - for p in bb: - hu += p + ", " + hu = "".join(f'{p}, ' for p in bb) area = a.get("area") - borders = "" hell = a.get("borders") - for fk in hell: - borders += fk + ", " - call = "" + borders = "".join(f'{fk}, ' for fk in hell) WhAt = a.get("callingCodes") - for what in WhAt: - call += what + " " + call = "".join(f'{what} ' for what in WhAt) capital = a.get("capital") - currencies = "" fker = a.get("currencies") - for FKer in fker: - currencies += FKer + ", " + currencies = "".join(f'{FKer}, ' for FKer in fker) HmM = a.get("demonym") geo = a.get("geoJSON") pablo = geo.get("features") @@ -68,26 +60,20 @@ async def country_(message): iSo = a.get("ISO") for zort in iSo: po = iSo.get(zort) - iso += po + ", " + iso += f'{po}, ' fla = iSo.get("alpha2") nox = fla.upper() okie = flag(nox) languages = a.get("languages") - lMAO = "" - for lmao in languages: - lMAO += lmao + ", " + lMAO = "".join(f'{lmao}, ' for lmao in languages) nonive = a.get("nativeName") waste = a.get("population") reg = a.get("region") sub = a.get("subregion") tik = a.get("timezones") - tom = "" - for jerry in tik: - tom += jerry + ", " + tom = "".join(f'{jerry}, ' for jerry in tik) GOT = a.get("tld") - lanester = "" - for targaryen in GOT: - lanester += targaryen + ", " + lanester = "".join(f'{targaryen}, ' for targaryen in GOT) wiki = a.get("wiki") caption = f"""{okie} Information of {name} diff --git a/userbot/plugins/custom.py b/userbot/plugins/custom.py index 1f2f21e..6f1154f 100644 --- a/userbot/plugins/custom.py +++ b/userbot/plugins/custom.py @@ -159,7 +159,7 @@ ], }, ) -async def dbsetter(event): # sourcery no-metrics +async def dbsetter(event): # sourcery no-metrics "To manage vars in database" cmd = event.pattern_match.group(1).lower() vname = event.pattern_match.group(2) @@ -189,13 +189,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 @@ -207,7 +204,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)}`") @@ -335,87 +332,86 @@ async def dbsetter(event): # sourcery no-metrics time=20, ) - else: - if gvar("DEV_MOD") == "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}**", - ) - - if gvarname == "OWNER_ID" or gvarname == "CACHE_OWNER_ID": - return - - if gvarname == "PMLOGGER" and gvarinfo == "False": - sgvar("PMLOGGER", "False") - dgvar("PMLOG") - dgvar("PM_LOGGER_GROUP_ID") - elif gvarname == "PLUGINS" and gvarinfo == "False": - sgvar("PLUGINS", "False") - else: - sgvar(gvarname, gvarinfo) - - if BOTLOG_CHATID: - await doge.bot.send_message( - BOTLOG_CHATID, - f"#SET_GLOBALDATAVAR\ - \n**⚙️ {gvarname}** is updated newly in database as below", - ) - await doge.bot.send_message(BOTLOG_CHATID, gvarinfo, silent=True) - msg = await edl( + elif gvar("DEV_MOD") == "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 vname in rlist: - await event.client.reload(msg) - if cmd == "g": - gvardata = gvar(gvarname) - await edl(event, "**I sent global data var to BOTLOG.**") + if gvarname in ["OWNER_ID", "CACHE_OWNER_ID"]: + return + + if gvarname == "PMLOGGER" and gvarinfo == "False": + sgvar("PMLOGGER", "False") + dgvar("PMLOG") + dgvar("PM_LOGGER_GROUP_ID") + elif gvarname == "PLUGINS" and gvarinfo == "False": + sgvar("PLUGINS", "False") + else: + sgvar(gvarname, gvarinfo) + + if BOTLOG_CHATID: await doge.bot.send_message( BOTLOG_CHATID, - f"⚙️ Value of **{gvarname}** is `{gvardata}`", + f"#SET_GLOBALDATAVAR\ + \n**⚙️ {gvarname}** is updated newly in database as below", ) + await doge.bot.send_message(BOTLOG_CHATID, gvarinfo, silent=True) + msg = await edl( + event, + f"⚙️ Value of **{gvarname}** is changed.", + ) + if vname in rlist: + await event.client.reload(msg) + + if cmd == "g": + gvardata = gvar(gvarname) + await edl(event, "**I sent global data var to BOTLOG.**") + await doge.bot.send_message( + BOTLOG_CHATID, + f"⚙️ Value of **{gvarname}** is `{gvardata}`", + ) + + if cmd == "d": + gvardata = gvar(gvarname) + if gvarname in ["OWNER_ID", "CACHE_OWNER_ID"]: + return + + if gvarname == "PMLOGGER" and gvarinfo == "False": + sgvar("PMLOGGER", "False") + dgvar("PMLOG") + dgvar("PM_LOGGER_GROUP_ID") + elif gvarname == "PLUGINS" and gvarinfo == "False": + sgvar("PLUGINS", "False") + else: + dgvar(gvarname) - if cmd == "d": - gvardata = gvar(gvarname) - if gvarname == "OWNER_ID" or gvarname == "CACHE_OWNER_ID": - return - - if gvarname == "PMLOGGER" and gvarinfo == "False": - sgvar("PMLOGGER", "False") - dgvar("PMLOG") - dgvar("PM_LOGGER_GROUP_ID") - elif gvarname == "PLUGINS" and gvarinfo == "False": - sgvar("PLUGINS", "False") - else: - dgvar(gvarname) - - if BOTLOG_CHATID: - await doge.bot.send_message( - BOTLOG_CHATID, - f"#DEL_GLOBALDATAVAR\ + if BOTLOG_CHATID: + await doge.bot.send_message( + BOTLOG_CHATID, + f"#DEL_GLOBALDATAVAR\ \n**{gvarname}** is deleted from database\ \n\ \n🚮 Deleted: `{gvardata}`", - ) - msg = await edl( - event, - f"⚙️ Value of **{gvarname}** is now deleted & set to default.", - time=20, ) - if vname in rlist: - await event.client.reload(msg) - - else: - await eor( + msg = await edl( event, - f"**🪀 Give correct VAR name from the list:**\n\n{vnlist}\n\ - \n**🔮 Give correct API name from the list:**\n\n{apilist}", + f"⚙️ Value of **{gvarname}** is now deleted & set to default.", + time=20, ) + if vname in rlist: + await event.client.reload(msg) + + else: + await eor( + event, + f"**🪀 Give correct VAR name from the list:**\n\n{vnlist}\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..8d9434b 100644 --- a/userbot/plugins/download.py +++ b/userbot/plugins/download.py @@ -45,7 +45,7 @@ async def _get_file_name(path: Path, full: bool = True) -> str: ], }, ) -async def _(event): # sourcery no-metrics +async def _(event): # sourcery no-metrics "To download the replied telegram file" mone = await eor(event, "`Downloading....`") input_str = event.pattern_match.group(3) @@ -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 6baf46e..2bdfffc 100644 --- a/userbot/plugins/evaluators.py +++ b/userbot/plugins/evaluators.py @@ -48,8 +48,7 @@ async def _(event): ) if BOTLOG: await doge.bot.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 doge.bot.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 d29c4ab..7562b16 100644 --- a/userbot/plugins/feds.py +++ b/userbot/plugins/feds.py @@ -151,7 +151,7 @@ async def group_fban(event): }, ) async def sfban(event): - msg = await eor(event, f"SüperFBan başlatılıyor...") + msg = await eor(event, "SüperFBan başlatılıyor...") inputt = event.pattern_match.group(1) if event.reply_to_msg_id: FBAN = (await event.get_reply_message()).sender_id @@ -167,8 +167,9 @@ async def sfban(event): REASON = event.text.split(maxsplit=2)[-1] else: return await msg.edit( - f"Lütfen geçerli bir kullanıcı adı ya da kullanıcı kimliği verin!" + "Lütfen geçerli bir kullanıcı adı ya da kullanıcı kimliği verin!" ) + else: return await msg.edit( "Kullanıcı belirtilmedi! SüperFBan kullanmak için lütfen bir kullanıcı belirtin ya da bir kullanıcısın mesajını yanıtlayın!" @@ -180,8 +181,9 @@ async def sfban(event): chat = int(FBAN_GROUP_ID) else: return await msg.edit( - f"SüperFBan özelliğini kullanmak için lütfen FBAN_GROUP_ID değeri ekleyin!" + "SüperFBan özelliğini kullanmak için lütfen FBAN_GROUP_ID değeri ekleyin!" ) + fedList = [] if not fedList: for a in range(3): @@ -196,9 +198,7 @@ async def sfban(event): conv.chat_id, message=response, clear_mentions=True ) except TimeoutError: - return await msg.edit( - f"@MissRose_Bot cevap vermiyor!", - ) + return await msg.edit("@MissRose_Bot cevap vermiyor!") await sleep(3) if "make a file" in response.text or "Looks like" in response.text: await response.click(0) @@ -222,8 +222,9 @@ async def sfban(event): await conv.get_edit ): return await msg.edit( - f"@MissRose_Bot kısıtlamaları yüzünden 5 dakika sonra tekrar deneyin!" + "@MissRose_Bot kısıtlamaları yüzünden 5 dakika sonra tekrar deneyin!" ) + await event.client.send_read_acknowledge( conv.chat_id, message=fedfile, clear_mentions=True ) @@ -256,8 +257,9 @@ async def sfban(event): await doge.send_message(chat, "/start") except BaseException: return await msg.edit( - f"Veritabanınızdaki FBAN_GROUP_ID değeri hatalı! Lütfen kontrol edip düznledikten sonra tekrar deneyin." + "Veritabanınızdaki FBAN_GROUP_ID değeri hatalı! Lütfen kontrol edip düznledikten sonra tekrar deneyin." ) + await sleep(3) for fed in fedList: await event.client.send_message(chat, f"/joinfed {fed}") @@ -379,7 +381,7 @@ async def group_unfban(event): }, ) async def sunfban(event): - msg = await eor(event, f"SüperUnFBan başlatılıyor..") + msg = await eor(event, "SüperUnFBan başlatılıyor..") fedList = [] if event.reply_to_msg_id: previous_message = await event.get_reply_message() @@ -414,20 +416,19 @@ async def sunfban(event): REASON = arg[2] except BaseException: return await msg.edit( - f"Lütfen geçerli bir kullanıcı adı ya da kullanıcı kimliği verin!" + "Lütfen geçerli bir kullanıcı adı ya da kullanıcı kimliği verin!" ) + else: try: FBAN = arg[1] REASON = " #DOGE_SUPERUNFBAN " except BaseException: return await msg.edit( - f"Lütfen geçerli bir kullanıcı adı ya da kullanıcı kimliği verin!" + "Lütfen geçerli bir kullanıcı adı ya da kullanıcı kimliği verin!" ) - if FBAN_GROUP_ID: - chat = int(FBAN_GROUP_ID) - else: - chat = await event.get_chat() + + chat = int(FBAN_GROUP_ID) if FBAN_GROUP_ID else await event.get_chat() if not fedList: for a in range(3): async with event.client.conversation(rose) as conv: @@ -528,7 +529,7 @@ async def sunfban(event): ], }, ) -async def quote_search(event): # sourcery no-metrics +async def quote_search(event): # sourcery no-metrics "Add the federation to database." fedgroup = event.pattern_match.group(1) fedid = event.pattern_match.group(2) @@ -573,9 +574,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, @@ -776,10 +780,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 d14c2a3..edf4bda 100644 --- a/userbot/plugins/fileconverts.py +++ b/userbot/plugins/fileconverts.py @@ -491,13 +491,9 @@ async def on_file_to_photo(event): "u": "{tr}gif quality ; fps(frames per second)", }, ) -async def _(event): # sourcery no-metrics +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( @@ -533,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: @@ -612,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", @@ -633,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..e45c40b 100644 --- a/userbot/plugins/filesummary.py +++ b/userbot/plugins/filesummary.py @@ -42,11 +42,10 @@ def weird_division(n, d): "e": "{tr}chatfs @DogeSup", }, ) -async def _(event): # sourcery no-metrics +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)) @@ -144,7 +143,7 @@ async def _(event): # sourcery no-metrics "e": "{tr}userfs @MissRose_bot", }, ) -async def _(event): # sourcery no-metrics +async def _(event): # sourcery no-metrics "Shows you the complete media/file summary of the that user in that group." reply = await event.get_reply_message() input_str = event.pattern_match.group(1) @@ -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 1507fd6..1d28663 100644 --- a/userbot/plugins/gdrive.py +++ b/userbot/plugins/gdrive.py @@ -169,7 +169,7 @@ async def get_file_id(input_str): return link, "unknown" -async def download(event, gdrive, service, uri=None): # sourcery no-metrics +async def download(event, gdrive, service, uri=None): # sourcery no-metrics """Download files to local then upload""" start = datetime.now() reply = "" @@ -280,7 +280,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: @@ -431,10 +431,13 @@ 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" @@ -486,14 +489,15 @@ async def gdrive_download( status, "".join( (gvar("FINISHED_PROGRESS_STR") or "▰") - for i in range(floor(percentage / 5)) + for _ in range(floor(percentage / 5)) ), "".join( (gvar("UNFINISHED_PROGRESS_STR") or "▱") - 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" @@ -643,15 +647,16 @@ async def upload(gdrive, service, file_path, file_name, mimeType, dir_id=None): prog_str = "`Uploading:`\n`[{0}{1}] {2}`".format( "".join( (gvar("FINISHED_PROGRESS_STR") or "▰") - for i in range(floor(percentage / 10)) + for _ in range(floor(percentage / 10)) ), "".join( (gvar("UNFINISHED_PROGRESS_STR") or "▱") - for i in range(10 - floor(percentage / 10)) + for _ in range(10 - floor(percentage / 10)) ), round(percentage, 2), ) + current_message = ( "**Uploading **\n\n" f"**Name:** `{file_name}`\n" @@ -772,11 +777,14 @@ 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(), ) + msg = ( "**[URL - DOWNLOAD]**\n\n" f"**Name:** `{file.name}`\n" From c0d5928945ff8ff96993c438ee885df95c27e9b9 Mon Sep 17 00:00:00 2001 From: TeleDoge Date: Sun, 27 Feb 2022 22:52:19 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=A6=B4=20Otomatik=20D=C3=BCzenleme?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: TeleDoge --- sample_config.py | 3 -- userbot/__main__.py | 2 +- userbot/assistant/botmanagers.py | 3 +- userbot/assistant/botpm.py | 10 ++---- userbot/assistant/iyoutube.py | 5 +-- userbot/assistant/settings.py | 4 +-- userbot/core/inlinebot.py | 44 ++++++++++++++++-------- userbot/helpers/functions/calculate.py | 1 - userbot/helpers/functions/jikan.py | 8 ++--- userbot/helpers/functions/utils.py | 2 +- userbot/helpers/functions/utube.py | 19 ++++------ userbot/helpers/google_image_download.py | 16 +++++---- userbot/helpers/progress.py | 8 ++--- userbot/helpers/utils/format.py | 2 +- userbot/plugins/android.py | 9 +++-- userbot/plugins/archive.py | 4 +-- userbot/plugins/climate.py | 10 +++--- userbot/plugins/countries.py | 16 ++++----- userbot/plugins/custom.py | 2 +- userbot/plugins/download.py | 6 ++-- userbot/plugins/fileconverts.py | 6 ++-- userbot/plugins/filesummary.py | 12 +++---- userbot/plugins/gdrive.py | 12 ++----- 23 files changed, 96 insertions(+), 108 deletions(-) diff --git a/sample_config.py b/sample_config.py index 9ad9086..3e9215f 100644 --- a/sample_config.py +++ b/sample_config.py @@ -19,8 +19,6 @@ from telethon.tl.types import ChatBannedRights - - class Config(object): LOGGER = True @@ -103,7 +101,6 @@ class Config(object): BOTLOG_CHATID = 0 - class Production(Config): LOGGER = False diff --git a/userbot/__main__.py b/userbot/__main__.py index 56434f5..0b64dfc 100644 --- a/userbot/__main__.py +++ b/userbot/__main__.py @@ -87,7 +87,7 @@ async def startup_process(): LOGS.info("🐶 %100 ~ DOGE USERBOT HAZIR!\n\n\n\n\n\n\n") LOGS.info(userbot.__copyright__) - LOGS.info(f'{userbot.__license__} ile korunmaktadır.') + LOGS.info(f"{userbot.__license__} ile korunmaktadır.") LOGS.info( f"\ \n➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\ diff --git a/userbot/assistant/botmanagers.py b/userbot/assistant/botmanagers.py index 643fc49..a3f154d 100644 --- a/userbot/assistant/botmanagers.py +++ b/userbot/assistant/botmanagers.py @@ -50,8 +50,7 @@ def progress_str(total: int, current: int) -> str: "Progress", percentage, "".join( - (gvar("FINISHED_PROGRESS_STR") or "▰") - for _ in range(floor(percentage / 5)) + (gvar("FINISHED_PROGRESS_STR") or "▰") for _ in range(floor(percentage / 5)) ), "".join( (gvar("UNFINISHED_PROGRESS_STR") or "▱") diff --git a/userbot/assistant/botpm.py b/userbot/assistant/botpm.py index f897d8a..140bce7 100644 --- a/userbot/assistant/botpm.py +++ b/userbot/assistant/botpm.py @@ -534,11 +534,7 @@ async def bot_pms_edit(event): # sourcery no-metrics if users is None: return if reply_msg := next( - ( - user.message_id - for user in users - if user.chat_id == str(chat.id) - ), + (user.message_id for user in users if user.chat_id == str(chat.id)), None, ): await event.client.send_message( @@ -550,9 +546,7 @@ async def bot_pms_edit(event): # sourcery no-metrics ) msg = await event.forward_to(int(gvar("OWNER_ID"))) try: - add_user_to_db( - msg.id, get_display_name(chat), chat.id, event.id, 0, 0 - ) + add_user_to_db(msg.id, get_display_name(chat), chat.id, event.id, 0, 0) except Exception as e: LOGS.error(f"🚨 {str(e)}") if BOTLOG: diff --git a/userbot/assistant/iyoutube.py b/userbot/assistant/iyoutube.py index 36f175b..e3caaed 100644 --- a/userbot/assistant/iyoutube.py +++ b/userbot/assistant/iyoutube.py @@ -78,7 +78,6 @@ async def yt_inline(event): event, "**📺 Geçerli bir YouTube URL'sine girin veya cevap verin!**" ) - dogevent = await eor( event, "**🔎 Şunun için YouTube'da arama yapıyorm:** `{}`...".format(input_url) ) @@ -288,9 +287,7 @@ async def ytdl_callback(c_q: CallbackQuery): file=await get_ytthumb(search_data.get("1").get("video_id")), buttons=[ Button.url("↗️ Açᴍᴀᴋ Içɪɴ Tıᴋʟᴀʏıɴ", url=telegraph), - Button.inline( - "📊 Dᴇᴛᴀʏʟᴀʀı Göʀ", data=f"ytdl_detail_{data_key}_{page}" - ), + Button.inline("📊 Dᴇᴛᴀʏʟᴀʀı Göʀ", data=f"ytdl_detail_{data_key}_{page}"), ], ) diff --git a/userbot/assistant/settings.py b/userbot/assistant/settings.py index 3c5e373..e497ccf 100644 --- a/userbot/assistant/settings.py +++ b/userbot/assistant/settings.py @@ -748,9 +748,7 @@ async def hlogger(event): ], ] buttons.append(get_back_button("sscg")) - await event.edit( - "Heroku Logger özelliği menünüzü özelleştirin.", buttons=buttons - ) + await event.edit("Heroku Logger özelliği menünüzü özelleştirin.", buttons=buttons) # heroku logger özelliğini kapatma işlemi diff --git a/userbot/core/inlinebot.py b/userbot/core/inlinebot.py index 0e4c71c..f27f599 100644 --- a/userbot/core/inlinebot.py +++ b/userbot/core/inlinebot.py @@ -48,7 +48,9 @@ def back_menu(back): text = f"**🐶 Doɢᴇ UsᴇʀBoᴛ\ \n🐾 Yᴀʀᴅıᴍᴄı\n\ \n◽ Doɢᴇ oғ {gvar('mention')}**" - buttons = [(Button.inline("ℹ️️ Bɪʟɢɪ", data="check"), ), ( + buttons = [ + (Button.inline("ℹ️️ Bɪʟɢɪ", data="check"),), + ( Button.inline( f"👮‍♂️ Aᴅᴍɪɴ ({len(GRP_INFO['admin'])})", data="admin_menu", @@ -57,7 +59,8 @@ def back_menu(back): f"🐶 Doɢᴇ ({len(GRP_INFO['bot'])})", data="bot_menu", ), - ), ( + ), + ( Button.inline( f"🎈 Eɢ̆ʟᴇɴᴄᴇ ({len(GRP_INFO['fun'])})", data="fun_menu", @@ -66,7 +69,8 @@ def back_menu(back): f"🪀 Çᴇşɪᴛʟɪ ({len(GRP_INFO['misc'])})", data="misc_menu", ), - ), ( + ), + ( Button.inline( f"🧰 Aʀᴀç ({len(GRP_INFO['tool'])})", data="tool_menu", @@ -75,7 +79,8 @@ def back_menu(back): f"🍑 Hᴜʙ ({len(GRP_INFO['hub'])})", data="hub_menu", ), - )] + ), + ] buttons.append(get_back_button(back)) return text, buttons @@ -84,7 +89,9 @@ def main_menu(): text = f"**🐶 Doɢᴇ UsᴇʀBoᴛ\ \n🐾 Yᴀʀᴅıᴍᴄı\n\ \n◽ Doɢᴇ oғ {gvar('mention')}**" - buttons = [(Button.inline("ℹ️️ Bɪʟɢɪ", data="check"), ), ( + buttons = [ + (Button.inline("ℹ️️ Bɪʟɢɪ", data="check"),), + ( Button.inline( f"👮‍♂️ Aᴅᴍɪɴ ({len(GRP_INFO['admin'])})", data="admin_menu", @@ -93,7 +100,8 @@ def main_menu(): f"🐶 Doɢᴇ ({len(GRP_INFO['bot'])})", data="bot_menu", ), - ), ( + ), + ( Button.inline( f"🎈 Eɢ̆ʟᴇɴᴄᴇ ({len(GRP_INFO['fun'])})", data="fun_menu", @@ -102,7 +110,8 @@ def main_menu(): f"🪀 Çᴇşɪᴛʟɪ ({len(GRP_INFO['misc'])})", data="misc_menu", ), - ), ( + ), + ( Button.inline( f"🧰 Aʀᴀç ({len(GRP_INFO['tool'])})", data="tool_menu", @@ -111,7 +120,9 @@ def main_menu(): f"🍑 Hᴜʙ ({len(GRP_INFO['hub'])})", data="hub_menu", ), - ), (Button.inline("⛔ KAPAT ⛔", data="close"), )] + ), + (Button.inline("⛔ KAPAT ⛔", data="close"),), + ] return text, buttons @@ -227,15 +238,22 @@ def paginate_help( modulo_page = page_number % max_num_pages if plugins: if len(pairs) > number_of_rows: - pairs = (pairs[ + pairs = pairs[ modulo_page * number_of_rows : number_of_rows * (modulo_page + 1) - ] + [(Button.inline( + ] + [ + ( + Button.inline( "⏪", data=f"{prefix}_prev({modulo_page})_plugin", - ), Button.inline("🐾 Mᴇɴᴜ", data="mainmenu"), Button.inline( + ), + Button.inline("🐾 Mᴇɴᴜ", data="mainmenu"), + Button.inline( "⏩", data=f"{prefix}_next({modulo_page})_plugin", - )), (Button.inline("⛔ Kᴀᴘᴀᴛ", data="close"), )]) + ), + ), + (Button.inline("⛔ Kᴀᴘᴀᴛ", data="close"),), + ] else: pairs = pairs + [ @@ -245,7 +263,6 @@ def paginate_help( ) ] - elif len(pairs) > number_of_rows: if category_pgno < 0: category_pgno = len(pairs) + category_pgno @@ -272,7 +289,6 @@ def paginate_help( ), ] - else: if category_pgno < 0: category_pgno = len(pairs) + category_pgno diff --git a/userbot/helpers/functions/calculate.py b/userbot/helpers/functions/calculate.py index 4387105..5924543 100644 --- a/userbot/helpers/functions/calculate.py +++ b/userbot/helpers/functions/calculate.py @@ -26,7 +26,6 @@ async def calcc(cmd, event, text=None): stderr = redirected_error.getvalue() sys.stdout = old_stdout sys.stderr = old_stderr - evaluation = "" if exc: return exc elif stderr: diff --git a/userbot/helpers/functions/jikan.py b/userbot/helpers/functions/jikan.py index 5a2e3f0..9106dce 100644 --- a/userbot/helpers/functions/jikan.py +++ b/userbot/helpers/functions/jikan.py @@ -225,7 +225,7 @@ async def formatJSON(outData): msg += f"\n\n**Tip:** {jsonData['format']}" msg += "\\n**Çeşitler:** " for g in jsonData["genres"]: - msg += f'{g} ' + msg += f"{g} " msg += f"\n**Durum:** {jsonData['status']}" msg += f"\n**Bölümler:** {jsonData['episodes']}" msg += f"\n**Yıl:** {jsonData['startDate']['year']}" @@ -326,9 +326,9 @@ def getBannerLink(mal, kitsu_search=True, anilistid=0): } """ data = {"query": query, "variables": {"idMal": int(mal)}} - if image := post("https://graphql.anilist.co", json=data).json()["data"][ - "Media" - ]["bannerImage"]: + if image := post("https://graphql.anilist.co", json=data).json()["data"]["Media"][ + "bannerImage" + ]: return image return getPosterLink(mal) diff --git a/userbot/helpers/functions/utils.py b/userbot/helpers/functions/utils.py index 6be2449..e297642 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 += f'{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 2f66af4..4d7d4f0 100644 --- a/userbot/helpers/functions/utube.py +++ b/userbot/helpers/functions/utube.py @@ -99,7 +99,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 = f'{url}?{query_string}' + url = f"{url}?{query_string}" with urlopen(url) as response: response_text = response.read() data = loads(response_text.decode()) @@ -142,7 +142,7 @@ def get_choice_by_id(choice_id, media_type: str): else: disp_str = str(choice_id) if media_type == "v": - choice_str = f'{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 @@ -183,9 +183,7 @@ def yt_search_btns( ): buttons = [ [ - Button.inline( - text="⬅️️ Gᴇʀɪ", data=f"ytdl_back_{data_key}_{page}" - ), + Button.inline(text="⬅️️ Gᴇʀɪ", data=f"ytdl_back_{data_key}_{page}"), Button.inline( text=f"🔹 {page} - {total} 🔹", data=f"ytdl_next_{data_key}_{page}", @@ -215,16 +213,11 @@ def download_button(vid: str, body: bool = False): # sourcery no-metrics vid_data = {"formats": []} buttons = [ [ - Button.inline( - "🌟 Eɴ İʏɪsɪ - 🎞 ᴍᴋᴠ", data=f"ytdl_download_{vid}_mkv_v" - ), - Button.inline( - "🌟 Eɴ İʏɪsɪ - 🎞 ᴡᴇʙᴍ/ᴍᴘ4", data=f"ytdl_download_{vid}_mp4_v" - ), + Button.inline("🌟 Eɴ İʏɪsɪ - 🎞 ᴍᴋᴠ", data=f"ytdl_download_{vid}_mkv_v"), + Button.inline("🌟 Eɴ İʏɪsɪ - 🎞 ᴡᴇʙᴍ/ᴍᴘ4", data=f"ytdl_download_{vid}_mp4_v"), ] ] - qual_dict = defaultdict(lambda: defaultdict(int)) qual_list = ["144p", "240p", "360p", "480p", "720p", "1080p", "1440p"] audio_dict = {} @@ -234,7 +227,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_, f'{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)) diff --git a/userbot/helpers/google_image_download.py b/userbot/helpers/google_image_download.py index c746017..8b017f8 100644 --- a/userbot/helpers/google_image_download.py +++ b/userbot/helpers/google_image_download.py @@ -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 = f'{main_directory}/{image_name}' + file_name = f"{main_directory}/{image_name}" else: - file_name = f'{main_directory}/{image_name}.jpg' - image_name = f'{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: @@ -905,7 +905,7 @@ def build_url_parameters(self, arguments): # add it to the built url built_url += ext_param else: - built_url = f'{built_url},{ext_param}' + built_url = f"{built_url},{ext_param}" counter += 1 built_url = lang_url + built_url + exact_size return built_url @@ -986,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 = f'{dir_name} - thumbnail' + dir_name_thumbnail = f"{dir_name} - thumbnail" # make a search keyword directory try: if not ospath.exists(main_directory): @@ -1054,7 +1054,7 @@ def download_image_thumbnail( with open(path, "wb") as output_file: output_file.write(data) if save_source: - list_path = f'{main_directory}/{save_source}.txt' + 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: @@ -1069,7 +1069,9 @@ def download_image_thumbnail( ) download_status = "success" - download_message = f"Completed Image Thumbnail ====> {return_image_name}" + download_message = ( + f"Completed Image Thumbnail ====> {return_image_name}" + ) # image size parameter if print_size: diff --git a/userbot/helpers/progress.py b/userbot/helpers/progress.py index 7091530..c7a3274 100644 --- a/userbot/helpers/progress.py +++ b/userbot/helpers/progress.py @@ -56,7 +56,7 @@ def humanbytes(size: int) -> str: while size > power: size /= power raised_to_pow += 1 - return f'{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: @@ -85,7 +85,7 @@ def afk_time(seconds, short=True): + ((str(minutes) + (" dakika, " if not short else "dk, ")) if minutes else "") + ((str(seconds) + (" saniye, " if not short else "s, ")) if seconds else "") ) - return f'{tmp[:-2]} önce' + return f"{tmp[:-2]} önce" def readable_time(seconds: int) -> str: @@ -94,8 +94,8 @@ def readable_time(seconds: int) -> str: days, hours = divmod(hours, 24) return ( (f"{int(days)} gün, " if days else "") - + (f'{int(hours)}:' if hours else "00:") - + (f'{int(minutes)}:' if minutes else "00:") + + (f"{int(hours)}:" if hours else "00:") + + (f"{int(minutes)}:" if minutes else "00:") + (str(int(seconds)) if seconds else "00") ) diff --git a/userbot/helpers/utils/format.py b/userbot/helpers/utils/format.py index c9d62c5..b724d9a 100644 --- a/userbot/helpers/utils/format.py +++ b/userbot/helpers/utils/format.py @@ -71,7 +71,7 @@ def parse_pre(text): # Based on TLObject.pretty_format -def yaml_format(obj, indent=0, max_str_len=256, max_byte_len=64): # sourcery no-metrics +def yaml_format(obj, indent=0, max_str_len=256, max_byte_len=64): # sourcery no-metrics """ Pretty formats the given object as a YAML string which is returned. """ diff --git a/userbot/plugins/android.py b/userbot/plugins/android.py index 4a9fbe4..69e9107 100644 --- a/userbot/plugins/android.py +++ b/userbot/plugins/android.py @@ -29,9 +29,9 @@ async def kakashi(event): "En son Magisk sürümlerini alır." magisk_repo = "https://raw.githubusercontent.com/topjohnwu/magisk-files/" magisk_dict = { - "⦁ Stabil": f'{magisk_repo}master/stable.json', - "⦁ Beta": f'{magisk_repo}master/beta.json', - "⦁ Canary": f'{magisk_repo}master/canary.json', + "⦁ Stabil": f"{magisk_repo}master/stable.json", + "⦁ Beta": f"{magisk_repo}master/beta.json", + "⦁ Canary": f"{magisk_repo}master/canary.json", } releases = "**En son magisk sürümleri**\n\n" @@ -117,8 +117,7 @@ async def codename_info(event): if results := [ i for i in devices - if i["name"].lower() == device.lower() - or i["model"].lower() == device.lower() + if i["name"].lower() == device.lower() or i["model"].lower() == device.lower() ]: reply = f"**{brand} {device} için arama sonucu:**\n\n" if len(results) > 8: diff --git a/userbot/plugins/archive.py b/userbot/plugins/archive.py index f17bb35..52c89ef 100644 --- a/userbot/plugins/archive.py +++ b/userbot/plugins/archive.py @@ -132,7 +132,7 @@ async def tar_file(event): ], }, ) -async def zip_file(event): # sourcery no-metrics +async def zip_file(event): # sourcery no-metrics "Zip dosyası açar." if input_str := event.pattern_match.group(1): path = Path(input_str) @@ -213,7 +213,7 @@ async def zip_file(event): # sourcery no-metrics ], }, ) -async def untar_file(event): # sourcery no-metrics +async def untar_file(event): # sourcery no-metrics "Tar dosyası açar." if input_str := event.pattern_match.group(1): path = Path(input_str) diff --git a/userbot/plugins/climate.py b/userbot/plugins/climate.py index 2331c9d..347ce47 100644 --- a/userbot/plugins/climate.py +++ b/userbot/plugins/climate.py @@ -61,7 +61,7 @@ def sun(unix, ctimezone): ], }, ) -async def get_weather(event): # sourcery no-metrics +async def get_weather(event): # sourcery no-metrics "To get the weather report of a city." # if WEATHER_API is None: # await eor(event, "`Get an API key from` https://openweathermap.org/ ``") @@ -75,14 +75,14 @@ async def get_weather(event): # sourcery no-metrics if "," in CITY: newcity = CITY.split(",") if len(newcity[1]) == 2: - CITY = f'{newcity[0].strip()},{newcity[1].strip()}' + CITY = f"{newcity[0].strip()},{newcity[1].strip()}" else: country = await get_tz((newcity[1].strip()).title()) try: countrycode = timezone_countries[f"{country}"] except KeyError: return await eor(event, "`Invalid Country.`") - CITY = f'{newcity[0].strip()},{countrycode.strip()}' + CITY = f"{newcity[0].strip()},{countrycode.strip()}" url = f"https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={(gvar('WEATHER_API') or '6fded1e1c5ef3f394283e3013a597879')}" async with ClientSession() as _session: async with _session.get(url) as request: @@ -160,14 +160,14 @@ async def set_default_city(event): if "," in CITY: newcity = CITY.split(",") if len(newcity[1]) == 2: - CITY = f'{newcity[0].strip()},{newcity[1].strip()}' + CITY = f"{newcity[0].strip()},{newcity[1].strip()}" else: country = await get_tz((newcity[1].strip()).title()) try: countrycode = timezone_countries[f"{country}"] except KeyError: return await eor(event, "`Invalid country.`") - CITY = f'{newcity[0].strip()},{countrycode.strip()}' + CITY = f"{newcity[0].strip()},{countrycode.strip()}" url = f"https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={(gvar('WEATHER_API') or '6fded1e1c5ef3f394283e3013a597879')}" request = get(url) result = loads(request.text) diff --git a/userbot/plugins/countries.py b/userbot/plugins/countries.py index 2f2eb40..cd50ece 100644 --- a/userbot/plugins/countries.py +++ b/userbot/plugins/countries.py @@ -41,15 +41,15 @@ async def country_(message): name = a.get("name") bb = a.get("altSpellings") - hu = "".join(f'{p}, ' for p in bb) + hu = "".join(f"{p}, " for p in bb) area = a.get("area") hell = a.get("borders") - borders = "".join(f'{fk}, ' for fk in hell) + borders = "".join(f"{fk}, " for fk in hell) WhAt = a.get("callingCodes") - call = "".join(f'{what} ' for what in WhAt) + call = "".join(f"{what} " for what in WhAt) capital = a.get("capital") fker = a.get("currencies") - currencies = "".join(f'{FKer}, ' for FKer in fker) + currencies = "".join(f"{FKer}, " for FKer in fker) HmM = a.get("demonym") geo = a.get("geoJSON") pablo = geo.get("features") @@ -60,20 +60,20 @@ async def country_(message): iSo = a.get("ISO") for zort in iSo: po = iSo.get(zort) - iso += f'{po}, ' + iso += f"{po}, " fla = iSo.get("alpha2") nox = fla.upper() okie = flag(nox) languages = a.get("languages") - lMAO = "".join(f'{lmao}, ' for lmao in languages) + lMAO = "".join(f"{lmao}, " for lmao in languages) nonive = a.get("nativeName") waste = a.get("population") reg = a.get("region") sub = a.get("subregion") tik = a.get("timezones") - tom = "".join(f'{jerry}, ' for jerry in tik) + tom = "".join(f"{jerry}, " for jerry in tik) GOT = a.get("tld") - lanester = "".join(f'{targaryen}, ' for targaryen in GOT) + lanester = "".join(f"{targaryen}, " for targaryen in GOT) wiki = a.get("wiki") caption = f"""{okie} Information of {name} diff --git a/userbot/plugins/custom.py b/userbot/plugins/custom.py index 6f1154f..323e8f6 100644 --- a/userbot/plugins/custom.py +++ b/userbot/plugins/custom.py @@ -159,7 +159,7 @@ ], }, ) -async def dbsetter(event): # sourcery no-metrics +async def dbsetter(event): # sourcery no-metrics "To manage vars in database" cmd = event.pattern_match.group(1).lower() vname = event.pattern_match.group(2) diff --git a/userbot/plugins/download.py b/userbot/plugins/download.py index 8d9434b..fb61a02 100644 --- a/userbot/plugins/download.py +++ b/userbot/plugins/download.py @@ -45,7 +45,7 @@ async def _get_file_name(path: Path, full: bool = True) -> str: ], }, ) -async def _(event): # sourcery no-metrics +async def _(event): # sourcery no-metrics "To download the replied telegram file" mone = await eor(event, "`Downloading....`") input_str = event.pattern_match.group(3) @@ -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 = f'{str(path.stem)}_OLD' + newname = f"{str(path.stem)}_OLD" path.rename(path.with_name(newname).with_suffix(path.suffix)) file_name = path else: @@ -224,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 = f'{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/fileconverts.py b/userbot/plugins/fileconverts.py index edf4bda..15efc25 100644 --- a/userbot/plugins/fileconverts.py +++ b/userbot/plugins/fileconverts.py @@ -491,7 +491,7 @@ async def on_file_to_photo(event): "u": "{tr}gif quality ; fps(frames per second)", }, ) -async def _(event): # sourcery no-metrics +async def _(event): # sourcery no-metrics "Converts Given animated sticker to gif" if input_str := event.pattern_match.group(1): loc = input_str.split(";") @@ -613,7 +613,7 @@ async def _(event): if input_str == "voice": new_required_file_caption = f"voice_{str(round(time()))}.opus" new_required_file_name = ( - f'{TMP_DOWNLOAD_DIRECTORY}/{new_required_file_caption}' + f"{TMP_DOWNLOAD_DIRECTORY}/{new_required_file_caption}" ) command_to_run = [ @@ -635,7 +635,7 @@ async def _(event): elif input_str == "mp3": new_required_file_caption = f"mp3_{str(round(time()))}.mp3" new_required_file_name = ( - f'{TMP_DOWNLOAD_DIRECTORY}/{new_required_file_caption}' + f"{TMP_DOWNLOAD_DIRECTORY}/{new_required_file_caption}" ) command_to_run = [ diff --git a/userbot/plugins/filesummary.py b/userbot/plugins/filesummary.py index e45c40b..7cbb8c5 100644 --- a/userbot/plugins/filesummary.py +++ b/userbot/plugins/filesummary.py @@ -42,7 +42,7 @@ def weird_division(n, d): "e": "{tr}chatfs @DogeSup", }, ) -async def _(event): # sourcery no-metrics +async def _(event): # sourcery no-metrics "Shows you the complete media/file summary of the that group" entity = event.chat_id if input_str := event.pattern_match.group(1): @@ -108,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 = f'{str(round(((endtime - starttime) / 60), 2))} minutes' + runtime = f"{str(round(((endtime - starttime) / 60), 2))} minutes" else: - runtime = f'{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)) @@ -143,7 +143,7 @@ async def _(event): # sourcery no-metrics "e": "{tr}userfs @MissRose_bot", }, ) -async def _(event): # sourcery no-metrics +async def _(event): # sourcery no-metrics "Shows you the complete media/file summary of the that user in that group." reply = await event.get_reply_message() input_str = event.pattern_match.group(1) @@ -230,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 = f'{str(round(((endtime - starttime) / 60), 2))} minutes' + runtime = f"{str(round(((endtime - starttime) / 60), 2))} minutes" else: - runtime = f'{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/gdrive.py b/userbot/plugins/gdrive.py index 1d28663..6dd2c4b 100644 --- a/userbot/plugins/gdrive.py +++ b/userbot/plugins/gdrive.py @@ -169,7 +169,7 @@ async def get_file_id(input_str): return link, "unknown" -async def download(event, gdrive, service, uri=None): # sourcery no-metrics +async def download(event, gdrive, service, uri=None): # sourcery no-metrics """Download files to local then upload""" start = datetime.now() reply = "" @@ -432,9 +432,7 @@ async def gdrive_download( eta = round((file_size - downloaded) / speed) prog_str = "`[{0}{1}] {2}%`".format( "".join("▰" for _ in range(floor(percentage / 10))), - "".join( - "▱" for _ in range(10 - floor(percentage / 10)) - ), + "".join("▱" for _ in range(10 - floor(percentage / 10))), round(percentage, 2), ) @@ -656,7 +654,6 @@ async def upload(gdrive, service, file_path, file_name, mimeType, dir_id=None): round(percentage, 2), ) - current_message = ( "**Uploading **\n\n" f"**Name:** `{file_name}`\n" @@ -778,13 +775,10 @@ async def check_progress_for_dl(event, gid, previous): # sourcery no-metrics downloaded = percentage * int(file.total_length) / 100 prog_str = "**Downloading:** `[{0}{1}] {2}`".format( "".join("▰" for _ in range(floor(percentage / 10))), - "".join( - "▱" for _ in range(10 - floor(percentage / 10)) - ), + "".join("▱" for _ in range(10 - floor(percentage / 10))), file.progress_string(), ) - msg = ( "**[URL - DOWNLOAD]**\n\n" f"**Name:** `{file.name}`\n"