diff --git a/Powers/__init__.py b/Powers/__init__.py
index e7dbdc2092b926243e065ccfed0e6a0ce80528c8..ab69a5fc658ddc6fd393ff3e08bf681fa3e136a6 100644
--- a/Powers/__init__.py
+++ b/Powers/__init__.py
@@ -18,13 +18,9 @@ from apscheduler.schedulers.asyncio import AsyncIOScheduler
LOG_DATETIME = datetime.now().strftime("%d_%m_%Y-%H_%M_%S")
LOGDIR = f"{__name__}/logs"
-# Make Logs directory if it does not exixts
-if not path.isdir(LOGDIR):
- mkdir(LOGDIR)
-else:
+if path.isdir(LOGDIR):
shutil.rmtree(LOGDIR)
- mkdir(LOGDIR)
-
+mkdir(LOGDIR)
LOGFILE = f"{LOGDIR}/{__name__}_{LOG_DATETIME}_log.txt"
file_handler = FileHandler(filename=LOGFILE)
@@ -64,12 +60,9 @@ except Exception as ef:
TIME_ZONE = pytz.timezone(Config.TIME_ZONE)
Vpath = "./Version"
-version = []
-for i in listdir(Vpath):
- if i.startswith("version") and i.endswith("md"):
- version.append(i)
- else:
- pass
+version = [
+ i for i in listdir(Vpath) if i.startswith("version") and i.endswith("md")
+]
VERSION = sorted(version)[-1][8:-3]
PYTHON_VERSION = python_version()
PYROGRAM_VERSION = pyrogram.__version__
@@ -96,7 +89,7 @@ if Config.GENIUS_API_TOKEN:
genius_lyrics.verbose = False
LOGGER.info("Client setup complete")
-elif not Config.GENIUS_API_TOKEN:
+else:
LOGGER.info("Genius api not found lyrics command will not work")
is_genius_lyrics = False
genius_lyrics = False
@@ -119,7 +112,7 @@ API_ID = Config.API_ID
API_HASH = Config.API_HASH
# General Config
-MESSAGE_DUMP = Config.MESSAGE_DUMP if Config.MESSAGE_DUMP else Config.OWNER_ID
+MESSAGE_DUMP = Config.MESSAGE_DUMP or Config.OWNER_ID
SUPPORT_GROUP = Config.SUPPORT_GROUP
SUPPORT_CHANNEL = Config.SUPPORT_CHANNEL
@@ -145,18 +138,13 @@ UPTIME = time() # Check bot uptime
#Make dir
youtube_dir = "./Youtube/"
-if not path.isdir(youtube_dir):
- mkdir(youtube_dir)
-else:
+if path.isdir(youtube_dir):
shutil.rmtree(youtube_dir)
- mkdir(youtube_dir)
-
+mkdir(youtube_dir)
scrap_dir = "./scrapped/"
-if not path.isdir(scrap_dir):
- mkdir(scrap_dir)
-else:
+if path.isdir(scrap_dir):
shutil.rmtree(scrap_dir)
- mkdir(scrap_dir)
+mkdir(scrap_dir)
scheduler = AsyncIOScheduler(timezone=TIME_ZONE)
diff --git a/Powers/bot_class.py b/Powers/bot_class.py
index d13b9e6160f89e37c023187599b97768492abcc5..aad3795420f4940bc2d765e433df1bd07ae6f557 100644
--- a/Powers/bot_class.py
+++ b/Powers/bot_class.py
@@ -93,11 +93,7 @@ class Gojo(Client):
LOGGER.info("Uploading logs before stopping...!\n")
# Send Logs to MESSAGE_DUMP and LOG_CHANNEL
scheduler.remove_all_jobs()
- if MESSAGE_DUMP:
- # LOG_CHANNEL is not necessary
- target = MESSAGE_DUMP
- else:
- target = OWNER_ID
+ target = MESSAGE_DUMP or OWNER_ID
await self.send_document(
target,
document=LOGFILE,
diff --git a/Powers/database/__init__.py b/Powers/database/__init__.py
index eed4ce9c8038400668e44db39cce7a4442c582c6..5b37029d66a4020af4e7b54f91ec15f8e81b5658 100644
--- a/Powers/database/__init__.py
+++ b/Powers/database/__init__.py
@@ -26,10 +26,7 @@ class MongoDB:
# Find one entry from collection
def find_one(self, query):
- result = self.collection.find_one(query)
- if result:
- return result
- return False
+ return result if (result := self.collection.find_one(query)) else False
# Find entries from collection
def find_all(self, query=None):
diff --git a/Powers/database/afk_db.py b/Powers/database/afk_db.py
index 0b2baad8ea952125a75c6c762c04d1236e6bbf47..dfe6962682e0369d5b45d97a9b303612369cc760 100644
--- a/Powers/database/afk_db.py
+++ b/Powers/database/afk_db.py
@@ -15,15 +15,13 @@ class AFK(MongoDB):
def insert_afk(self, chat_id, user_id, time, reason, media_type, media=None):
with INSERTION_LOCK:
- curr = self.check_afk(chat_id=chat_id, user_id=user_id)
- if curr:
+ if curr := self.check_afk(chat_id=chat_id, user_id=user_id):
if reason:
self.update({"chat_id": chat_id, "user_id": user_id}, {
"reason": reason, "time": time})
if media:
self.update({"chat_id": chat_id, "user_id": user_id}, {
'media': media, 'media_type': media_type, "time": time})
- return True
else:
self.insert_one(
{
@@ -35,23 +33,18 @@ class AFK(MongoDB):
"media_type": media_type
}
)
- return True
+ return True
def check_afk(self, chat_id, user_id):
- curr = self.find_one({"chat_id": chat_id, "user_id": user_id})
- if curr:
- return True
- return False
+ return bool(curr := self.find_one({"chat_id": chat_id, "user_id": user_id}))
def get_afk(self, chat_id, user_id):
- curr = self.find_one({"chat_id": chat_id, "user_id": user_id})
- if curr:
+ if curr := self.find_one({"chat_id": chat_id, "user_id": user_id}):
return curr
return
def delete_afk(self, chat_id, user_id):
with INSERTION_LOCK:
- curr = self.check_afk(chat_id, user_id)
- if curr:
+ if curr := self.check_afk(chat_id, user_id):
self.delete_one({"chat_id": chat_id, "user_id": user_id})
return
diff --git a/Powers/database/antispam_db.py b/Powers/database/antispam_db.py
index 67ff591c5aac5c707ed44ff8c4898dbbe16e9077..51c4868355677cb440c665ff295f0d32e16a574b 100644
--- a/Powers/database/antispam_db.py
+++ b/Powers/database/antispam_db.py
@@ -50,8 +50,7 @@ class GBan(MongoDB):
def get_gban(self, user_id: int):
if self.check_gban(user_id):
- curr = self.find_one({"_id": user_id})
- if curr:
+ if curr := self.find_one({"_id": user_id}):
return True, curr["reason"]
return False, ""
diff --git a/Powers/database/approve_db.py b/Powers/database/approve_db.py
index 899af43e4b632920cc241c648b49f9fb179a51a1..41b2901e4f39f3968068f160f7b54f33ea93d3d3 100644
--- a/Powers/database/approve_db.py
+++ b/Powers/database/approve_db.py
@@ -41,11 +41,14 @@ class Approve(MongoDB):
def remove_approve(self, user_id: int):
with INSERTION_LOCK:
if self.check_approve(user_id):
- inde = 0
- for index, user in enumerate(self.chat_info["users"]):
- if user[0] == user_id:
- inde = index
- break
+ inde = next(
+ (
+ index
+ for index, user in enumerate(self.chat_info["users"])
+ if user[0] == user_id
+ ),
+ 0,
+ )
self.chat_info["users"].pop(inde)
return self.update(
{"_id": self.chat_id},
diff --git a/Powers/database/autojoin_db.py b/Powers/database/autojoin_db.py
index 3bff8a50745e9a99d05a218598cee907b5b98b4e..7d7fa3fa20f2d3f60262f806479ccead328d827e 100644
--- a/Powers/database/autojoin_db.py
+++ b/Powers/database/autojoin_db.py
@@ -30,21 +30,14 @@ class AUTOJOIN(MongoDB):
def get_autojoin(self, chat):
curr = self.find_one({"chat_id": chat})
- if not curr:
- return False
- else:
- return curr["type"]
+ return curr["type"] if curr else False
def update_join_type(self, chat, mode):
- curr = self.find_one({"chat_id": chat})
- if curr:
+ if curr := self.find_one({"chat_id": chat}):
self.update({"chat_id": chat}, {"type": mode})
- return
- else:
- return
+ return
def remove_autojoin(self, chat):
- curr = self.find_one({"chat_id": chat})
- if curr:
+ if curr := self.find_one({"chat_id": chat}):
self.delete_one({"chat_id": chat})
return
diff --git a/Powers/database/blacklist_db.py b/Powers/database/blacklist_db.py
index 7252ae288b6a5193936171c03007d68b078bb5c2..a53a4090e28a9cba1557c7470b161b212d47bd86 100644
--- a/Powers/database/blacklist_db.py
+++ b/Powers/database/blacklist_db.py
@@ -21,7 +21,7 @@ class Blacklist(MongoDB):
def check_word_blacklist_status(self, word: str):
with INSERTION_LOCK:
bl_words = self.chat_info["triggers"]
- return bool(word in bl_words)
+ return word in bl_words
def add_blacklist(self, trigger: str):
with INSERTION_LOCK:
@@ -62,7 +62,8 @@ class Blacklist(MongoDB):
with INSERTION_LOCK:
collection = MongoDB(Blacklist.db_name)
curr = collection.find_all()
- return sum(1 for chat in curr if chat["triggers"])
+ return sum(bool(chat["triggers"])
+ for chat in curr)
def set_action(self, action: str):
with INSERTION_LOCK:
diff --git a/Powers/database/captcha_db.py b/Powers/database/captcha_db.py
index 34d41a69b9192b37b542a4a71b7f488c71c7c4c8..b8ffecf20a66b84f93345c66e4ae8325d180436e 100644
--- a/Powers/database/captcha_db.py
+++ b/Powers/database/captcha_db.py
@@ -27,38 +27,29 @@ class CAPTCHA(MongoDB):
return
def is_captcha(self, chat):
- curr = self.find_one({"chat_id": chat})
- if curr:
- return True
- return False
+ return bool(curr := self.find_one({"chat_id": chat}))
def update_type(self, chat, captcha_type):
with INSERTION_LOCK:
- curr = self.is_captcha(chat)
- if curr:
+ if curr := self.is_captcha(chat):
self.update({"chat_id": chat}, {"captcha_type": captcha_type})
return
def update_action(self, chat, captcha_action):
with INSERTION_LOCK:
- curr = self.is_captcha(chat)
- if curr:
+ if curr := self.is_captcha(chat):
self.update({"chat_id": chat}, {
"captcha_action": captcha_action})
return
def remove_captcha(self, chat):
with INSERTION_LOCK:
- curr = self.is_captcha(chat)
- if curr:
+ if curr := self.is_captcha(chat):
self.delete_one({"chat_id": chat})
return
def get_captcha(self, chat):
- curr = self.find_one({"chat_id": chat})
- if curr:
- return curr
- return False
+ return curr if (curr := self.find_one({"chat_id": chat})) else False
class CAPTCHA_DATA(MongoDB):
@@ -69,49 +60,41 @@ class CAPTCHA_DATA(MongoDB):
super().__init__(self.db_name)
def load_cap_data(self, chat, user, data):
- curr = self.find_one({"chat_id": chat, "user_id": user})
- if not curr:
- with INSERTION_LOCK:
- self.insert_one(
- {"chat_id": chat, "user_id": user, "data": data})
- return True
- else:
+ if curr := self.find_one({"chat_id": chat, "user_id": user}):
return
+ with INSERTION_LOCK:
+ self.insert_one(
+ {"chat_id": chat, "user_id": user, "data": data})
+ return True
def get_cap_data(self, chat, user):
- curr = self.find_one({"chat_id": chat, "user_id": user})
- if curr:
+ if curr := self.find_one({"chat_id": chat, "user_id": user}):
return curr["data"]
else:
return False
def remove_cap_data(self, chat, user):
- curr = self.find_one({"chat_id": chat, "user_id": user})
- if curr:
+ if curr := self.find_one({"chat_id": chat, "user_id": user}):
with INSERTION_LOCK:
self.delete_one({"chat_id": chat, "user_id": user})
return
def store_message_id(self, chat, user, message):
- curr = self.find_one({"chat_id": chat, "user_id": user})
- if not curr:
- with INSERTION_LOCK:
- self.insert_one(
- {"chat_id": chat, "user_id": user, "message_id": message})
- return
- else:
+ if curr := self.find_one({"chat_id": chat, "user_id": user}):
+ return
+ with INSERTION_LOCK:
+ self.insert_one(
+ {"chat_id": chat, "user_id": user, "message_id": message})
return
def get_message_id(self, chat, user):
- curr = self.find_one({"chat_id": chat, "user_id": user})
- if curr:
+ if curr := self.find_one({"chat_id": chat, "user_id": user}):
return curr["message_id"]
else:
return False
def is_already_data(self, chat, user):
- curr = self.find_one({"chat_id": chat, "user_id": user})
- if curr:
+ if curr := self.find_one({"chat_id": chat, "user_id": user}):
return curr.get("message_id", False)
else:
return False
diff --git a/Powers/database/chats_db.py b/Powers/database/chats_db.py
index e580f7ffc3ca213f91160edc5e38c3115c33f732..8592a7dc356980c0b65f9141b21cc97ad4edc2fb 100644
--- a/Powers/database/chats_db.py
+++ b/Powers/database/chats_db.py
@@ -19,7 +19,7 @@ class Chats(MongoDB):
self.chat_info = self.__ensure_in_db()
def user_is_in_chat(self, user_id: int):
- return bool(user_id in set(self.chat_info["users"]))
+ return user_id in set(self.chat_info["users"])
def update_chat(self, chat_name: str, user_id: int):
with INSERTION_LOCK:
diff --git a/Powers/database/disable_db.py b/Powers/database/disable_db.py
index 6f821b78a5d7009eeb4b08ed4901564218fe35b7..c64ffa6673553c76718facc8d6d14a618805abb8 100644
--- a/Powers/database/disable_db.py
+++ b/Powers/database/disable_db.py
@@ -27,8 +27,8 @@ class Disabling(MongoDB):
cmds = self.chat_info["commands"]
act = self.chat_info["action"]
DISABLED_CMDS[self.chat_id] = {
- "command": cmds if cmds else [],
- "action": act if act else "none",
+ "command": cmds or [],
+ "action": act or "none",
}
# return bool(cmd in cmds)
return bool(cmd in cmds if cmds else [])
@@ -63,10 +63,10 @@ class Disabling(MongoDB):
except KeyError:
cmds = self.chat_info["commands"]
DISABLED_CMDS[self.chat_id] = {
- "commands": cmds if cmds else [],
+ "commands": cmds or [],
"action": self.chat_info["action"],
}
- return cmds if cmds else []
+ return cmds or []
@staticmethod
def count_disabled_all():
@@ -74,7 +74,7 @@ class Disabling(MongoDB):
collection = MongoDB(Disabling.db_name)
curr = collection.find_all()
return sum(
- len(chat["commands"] if chat["commands"] else []) for chat in curr
+ len(chat["commands"] or []) for chat in curr
)
@staticmethod
@@ -82,7 +82,8 @@ class Disabling(MongoDB):
with INSERTION_LOCK:
collection = MongoDB(Disabling.db_name)
curr = collection.find_all()
- return sum(1 for chat in curr if chat["commands"])
+ return sum(bool(chat["commands"])
+ for chat in curr)
def set_action(self, action: str):
with INSERTION_LOCK:
@@ -91,7 +92,7 @@ class Disabling(MongoDB):
except KeyError:
cmds = self.chat_info["commands"]
DISABLED_CMDS[self.chat_id] = {
- "commands": cmds if cmds else [],
+ "commands": cmds or [],
"action": action,
}
return self.update(
@@ -107,10 +108,10 @@ class Disabling(MongoDB):
cmds = self.chat_info["commands"]
val = self.chat_info["action"]
DISABLED_CMDS[self.chat_id] = {
- "commands": cmds if cmds else [],
+ "commands": cmds or [],
"action": val,
}
- return val if val else "none"
+ return val or "none"
@staticmethod
def count_action_dis_all(action: str):
@@ -118,7 +119,7 @@ class Disabling(MongoDB):
collection = MongoDB(Disabling.db_name)
all_data = collection.find_all({"action": action})
return sum(
- len(i["commands"] if i["commands"] else []) >= 1 for i in all_data
+ len(i["commands"] or []) >= 1 for i in all_data
)
def rm_all_disabled(self):
@@ -171,8 +172,8 @@ class Disabling(MongoDB):
all_data = collection.find_all()
DISABLED_CMDS = {
i["_id"]: {
- "action": i["action"] if i["action"] else "none",
- "commands": i["commands"] if i["commands"] else [],
+ "action": i["action"] or "none",
+ "commands": i["commands"] or [],
}
for i in all_data
}
diff --git a/Powers/database/filters_db.py b/Powers/database/filters_db.py
index 3172a62eeb71ae3d9cd9a3c66db79e65731b053e..7f25b2af3709b97c2cf8be78440e521df7b153eb 100644
--- a/Powers/database/filters_db.py
+++ b/Powers/database/filters_db.py
@@ -21,9 +21,7 @@ class Filters(MongoDB):
fileid="",
):
with INSERTION_LOCK:
- # Database update
- curr = self.find_one({"chat_id": chat_id, "keyword": keyword})
- if curr:
+ if curr := self.find_one({"chat_id": chat_id, "keyword": keyword}):
self.update(
{"chat_id": chat_id, "keyword": keyword},
{
@@ -45,23 +43,20 @@ class Filters(MongoDB):
def get_filter(self, chat_id: int, keyword: str):
with INSERTION_LOCK:
- curr = self.find_one({"chat_id": chat_id, "keyword": keyword})
- if curr:
+ if curr := self.find_one({"chat_id": chat_id, "keyword": keyword}):
return curr
return "Filter does not exist!"
def get_all_filters(self, chat_id: int):
with INSERTION_LOCK:
- curr = self.find_all({"chat_id": chat_id})
- if curr:
+ if curr := self.find_all({"chat_id": chat_id}):
filter_list = {i["keyword"] for i in curr}
return list(filter_list)
return []
def rm_filter(self, chat_id: int, keyword: str):
with INSERTION_LOCK:
- curr = self.find_one({"chat_id": chat_id, "keyword": keyword})
- if curr:
+ if curr := self.find_one({"chat_id": chat_id, "keyword": keyword}):
self.delete_one(curr)
return True
return False
@@ -76,8 +71,7 @@ class Filters(MongoDB):
def count_filter_aliases(self):
with INSERTION_LOCK:
- curr = self.find_all()
- if curr:
+ if curr := self.find_all():
return len(
[z for z in (i["keyword"].split("|")
for i in curr) if len(z) >= 2],
@@ -105,8 +99,7 @@ class Filters(MongoDB):
# Migrate if chat id changes!
def migrate_chat(self, old_chat_id: int, new_chat_id: int):
with INSERTION_LOCK:
- old_chat_db = self.find_one({"_id": old_chat_id})
- if old_chat_db:
+ if old_chat_db := self.find_one({"_id": old_chat_id}):
new_data = old_chat_db.update({"_id": new_chat_id})
self.delete_one({"_id": old_chat_id})
self.insert_one(new_data)
diff --git a/Powers/database/flood_db.py b/Powers/database/flood_db.py
index 99528ec3b21edeb1a2688998f798fe85e8d23bbc..f4ae787981f9306dbe51e92869a02c2abdf12baa 100644
--- a/Powers/database/flood_db.py
+++ b/Powers/database/flood_db.py
@@ -23,22 +23,7 @@ class Floods(MongoDB):
action: str,
):
with INSERTION_LOCK:
- curr = self.find_one({"chat_id": chat_id})
- if curr:
- if not (limit == int(curr['limit']) and within == int(curr['within']) and action == str(curr['action'])):
- return self.update(
- {
- "chat_id": chat_id
- },
- {
- "limit": limit,
- "within": within,
- "action": action,
- }
- )
- else:
- return
- else:
+ if not (curr := self.find_one({"chat_id": chat_id})):
return self.insert_one(
{
"chat_id": chat_id,
@@ -47,27 +32,43 @@ class Floods(MongoDB):
"action": action
},
)
+ if (
+ limit != int(curr['limit'])
+ or within != int(curr['within'])
+ or action != str(curr['action'])
+ ):
+ return self.update(
+ {
+ "chat_id": chat_id
+ },
+ {
+ "limit": limit,
+ "within": within,
+ "action": action,
+ }
+ )
+ else:
+ return
def is_chat(self, chat_id: int):
with INSERTION_LOCK:
- curr = self.find_one({"chat_id": chat_id})
- if curr:
- action = [str(curr['limit']), str(
- curr['within']), str(curr['action'])]
- return action
+ if curr := self.find_one({"chat_id": chat_id}):
+ return [
+ str(curr['limit']),
+ str(curr['within']),
+ str(curr['action']),
+ ]
return False
def get_action(self, chat_id: int):
with INSERTION_LOCK:
- curr = self.find_one({"chat_id": chat_id})
- if curr:
+ if curr := self.find_one({"chat_id": chat_id}):
return curr['action']
return "Flood haven't set"
def rm_flood(self, chat_id: int):
with INSERTION_LOCK:
- curr = self.find_one({"chat_id": chat_id})
- if curr:
+ if curr := self.find_one({"chat_id": chat_id}):
self.delete_one({"chat_id": chat_id})
return True
return False
diff --git a/Powers/database/locks_db.py b/Powers/database/locks_db.py
index 222ecbc098e8316020c9a258c378fb986f964abc..40c118aa169c5d314196d3a8942704bccc504eb7 100644
--- a/Powers/database/locks_db.py
+++ b/Powers/database/locks_db.py
@@ -30,15 +30,13 @@ class LOCKS(MongoDB):
continue
self.insert_one({"chat_id": chat, "locktype": i})
return True
- curr = self.find_one({"chat_id": chat, "locktype": locktype})
- if curr:
+ if curr := self.find_one({"chat_id": chat, "locktype": locktype}):
return False
- else:
- with INSERTION_LOCK:
- hmm = self.merge_u_and_c(chat, locktype)
- if not hmm:
- self.insert_one({"chat_id": chat, "locktype": locktype})
- return True
+ with INSERTION_LOCK:
+ hmm = self.merge_u_and_c(chat, locktype)
+ if not hmm:
+ self.insert_one({"chat_id": chat, "locktype": locktype})
+ return True
def remove_lock_channel(self, chat: int, locktype: str):
"""
@@ -46,12 +44,10 @@ class LOCKS(MongoDB):
"""
if locktype == "all":
for i in lock_t:
- curr = self.find_one({"chat_id": chat, "locktype": i})
- if curr:
+ if curr := self.find_one({"chat_id": chat, "locktype": i}):
self.delete_one({"chat_id": chat, "locktype": i})
return True
- curr = self.find_one({"chat_id": chat, "locktype": locktype})
- if curr:
+ if curr := self.find_one({"chat_id": chat, "locktype": locktype}):
with INSERTION_LOCK:
self.delete_one({"chat_id": chat, "locktype": locktype})
return True
@@ -62,14 +58,22 @@ class LOCKS(MongoDB):
"""
locktypes: anti_c_send, anti_fwd, anti_fwd_u, anti_fwd_c, anti_links, bot
"""
- if locktype not in ["anti_c_send", "anti_fwd", "anti_fwd_u", "anti_fwd_c", "anti_links", "bot", "all"]:
+ if locktype not in [
+ "anti_c_send",
+ "anti_fwd",
+ "anti_fwd_u",
+ "anti_fwd_c",
+ "anti_links",
+ "bot",
+ "all",
+ ]:
return False
+ if locktype != "all":
+ curr = self.find_one(
+ {"chat_id": chat, "locktype": locktype})
+ return bool(curr)
else:
- if locktype != "all":
- curr = self.find_one(
- {"chat_id": chat, "locktype": locktype})
- return bool(curr)
- else:
+ if curr := self.find_all({"chat_id": chat}):
to_return = {
"anti_channel": False,
"anti_fwd": {
@@ -79,26 +83,24 @@ class LOCKS(MongoDB):
"anti_links": False,
"bot": False
}
- curr = self.find_all({"chat_id": chat})
- if not curr:
- return None
- else:
- for i in list(curr):
- if i["locktype"] == "anti_c_send":
- to_return["anti_channel"] = True
- elif i["locktype"] == "anti_fwd":
- to_return["anti_fwd"]["user"] = to_return["anti_fwd"]["chat"] = True
- elif i["locktype"] == "anti_fwd_u":
- to_return["anti_fwd"]["user"] = True
- elif i["locktype"] == "anti_fwd_c":
- to_return["anti_fwd"]["chat"] = True
- elif i["anti_links"] == "anti_links":
- to_return["anti_links"] = True
- elif i["locktype"] == "bot":
- to_return["bot"] = True
- else:
- continue
- return to_return
+ for i in list(curr):
+ if i["locktype"] == "anti_c_send":
+ to_return["anti_channel"] = True
+ elif i["locktype"] == "anti_fwd":
+ to_return["anti_fwd"]["user"] = to_return["anti_fwd"]["chat"] = True
+ elif i["locktype"] == "anti_fwd_u":
+ to_return["anti_fwd"]["user"] = True
+ elif i["locktype"] == "anti_fwd_c":
+ to_return["anti_fwd"]["chat"] = True
+ elif i["anti_links"] == "anti_links":
+ to_return["anti_links"] = True
+ elif i["locktype"] == "bot":
+ to_return["bot"] = True
+ else:
+ continue
+ return to_return
+ else:
+ return None
def merge_u_and_c(self, chat: int, locktype: str):
if locktype == "anti_fwd_u":
@@ -119,8 +121,4 @@ class LOCKS(MongoDB):
"""
locktypes: anti_c_send, anti_fwd, anti_fwd_u, anti_fwd_c, anti_links
"""
- curr = self.find_one({"chat_id": chat, "locktype": locktype})
- if curr:
- return True
- else:
- return False
+ return bool(curr := self.find_one({"chat_id": chat, "locktype": locktype}))
diff --git a/Powers/database/notes_db.py b/Powers/database/notes_db.py
index ad8b757067f9b8a8424de0b24787c4cca72ac101..6e2c9de63f4df2bcf94e9a34007fc51e01e79263 100644
--- a/Powers/database/notes_db.py
+++ b/Powers/database/notes_db.py
@@ -23,10 +23,9 @@ class Notes(MongoDB):
fileid="",
):
with INSERTION_LOCK:
- curr = self.find_one(
+ if curr := self.find_one(
{"chat_id": chat_id, "note_name": note_name},
- )
- if curr:
+ ):
return False
hash_gen = md5(
(note_name + note_value + str(chat_id) + str(int(time()))).encode(),
@@ -44,10 +43,9 @@ class Notes(MongoDB):
def get_note(self, chat_id: int, note_name: str):
with INSERTION_LOCK:
- curr = self.find_one(
+ if curr := self.find_one(
{"chat_id": chat_id, "note_name": note_name},
- )
- if curr:
+ ):
return curr
return "Note does not exist!"
@@ -57,16 +55,13 @@ class Notes(MongoDB):
def get_all_notes(self, chat_id: int):
with INSERTION_LOCK:
curr = self.find_all({"chat_id": chat_id})
- note_list = sorted([(note["note_name"], note["hash"])
- for note in curr])
- return note_list
+ return sorted([(note["note_name"], note["hash"]) for note in curr])
def rm_note(self, chat_id: int, note_name: str):
with INSERTION_LOCK:
- curr = self.find_one(
+ if curr := self.find_one(
{"chat_id": chat_id, "note_name": note_name},
- )
- if curr:
+ ):
self.delete_one(curr)
return True
return False
@@ -77,10 +72,7 @@ class Notes(MongoDB):
def count_notes(self, chat_id: int):
with INSERTION_LOCK:
- curr = self.find_all({"chat_id": chat_id})
- if curr:
- return len(curr)
- return 0
+ return len(curr) if (curr := self.find_all({"chat_id": chat_id})) else 0
def count_notes_chats(self):
with INSERTION_LOCK:
@@ -99,8 +91,7 @@ class Notes(MongoDB):
# Migrate if chat id changes!
def migrate_chat(self, old_chat_id: int, new_chat_id: int):
with INSERTION_LOCK:
- old_chat_db = self.find_one({"_id": old_chat_id})
- if old_chat_db:
+ if old_chat_db := self.find_one({"_id": old_chat_id}):
new_data = old_chat_db.update({"_id": new_chat_id})
self.delete_one({"_id": old_chat_id})
self.insert_one(new_data)
@@ -113,14 +104,12 @@ class NotesSettings(MongoDB):
super().__init__(self.db_name)
def set_privatenotes(self, chat_id: int, status: bool = False):
- curr = self.find_one({"_id": chat_id})
- if curr:
+ if curr := self.find_one({"_id": chat_id}):
return self.update({"_id": chat_id}, {"privatenotes": status})
return self.insert_one({"_id": chat_id, "privatenotes": status})
def get_privatenotes(self, chat_id: int):
- curr = self.find_one({"_id": chat_id})
- if curr:
+ if curr := self.find_one({"_id": chat_id}):
return curr["privatenotes"]
self.update({"_id": chat_id}, {"privatenotes": False})
return False
@@ -138,8 +127,7 @@ class NotesSettings(MongoDB):
# Migrate if chat id changes!
def migrate_chat(self, old_chat_id: int, new_chat_id: int):
with INSERTION_LOCK:
- old_chat_db = self.find_one({"_id": old_chat_id})
- if old_chat_db:
+ if old_chat_db := self.find_one({"_id": old_chat_id}):
new_data = old_chat_db.update({"_id": new_chat_id})
self.delete_one({"_id": old_chat_id})
self.insert_one(new_data)
diff --git a/Powers/database/support_db.py b/Powers/database/support_db.py
index 35148c81813fa9c67a1941b20c0faba5c9748e84..58f3105cc1d2ef954db91caada21fd37b229b80d 100644
--- a/Powers/database/support_db.py
+++ b/Powers/database/support_db.py
@@ -30,8 +30,7 @@ class SUPPORTS(MongoDB):
return
def update_support_user_type(self, user, new_type):
- curr = self.is_support_user(user)
- if curr:
+ if curr := self.is_support_user(user):
with INSERTION_LOCK:
self.update(
{
@@ -44,27 +43,21 @@ class SUPPORTS(MongoDB):
return
def is_support_user(self, user_id):
- curr = self.find_one({"user_id": user_id})
- if curr:
- return True
- return False
+ return bool(curr := self.find_one({"user_id": user_id}))
def delete_support_user(self, user):
- curr = self.is_support_user(user)
- if curr:
+ if curr := self.is_support_user(user):
with INSERTION_LOCK:
self.delete_one({"user_id": user})
return
def get_particular_support(self, support_type):
- curr = self.find_all({"support_type": support_type})
- if curr:
+ if curr := self.find_all({"support_type": support_type}):
return [i['user_id'] for i in curr]
else:
return []
def get_support_type(self, user):
- curr = self.find_one({"user_id": user})
- if curr:
+ if curr := self.find_one({"user_id": user}):
return curr["support_type"]
return False
diff --git a/Powers/database/users_db.py b/Powers/database/users_db.py
index 4a194fe3185e8a5bb03360341e85016bdb21f9cc..b583c09b5960bae3e88a3c2edfe3630fdc208b52 100644
--- a/Powers/database/users_db.py
+++ b/Powers/database/users_db.py
@@ -59,10 +59,7 @@ class Users(MongoDB):
else:
curr = None
- if curr:
- return curr
-
- return {}
+ return curr or {}
def __ensure_in_db(self):
chat_data = self.find_one({"_id": self.user_id})
diff --git a/Powers/plugins/__init__.py b/Powers/plugins/__init__.py
index aa74eba62fe2fd143b067f7944d3f6b9dfff3f82..ad500bbae515cd3a5f316d20b35b78dd1ff7e53b 100644
--- a/Powers/plugins/__init__.py
+++ b/Powers/plugins/__init__.py
@@ -5,7 +5,7 @@ async def all_plugins():
from glob import glob
from os.path import basename, dirname, isfile
- mod_paths = glob(dirname(__file__) + "/*.py")
+ mod_paths = glob(f"{dirname(__file__)}/*.py")
all_plugs = [
basename(f)[:-3]
for f in mod_paths
@@ -36,6 +36,5 @@ from datetime import datetime
def till_date(date):
form = "%Y-%m-%d %H:%M:%S"
- z = datetime.strptime(date,form)
- return z
+ return datetime.strptime(date,form)
diff --git a/Powers/plugins/admin.py b/Powers/plugins/admin.py
index a28b925bcd6d4d3dac9d6345faa5edb3d96ba91f..698690c7e0b352ef5a08bdea36a6e205ddc56a1c 100644
--- a/Powers/plugins/admin.py
+++ b/Powers/plugins/admin.py
@@ -64,12 +64,12 @@ async def adminlist_show(_, m: Message):
adminstr += "\n\nBots:\n"
adminstr += "\n".join(f"- {i}" for i in mention_bots)
await m.reply_text(adminstr + "\n\n" + note)
-
+
except Exception as ef:
if str(ef) == str(m.chat.id):
await m.reply_text(text="Use /admincache to reload admins!")
else:
- ef = str(ef) + f"{admin_list}\n"
+ ef = f"{str(ef)}{admin_list}\n"
await m.reply_text(
text=f"Some error occured, report it using `/bug` \n Error: {ef}
"
)
@@ -95,7 +95,7 @@ async def zombie_clean(c: Gojo, m: Message):
await sleep(e.value)
try:
await c.ban_chat_member(m.chat.id, member.user.id)
- except:
+ except Exception:
pass
if zombie == 0:
return await wait.edit_text("Group is clean!")
@@ -499,9 +499,8 @@ async def set_user_title(c: Gojo, m: Message):
if m.reply_to_message:
if len(m.text.split()) >= 2:
reason = m.text.split(None, 1)[1]
- else:
- if len(m.text.split()) >= 3:
- reason = m.text.split(None, 2)[2]
+ elif len(m.text.split()) >= 3:
+ reason = m.text.split(None, 2)[2]
try:
user_id, _, _ = await extract_user(c, m)
except Exception:
@@ -536,9 +535,7 @@ async def setgpic(c: Gojo, m: Message):
if not m.reply_to_message.photo and not m.reply_to_message.document:
return await m.reply_text("Reply to a photo to set it as chat photo")
photo = await m.reply_to_message.download()
- is_vid = False
- if m.reply_to_message.video:
- is_vid = True
+ is_vid = bool(m.reply_to_message.video)
try:
await m.chat.set_photo(photo,video=is_vid)
except Exception as e:
diff --git a/Powers/plugins/afk.py b/Powers/plugins/afk.py
index 58bced21298ab116d036355ad3ab10363a2095e6..185b9503f086bc040e01ecd4cb8ed07a571560d3 100644
--- a/Powers/plugins/afk.py
+++ b/Powers/plugins/afk.py
@@ -58,12 +58,12 @@ async def get_hours(hour:str):
tim = hour.strip().split(":")
txt = ""
if int(tim[0]):
- txt += tim[0] + " hours "
+ txt += f"{tim[0]} hours "
if int(tim[1]):
- txt += tim[1] + " minutes "
+ txt += f"{tim[1]} minutes "
if int(round(float(tim[2]))):
- txt += str(round(float(tim[2]))) + " seconds"
-
+ txt += f"{str(round(float(tim[2])))} seconds"
+
return txt
@@ -74,12 +74,8 @@ async def afk_checker(c: Gojo, m: Message):
user = m.from_user.id
chat = m.chat.id
repl = m.reply_to_message
-
- if repl and repl.from_user:
- rep_user = repl.from_user.id
- else:
- rep_user = False
+ rep_user = repl.from_user.id if repl and repl.from_user else False
is_afk = afk.check_afk(chat,user)
is_rep_afk = False
if rep_user:
@@ -96,7 +92,7 @@ async def afk_checker(c: Gojo, m: Message):
if len(tim_) == 1:
tims = tim
elif len(tim_) == 2:
- tims = tim_[0] + " " + tim
+ tims = f"{tim_[0]} {tim}"
reason = f"{repl.from_user.first_name} is afk since {tims}\n"
if con['reason'] not in res:
reason += f"\nDue to: {con['reason'].format(first=repl.from_user.first_name)}"
@@ -119,7 +115,7 @@ async def afk_checker(c: Gojo, m: Message):
parse_mode=PM.MARKDOWN,
reply_to_message_id=repl.id
)
-
+
if is_afk:
txt = False
try:
@@ -138,7 +134,7 @@ async def afk_checker(c: Gojo, m: Message):
if len(tim_) == 1:
tims = tim
elif len(tim_) == 2:
- tims = tim_[0] + " " + tim
+ tims = f"{tim_[0]} " + tim
txt = back_.format(first=m.from_user.mention) + f"\n\nAfk for: {tims}"
await m.reply_text(txt)
afk.delete_afk(chat,user)
diff --git a/Powers/plugins/approve.py b/Powers/plugins/approve.py
index f84822f4d9efaee2396660732f7bc13a01fdc5a1..e4437e312da49ebd6949eae10c205ae0c6dec347 100644
--- a/Powers/plugins/approve.py
+++ b/Powers/plugins/approve.py
@@ -44,8 +44,7 @@ async def approve_user(c: Gojo, m: Message):
"User is already admin - blacklists and locks already don't apply to them.",
)
return
- already_approved = db.check_approve(user_id)
- if already_approved:
+ if already_approved := db.check_approve(user_id):
await m.reply_text(
f"{(await mention_html(user_first_name, user_id))} is already approved in {chat_title}",
)
diff --git a/Powers/plugins/auto_join.py b/Powers/plugins/auto_join.py
index 52c6d4fc18ec7d33ba7de49e1d8f18e635888959..816ae68bb1295200e1f88ddb950eb6a2203e19dd 100644
--- a/Powers/plugins/auto_join.py
+++ b/Powers/plugins/auto_join.py
@@ -38,29 +38,21 @@ async def accept_join_requests(c: Gojo, m: Message):
return
else:
yes_no = split[1].lower()
- if yes_no not in ["on","off"]:
- txt = "**USAGE**\n/joinreq [on | off]"
- await m.reply_text(txt)
- return
-
+ if yes_no == "on":
+ is_al = a_j.load_autojoin(m.chat.id)
+
+ txt = (
+ "Now I will approve all the join request of the chat\nIf you want that I will just notify admins about the join request use command\n/joinreqmode [manual | auto]"
+ if is_al
+ else "Auto approve join request is already on for this chat\nIf you want that I will just notify admins about the join request use command\n/joinreqmode [manual | auto]"
+ )
+ elif yes_no == "off":
+ a_j.remove_autojoin(m.chat.id)
+ txt = "Now I will neither auto approve join request nor notify any admins about it"
else:
- if yes_no == "on":
- is_al = a_j.load_autojoin(m.chat.id)
-
- if is_al:
- txt = "Now I will approve all the join request of the chat\nIf you want that I will just notify admins about the join request use command\n/joinreqmode [manual | auto]"
- await m.reply_text(txt)
- return
- else:
- txt = "Auto approve join request is already on for this chat\nIf you want that I will just notify admins about the join request use command\n/joinreqmode [manual | auto]"
- await m.reply_text(txt)
- return
-
- elif yes_no == "off":
- a_j.remove_autojoin(m.chat.id)
- txt = "Now I will neither auto approve join request nor notify any admins about it"
- await m.reply_text(txt)
- return
+ txt = "**USAGE**\n/joinreq [on | off]"
+ await m.reply_text(txt)
+ return
@Gojo.on_message(command("joinreqmode") & admin_filter)
async def join_request_mode(c: Gojo, m: Message):
@@ -68,24 +60,22 @@ async def join_request_mode(c: Gojo, m: Message):
await m.reply_text("Use it in groups")
return
u_text = "**USAGE**\n/joinreqmode [auto | manual]\nauto: auto approve joins\nmanual: will notify admin about the join request"
-
+
split = m.command
a_j = AUTOJOIN()
-
+
if len(split) == 1:
await m.reply_text(u_text)
- return
-
else:
auto_manual = split[1]
if auto_manual not in ["auto","manual"]:
await m.reply_text(u_text)
- return
else:
a_j.update_join_type(m.chat.id,auto_manual)
txt = "Changed join request type"
await m.reply_text(txt)
- return
+
+ return
@Gojo.on_chat_join_request(auto_join_filter)
@@ -138,7 +128,7 @@ async def accept_decline_request(c:Gojo, q: CallbackQuery):
show_alert=True,
)
return
- except:
+ except Exception:
await q.answer("Unknow error occured. You are not admin or owner")
return
split = q.data.split("_")
@@ -147,7 +137,7 @@ async def accept_decline_request(c:Gojo, q: CallbackQuery):
data = split[0]
try:
userr = await c.get_users(user)
- except:
+ except Exception:
userr = None
if data == "accept":
try:
@@ -158,7 +148,7 @@ async def accept_decline_request(c:Gojo, q: CallbackQuery):
await c.send_message(chat,f"Some error occured while approving request, report it using `/bug`\nError: {ef}
")
LOGGER.error(ef)
LOGGER.error(format_exc())
-
+
elif data == "decline":
try:
await c.decline_chat_join_request(chat,user)
diff --git a/Powers/plugins/bans.py b/Powers/plugins/bans.py
index 69b035b8d6ceec5ca0e9fd61b772f9d29e8a5c87..bc04fda2dfc5089ca3189debccc32aeac984ffbe 100644
--- a/Powers/plugins/bans.py
+++ b/Powers/plugins/bans.py
@@ -395,7 +395,7 @@ async def kick_usr(c: Gojo, m: Message):
await m.reply_text(
text="This user is in my support staff, cannot restrict them."
)
-
+
await m.stop_propagation()
try:
@@ -424,7 +424,7 @@ async def kick_usr(c: Gojo, m: Message):
caption=txt,
parse_mode=enums.ParseMode.HTML,
)
- except:
+ except Exception:
await m.reply_text(
reply_to_message_id=r_id,
text=txt,
@@ -554,7 +554,7 @@ async def dkick_usr(c: Gojo, m: Message):
await m.reply_text(
text="This user is in my support staff, cannot restrict them."
)
-
+
await m.stop_propagation()
try:
@@ -582,7 +582,7 @@ async def dkick_usr(c: Gojo, m: Message):
caption=txt,
parse_mode=enums.ParseMode.HTML,
)
- except:
+ except Exception:
await m.reply_text(
txt,
parse_mode=enums.ParseMode.HTML,
@@ -752,7 +752,7 @@ async def dban_usr(c: Gojo, m: Message):
if not m.reply_to_message:
return await m.reply_text("Reply to a message to delete it and ban the user!")
- if m.reply_to_message and not m.reply_to_message.from_user:
+ if not m.reply_to_message.from_user:
user_id, user_first_name = (
m.reply_to_message.sender_chat.id,
m.reply_to_message.sender_chat.title,
@@ -790,10 +790,7 @@ async def dban_usr(c: Gojo, m: Message):
await m.reply_text(text="This user is an admin, I cannot ban them!")
await m.stop_propagation()
- reason = None
- if len(m.text.split()) >= 2:
- reason = m.text.split(None, 1)[1]
-
+ reason = m.text.split(None, 1)[1] if len(m.text.split()) >= 2 else None
try:
await m.reply_to_message.delete()
await m.chat.ban_member(user_id)
@@ -970,14 +967,14 @@ async def unbanbutton(c: Gojo, q: CallbackQuery):
)
return
- elif user and not user.privileges.can_restrict_members and q.from_user.id != OWNER_ID:
+ elif not user.privileges.can_restrict_members and q.from_user.id != OWNER_ID:
await q.answer(
"You don't have enough permission to do this!\nStay in your limits!",
show_alert=True,
)
return
whoo = await c.get_chat(user_id)
- doneto = whoo.first_name if whoo.first_name else whoo.title
+ doneto = whoo.first_name or whoo.title
try:
await q.message.chat.unban_member(user_id)
except RPCError as e:
@@ -989,9 +986,7 @@ async def unbanbutton(c: Gojo, q: CallbackQuery):
@Gojo.on_message(command("kickme"))
async def kickme(c: Gojo, m: Message):
- reason = None
- if len(m.text.split()) >= 2:
- reason = m.text.split(None, 1)[1]
+ reason = m.text.split(None, 1)[1] if len(m.text.split()) >= 2 else None
try:
mem = await c.get_chat_member(m.chat.id,m.from_user.id)
if mem.status in [enums.ChatMemberStatus.ADMINISTRATOR, enums.ChatMemberStatus.OWNER]:
diff --git a/Powers/plugins/birthday.py b/Powers/plugins/birthday.py
index ddaccb545589fb46970b3b263bb3296db480a902..32721858e37b561069c3200ca32bcc22721ed60d 100644
--- a/Powers/plugins/birthday.py
+++ b/Powers/plugins/birthday.py
@@ -19,8 +19,7 @@ from Powers.utils.custom_filters import command
def give_date(date,form = "%d/%m/%Y"):
- datee = datetime.strptime(date,form).date()
- return datee
+ return datetime.strptime(date,form).date()
@Gojo.on_message(command("remember"))
async def remember_me(c: Gojo, m: Message):
@@ -37,24 +36,10 @@ async def remember_me(c: Gojo, m: Message):
DOB = splited[1] if len(splited) == 2 else splited[2]
if len(splited) == 2 and m.reply_to_message:
user = m.reply_to_message.from_user.id
- elif not m.reply_to_message:
- user = m.from_user.id
else:
- try:
- u_id = int(splited[1])
- except ValueError:
- pass
- try:
- user = await c.get_users(u_id)
- except Exception:
- u_u = await c.resolve_peer(u_id)
- try:
- user = (await c.get_users(u_u.user_id)).id
- except KeyError:
- await m.reply_text("Unable to find the user")
- return
+ user = m.from_user.id
DOB = DOB.split("/")
- if len(DOB) != 3 and len(DOB) != 2:
+ if len(DOB) not in [3, 2]:
await m.reply_text("DOB should be in format of dd/mm/yyyy\nYear is optional it is not necessary to pass it")
return
is_correct = False
@@ -72,15 +57,14 @@ async def remember_me(c: Gojo, m: Message):
else:
year = "1900"
is_year = 0
- DOB = f"{str(date)}/{str(month)}/{str(year)}"
+ DOB = f"{date}/{str(month)}/{str(year)}"
except ValueError:
await m.reply_text("DOB should be numbers only")
return
data = {"user_id":user,"dob":DOB,"is_year":is_year}
try:
- result = bday_info.find_one({"user_id":user})
- if result:
+ if result := bday_info.find_one({"user_id": user}):
await m.reply_text("User is already in my database")
return
except Exception as e:
@@ -104,14 +88,12 @@ async def who_are_you_again(c: Gojo, m: Message):
return
user = m.from_user.id
try:
- result = bday_info.find_one({"user_id":user})
- if not result:
- await m.reply_text("User is not in my database")
- return
- elif result:
+ if result := bday_info.find_one({"user_id": user}):
bday_info.delete_one({"user_id":user})
await m.reply_text("Removed your birthday")
- return
+ else:
+ await m.reply_text("User is not in my database")
+ return
except Exception as e:
await m.reply_text(f"Got an error\n{e}")
return
@@ -133,10 +115,7 @@ async def who_is_next(c: Gojo, m: Message):
if Chats(m.chat.id).user_is_in_chat(i["user_id"]):
dob = give_date(i["dob"])
if dob.month >= curr.month:
- if (dob.month == curr.month and not dob.day < curr.day) or dob.month >= curr.month:
- users.append(i)
- elif dob.month < curr.month:
- pass
+ users.append(i)
if len(users) == 10:
break
if not users:
@@ -210,7 +189,7 @@ async def chat_birthday_settings(c: Gojo, m: Message):
kb = IKM(
[
[
- IKB(f"{'Yes' if not c_in else 'No'}",f"switchh_{'yes' if not c_in else 'no'}"),
+ IKB(f"{'No' if c_in else 'Yes'}",f"switchh_{'no' if c_in else 'yes'}"),
IKB("Close", "f_close")
]
]
diff --git a/Powers/plugins/captcha.py b/Powers/plugins/captcha.py
index c288e4c497954f9085173c7d5735d47603f576f8..f05a9dcbf5f394294862bdde6d8d893e7dcb773b 100644
--- a/Powers/plugins/captcha.py
+++ b/Powers/plugins/captcha.py
@@ -32,20 +32,18 @@ async def start_captcha(_, m: Message):
else:
txt = "Captcha verification is currently **off** for this chat"
await m.reply_text(txt)
- return
else:
on_off = split[1].lower()
if on_off in ["on", "yes", "enable"]:
captcha.insert_captcha(m.chat.id)
await m.reply_text("Captcha verification is now **on** for this chat")
- return
elif on_off in ["off", "no", "disable"]:
captcha.remove_captcha(m.chat.id)
await m.reply_text("Captcha verification is now **off** for this chat")
- return
else:
await m.reply_text("**USAGE**\n/captcha [on | yes | enable | off | no | disable]")
- return
+
+ return
@Gojo.on_message(command("captchamode") & admin_filter & ~filters.private)
@@ -53,28 +51,22 @@ async def set_captcha_mode(c: Gojo, m: Message):
split = m.command
captcha = CAPTCHA()
if len(split) == 1:
- curr = captcha.get_captcha(m.chat.id)
- if curr:
+ if curr := captcha.get_captcha(m.chat.id):
capatcha_type = curr["captcha_type"]
await m.reply_text(f"Current captcha verification methode is {capatcha_type}\nAvailable methodes:\nβ qr\nβ image")
- return
else:
await m.reply_text("Captcha verification is off for the current chat")
- return
else:
type_ = split[1].lower()
if type_ == "qr":
await m.reply_text("This feature is not implemented yet\nUse /captchamode image")
- # captcha.update_type(m.chat.id, "qr")
- # await m.reply_text("Captcha verification is now changed to qr code")
- return
elif type_ == "image":
captcha.update_type(m.chat.id, "image")
await m.reply_text("Captcha verication is now changed to image")
- return
else:
await m.reply_text("**USAGE**\n/captchamode [qr | image]")
- return
+
+ return
@Gojo.on_callback_query(filters.regex("^captcha_"))
@@ -103,7 +95,6 @@ async def captcha_codes_check(c: Gojo, q: CallbackQuery):
return
await c.send_message(chat, f"{q.from_user.mention} now you are free to talk")
await q.message.delete()
- return
else:
caps = q.message.caption.split(":")
tries = int(caps[1].strip()) - 1
@@ -139,7 +130,7 @@ async def captcha_codes_check(c: Gojo, q: CallbackQuery):
parse_mode=PM.HTML,
)
except Exception:
-
+
await c.send_animation(
chat_id=q.message.chat.id,
text=txt,
@@ -149,10 +140,10 @@ async def captcha_codes_check(c: Gojo, q: CallbackQuery):
await c.send_message(MESSAGE_DUMP,f"#REMOVE from BAN_GFIS\n{anim}")
c_data.remove_cap_data(chat, user)
c_data.del_message_id(q.message.chat.id, user)
- return
else:
await q.edit_message_caption(new_cap, reply_markup=q.message.reply_markup)
- return
+
+ return
@Gojo.on_message(filters.group & captcha_filter & filters.new_chat_members, group=3)
@@ -163,7 +154,7 @@ async def on_chat_members_updatess(c: Gojo, m: Message):
for user in users:
captcha = CAPTCHA()
cap_data = CAPTCHA_DATA()
-
+
if user.is_bot:
continue
SUPPORT_STAFF = DEV_USERS.union(SUDO_USERS).union(WHITELIST_USERS)
@@ -172,7 +163,7 @@ async def on_chat_members_updatess(c: Gojo, m: Message):
status = (await m.chat.get_member(user)).status
if status in [CMS.OWNER, CMS.ADMINISTRATOR]:
continue
- except:
+ except Exception:
pass
if user.id in SUPPORT_STAFF:
continue
@@ -202,23 +193,15 @@ async def on_chat_members_updatess(c: Gojo, m: Message):
if not is_already:
captcha_type = "image" # I am not going to apply qr captcha in this update
- if captcha_type == "qr":
- pic = await get_qr_captcha(chat, user.id, c.me.username)
- cap = f"Please {user.mention} scan this qr code with your phone to verify that you are human"
- ms = await c.send_photo(chat, pic, caption=cap)
- os.remove(pic)
- cap_data.store_message_id(chat, user.id, ms.id)
- continue
- elif captcha_type == "image":
+ if captcha_type == "image":
img, code = await get_image_captcha(chat, user.id)
cap = f"Please {user.mention} please choose the correct code from the one given bellow\nYou have three tries if you get all three wrong u will be banned from the chat.\nTries left: 3"
cap_data.load_cap_data(chat, user.id, code)
rand = [code]
while len(rand) != 5:
hehe = genrator()
- if hehe == code:
- continue
- rand.append(hehe)
+ if hehe != code:
+ rand.append(hehe)
shuffle(rand)
@@ -245,8 +228,13 @@ async def on_chat_members_updatess(c: Gojo, m: Message):
)
await c.send_photo(chat, img, caption=cap, reply_markup=kb)
os.remove(img)
- continue
- elif is_already and mess:
+ elif captcha_type == "qr":
+ pic = await get_qr_captcha(chat, user.id, c.me.username)
+ cap = f"Please {user.mention} scan this qr code with your phone to verify that you are human"
+ ms = await c.send_photo(chat, pic, caption=cap)
+ os.remove(pic)
+ cap_data.store_message_id(chat, user.id, ms.id)
+ elif mess:
kb = ikm(
[
[
diff --git a/Powers/plugins/chat_blacklist.py b/Powers/plugins/chat_blacklist.py
index 16960625ac666988a6006a09307232e83327cd06..c427415c0b2b592893d015244eea284ae4c7e0ae 100644
--- a/Powers/plugins/chat_blacklist.py
+++ b/Powers/plugins/chat_blacklist.py
@@ -33,13 +33,12 @@ async def blacklist_chat(c: Gojo, m: Message):
await replymsg.edit_text(
f"Added the following chats to Blacklist.\n{', '.join(chat_ids)}
.",
)
+ elif m.chat.type == CT.PRIVATE:
+ await m.reply_text("Use in groups")
else:
- if m.chat.type == CT.PRIVATE:
- await m.reply_text("Use in groups")
- else:
- chat_id = m.chat.id
- db.add_chat(chat_id)
- await m.reply_text("Added this chat to blacklist chats")
+ chat_id = m.chat.id
+ db.add_chat(chat_id)
+ await m.reply_text("Added this chat to blacklist chats")
return
@@ -69,16 +68,15 @@ async def unblacklist_chat(c: Gojo, m: Message):
await replymsg.edit_text(
f"Removed the following chats to Blacklist.\n{', '.join(chat_ids)}
.",
)
+ elif m.chat.type == CT.PRIVATE:
+ await m.reply_text("Use in groups")
else:
- if m.chat.type == CT.PRIVATE:
- await m.reply_text("Use in groups")
+ chat_id = m.chat.id
+ bl_chats = bl_chats = db.list_all_chats()
+ if chat_id in bl_chats:
+ await m.reply_text("Removed this chat from blacklist chats")
else:
- chat_id = m.chat.id
- bl_chats = bl_chats = db.list_all_chats()
- if chat_id not in bl_chats:
- await m.reply_text("This chat is not in my list of blacklisted chats")
- else:
- await m.reply_text("Removed this chat from blacklist chats")
+ await m.reply_text("This chat is not in my list of blacklisted chats")
return
@@ -86,8 +84,7 @@ async def unblacklist_chat(c: Gojo, m: Message):
command(["blchatlist", "blchats"], dev_cmd=True),
)
async def list_blacklist_chats(_, m: Message):
- bl_chats = db.list_all_chats()
- if bl_chats:
+ if bl_chats := db.list_all_chats():
txt = (
(
"These Chats are Blacklisted:\n"
diff --git a/Powers/plugins/dev.py b/Powers/plugins/dev.py
index c64056b6bf6636b854bfda1bd4822060d2fee598..750fa9b2394d28da612b4f0927d0d4188e35c318 100644
--- a/Powers/plugins/dev.py
+++ b/Powers/plugins/dev.py
@@ -46,8 +46,7 @@ async def add_support(c: Gojo, m:Message):
await m.reply_text("Stay in you limit")
return
split = m.command
- reply_to = m.reply_to_message
- if reply_to:
+ if reply_to := m.reply_to_message:
try:
userr = reply_to.from_user.id
except Exception:
@@ -65,7 +64,6 @@ async def add_support(c: Gojo, m:Message):
if m.from_user.id == int(OWNER_ID):
if to == curr:
await m.reply_text(f"This user is already in {to} users")
- return
elif curr:
kb = IKM(
[
@@ -76,7 +74,6 @@ async def add_support(c: Gojo, m:Message):
]
)
await m.reply_text(f"This is user is already in {curr} users\nDo you want to make him {to} user?",reply_markup=kb)
- return
else:
support.insert_support_user(userr,to)
if to == "dev":
@@ -86,12 +83,10 @@ async def add_support(c: Gojo, m:Message):
else:
WHITELIST_USERS.add(userr)
await m.reply_text(f"This user is now a {to} user")
- return
- can_do = can_change_type(curr_user,to)
- if can_do:
+ return
+ if can_do := can_change_type(curr_user, to):
if to == curr:
await m.reply_text(f"This user is already in {to} users")
- return
elif curr:
kb = IKM(
[
@@ -102,14 +97,12 @@ async def add_support(c: Gojo, m:Message):
]
)
await m.reply_text(f"This is user is already in {curr} users\nDo you want to make him {to} user?",reply_markup=kb)
- return
else:
support.insert_support_user(userr,to)
await m.reply_text(f"This user is now a {to} user")
- return
else:
await m.reply_text("Sorry you can't do it")
- return
+ return
elif len(split) >= 3:
user = split[1]
try:
@@ -129,7 +122,6 @@ async def add_support(c: Gojo, m:Message):
if m.from_user.id == int(OWNER_ID):
if to == curr:
await m.reply_text(f"This user is already in {to} users")
- return
elif curr:
kb = IKM(
[
@@ -140,16 +132,13 @@ async def add_support(c: Gojo, m:Message):
]
)
await m.reply_text(f"This is user is already in {curr} users\nDo you want to make him {to} user?",reply_markup=kb)
- return
else:
support.insert_support_user(userr,to)
await m.reply_text(f"This user is now a {to} user")
- return
- can_do = can_change_type(curr_user,to)
- if can_do:
+ return
+ if can_do := can_change_type(curr_user, to):
if to == curr:
await m.reply_text(f"This user is already in {to} users")
- return
elif curr:
kb = IKM(
[
@@ -160,14 +149,12 @@ async def add_support(c: Gojo, m:Message):
]
)
await m.reply_text(f"This is user is already in {curr} users\nDo you want to make him {to} user?",reply_markup=kb)
- return
else:
support.insert_support_user(userr,to)
await m.reply_text(f"This user is now a {to} user")
- return
else:
await m.reply_text("Sorry you can't do it")
- return
+ return
@Gojo.on_message(command("rmsupport"))
async def rm_support(c: Gojo, m: Message):
@@ -177,9 +164,7 @@ async def rm_support(c: Gojo, m: Message):
await m.reply_text("Stay in you limit")
return
split = m.command
- reply_to = m.reply_to_message
-
- if reply_to:
+ if reply_to := m.reply_to_message:
try:
curr = reply_to.from_user.id
except Exception:
@@ -292,12 +277,8 @@ async def neofetch_stats(_, m: Message):
stderr=subprocess.PIPE,
)
stdout, stderr = await process.communicate()
- e = stderr.decode()
- if not e:
- e = "No Error"
- OUTPUT = stdout.decode()
- if not OUTPUT:
- OUTPUT = "No Output"
+ e = stderr.decode() or "No Error"
+ OUTPUT = stdout.decode() or "No Output"
try:
await m.reply_text(OUTPUT, quote=True)
@@ -347,15 +328,11 @@ async def evaluate_code(c: Gojo, m: Message):
f"@{m.from_user.username} TREID TO USE `while True` \n userid = {m.from_user.id}"
)
return
- if m.reply_to_message and m.reply_to_message.document:
- if m.reply_to_message.document.mime_type.split("/")[1] == "x-python" or m.reply_to_message.document.file_name.endswith("py"):
- await sm.delete()
- await m.reply_text("Loading external plugin is prohibited")
- return
- reply_to_id = m.id
- if m.reply_to_message:
- reply_to_id = m.reply_to_message.id
-
+ if m.reply_to_message and m.reply_to_message.document and (m.reply_to_message.document.mime_type.split("/")[1] == "x-python" or m.reply_to_message.document.file_name.endswith("py")):
+ await sm.delete()
+ await m.reply_text("Loading external plugin is prohibited")
+ return
+ reply_to_id = m.reply_to_message.id if m.reply_to_message else m.id
old_stderr = sys.stderr
old_stdout = sys.stdout
redirected_output = sys.stdout = StringIO()
@@ -398,27 +375,25 @@ async def evaluate_code(c: Gojo, m: Message):
return
for j in HARMFUL:
- if j in evaluation.split() or j in cmd:
- if m.from_user.id != OWNER_ID:
+ if (j in evaluation.split() or j in cmd) and m.from_user.id != OWNER_ID:
+ evaluation = "Bhaag ja bsdk"
+ await c.send_message(
+ MESSAGE_DUMP,
+ f"@{m.from_user.username} TREID TO FETCH ENV OF BOT \n userid = {m.from_user.id}")
+ final_output = f"**EVAL**: ```python\n{cmd}```\n\nOUTPUT:\n```powershell\n{evaluation}``` \n"
+ await sm.edit(final_output)
+ return
+ for i in evaluation.split():
+ for j in i.split("="):
+ if j and j[0] in HARMFUL and m.from_user.id != OWNER_ID:
evaluation = "Bhaag ja bsdk"
await c.send_message(
MESSAGE_DUMP,
- f"@{m.from_user.username} TREID TO FETCH ENV OF BOT \n userid = {m.from_user.id}")
+ f"@{m.from_user.username} TREID TO FETCH ENV OF BOT \n userid = {m.from_user.id}"
+ )
final_output = f"**EVAL**: ```python\n{cmd}```\n\nOUTPUT:\n```powershell\n{evaluation}``` \n"
await sm.edit(final_output)
return
- for i in evaluation.split():
- for j in i.split("="):
- if j and j[0] in HARMFUL:
- if m.from_user.id != OWNER_ID:
- evaluation = "Bhaag ja bsdk"
- await c.send_message(
- MESSAGE_DUMP,
- f"@{m.from_user.username} TREID TO FETCH ENV OF BOT \n userid = {m.from_user.id}"
- )
- final_output = f"**EVAL**: ```python\n{cmd}```\n\nOUTPUT:\n```powershell\n{evaluation}``` \n"
- await sm.edit(final_output)
- return
try:
final_output = f"**EVAL**: ```python\n{cmd}```\n\nOUTPUT:\n```powershell\n{evaluation}``` \n"
@@ -456,22 +431,15 @@ async def execution(c: Gojo, m: Message):
sm = await m.reply_text("`Processing...`\n")
cmd = m.text.split(maxsplit=1)[1]
- reply_to_id = m.id
- if m.reply_to_message:
- reply_to_id = m.reply_to_message.id
-
+ reply_to_id = m.reply_to_message.id if m.reply_to_message else m.id
process = await create_subprocess_shell(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = await process.communicate()
- e = stderr.decode().strip()
- if not e:
- e = "No Error"
- o = stdout.decode().strip()
- if not o:
- o = "No Output"
+ e = stderr.decode().strip() or "No Error"
+ o = stdout.decode().strip() or "No Output"
out = o
xxx = o.split()
for OwO in xxx:
@@ -480,31 +448,19 @@ async def execution(c: Gojo, m: Message):
break
for x in xxx:
xx = x.split("=")
- if xx and xx[0] in HARMFUL:
- if m.from_user.id != OWNER_ID:
- out = "You can't access them"
- await c.send_message(
- MESSAGE_DUMP,
- f"@{m.from_user.username} TREID TO FETCH ENV OF BOT \n userid = {m.from_user.id}",
- )
- else:
- pass
- else:
- pass
+ if xx and xx[0] in HARMFUL and m.from_user.id != OWNER_ID:
+ out = "You can't access them"
+ await c.send_message(
+ MESSAGE_DUMP,
+ f"@{m.from_user.username} TREID TO FETCH ENV OF BOT \n userid = {m.from_user.id}",
+ )
for x in HARMFUL:
- if x in out:
- if m.from_user.id != OWNER_ID:
- out = "You can't access them"
- await c.send_message(
- MESSAGE_DUMP,
- f"@{m.from_user.username} TREID TO FETCH ENV OF BOT \n userid = {m.from_user.id}",
- )
- else:
- pass
- else:
- pass
-
-
+ if x in out and m.from_user.id != OWNER_ID:
+ out = "You can't access them"
+ await c.send_message(
+ MESSAGE_DUMP,
+ f"@{m.from_user.username} TREID TO FETCH ENV OF BOT \n userid = {m.from_user.id}",
+ )
OUTPUT = ""
OUTPUT += f"QUERY:\nCommand:\n{cmd}
\n"
OUTPUT += f"PID: {process.pid}
\n\n"
@@ -692,7 +648,7 @@ async def forward_type_broadcast(c: Gojo, m: Message):
await m.reply_text("Please reply to message to broadcast it")
return
split = m.command
-
+
chat = Chats.list_chats_by_id()
user = [i["_id"] for i in Users.list_users()]
alll = chat + user
@@ -714,7 +670,7 @@ async def forward_type_broadcast(c: Gojo, m: Message):
peers = user
else:
peers = alll
-
+
xx = await m.reply_text("Broadcasting...")
failed = 0
@@ -725,7 +681,6 @@ async def forward_type_broadcast(c: Gojo, m: Message):
await sleep(0.1)
except Exception:
failed += 1
- pass
txt = f"Broadcasted message to {total-failed} peers out of {total}\nFailed to broadcast message to {failed} peers"
if not failed:
txt = f"Broadcasted message to {total} peers"
diff --git a/Powers/plugins/disable.py b/Powers/plugins/disable.py
index a616edeb135133fdb8f2e0588fbe6790a48d7ed2..edcd12fa4d8080de89eed653b83a756e3447a098 100644
--- a/Powers/plugins/disable.py
+++ b/Powers/plugins/disable.py
@@ -41,10 +41,7 @@ async def set_dsbl_action(_, m: Message):
db = Disabling(m.chat.id)
status = db.get_action()
- if status == "none":
- cur = False
- else:
- cur = True
+ cur = status != "none"
args = m.text.split(" ", 1)
if len(args) >= 2:
@@ -80,8 +77,9 @@ async def disabling(_, m: Message):
for j in [HELP_COMMANDS[i]["disablable"] for i in list(HELP_COMMANDS.keys())]
for k in j
)
- tes = "List of commnds that can be disabled:\n"
- tes += "\n".join(f" β’ {escape(i)}
" for i in disable_cmd_keys)
+ tes = "List of commnds that can be disabled:\n" + "\n".join(
+ f" β’ {escape(i)}
" for i in disable_cmd_keys
+ )
return await m.reply_text(tes)
@@ -92,8 +90,9 @@ async def disabled(_, m: Message):
if not disable_list:
await m.reply_text("No disabled items!")
return
- tex = "Disabled commands:\n"
- tex += "\n".join(f" β’ {escape(i)}
" for i in disable_list)
+ tex = "Disabled commands:\n" + "\n".join(
+ f" β’ {escape(i)}
" for i in disable_list
+ )
return await m.reply_text(tex)
diff --git a/Powers/plugins/filters.py b/Powers/plugins/filters.py
index 222dbc3a23db8e25fc2577b349b50f289b943bd9..034cfd5fb2ebb2133610c3f60ba7485b65ac7581 100644
--- a/Powers/plugins/filters.py
+++ b/Powers/plugins/filters.py
@@ -95,8 +95,7 @@ async def add_filter(_, m: Message):
"Please provide data for this filter reply with!",
)
- add = db.save_filter(m.chat.id, keyword, teks, msgtype, file_id)
- if add:
+ if add := db.save_filter(m.chat.id, keyword, teks, msgtype, file_id):
await m.reply_text(
f"Saved filter for '{', '.join(keyword.split('|'))}
' in {m.chat.title}!",
)
@@ -137,17 +136,16 @@ async def stop_filter(_, m: Message):
& owner_filter,
)
async def rm_allfilters(_, m: Message):
- all_bls = db.get_all_filters(m.chat.id)
- if not all_bls:
+ if all_bls := db.get_all_filters(m.chat.id):
+ return await m.reply_text(
+ "Are you sure you want to clear all filters?",
+ reply_markup=ikb(
+ [[("β οΈ Confirm", "rm_allfilters"), ("β Cancel", "close_admin")]],
+ ),
+ )
+ else:
return await m.reply_text("No filters to stop in this chat.")
- return await m.reply_text(
- "Are you sure you want to clear all filters?",
- reply_markup=ikb(
- [[("β οΈ Confirm", "rm_allfilters"), ("β Cancel", "close_admin")]],
- ),
- )
-
@Gojo.on_callback_query(filters.regex("^rm_allfilters$"))
async def rm_allfilters_callback(_, q: CallbackQuery):
diff --git a/Powers/plugins/flood.py b/Powers/plugins/flood.py
index 0216ffe1da5b48863fc9fb78bb4f29b3396274d2..12024f6c178b72710ca765272bfd00bbe7ba005f 100644
--- a/Powers/plugins/flood.py
+++ b/Powers/plugins/flood.py
@@ -21,35 +21,20 @@ on_key = ["on", "start", "disable"]
off_key = ["off", "end", "enable", "stop"]
async def get_what_temp(what):
- temp_duration = InlineKeyboardMarkup(
+ return InlineKeyboardMarkup(
[
[
- InlineKeyboardButton(
- "5 minutes",
- f"f_temp_{what}_5min"
- ),
+ InlineKeyboardButton("5 minutes", f"f_temp_{what}_5min"),
InlineKeyboardButton(
"10 minute",
f"f_temp_{what}_10min",
),
- InlineKeyboardButton(
- "30 minute",
- f"f_temp_{what}_30min"
- ),
- InlineKeyboardButton(
- "1 hour",
- f"f_temp_{what}_60min"
- )
+ InlineKeyboardButton("30 minute", f"f_temp_{what}_30min"),
+ InlineKeyboardButton("1 hour", f"f_temp_{what}_60min"),
],
- [
- InlineKeyboardButton(
- "Β« Back",
- "f_temp_back"
- )
- ]
+ [InlineKeyboardButton("Β« Back", "f_temp_back")],
]
)
- return temp_duration
close_kb =InlineKeyboardMarkup(
[
@@ -152,15 +137,13 @@ async def flood_action(c: Gojo, m: Message):
Flood = Floods()
bot = await c.get_chat_member(m.chat.id, c.me.id)
status = bot.status
- if not status in [CMS.OWNER, CMS.ADMINISTRATOR]:
- if not bot.privileges.can_restrict_members:
+ if status not in [CMS.OWNER, CMS.ADMINISTRATOR] and not bot.privileges.can_restrict_members:
return await m.reply_text("Give me permission to restict member first")
if m.chat.type == CT.PRIVATE:
await m.reply_text("Use this command in group")
return
c_id = m.chat.id
- is_flood = Flood.is_chat(c_id)
- if is_flood:
+ if is_flood := Flood.is_chat(c_id):
saction = is_flood[2]
await m.reply_text(
f"Choose a action given bellow to do when flood happens.\n **CURRENT ACTION** is {saction}",
@@ -190,8 +173,7 @@ async def flood_set(c: Gojo, m: Message):
bot = await c.get_chat_member(m.chat.id, c.me.id)
Flood = Floods()
status = bot.status
- if not status in [CMS.OWNER, CMS.ADMINISTRATOR]:
- if not bot.privileges.can_restrict_members:
+ if status not in [CMS.OWNER, CMS.ADMINISTRATOR] and not bot.privileges.can_restrict_members:
return await m.reply_text("Give me permission to restict member first")
if m.chat.type == CT.PRIVATE:
return await m.reply_text("This command is ment to be used in groups.")
@@ -207,7 +189,7 @@ async def flood_set(c: Gojo, m: Message):
swithin = is_flood[1]
return await m.reply_text(f"Flood is on for this chat\n**Action**:{saction}\n**Messages**:{slimit} within {swithin} sec")
return await m.reply_text("Flood protection is off of this chat.")
-
+
if len(split) == 2:
c_id = m.chat.id
if split[1].lower() in on_key:
@@ -241,8 +223,7 @@ async def callbacks(c: Gojo, q: CallbackQuery):
return
c_id = q.message.chat.id
Flood = Floods()
- is_flood = Flood.is_chat(c_id)
- if is_flood:
+ if is_flood := Flood.is_chat(c_id):
saction = is_flood[2]
slimit = is_flood[0]
swithin = is_flood[1]
@@ -251,7 +232,7 @@ async def callbacks(c: Gojo, q: CallbackQuery):
if user in SUPPORT_STAFF or user_status in [CMS.OWNER, CMS.ADMINISTRATOR]:
if data in ["f_mute", "f_ban", "f_kick", "f_skip"]:
change = data.split("_")[1]
- if not change == saction:
+ if change != saction:
Flood.save_flood(c_id, slimit, swithin, change)
await q.answer("Updated action", show_alert=True)
await q.edit_message_text(
@@ -279,7 +260,7 @@ async def callbacks(c: Gojo, q: CallbackQuery):
kb = action_kb
await q.edit_message_text(
f"Choose a action given bellow to do when flood happens.\n **CURRENT ACTION** is {saction}",
- reply_markup=action_kb
+ reply_markup=kb,
)
return
kb = await get_what_temp(to_do)
@@ -303,21 +284,16 @@ async def callbacks(c: Gojo, q: CallbackQuery):
reply_markup=within_kb
)
return
- if not change == slimit:
+ if change != slimit:
Flood.save_flood(c_id, change, swithin, saction)
await q.answer("Updated limit", show_alert=True)
- await q.edit_message_text(
- f"Set the time with the number of message recived treated as flood\n **CUURENT TIME** {swithin}",
- reply_markup=within_kb
- )
- return
else:
await q.answer("Updated action", show_alert=True)
- await q.edit_message_text(
- f"Set the time with the number of message recived treated as flood\n **CUURENT TIME** {swithin}",
- reply_markup=within_kb
- )
- return
+ await q.edit_message_text(
+ f"Set the time with the number of message recived treated as flood\n **CUURENT TIME** {swithin}",
+ reply_markup=within_kb
+ )
+ return
elif data in ["f_f_5", "f_f_10", "f_f_15", "f_f_skip"]:
data = data.split("_")[-1]
try:
@@ -329,7 +305,7 @@ async def callbacks(c: Gojo, q: CallbackQuery):
)
await q.answer("skip")
return
- if not change == swithin:
+ if change != swithin:
Flood.save_flood(c_id, slimit, change, saction)
await q.answer("Updated", show_alert=True)
await q.edit_message_text(
@@ -367,7 +343,7 @@ async def reverse_callbacks(c: Gojo, q: CallbackQuery):
)
return
whoo = await c.get_chat(user_id)
- doneto = whoo.first_name if whoo.first_name else whoo.title
+ doneto = whoo.first_name or whoo.title
try:
await q.message.chat.unban_member(user_id)
except RPCError as e:
@@ -398,22 +374,22 @@ dic = {}
@Gojo.on_message(flood_filter, 18)
async def flood_watcher(c: Gojo, m: Message):
c_id = m.chat.id
-
+
Flood = Floods()
-
+
u_id = m.from_user.id
-
+
is_flood = Flood.is_chat(c_id)
-
+
action = is_flood[2]
limit = int(is_flood[0])
within = int(is_flood[1])
-
+
if not len(dic):
z = {c_id : {u_id : [[],[]]}}
dic.update(z)
-
+
try:
dic[c_id] # access and check weather the c_id present or not
except KeyError:
@@ -425,18 +401,18 @@ async def flood_watcher(c: Gojo, m: Message):
except KeyError:
z = {u_id : [[],[]]}
dic[c_id].update(z) # make the dic something like {c_id : {u_id : [[for time],[for msg]]}}
-
+
sec = round(time.time())
-
+
try:
dic[c_id][u_id][0].append(sec)
dic[c_id][u_id][1].append("x")
except KeyError:
dic[c_id].update({u_id : [[sec], ["x"]]})
-
+
x = int(dic[c_id][u_id][0][0])
y = int(dic[c_id][u_id][0][-1])
-
+
if len(dic[c_id][u_id][1]) == limit:
if y-x <= within:
action = action.split("_")
@@ -444,11 +420,11 @@ async def flood_watcher(c: Gojo, m: Message):
try:
to_do = action[0]
for_tim = int(action[1].replace("min",""))
- except:
+ except Exception:
for_tim = 30
for_how_much = datetime.now() + timedelta(minutes=for_tim)
- if to_do == "ban":
- try:
+ try:
+ if to_do == "ban":
await m.chat.ban_member(u_id, until_date=for_how_much)
keyboard = InlineKeyboardMarkup(
[
@@ -466,30 +442,7 @@ async def flood_watcher(c: Gojo, m: Message):
caption=txt,
reply_markup=keyboard,
)
- dic[c_id][u_id][1].clear()
- dic[c_id][u_id][0].clear()
- return
-
- except UserAdminInvalid:
- await m.reply_text(
- "I can't protect this chat from this user",
- )
- dic[c_id][u_id][1].clear()
- dic[c_id][u_id][0].clear()
- return
- except RPCError as ef:
- await m.reply_text(
- text=f"""Some error occured, report it using `/bug`
-
- Error: {ef}
"""
- )
- LOGGER.error(ef)
- LOGGER.error(format_exc())
- dic[c_id][u_id][1].clear()
- dic[c_id][u_id][0].clear()
- return
- else:
- try:
+ else:
await m.chat.restrict_member(
u_id,
ChatPermissions(),
@@ -511,27 +464,28 @@ async def flood_watcher(c: Gojo, m: Message):
caption=txt,
reply_markup=keyboard,
)
- dic[c_id][u_id][1].clear()
- dic[c_id][u_id][0].clear()
- return
- except UserAdminInvalid:
- await m.reply_text(
- "I can't protect this chat from this user",
+ dic[c_id][u_id][1].clear()
+ dic[c_id][u_id][0].clear()
+ return
+
+ except UserAdminInvalid:
+ await m.reply_text(
+ "I can't protect this chat from this user",
)
- dic[c_id][u_id][1].clear()
- dic[c_id][u_id][0].clear()
- return
- except RPCError as ef:
- await m.reply_text(
- text=f"""Some error occured, report it using `/bug`
+ dic[c_id][u_id][1].clear()
+ dic[c_id][u_id][0].clear()
+ return
+ except RPCError as ef:
+ await m.reply_text(
+ text=f"""Some error occured, report it using `/bug`
Error: {ef}
"""
)
- LOGGER.error(ef)
- LOGGER.error(format_exc())
- dic[c_id][u_id][1].clear()
- dic[c_id][u_id][0].clear()
- return
+ LOGGER.error(ef)
+ LOGGER.error(format_exc())
+ dic[c_id][u_id][1].clear()
+ dic[c_id][u_id][0].clear()
+ return
else:
action = action[0]
if action == "ban":
@@ -575,7 +529,7 @@ async def flood_watcher(c: Gojo, m: Message):
dic[c_id][u_id][1].clear()
dic[c_id][u_id][0].clear()
return
-
+
elif action == "kick":
try:
d = datetime.now()+timedelta(seconds=31) #will automatically unban user after 31 seconds kind of fail safe if unban members doesn't work properly
diff --git a/Powers/plugins/fun.py b/Powers/plugins/fun.py
index 303aab6294a103142e4036cf68ede233bd424d5d..da7c7c96bd384d029bdeefd1a651b4e7f87f4f94 100644
--- a/Powers/plugins/fun.py
+++ b/Powers/plugins/fun.py
@@ -24,8 +24,10 @@ async def fun_shout(_, m: Message):
try:
text = " ".join(m.text.split(None, 1)[1])
result = [" ".join(list(text))]
- for pos, symbol in enumerate(text[1:]):
- result.append(symbol + " " + " " * pos + symbol)
+ result.extend(
+ f"{symbol} " + " " * pos + symbol
+ for pos, symbol in enumerate(text[1:])
+ )
result = list("\n".join(result))
result[0] = text[0]
result = "".join(result)
@@ -50,12 +52,9 @@ async def fun_slap(c: Gojo, m: Message):
reply_text = m.reply_to_message.reply_text if m.reply_to_message else m.reply_text
curr_user = escape(m.from_user.first_name)
- if m.reply_to_message:
- user = m.reply_to_message.from_user
- else:
- user = m.from_user
+ user = m.reply_to_message.from_user if m.reply_to_message else m.from_user
user_id = user.id
-
+
if user_id == me.id:
temp = choice(extras.SLAP_GOJO_TEMPLATES)
else:
@@ -64,7 +63,7 @@ async def fun_slap(c: Gojo, m: Message):
if user_id != m.from_user.id:
user1 = curr_user
user2 = user.first_name
-
+
else:
user1 = me.first_name
user2 = curr_user
diff --git a/Powers/plugins/greetings.py b/Powers/plugins/greetings.py
index 20ce0878357f159aac0c451ca126e03ac6fc589f..72773404f5fa11919960c78b88a6f0568b62fef1 100644
--- a/Powers/plugins/greetings.py
+++ b/Powers/plugins/greetings.py
@@ -273,78 +273,8 @@ async def member_has_joined(c: Gojo, m: Message):
"chatname",
]
hmm = await escape_mentions_using_curly_brackets_wl(user, m, oo, parse_words)
- if status:
- tek, button = await parse_button(hmm)
- button = await build_keyboard(button)
- button = ikb(button) if button else None
-
- if "%%%" in tek:
- filter_reply = tek.split("%%%")
- teks = choice(filter_reply)
- else:
- teks = tek
-
- if not teks:
- teks = f"A wild {user.mention} appeared in {m.chat.title}! Everyone be aware."
-
- ifff = db.get_current_cleanwelcome_id()
- gg = db.get_current_cleanwelcome_settings()
- if ifff and gg:
- try:
- await c.delete_messages(m.chat.id, int(ifff))
- except RPCError:
- pass
- if not teks:
- teks = "Hey {first}, welcome to {chatname}"
- try:
- if not UwU:
- jj = await c.send_message(
- m.chat.id,
- text=teks,
- reply_markup=button,
- disable_web_page_preview=True,
- )
- elif UwU:
- jj = await (await send_cmd(c,mtype))(
- m.chat.id,
- UwU,
- caption=teks,
- reply_markup=button,
- )
-
- if jj:
- db.set_cleanwlcm_id(int(jj.id))
- except ChannelPrivate:
- continue
- except RPCError as e:
- LOGGER.error(e)
- LOGGER.error(format_exc(e))
- continue
- else:
+ if not status:
continue
-
-
-@Gojo.on_message(filters.group & filters.left_chat_member, group=99)
-async def member_has_left(c: Gojo, m: Message):
- db = Greetings(m.chat.id)
- status = db.get_goodbye_status()
- oo = db.get_goodbye_text()
- UwU = db.get_goodbye_media()
- mtype = db.get_goodbye_msgtype()
- parse_words = [
- "first",
- "last",
- "fullname",
- "id",
- "username",
- "mention",
- "chatname",
- ]
-
- user = m.left_chat_member if m.left_chat_member else m.from_user
-
- hmm = await escape_mentions_using_curly_brackets_wl(user, m, oo, parse_words)
- if status:
tek, button = await parse_button(hmm)
button = await build_keyboard(button)
button = ikb(button) if button else None
@@ -355,50 +285,115 @@ async def member_has_left(c: Gojo, m: Message):
else:
teks = tek
- if not teks: #Just in case
- teks = f"Thanks for being part of this group {user.mention}. But I don't like your arrogance and leaving the group {emoji.EYES}"
-
- ifff = db.get_current_cleangoodbye_id()
- iii = db.get_current_cleangoodbye_settings()
- if ifff and iii:
+ if not teks:
+ teks = f"A wild {user.mention} appeared in {m.chat.title}! Everyone be aware."
+
+ ifff = db.get_current_cleanwelcome_id()
+ gg = db.get_current_cleanwelcome_settings()
+ if ifff and gg:
try:
await c.delete_messages(m.chat.id, int(ifff))
except RPCError:
pass
- if user.id in DEV_USERS:
- await c.send_message(
- m.chat.id,
- f"Will miss you my master {user.mention} :(",
- )
- return
if not teks:
- teks = "Sad to see you leaving {first}\nTake Care!"
+ teks = "Hey {first}, welcome to {chatname}"
try:
if not UwU:
- ooo = await c.send_message(
+ jj = await c.send_message(
m.chat.id,
text=teks,
reply_markup=button,
disable_web_page_preview=True,
)
- elif UwU:
- ooo = await (await send_cmd(c,mtype))(
+ else:
+ jj = await (await send_cmd(c,mtype))(
m.chat.id,
UwU,
caption=teks,
reply_markup=button,
)
- if ooo:
- db.set_cleangoodbye_id(int(ooo.id))
- return
+ if jj:
+ db.set_cleanwlcm_id(int(jj.id))
except ChannelPrivate:
- pass
+ continue
except RPCError as e:
LOGGER.error(e)
LOGGER.error(format_exc(e))
- return
+
+
+@Gojo.on_message(filters.group & filters.left_chat_member, group=99)
+async def member_has_left(c: Gojo, m: Message):
+ db = Greetings(m.chat.id)
+ status = db.get_goodbye_status()
+ oo = db.get_goodbye_text()
+ UwU = db.get_goodbye_media()
+ mtype = db.get_goodbye_msgtype()
+ parse_words = [
+ "first",
+ "last",
+ "fullname",
+ "id",
+ "username",
+ "mention",
+ "chatname",
+ ]
+
+ user = m.left_chat_member or m.from_user
+
+ hmm = await escape_mentions_using_curly_brackets_wl(user, m, oo, parse_words)
+ if not status:
+ return
+ tek, button = await parse_button(hmm)
+ button = await build_keyboard(button)
+ button = ikb(button) if button else None
+
+ if "%%%" in tek:
+ filter_reply = tek.split("%%%")
+ teks = choice(filter_reply)
else:
+ teks = tek
+
+ if not teks: #Just in case
+ teks = f"Thanks for being part of this group {user.mention}. But I don't like your arrogance and leaving the group {emoji.EYES}"
+
+ ifff = db.get_current_cleangoodbye_id()
+ iii = db.get_current_cleangoodbye_settings()
+ if ifff and iii:
+ try:
+ await c.delete_messages(m.chat.id, int(ifff))
+ except RPCError:
+ pass
+ if user.id in DEV_USERS:
+ await c.send_message(
+ m.chat.id,
+ f"Will miss you my master {user.mention} :(",
+ )
+ return
+ if not teks:
+ teks = "Sad to see you leaving {first}\nTake Care!"
+ try:
+ ooo = (
+ await (await send_cmd(c, mtype))(
+ m.chat.id,
+ UwU,
+ caption=teks,
+ reply_markup=button,
+ ) if UwU else await c.send_message(
+ m.chat.id,
+ text=teks,
+ reply_markup=button,
+ disable_web_page_preview=True,
+ )
+ )
+ if ooo:
+ db.set_cleangoodbye_id(int(ooo.id))
+ return
+ except ChannelPrivate:
+ pass
+ except RPCError as e:
+ LOGGER.error(e)
+ LOGGER.error(format_exc(e))
return
@@ -456,7 +451,7 @@ async def welcome(c: Gojo, m: Message):
reply_markup=button,
disable_web_page_preview=True,
)
- elif UwU:
+ else:
await (await send_cmd(c,mtype))(
m.chat.id,
UwU,
@@ -518,7 +513,7 @@ async def goodbye(c: Gojo, m: Message):
reply_markup=button,
disable_web_page_preview=True,
)
- elif UwU:
+ else:
await (await send_cmd(c,mtype))(
m.chat.id,
UwU,
diff --git a/Powers/plugins/info.py b/Powers/plugins/info.py
index c3698ef57f2653272bf61b11d1b0e5e8b567843d..9587f844bb517e795054a09c0aaad90f407af190 100644
--- a/Powers/plugins/info.py
+++ b/Powers/plugins/info.py
@@ -90,7 +90,7 @@ async def user_info(c: Gojo, user, already=False):
is_verified = user.is_verified
is_restricted = user.is_restricted
photo_id = user.photo.big_file_id if user.photo else None
- is_support = True if user_id in SUPPORT_STAFF else False
+ is_support = bool(user_id in SUPPORT_STAFF)
if user_id == c.me.id:
is_support = "A person is a great support to himself"
omp = "Hmmm.......Who is that again?"
@@ -107,7 +107,7 @@ async def user_info(c: Gojo, user, already=False):
omp = "Owner of the bot"
if user_id in DEV_USERS and user_id == OWNER_ID:
omp = "Dev and Owner"
-
+
is_scam = user.is_scam
is_bot = user.is_bot
is_fake = user.is_fake
@@ -194,10 +194,7 @@ async def chat_info(c: Gojo, chat, already=False):
caption = f"Failed to find the chat due to\n{e}"
return caption, None
chat_id = chat.id
- if u_name:
- username = " ".join([f"@{i}"for i in u_name])
- elif not u_name:
- username = chat.username
+ username = " ".join([f"@{i}"for i in u_name]) if u_name else chat.username
total_bot, total_admin, total_bot_admin, total_banned = await count(c, chat.id)
title = chat.title
type_ = str(chat.type).split(".")[1]
@@ -218,7 +215,7 @@ async def chat_info(c: Gojo, chat, already=False):
π Chat Title: {title}
β¨ Chat Type: {type_}
π DataCentre ID: {dc_id}
-π Username: {("@" + username) if username else "NA"}
+π Username: {f"@{username}" if username else "NA"}
βοΈ Administrators: {total_admin}
π€ Bots: {total_bot}
π« Banned: {total_banned}
@@ -243,7 +240,7 @@ async def info_func(c: Gojo, message: Message):
return
try:
user, _, user_name = await extract_user(c, message)
- except:
+ except Exception:
await message.reply_text("Got Some errors failed to fetch user info")
LOGGER.error(e)
LOGGER.error(format_exc)
@@ -251,7 +248,7 @@ async def info_func(c: Gojo, message: Message):
await message.reply_text("Can't find user to fetch info!")
m = await message.reply_text(
- f"Fetching {('@' + user_name) if user_name else 'user'} info from telegram's database..."
+ f"Fetching {f'@{user_name}' if user_name else 'user'} info from telegram's database..."
)
try:
@@ -287,7 +284,7 @@ async def info_func(c: Gojo, message: Message):
if e == "User not found ! Error: 'InputPeerChannel' object has no attribute 'user_id'":
await m.reply_text("Looks like you are trying to fetch info of a chat not an user. In that case please use /chinfo")
return
-
+
await message.reply_text(text=e)
LOGGER.error(e)
LOGGER.error(format_exc())
@@ -311,7 +308,7 @@ async def chat_info_func(c: Gojo, message: Message):
try:
chat = int(chat)
- except (ValueError, Exception) as ef:
+ except Exception as ef:
if "invalid literal for int() with base 10:" in str(ef):
chat = str(chat)
if chat.startswith("https://"):
@@ -322,9 +319,9 @@ async def chat_info_func(c: Gojo, message: Message):
)
m = await message.reply_text(
- f"Fetching chat info of chat from telegram's database....."
+ "Fetching chat info of chat from telegram's database....."
)
-
+
try:
info_caption, photo_id = await chat_info(c, chat=chat)
if info_caption.startswith("Failed to find the chat due"):
diff --git a/Powers/plugins/locks.py b/Powers/plugins/locks.py
index dedc9aa54269a32485abf032d3c59c7f27f6d20c..f593ac5ddadcdd95b18b87ac213d3a64fe3e946f 100644
--- a/Powers/plugins/locks.py
+++ b/Powers/plugins/locks.py
@@ -195,9 +195,7 @@ Use /locktypes to get the lock types"""
pass
except ChatAdminRequired:
await m.reply_text(text="I don't have permission to do that")
- await m.reply_text(
- "π " + f"Locked {perm} for this Chat.",
- )
+ await m.reply_text(f"π Locked {perm} for this Chat.")
await prevent_approved(m)
return
@@ -208,9 +206,7 @@ async def view_locks(_, m: Message):
v_perm = m.chat.permissions
async def convert_to_emoji(val: bool):
- if val:
- return "β
"
- return "β"
+ return "β
" if val else "β"
lock = LOCKS()
anon = lock.get_lock_channel(m.chat.id, "anti_c_send")
@@ -369,13 +365,11 @@ async def unlock_perm(c: Gojo, m: Message):
await m.reply_text("Send as chat is now enabled for this chat")
return
elif unlock_type in ["links", "url"]:
- curr = lock.remove_lock_channel(m.chat.id, "anti_links")
- if curr:
+ if curr := lock.remove_lock_channel(m.chat.id, "anti_links"):
await m.reply_text("Sending link is now allowed")
- return
else:
await m.reply_text("Sending link is not allowed")
- return
+ return
elif unlock_type == "forwardall":
curr = lock.remove_lock_channel(m.chat.id, "anti_fwd")
@@ -432,9 +426,7 @@ async def unlock_perm(c: Gojo, m: Message):
pass
except ChatAdminRequired:
await m.reply_text(text="I don't have permission to do that")
- await m.reply_text(
- "π " + f"Unlocked {uperm} for this Chat.",
- )
+ await m.reply_text(f"π Unlocked {uperm} for this Chat.")
await prevent_approved(m)
return
@@ -460,9 +452,15 @@ async def is_approved_user(c: Gojo, m: Message):
SUDO_LEVEL = DEV_USERS.union(SUDO_USERS)
if m.forward_from:
- if m.from_user and (m.from_user.id in ul or m.from_user.id in SUDO_LEVEL or m.from_user.id in admins_group or m.from_user.id == c.me.id):
- return True
- return False
+ return bool(
+ m.from_user
+ and (
+ m.from_user.id in ul
+ or m.from_user.id in SUDO_LEVEL
+ or m.from_user.id in admins_group
+ or m.from_user.id == c.me.id
+ )
+ )
elif m.forward_from_chat:
if m.from_user and (m.from_user.id in ul or m.from_user.id in SUDO_LEVEL or m.from_user.id in admins_group or m.from_user.id == c.me.id):
return True
@@ -471,9 +469,12 @@ async def is_approved_user(c: Gojo, m: Message):
else:
return False
elif m.from_user:
- if m.from_user.id in ul or m.from_user.id in SUDO_LEVEL or m.from_user.id in admins_group or m.from_user.id == c.me.id:
- return True
- return False
+ return (
+ m.from_user.id in ul
+ or m.from_user.id in SUDO_LEVEL
+ or m.from_user.id in admins_group
+ or m.from_user.id == c.me.id
+ )
else:
return False
@@ -504,7 +505,12 @@ async def lock_del_mess(c: Gojo, m: Message):
if not chat_locks:
return
- if chat_locks["anti_channel"] and m.sender_chat and not (m.forward_from_chat or m.forward_from):
+ if (
+ chat_locks["anti_channel"]
+ and m.sender_chat
+ and not m.forward_from_chat
+ and not m.forward_from
+ ):
if m.chat.is_admin:
return
await delete_messages(c, m)
diff --git a/Powers/plugins/muting.py b/Powers/plugins/muting.py
index ffdf6f2258bae067e0125ad4ec326679a97b1a30..295ef9c7c96893994e58706a020a45944630b775 100644
--- a/Powers/plugins/muting.py
+++ b/Powers/plugins/muting.py
@@ -479,13 +479,7 @@ async def dmute_usr(c: Gojo, m: Message):
if not m.reply_to_message:
return await m.reply_text("No replied message and user to delete and mute!")
- reason = None
- if m.reply_to_message:
- if len(m.text.split()) >= 2:
- reason = m.text.split(None, 1)[1]
- else:
- if len(m.text.split()) >= 3:
- reason = m.text.split(None, 2)[2]
+ reason = m.text.split(None, 1)[1] if len(m.text.split()) >= 2 else None
user_id = m.reply_to_message.from_user.id
user_first_name = m.reply_to_message.from_user.first_name
diff --git a/Powers/plugins/notes.py b/Powers/plugins/notes.py
index a62cc3896a73a752adb37dd212de61f8364e0d52..920d7e9713221a6df5c5f1cd5e8ca0af2ee4e7e5 100644
--- a/Powers/plugins/notes.py
+++ b/Powers/plugins/notes.py
@@ -323,9 +323,7 @@ async def local_notes(c: Gojo, m: Message):
msg_id = m.reply_to_message.id if m.reply_to_message else m.id
- curr_pref = db_settings.get_privatenotes(m.chat.id)
- if curr_pref:
-
+ if curr_pref := db_settings.get_privatenotes(m.chat.id):
pm_kb = ikb(
[
[
diff --git a/Powers/plugins/pin.py b/Powers/plugins/pin.py
index 58ac70a04e734ee300717684705ad762499f807b..12c4265b7d68bca490facd4c184dbdfb1b7a4101 100644
--- a/Powers/plugins/pin.py
+++ b/Powers/plugins/pin.py
@@ -18,15 +18,15 @@ async def pin_message(_, m: Message):
pin_args = m.text.split(None, 1)
if m.reply_to_message:
try:
- disable_notification = True
-
- if len(pin_args) >= 2 and pin_args[1] in ["alert", "notify", "loud"]:
- disable_notification = False
-
+ disable_notification = len(pin_args) < 2 or pin_args[1] not in [
+ "alert",
+ "notify",
+ "loud",
+ ]
await m.reply_to_message.pin(
disable_notification=disable_notification,
)
-
+
if m.chat.username:
# If chat has a username, use this format
@@ -162,8 +162,6 @@ async def anti_channel_pin(_, m: Message):
async def pinned_message(c: Gojo, m: Message):
chat_title = m.chat.title
chat = await c.get_chat(chat_id=m.chat.id)
- msg_id = m.reply_to_message.id if m.reply_to_message else m.id
-
if chat.pinned_message:
pinned_id = chat.pinned_message.id
if m.chat.username:
@@ -173,6 +171,8 @@ async def pinned_message(c: Gojo, m: Message):
link_chat_id = (str(m.chat.id)).replace("-100", "")
message_link = f"https://t.me/c/{link_chat_id}/{pinned_id}"
+ msg_id = m.reply_to_message.id if m.reply_to_message else m.id
+
await m.reply_text(
f"The pinned message of {escape_html(chat_title)} is [here]({message_link}).",
reply_to_message_id=msg_id,
diff --git a/Powers/plugins/rules.py b/Powers/plugins/rules.py
index a2a22ef94dc861e7d589a364d816d20303d0734f..29bcf0fc5fe09a6ca2847a49b1be04755a87cd0a 100644
--- a/Powers/plugins/rules.py
+++ b/Powers/plugins/rules.py
@@ -25,9 +25,7 @@ async def get_rules(c: Gojo, m: Message):
)
return
- priv_rules_status = db.get_privrules()
-
- if priv_rules_status:
+ if priv_rules_status := db.get_privrules():
pm_kb = ikb(
[
[
@@ -76,7 +74,7 @@ async def set_rules(_, m: Message):
return await m.reply_text("Provide some text to set as rules !!")
if len(rules) > 4000:
- rules = rules[0:3949] # Split Rules if len > 4000 chars
+ rules = rules[:3949]
await m.reply_text("Rules are truncated to 3950 characters!")
db.set_rules(rules)
diff --git a/Powers/plugins/scheduled_jobs.py b/Powers/plugins/scheduled_jobs.py
index 9a4fad38af7ecbda0e64e5998b37e336e439d835..9a5618762c2b8fde96f53954b9252bd5c294cb06 100644
--- a/Powers/plugins/scheduled_jobs.py
+++ b/Powers/plugins/scheduled_jobs.py
@@ -17,8 +17,7 @@ from Powers.utils.extras import birthday_wish
def give_date(date,form = "%d/%m/%Y"):
- datee = datetime.strptime(date,form).date()
- return datee
+ return datetime.strptime(date,form).date()
scheduler = AsyncIOScheduler()
scheduler.timezone = TIME_ZONE
@@ -38,10 +37,10 @@ async def send_wishish(JJK: Client):
agee = ""
if i["is_year"]:
agee = curr.year - dob.year
- suffix = {1: 'st', 2: 'nd', 3: 'rd'}
if int(agee/10) == 1:
suf = "th"
else:
+ suffix = {1: 'st', 2: 'nd', 3: 'rd'}
suffix.get((agee%10), "th")
agee = f"{agee}{suf}"
U = await JJK.get_chat_member(chat_id=j,user_id=i["user_id"])
diff --git a/Powers/plugins/search.py b/Powers/plugins/search.py
index 1e0ee22697f97adc16a12afc1bb6a908d848c537..010f9cc2d8c0459aa7fdcc747f715146c0644e0a 100644
--- a/Powers/plugins/search.py
+++ b/Powers/plugins/search.py
@@ -233,14 +233,11 @@ async def getText(message: Message):
text_to_return = message.text
if message.text is None:
return None
- if " " in text_to_return:
- try:
- return message.text.split(None, 1)[1]
- except IndexError:
- return None
- except Exception:
- return None
- else:
+ if " " not in text_to_return:
+ return None
+ try:
+ return message.text.split(None, 1)[1]
+ except Exception:
return None
@Gojo.on_message(command(["images","imgs"]))
@@ -258,9 +255,7 @@ async def get_image_search(_, m: Message):
return
image_urls = resp.get("image_urls", [])[:10]
ab = await m.reply_text("Getting Your Images... Wait A Min..\nCredits: @NovaXMod")
- Ok = []
- for a in image_urls:
- Ok.append(InputMediaPhoto(a))
+ Ok = [InputMediaPhoto(a) for a in image_urls]
try:
await m.reply_media_group(media=Ok)
await ab.delete()
diff --git a/Powers/plugins/start.py b/Powers/plugins/start.py
index 95e3ad5c6665973a649a57e25c60a0f36790f5e7..16a1a097742465a28f58178e60040ed79807a7d5 100644
--- a/Powers/plugins/start.py
+++ b/Powers/plugins/start.py
@@ -127,13 +127,13 @@ async def start(c: Gojo, m: Message):
]
]
)
- except:
+ except Exception:
chat_ = False
kb = None
await m.reply_text("You can now talk in the chat", reply_markup=kb)
try:
await c.delete_messages(chat, msg)
- except:
+ except Exception:
pass
return
except Exception:
@@ -313,7 +313,10 @@ async def get_divided_msg(plugin_name: str, page:int=1, back_to_do = None):
new_msg += f"{i}\n"
kb = [
[
- ("Next page βΆοΈ", f"iter_page_{plugin_name}_{(back_to_do+'_') if back_to_do else ''}{page+1}")
+ (
+ "Next page βΆοΈ",
+ f"iter_page_{plugin_name}_{f'{back_to_do}_' if back_to_do else ''}{page + 1}",
+ )
]
]
else:
@@ -323,23 +326,28 @@ async def get_divided_msg(plugin_name: str, page:int=1, back_to_do = None):
new_msg += f"{i}\n"
kb = [
[
- ("βοΈ Previous page", f"iter_page_{plugin_name}_{(back_to_do+'_') if back_to_do else ''}{page-1}")
+ (
+ "βοΈ Previous page",
+ f"iter_page_{plugin_name}_{f'{back_to_do}_' if back_to_do else ''}{page - 1}",
+ )
]
]
else:
for i in msg[first:last]:
new_msg += f"{i}\n"
kb = [
- [
- ("βοΈ Previous page", f"iter_page_{plugin_name}_{(back_to_do+'_') if back_to_do else ''}{page-1}"),
- ("Next page βΆοΈ", f"iter_page_{plugin_name}_{(back_to_do+'_') if back_to_do else ''}{page+1}")
- ]
+ [
+ (
+ "βοΈ Previous page",
+ f"iter_page_{plugin_name}_{f'{back_to_do}_' if back_to_do else ''}{page - 1}",
+ ),
+ (
+ "Next page βΆοΈ",
+ f"iter_page_{plugin_name}_{f'{back_to_do}_' if back_to_do else ''}{page + 1}",
+ ),
]
- if back_to_do:
- kb = ikb(kb, True, back_to_do)
- else:
- kb = ikb(kb)
-
+ ]
+ kb = ikb(kb, True, back_to_do) if back_to_do else ikb(kb)
return new_msg, kb
@Gojo.on_callback_query(filters.regex(r"^iter_page_.*[0-9]$"))
@@ -348,7 +356,7 @@ async def helppp_page_iter(c: Gojo, q: CallbackQuery):
plugin_ = data[2]
try:
back_to = data[-2]
- except:
+ except Exception:
back_to = None
curr_page = int(data[-1])
msg, kb = await get_divided_msg(plugin_, curr_page, back_to_do=back_to)
@@ -420,7 +428,7 @@ async def give_bot_staffs(c: Gojo, q: CallbackQuery):
pass
true_sudo = list(set(SUDO_USERS) - set(DEV_USERS))
reply += "\nSudo Users π:\n"
- if true_sudo == []:
+ if not true_sudo:
reply += "No Sudo Users\n"
else:
for each_user in true_sudo:
diff --git a/Powers/plugins/stats.py b/Powers/plugins/stats.py
index da0bac422083ea8079fce19a6db2703384b3a482..726bee2475436d6ad22f3507941e895561b138e8 100644
--- a/Powers/plugins/stats.py
+++ b/Powers/plugins/stats.py
@@ -67,6 +67,6 @@ async def get_stats(c: Gojo, m: Message):
)
try:
await replymsg.edit_text(rply, parse_mode=enums.ParseMode.HTML)
- except:
+ except Exception:
await c.send_message(m.chat.id, rply, parse_mode=enums.ParseMode.HTML)
return
diff --git a/Powers/plugins/stickers.py b/Powers/plugins/stickers.py
index f32dec66663aad70c46c6a1a5ac0d790264041fb..a49378ecb98d23a4ed28f7ad426088995c16d474 100644
--- a/Powers/plugins/stickers.py
+++ b/Powers/plugins/stickers.py
@@ -22,10 +22,7 @@ from Powers.utils.web_helpers import get_file_size
@Gojo.on_message(command(["stickerinfo","stinfo"]))
async def give_st_info(c: Gojo , m: Message):
- if not m.reply_to_message:
- await m.reply_text("Reply to a sticker")
- return
- elif not m.reply_to_message.sticker:
+ if not m.reply_to_message or not m.reply_to_message.sticker:
await m.reply_text("Reply to a sticker")
return
st_in = m.reply_to_message.sticker
@@ -49,10 +46,7 @@ Pack name : {st_in.set_name}
@Gojo.on_message(command(["stickerid","stid"]))
async def sticker_id_gib(c: Gojo, m: Message):
- if not m.reply_to_message:
- await m.reply_text("Reply to a sticker")
- return
- elif not m.reply_to_message.sticker:
+ if not m.reply_to_message or not m.reply_to_message.sticker:
await m.reply_text("Reply to a sticker")
return
st_in = m.reply_to_message.sticker
@@ -70,9 +64,8 @@ async def kang(c:Gojo, m: Message):
return await m.reply_text("You are anon admin, kang stickers in my pm.")
msg = await m.reply_text("Kanging Sticker..")
is_requ = False
- if m.reply_to_message.sticker:
- if m.reply_to_message.sticker.is_animated or m.reply_to_message.sticker.is_video:
- is_requ = True
+ if m.reply_to_message.sticker and (m.reply_to_message.sticker.is_animated or m.reply_to_message.sticker.is_video):
+ is_requ = True
# Find the proper emoji
args = m.text.split()
if len(args) > 1:
@@ -120,7 +113,7 @@ async def kang(c:Gojo, m: Message):
sticker_emoji
)
os.remove(path)
- elif m.reply_to_message.sticker and not is_requ:
+ elif m.reply_to_message.sticker:
sticker = await create_sticker(
await get_document_from_file_id(
m.reply_to_message.sticker.file_id
@@ -128,8 +121,8 @@ async def kang(c:Gojo, m: Message):
sticker_emoji
)
else:
- await m.reply_text("Unsupported media file...")
- return
+ await m.reply_text("Unsupported media file...")
+ return
except ShortnameOccupyFailed:
await m.reply_text("Change Your Name Or Username")
return
@@ -151,7 +144,7 @@ async def kang(c:Gojo, m: Message):
try:
while not packname_found:
packname = f"CE{m.from_user.id}{packnum}_by_{c.me.username}"
- kangpack = f"{('@'+m.from_user.username) if m.from_user.username else m.from_user.first_name[:10]} {('vOl '+str(volume)) if volume else ''} by @{c.me.username}"
+ kangpack = f"{f'@{m.from_user.username}' if m.from_user.username else m.from_user.first_name[:10]} {f'vOl {str(volume)}' if volume else ''} by @{c.me.username}"
if limit >= 50: # To prevent this loop from running forever
await m.reply_text("Failed to kang\nMay be you have made more than 50 sticker packs with me try deleting some")
return
@@ -225,16 +218,16 @@ async def remove_sticker_from_pack(c: Gojo, m: Message):
return await m.reply_text(
"Reply to a sticker to remove it from the pack."
)
-
+
sticker = m.reply_to_message.sticker
- to_modify = await m.reply_text(f"Removing the sticker from your pack")
+ to_modify = await m.reply_text("Removing the sticker from your pack")
sticker_set = await get_sticker_set_by_name(c, sticker.set_name)
if not sticker_set:
await to_modify.edit_text("This sticker is not part for your pack")
return
-
+
try:
await remove_sticker(c, sticker.file_id)
await to_modify.edit_text(f"Successfully removed [sticker]({m.reply_to_message.link}) from {sticker_set.set.title}")
@@ -269,17 +262,12 @@ async def memify_it(c: Gojo, m: Message):
await m.reply_text("Give me something to write")
return
filll = m.command[0][-1]
- if filll == "b":
- fiil = "black"
- else:
- fiil = "white"
+ fiil = "black" if filll == "b" else "white"
x = await m.reply_text("Memifying...")
meme = m.text.split(None,1)[1].strip()
name = f"@memesofdank_{m.id}.png"
path = await rep_to.download(name)
- is_sticker = False
- if rep_to.sticker:
- is_sticker = True
+ is_sticker = bool(rep_to.sticker)
output = await draw_meme(path,meme,is_sticker,fiil)
await x.delete()
xNx = await m.reply_photo(output[0],reply_markup=kb)
@@ -299,12 +287,23 @@ async def get_sticker_from_file(c: Gojo, m: Message):
if not repl:
await m.reply_text("Reply to a sticker or file")
return
- to_vid = False
- if not (repl.animation or repl.video or repl.sticker or repl.photo or (repl.document and repl.document.mime_type.split("/")[0] in ["image","video"])):
+ if (
+ not repl.animation
+ and not repl.video
+ and not repl.sticker
+ and not repl.photo
+ and (
+ not repl.document
+ or repl.document.mime_type.split("/")[0] not in ["image", "video"]
+ )
+ ):
await m.reply_text("I only support conversion of plain stickers, images, videos and animation for now")
return
- if repl.animation or repl.video or (repl.document and repl.document.mime_type.split("/")[0]=="video"):
- to_vid = True
+ to_vid = bool(
+ repl.animation
+ or repl.video
+ or (repl.document and repl.document.mime_type.split("/")[0] == "video")
+ )
x = await m.reply_text("Converting...")
if repl.sticker:
if repl.sticker.is_animated:
@@ -312,22 +311,18 @@ async def get_sticker_from_file(c: Gojo, m: Message):
up = tgs_to_gif(upp,True)
await x.delete()
await m.reply_animation(up,caption=Caption)
- os.remove(up)
- return
elif repl.sticker.is_video:
upp = await repl.download()
up = await webm_to_gif(upp)
await x.delete()
await m.reply_animation(up,caption=Caption)
- os.remove(up)
- return
else:
upp = await repl.download()
up = toimage(upp,is_direc=True)
await x.delete()
await m.reply_document(up, caption=Caption)
- os.remove(up)
- return
+ os.remove(up)
+ return
elif repl.photo:
upp = await repl.download()
up = tosticker(upp,is_direc=True)
@@ -335,7 +330,7 @@ async def get_sticker_from_file(c: Gojo, m: Message):
await m.reply_sticker(up)
os.remove(up)
return
-
+
elif to_vid:
up = await Vsticker(c,repl)
await x.delete()
@@ -389,9 +384,7 @@ async def quote_the_msg(_, m: Message):
msg_data = []
if len(m.command) > 1 and m.command[1].lower() == "r":
reply_msg = m.reply_to_message.reply_to_message
- if not reply_msg:
- reply_message = {}
- elif reply_msg and not reply_msg.text:
+ if not reply_msg or not reply_msg.text:
reply_message = {}
else:
to_edit = await to_edit.edit_text("Genrating quote with reply to the message...")
@@ -444,20 +437,19 @@ async def sticker_callbacks(c: Gojo, q: CallbackQuery):
data = q.data.split("_")
decoded = await encode_decode(data[-1], "decode")
user = int(decoded.split("_")[-1])
- offset = int(decoded.split("_")[0])
-
if q.from_user.id != user:
await q.answer("This is not for you")
- return
else:
+ offset = int(decoded.split("_")[0])
+
txt, kb = await get_all_sticker_packs(c, q.from_user.id, offset)
if not txt:
await q.answer("No sticker pack found....")
- return
else:
- await q.answer(f"Showing your sticker set")
+ await q.answer("Showing your sticker set")
await q.edit_message_text(txt, reply_markup=kb)
- return
+
+ return
__PLUGIN__ = "sticker"
__alt_name__ = [
diff --git a/Powers/plugins/utils.py b/Powers/plugins/utils.py
index fb33c9b03ca1a48bf411da189f9f61dcaaa3a348..934df85c827ee8b019cf73132e7e4cca013be552 100644
--- a/Powers/plugins/utils.py
+++ b/Powers/plugins/utils.py
@@ -109,15 +109,12 @@ async def get_lyrics(_, m: Message):
await em.delete()
await m.reply_text("Connection error try again after sometime")
return
-
+
if song:
if song.lyrics:
reply = song.lyrics
reply = reply.split("\n",1)[1]
- if not artist:
- artist = song.artist
- else:
- artist = artist
+ artist = artist or song.artist
else:
reply = "Couldn't find any lyrics for that song!"
else:
@@ -221,9 +218,7 @@ async def github(_, m: Message):
if len(m.text.split()) == 2:
username = m.text.split(maxsplit=1)[1]
else:
- await m.reply_text(
- f"Usage: /github username
",
- )
+ await m.reply_text("Usage: /github username
")
return
username = username.split("/")[-1].strip("@")
URL = f"https://api.github.com/users/{username}"
@@ -350,13 +345,13 @@ async def paste_func(_, message: Message):
if not link:
await m.edit_text("Failed to post!")
return
- kb = [[InlineKeyboardButton(text="π Paste π", url=link + f".{exe}")]]
+ kb = [[InlineKeyboardButton(text="π Paste π", url=f"{link}.{exe}")]]
await m.delete()
try:
await message.reply_text("Here's your paste", reply_markup=InlineKeyboardMarkup(kb))
except Exception as e:
if link:
- return await message.reply_text(f"Here's your paste:\n [link]({link + f'.{exe}'})",)
+ return await message.reply_text(f"Here's your paste:\n [link]({link}.{exe})")
return await message.reply_text(f"Failed to post. Due to following error:\n{e}")
@@ -439,7 +434,7 @@ async def botstaff(c: Gojo, m: Message):
pass
true_sudo = list(set(SUDO_USERS) - set(DEV_USERS))
reply += "\nSudo Users π:\n"
- if true_sudo == []:
+ if not true_sudo:
reply += "No Sudo Users\n"
else:
for each_user in true_sudo:
diff --git a/Powers/plugins/warns.py b/Powers/plugins/warns.py
index a4c44f4e3f8e689c12a4108c9b52de21d54b283c..ced25fa35eb23f65c7d61fde78e93f54454c27c5 100644
--- a/Powers/plugins/warns.py
+++ b/Powers/plugins/warns.py
@@ -23,19 +23,10 @@ from Powers.utils.parser import mention_html
async def warn(c: Gojo, m: Message):
if m.reply_to_message:
r_id = m.reply_to_message.id
- if len(m.text.split()) >= 2:
- reason = m.text.split(None, 1)[1]
- else:
- reason = None
- elif not m.reply_to_message:
- r_id = m.id
- if len(m.text.split()) >= 3:
- reason = m.text.split(None, 2)[2]
- else:
- reason = None
+ reason = m.text.split(None, 1)[1] if len(m.text.split()) >= 2 else None
else:
- reason = None
-
+ r_id = m.id
+ reason = m.text.split(None, 2)[2] if len(m.text.split()) >= 3 else None
if not len(m.command) > 1 and not m.reply_to_message:
await m.reply_text("I can't warn nothing! Tell me user whom I should warn")
return
@@ -69,18 +60,17 @@ async def warn(c: Gojo, m: Message):
warn_settings = warn_settings_db.get_warnings_settings()
if num >= warn_settings["warn_limit"]:
timeee = datetime.now(TIME_ZONE) + timedelta(minutes=45)
- if warn_settings["warn_mode"] == "kick":
+ if warn_settings["warn_mode"] == "kick" or warn_settings[
+ "warn_mode"
+ ] not in ["ban", "mute"]:
await m.chat.ban_member(user_id, until_date=timeee)
action = "kicked"
elif warn_settings["warn_mode"] == "ban":
await m.chat.ban_member(user_id)
action = "banned"
- elif warn_settings["warn_mode"] == "mute":
+ else:
await m.chat.restrict_member(user_id, ChatPermissions())
action = "muted"
- else:
- await m.chat.ban_member(user_id, until_date=timeee)
- action = "kicked"
await m.reply_text(
(
f"Warnings {num}/{warn_settings['warn_limit']}!"
@@ -93,8 +83,7 @@ async def warn(c: Gojo, m: Message):
)
await m.stop_propagation()
- rules = Rules(m.chat.id).get_rules()
- if rules:
+ if rules := Rules(m.chat.id).get_rules():
kb = InlineKeyboardButton(
"Rules π",
url=f"https://t.me/{c.me.username}?start=rules_{m.chat.id}",
@@ -136,7 +125,7 @@ async def warn(c: Gojo, m: Message):
@Gojo.on_message(command("resetwarns") & restrict_filter)
async def reset_warn(c: Gojo, m: Message):
- if not len(m.command) > 1 and not m.reply_to_message:
+ if len(m.command) <= 1 and not m.reply_to_message:
await m.reply_text("I can't warn nothing! Tell me user whom I should warn")
return
@@ -213,7 +202,7 @@ async def list_warns(c: Gojo, m: Message):
)
async def remove_warn(c: Gojo, m: Message):
- if not len(m.command) > 1 and not m.reply_to_message:
+ if len(m.command) <= 1 and not m.reply_to_message:
await m.reply_text(
"I can't remove warns of nothing! Tell me user whose warn should be removed!",
)
@@ -273,20 +262,9 @@ async def remove_last_warn_btn(c: Gojo, q: CallbackQuery):
action = args[1]
user_id = int(args[2])
chat_id = int(q.message.chat.id)
- user = Users.get_user_info(int(user_id))
+ user = Users.get_user_info(user_id)
user_first_name = user["name"]
- if action == "remove":
- warn_db = Warns(q.message.chat.id)
- _, num_warns = warn_db.remove_warn(user_id)
- await q.message.edit_text(
- (
- f"Admin {(await mention_html(q.from_user.first_name, q.from_user.id))} "
- "removed last warn for "
- f"{(await mention_html(user_first_name, user_id))}\n"
- f"Current Warnings: {num_warns}"
- ),
- )
if action == "kick":
try:
timee = datetime.now(TIME_ZONE) + timedelta(minutes=45)
@@ -305,6 +283,17 @@ async def remove_last_warn_btn(c: Gojo, q: CallbackQuery):
f"π Failed to Kick\nError:\n{err}",
)
+ elif action == "remove":
+ warn_db = Warns(q.message.chat.id)
+ _, num_warns = warn_db.remove_warn(user_id)
+ await q.message.edit_text(
+ (
+ f"Admin {(await mention_html(q.from_user.first_name, q.from_user.id))} "
+ "removed last warn for "
+ f"{(await mention_html(user_first_name, user_id))}\n"
+ f"Current Warnings: {num_warns}"
+ ),
+ )
await q.answer()
return
diff --git a/Powers/plugins/web_con.py b/Powers/plugins/web_con.py
index ba1a8f3177b8c8522dcfbea454b7686a3efc5abb..849607f0baf9c3cad089cee16eb244a662f9dadb 100644
--- a/Powers/plugins/web_con.py
+++ b/Powers/plugins/web_con.py
@@ -105,7 +105,7 @@ from Powers.utils.web_scrapper import INSTAGRAM, SCRAP_DATA
# pass
# return
-songs = dict()
+songs = {}
@Gojo.on_callback_query(filters.regex("^lyrics_"))
async def lyrics_for_song(c: Gojo, q: CallbackQuery):
@@ -117,7 +117,7 @@ async def lyrics_for_song(c: Gojo, q: CallbackQuery):
artist = None
if artist:
song = genius_lyrics.search_song(song,artist)
- elif not artist:
+ else:
song = genius_lyrics.search_song(song)
artist = song.artist
if not song.lyrics:
@@ -128,10 +128,10 @@ async def lyrics_for_song(c: Gojo, q: CallbackQuery):
await q.answer("Fetching lyrics")
reply = song.lyrics.split("\n",1)[1]
if len(reply) >= 4096:
- cap = f"{header}\n{reply[0:4080]}..."
+ cap = f"{header}\n{reply[:4080]}..."
if artist:
songs[f"{songe}"][f"{artist}"] = reply
- art = '_'+artist
+ art = f'_{artist}'
else:
songs[f"{songe}"] = reply
art = ''
@@ -162,25 +162,19 @@ async def lyrics_for_song_next(c: Gojo, q: CallbackQuery):
try:
artist = split[3]
header = f"{song.capitalize()} by {artist}"
- art = '_'+artist
+ art = f'_{artist}'
except IndexError:
artist = False
header = f"{song.capitalize()}"
art = ''
try:
- if artist:
- songe = songs[song][artist]
- else:
- songe = songs[song]
+ songe = songs[song][artist] if artist else songs[song]
except KeyError:
if artist:
songe = genius_lyrics.search_song(song,artist)
- elif not artist:
- songe = genius_lyrics.search_song(song)
- if todo == "next":
- next_part = songe[4080:]
else:
- next_part = songe[:4080]
+ songe = genius_lyrics.search_song(song)
+ next_part = songe[4080:] if todo == "next" else songe[:4080]
next_part = f"{header}\n{next_part}"
new_kb = [
[
@@ -198,7 +192,7 @@ async def remove_background(c: Gojo, m: Message):
if not is_rmbg:
await m.reply_text("Add rmbg api to use this command")
return
-
+
reply = m.reply_to_message
if not reply:
await m.reply_text("Reply to image/sticker to remove it's background")
@@ -231,10 +225,7 @@ async def remove_background(c: Gojo, m: Message):
os.remove(file)
return
to_path = "./downloads"
- if reply.sticker:
- to_path = f'{to_path}/no-bg.webp'
- else:
- to_path = f'{to_path}/no-bg.png'
+ to_path = f'{to_path}/no-bg.webp' if reply.sticker else f'{to_path}/no-bg.png'
with open(to_path,'wb') as out:
out.write(result.content)
if reply.sticker:
@@ -256,17 +247,14 @@ async def song_down_up(c: Gojo, m: Message):
await m.reply_text("**USAGE**\n /song [song name | link]")
return
_id = get_video_id(splited)
- if not _id:
- query = splited
- else:
- query = _id
+ query = _id or splited
to_edit = await m.reply_text("β³")
try:
await youtube_downloader(c,m,query, "a")
await to_edit.delete()
return
except KeyError:
- await to_edit.edit_text(f"Failed to find any result")
+ await to_edit.edit_text("Failed to find any result")
return
except Exception as e:
await to_edit.edit_text(f"Got an error\n{e}")
@@ -282,17 +270,14 @@ async def video_down_up(c: Gojo, m: Message):
await m.reply_text("**USAGE**\n /vsong [song name | link]")
return
_id = get_video_id(splited)
- if not _id:
- query = splited
- else:
- query = _id
+ query = _id or splited
to_edit = await m.reply_text("β³")
try:
await youtube_downloader(c,m,query,"v")
await to_edit.delete()
return
except KeyError:
- await to_edit.edit_text(f"Failed to find any result")
+ await to_edit.edit_text("Failed to find any result")
return
except Exception as e:
await to_edit.edit_text(f"Got an error\n{e}")
diff --git a/Powers/supports.py b/Powers/supports.py
index e9ee9b7451dc3e2e3885967aaa0454362057a0f4..f3e3140dcfef8928f99f33056a0f6a4115ba0540 100644
--- a/Powers/supports.py
+++ b/Powers/supports.py
@@ -32,7 +32,7 @@ def get_support_staff(want="all"):
else:
wanted = list(set([int(OWNER_ID)] + devs + sudo + whitelist))
- return wanted if wanted else []
+ return wanted or []
async def cache_support():
dev = get_support_staff("dev")
diff --git a/Powers/utils/captcha_helper.py b/Powers/utils/captcha_helper.py
index 366185ccdfa0bc14f8aa46a632faaf90aee0cb1b..aa276ab519ec3950a8ff7f7c93046e09b1b6870d 100644
--- a/Powers/utils/captcha_helper.py
+++ b/Powers/utils/captcha_helper.py
@@ -26,11 +26,7 @@ def genrator():
rand_alpha = choice(alpha)
if_ = randint(0, 1)
- if if_:
- new_alpha = rand_alpha.upper()
- else:
- new_alpha = rand_alpha
-
+ new_alpha = rand_alpha.upper() if if_ else rand_alpha
list_ = [new_alpha]
while len(list_) != 4:
xXx = randrange(0, 9)
diff --git a/Powers/utils/custom_filters.py b/Powers/utils/custom_filters.py
index 9153a4f3100d6dd405f20b5ce952b8342864f102..19cb678a7b8dc636713feaaf60f90f9d50c2531c 100644
--- a/Powers/utils/custom_filters.py
+++ b/Powers/utils/custom_filters.py
@@ -38,7 +38,7 @@ def command(
if m.chat and m.chat.type == ChatType.CHANNEL:
return False
- if m and not (m.from_user or m.chat.is_admin):
+ if m and not m.from_user and not m.chat.is_admin:
return False
if m.from_user.is_bot:
@@ -85,15 +85,13 @@ def command(
ddb = Disabling(m.chat.id)
if str(matches.group(1)) in ddb.get_disabled() and user_status not in (
- CMS.OWNER,
- CMS.ADMINISTRATOR,
- ):
- if bool(ddb.get_action() == "del"):
- try:
- await m.delete()
- except RPCError:
- pass
- return False
+ CMS.OWNER,
+ CMS.ADMINISTRATOR,
+ ) and ddb.get_action() == "del":
+ try:
+ await m.delete()
+ except RPCError:
+ return False
if matches.group(3) == "":
return True
try:
@@ -313,10 +311,7 @@ async def auto_join_check_filter(_, __, j: ChatJoinRequest):
aj = AUTOJOIN()
join_type = aj.get_autojoin(chat)
- if not join_type:
- return False
- else:
- return True
+ return bool(join_type)
async def afk_check_filter(_, __, m: Message):
@@ -333,8 +328,7 @@ async def afk_check_filter(_, __, m: Message):
chat = m.chat.id
is_repl_afk = None
if m.reply_to_message:
- repl_user = m.reply_to_message.from_user
- if repl_user:
+ if repl_user := m.reply_to_message.from_user:
repl_user = m.reply_to_message.from_user.id
is_repl_afk = afk.check_afk(chat, repl_user)
@@ -342,10 +336,7 @@ async def afk_check_filter(_, __, m: Message):
is_afk = afk.check_afk(chat, user)
- if not (is_afk or is_repl_afk):
- return False
- else:
- return True
+ return bool((is_afk or is_repl_afk))
async def flood_check_filter(_, __, m: Message):
@@ -388,7 +379,7 @@ async def flood_check_filter(_, __, m: Message):
async def captcha_filt(_, __, m: Message):
try:
return CAPTCHA().is_captcha(m.chat.id)
- except:
+ except Exception:
return False
captcha_filter = create(captcha_filt)
diff --git a/Powers/utils/extract_user.py b/Powers/utils/extract_user.py
index 6a9662edfe8c4c1258d3028d074b955637aebf4b..0786f661f6e5d666d4ae700dbd4660e960017d54 100644
--- a/Powers/utils/extract_user.py
+++ b/Powers/utils/extract_user.py
@@ -37,7 +37,7 @@ async def extract_user(c: Gojo, m: Message) -> Tuple[int, str, str]:
try:
user_found = int(user_found)
- except (ValueError, Exception) as ef:
+ except Exception as ef:
if "invalid literal for int() with base 10:" in str(ef):
user_found = str(user_found)
else:
@@ -72,7 +72,7 @@ async def extract_user(c: Gojo, m: Message) -> Tuple[int, str, str]:
else:
try:
user_id = int(m.text.split()[1])
- except (ValueError, Exception) as ef:
+ except Exception as ef:
if "invalid literal for int() with base 10:" in str(ef):
user_id = (
str(m.text.split()[1])
diff --git a/Powers/utils/parser.py b/Powers/utils/parser.py
index 9b3556825a13873e8300a51568d04bc78ef19c05..0baa1bac88b5b71fb64984db06c3f60ffd4c7431 100644
--- a/Powers/utils/parser.py
+++ b/Powers/utils/parser.py
@@ -12,7 +12,7 @@ async def cleanhtml(raw_html: str) -> str:
async def escape_markdown(text: str) -> str:
"""Escape markdown data."""
escape_chars = r"\*_`\["
- return sub(r"([%s])" % escape_chars, r"\\\1", text)
+ return sub(f"([{escape_chars}])", r"\\\1", text)
async def mention_html(name: str, user_id: int) -> str:
diff --git a/Powers/utils/start_utils.py b/Powers/utils/start_utils.py
index 371893c1b34011afcbc914a374875692fba53b63..ef3d60f3669fa7f86db276d67a2e51915d551aa8 100644
--- a/Powers/utils/start_utils.py
+++ b/Powers/utils/start_utils.py
@@ -43,19 +43,11 @@ async def gen_start_kb(q: Message or CallbackQuery):
f"https://t.me/{Config.BOT_USERNAME}?startgroup=new",
"url",
),
- (
- "Bot Staffs π",
- f"give_bot_staffs",
- ),
+ ("Bot Staffs π", "give_bot_staffs"),
],
[
- (
- "π Commands & Help", "commands"
- ),
- (
- "Bot info πΎ",
- "bot_curr_info"
- )
+ ("π Commands & Help", "commands"),
+ ("Bot info πΎ", "bot_curr_info"),
],
[
(
@@ -81,7 +73,7 @@ async def gen_start_kb(q: Message or CallbackQuery):
"url",
),
],
- ],
+ ]
)
@@ -259,12 +251,9 @@ async def get_help_msg(c: Gojo, m: Message or CallbackQuery, help_option: str):
)
help_kb = ikb(ou, True, "commands")
help_msg = f"**{(help_option_value)}:**"
-
+
else:
- if isinstance(m, CallbackQuery):
- mes = m.message
- else:
- mes = m
+ mes = m.message if isinstance(m, CallbackQuery) else m
help_msg = f"""
Hey **[{mes.from_user.first_name}](http://t.me/{mes.from_user.username})**!I am {c.me.first_name}β¨.
I'm here to help you manage your groups!
diff --git a/Powers/utils/sticker_help.py b/Powers/utils/sticker_help.py
index 5e7009925e949caac89618149a5aabf820549eef..fa1d007e31488d22b0083254e836947caf84e4a8 100644
--- a/Powers/utils/sticker_help.py
+++ b/Powers/utils/sticker_help.py
@@ -49,22 +49,21 @@ def get_msg_entities(m: Message) -> List[dict]:
entities = []
if m.entities:
- for entity in m.entities:
- entities.append(
- {
- "type": entity.type.name.lower(),
- "offset": entity.offset,
- "length": entity.length,
- }
- )
-
+ entities.extend(
+ {
+ "type": entity.type.name.lower(),
+ "offset": entity.offset,
+ "length": entity.length,
+ }
+ for entity in m.entities
+ )
return entities
async def get_all_sticker_packs(c: Gojo, user_id: int, offset: int = 1, limit: int = 25):
packnum = 25 * (offset - 1)
txt = f"Here is your stickers pack that I have created:\nPage: {offset}\n\nNOTE: I may have kanged more sticker sets for you, but since last update I will no longer add stickers in those packs due to recent telegram update in bot api sorry."
while True:
- packname = f"CE{str(user_id)}{packnum}_by_{c.me.username}"
+ packname = f"CE{user_id}{packnum}_by_{c.me.username}"
sticker_set = await get_sticker_set_by_name(c,packname)
if not sticker_set and packnum == 0:
txt, kb = None, None
@@ -85,21 +84,21 @@ async def get_all_sticker_packs(c: Gojo, user_id: int, offset: int = 1, limit: i
ikb("Next", f"stickers_{b64_next}")
],
]
-
- elif offset >= 2 and (packnum <= (packnum + limit - 1)):
+
+ elif offset >= 2:
kb = [
[
ikb("Previous", f"stickers_{b64_prev}")
],
]
-
+
elif packnum > (packnum + limit - 1) and offset == 1:
kb = [
[
ikb("Next", f"stickers_{b64_next}")
],
]
-
+
else:
kb = [
[
@@ -111,7 +110,7 @@ async def get_all_sticker_packs(c: Gojo, user_id: int, offset: int = 1, limit: i
]
kb = ikm(kb)
break
-
+
return txt, kb
@@ -235,10 +234,7 @@ async def Vsticker(c: Gojo, file: Message):
file = file.video
_width_ = file.width
_height_ = file.height
- if _height_ > _width_:
- _height_, _width_ = (512, -1)
- else:
- _height_, _width_ = (-1, 512)
+ _height_, _width_ = (512, -1) if _height_ > _width_ else (-1, 512)
file = await c.download_media(file)
await runcmd(
f"ffmpeg -to 00:00:02.900 -i '{file}' -vf scale={_width_}:{_height_} -c:v libvpx-vp9 -crf 30 -b:v 560k -maxrate 560k -bufsize 256k -an 'VideoSticker.webm'"
@@ -349,7 +345,7 @@ async def draw_meme(image_path: str, text: str, sticker: bool, fiill: str) -> li
def toimage(image, filename=None, is_direc=False):
- filename = filename if filename else "gojo.png"
+ filename = filename or "gojo.png"
if is_direc:
os.rename(image, filename)
return filename
@@ -362,7 +358,7 @@ def toimage(image, filename=None, is_direc=False):
def tosticker(response, filename=None, is_direc=False):
- filename = filename if filename else "gojo.webp"
+ filename = filename or "gojo.webp"
if is_direc:
os.rename(response, filename)
return filename
diff --git a/Powers/utils/string.py b/Powers/utils/string.py
index 2051ff0e8fb674a0ea1aaaf176f0e4e56f3e31ac..77ee04a8848b12fc3b1f28110f66c78fd22ce464 100644
--- a/Powers/utils/string.py
+++ b/Powers/utils/string.py
@@ -46,13 +46,12 @@ async def parse_button(text: str):
note_data = ""
buttons = []
for match in BTN_URL_REGEX.finditer(markdown_note):
- # Check if btnurl is escaped
n_escapes = 0
to_check = match.start(1) - 1
while to_check > 0 and markdown_note[to_check] == "\\":
n_escapes += 1
to_check -= 1
-
+
# if even, not escaped -> create button
if n_escapes % 2 == 0:
# create a thruple with button label, url, and newline status
@@ -64,8 +63,7 @@ async def parse_button(text: str):
else:
note_data += markdown_note[prev:to_check]
prev = match.start(1) - 1
- else:
- note_data += markdown_note[prev:]
+ note_data += markdown_note[prev:]
return note_data, buttons
@@ -206,14 +204,12 @@ async def encode_decode(string: str, to_do="encode"):
if to_do.lower() == "encode":
encodee = string.encode("ascii")
base64_ = base64.b64encode(encodee)
- B64 = base64_.decode("ascii")
+ return base64_.decode("ascii")
elif to_do.lower() == "decode":
decodee = string.encode("ascii")
base64_ = base64.b64decode(decodee)
- B64 = base64_.decode("ascii")
+ return base64_.decode("ascii")
else:
- B64 = None
-
- return B64
+ return None
diff --git a/Powers/utils/web_helpers.py b/Powers/utils/web_helpers.py
index 18359ec47d3b0276c410bcfbb9c8fc6c85fbf986..d7349e6415d1f37fcf35d97d1e3eca7a88f52225 100644
--- a/Powers/utils/web_helpers.py
+++ b/Powers/utils/web_helpers.py
@@ -36,7 +36,7 @@ def readable_time(seconds: int) -> str:
time_list[x] = str(time_list[x]) + time_suffix_list[x]
if len(time_list) == 4:
- out_time += time_list.pop() + ", "
+ out_time += f"{time_list.pop()}, "
time_list.reverse()
out_time += " ".join(time_list)
@@ -53,7 +53,7 @@ def humanbytes(size: int):
while size > power:
size /= power
number += 1
- return str(round(size, 2)) + " " + dict_power_n[number] + "B"
+ return f"{str(round(size, 2))} {dict_power_n[number]}B"
async def progress(
current: int, total: int, message: Message, start: float, process: str
@@ -67,8 +67,8 @@ async def progress(
complete_time = round((total - current) / speed) * 1000
estimated_total_time = elapsed_time + complete_time
progress_str = "**[{0}{1}] : {2}%\n**".format(
- "".join(["β" for i in range(math.floor(percentage / 10))]),
- "".join(["β" for i in range(10 - math.floor(percentage / 10))]),
+ "".join(["β" for _ in range(math.floor(percentage / 10))]),
+ "".join(["β" for _ in range(10 - math.floor(percentage / 10))]),
round(percentage, 2),
)
msg = (
@@ -103,31 +103,27 @@ async def get_file_size(file: Message):
if size <= 1024:
return f"{round(size)} kb"
+ size = size/1024
+ if size <= 1024:
+ return f"{round(size)} mb"
elif size > 1024:
size = size/1024
- if size <= 1024:
- return f"{round(size)} mb"
- elif size > 1024:
- size = size/1024
- return f"{round(size)} gb"
+ return f"{round(size)} gb"
def get_video_id(url):
try:
_id = extract.video_id(url)
- if not _id:
- return None
- else:
- return _id
- except:
+ return _id or None
+ except Exception:
return None
def get_duration_in_sec(dur: str):
duration = dur.split(":")
- if len(duration) == 2:
- dur = (int(duration[0]) * 60) + int(duration[1])
- else:
- dur = int(duration[0])
- return dur
+ return (
+ (int(duration[0]) * 60) + int(duration[1])
+ if len(duration) == 2
+ else int(duration[0])
+ )
# Gets yt result of given query.
@@ -151,7 +147,7 @@ async def song_search(query, max_results=1):
if len(durr) == 2:
minutes_to_sec = int(durr[0])*60
total = minutes_to_sec + int(durr[1])
- if not (total > 600):
+ if total <= 600:
dict_form = {
"link": i["link"],
"title": i["title"],
@@ -163,17 +159,15 @@ async def song_search(query, max_results=1):
}
try:
dict_form["uploader"] = i["channel"]["name"]
- except:
+ except Exception:
dict_form["uploader"] = "Captain D. Ezio"
try:
thumb = {"thumbnail": i["thumbnails"][0]["url"]}
except Exception:
thumb = {"thumbnail": None}
- dict_form.update(thumb)
- yt_dict.update({nums: dict_form})
+ dict_form |= thumb
+ yt_dict[nums] = dict_form
nums += 1
- else:
- pass
return yt_dict
song_opts = {
@@ -258,7 +252,7 @@ async def youtube_downloader(c: Gojo, m: Message, query: str, type_: str):
LOGGER.info("Using back up image as thumbnail")
thumb = SCRAP_DATA(backUP).get_images()
thumb = await resize_file_to_sticker_size(thumb[0], 320, 320)
-
+
else:
thumb = SCRAP_DATA(backUP).get_images()
thumb = await resize_file_to_sticker_size(thumb[0], 320, 320)
@@ -276,12 +270,8 @@ Downloaded by: @{c.me.username}
upload_text = f"**β¬οΈ π΄ππ
ππΊπ½πππ {'audio' if song else 'video'}** \\**β π³πππ
πΎ:** `{f_name[:50]}`\n*β π’ππΊπππΎπ
:** `{uploader}`"
kb = IKM(
[
- [
- IKB(f"β {uploader.capitalize()} β", url=f"{up_url}")
- ],
- [
- IKB(f"β Youtube url β", url=f"{url}")
- ]
+ [IKB(f"β {uploader.capitalize()} β", url=f"{up_url}")],
+ [IKB("β Youtube url β", url=f"{url}")],
]
)
@@ -291,9 +281,7 @@ Downloaded by: @{c.me.username}
ydl.download([query])
info = ydl.extract_info(query, False)
file_name = ydl.prepare_filename(info)
- if len(file_name.rsplit(".", 1)) == 2:
- pass
- else:
+ if len(file_name.rsplit(".", 1)) != 2:
file_name = f"{file_name}.{ext}"
new = info['title'].replace('/','|').replace('\\','|')
new_file = f"{youtube_dir}{new}.{ext}"
diff --git a/Powers/utils/web_scrapper.py b/Powers/utils/web_scrapper.py
index 8eef1cdebfc7a68277c19ca703769de7a9ea7e9e..4fb635c0a11025ed6c7c59afee5f8bfebcd0d23a 100644
--- a/Powers/utils/web_scrapper.py
+++ b/Powers/utils/web_scrapper.py
@@ -31,7 +31,7 @@ class SCRAP_DATA:
if isinstance(self.urls, str):
requested = httpx.get(self.urls)
try:
- name = self.path + f"img_{str(time()).replace('.','_')}.jpg"
+ name = f"{self.path}img_{str(time()).replace('.', '_')}.jpg"
with open(name, "wb") as f:
f.write(requested.content)
images.append(name)
@@ -46,7 +46,7 @@ class SCRAP_DATA:
else:
continue
try:
- name = self.path + f"img_{str(time()).replace('.','_')}.jpg"
+ name = f"{self.path}img_{str(time()).replace('.', '_')}.jpg"
with open(name, "wb") as f:
f.write(requested.content)
images.append(name)
@@ -65,7 +65,7 @@ class SCRAP_DATA:
else:
return []
try:
- name = self.path + f"vid_{str(time()).replace('.','_')}.mp4"
+ name = f"{self.path}vid_{str(time()).replace('.', '_')}.mp4"
with open(name, "wb") as f:
f.write(requested.content)
videos.append(name)
@@ -80,7 +80,7 @@ class SCRAP_DATA:
else:
continue
try:
- name = self.path + f"vid_{str(time()).replace('.','_')}.mp4"
+ name = f"{self.path}vid_{str(time()).replace('.', '_')}.mp4"
with open(name, "wb") as f:
f.write(requested.content)
videos.append(name)
@@ -221,8 +221,9 @@ class INSTAGRAM:
def get_media(self):
try:
- response = httpx.post(f"https://api.qewertyy.dev/downloaders/instagram?url={self.url}").json()
- return response
+ return httpx.post(
+ f"https://api.qewertyy.dev/downloaders/instagram?url={self.url}"
+ ).json()
except Exception as e:
LOGGER.error(e)
LOGGER.error(format_exc())
diff --git a/requirements.txt b/requirements.txt
index d9c87424c57e2dbf6ca06e09aeb24124e8991a0c..48323d4ca52eaf7064b05fdedff256f7055be705 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,42 +1 @@
-aiofiles==23.2.1
-apscheduler==3.10.4
-asyncio==3.4.3
-beautifulsoup4==4.12.3
-cachetools==5.2.0
-captcha==0.5.0
-certifi==2024.7.4
-charset-normalizer==2.1.0
-dnspython==2.6.1
-google==3.0.0
-gpytranslate==1.5.1
-httpx
-lyricsgenius==3.0.1
-pillow == 10.3.0
-lxml==4.9.1
-pillow == 10.3.0
-prettyconf==2.2.1
-pyaes==1.6.1
-pymongo==4.6.3
-git+https://github.com/KurimuzonAkuma/pyrogram.git@v2.1.32
-pysocks==1.7.1
-python-dateutil==2.8.2
-pytube==15.0.0
-pytz==2024.1
-pyyaml==6.0.1
-qrcode==7.4.2
-regex==2023.12.25
-requests==2.32.2
-rfc3986==1.5.0
-search-engine-parser==0.6.8
-six==1.16.0
-sniffio==1.3.0
-soupsieve==2.4
-tgcrypto==1.2.5
-tswift==0.7.0
-typing-extensions
-ujson==5.8.0
-Unidecode
-uvloop==0.19.0
-wikipedia==1.4.0
-youtube-search-python==1.6.6
-yt-dlp@git+https://github.com/HellBoy-OP/yt-dp-fork.git@af1fd12f675220df6793fc019dff320bc76e8080
\ No newline at end of file
+pyrofork
\ No newline at end of file