diff --git a/Powers/__init__.py b/Powers/__init__.py
index e7dbdc2092b926243e065ccfed0e6a0ce80528c8..bb32cc15121982d6a699a817becf10c853b8e5e5 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)
@@ -52,6 +48,7 @@ if version_info[0] < 3 or version_info[1] < 7:
# the secret configuration specific things
try:
from Powers.vars import is_env
+
if is_env or environ.get("ENV"):
from Powers.vars import Config
else:
@@ -64,12 +61,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 +90,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 +113,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
@@ -142,21 +136,15 @@ PREFIX_HANDLER = Config.PREFIX_HANDLER
HELP_COMMANDS = {} # For help menu
UPTIME = time() # Check bot uptime
-
-#Make dir
+# 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)
@@ -207,7 +195,7 @@ async def load_cmds(all_plugins):
LOGGER.warning(f"Not loading Plugins - {NO_LOAD}")
return (
- ", ".join((i.split(".")[1]).capitalize()
- for i in list(HELP_COMMANDS.keys()))
- + "\n"
+ ", ".join((i.split(".")[1]).capitalize()
+ for i in list(HELP_COMMANDS.keys()))
+ + "\n"
)
diff --git a/Powers/bot_class.py b/Powers/bot_class.py
index d13b9e6160f89e37c023187599b97768492abcc5..2b896701e0c90cde77983c95de0d6fd888158fea 100644
--- a/Powers/bot_class.py
+++ b/Powers/bot_class.py
@@ -7,8 +7,8 @@ from pyrogram import Client, __version__
from pyrogram.raw.all import layer
from pyrogram.types import BotCommand
-from Powers import (API_HASH, API_ID, BDB_URI, BOT_TOKEN, LOG_DATETIME,
- LOGFILE, LOGGER, MESSAGE_DUMP, NO_LOAD, OWNER_ID, UPTIME,
+from Powers import (API_HASH, API_ID, BOT_TOKEN, LOG_DATETIME,
+ LOGFILE, LOGGER, MESSAGE_DUMP, NO_LOAD, UPTIME,
WORKERS, load_cmds, scheduler)
from Powers.database import MongoDB
from Powers.plugins import all_plugins
@@ -72,7 +72,7 @@ class Gojo(Client):
LOGGER.info(f"Plugins Loaded: {cmd_list}")
if BDB_URI:
scheduler.add_job(send_wishish, 'cron', [
- self], hour=0, minute=0, second=0)
+ self], hour=0, minute=0, second=0)
scheduler.start()
# Send a message to MESSAGE_DUMP telling that the
# bot has started and has loaded all plugins!
@@ -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..537cb2b59866330eefee043571da8b2190026fe7 100644
--- a/Powers/database/afk_db.py
+++ b/Powers/database/afk_db.py
@@ -1,6 +1,5 @@
from threading import RLock
-from Powers import LOGGER
from Powers.database import MongoDB
INSERTION_LOCK = RLock()
@@ -15,15 +14,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})
+ "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
+ 'media': media, 'media_type': media_type, "time": time})
else:
self.insert_one(
{
@@ -35,23 +32,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..28800eb5bc8d64b8813862f3edd3a14508947c3d 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},
@@ -83,6 +86,7 @@ class Approve(MongoDB):
self.insert_one(new_data)
return new_data
return chat_data
+
# Migrate if chat id changes!
def migrate_chat(self, new_chat_id: int):
diff --git a/Powers/database/autojoin_db.py b/Powers/database/autojoin_db.py
index 3bff8a50745e9a99d05a218598cee907b5b98b4e..423de0512c12e01d223768644898373778e7c6b1 100644
--- a/Powers/database/autojoin_db.py
+++ b/Powers/database/autojoin_db.py
@@ -1,7 +1,5 @@
from threading import RLock
-from time import time
-from Powers import LOGGER
from Powers.database import MongoDB
INSERTION_LOCK = RLock()
@@ -30,21 +28,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..f4d5dec9ca1e91198d577cefa0fa3cf59a8e8a2c 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..400255ded11421d6f6f0eb7df3484d5c66c1a008 100644
--- a/Powers/database/captcha_db.py
+++ b/Powers/database/captcha_db.py
@@ -1,6 +1,5 @@
from threading import RLock
-from Powers import LOGGER
from Powers.database import MongoDB
INSERTION_LOCK = RLock()
@@ -27,38 +26,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})
+ "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 +59,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
@@ -122,4 +104,4 @@ class CAPTCHA_DATA(MongoDB):
with INSERTION_LOCK:
self.delete_one({"chat_id": chat, "user_id": user})
- return curr["message_id"]
\ No newline at end of file
+ return curr["message_id"]
diff --git a/Powers/database/chats_db.py b/Powers/database/chats_db.py
index e580f7ffc3ca213f91160edc5e38c3115c33f732..8e5993600e77fb2638df5250baaf5ecad8f152f8 100644
--- a/Powers/database/chats_db.py
+++ b/Powers/database/chats_db.py
@@ -19,18 +19,18 @@ 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:
if chat_name == self.chat_info["chat_name"] and self.user_is_in_chat(
- user_id,
+ user_id,
):
return True
if chat_name != self.chat_info["chat_name"] and self.user_is_in_chat(
- user_id,
+ user_id,
):
return self.update(
{"_id": self.chat_id},
@@ -38,7 +38,7 @@ class Chats(MongoDB):
)
if chat_name == self.chat_info["chat_name"] and not self.user_is_in_chat(
- user_id,
+ user_id,
):
self.chat_info["users"].append(user_id)
return self.update(
diff --git a/Powers/database/disable_db.py b/Powers/database/disable_db.py
index 6f821b78a5d7009eeb4b08ed4901564218fe35b7..df26070578947afea7b8479544622aa0085dbc2b 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..72a6b74b86bf641d5c8ecc42d54efbb83a71f209 100644
--- a/Powers/database/filters_db.py
+++ b/Powers/database/filters_db.py
@@ -13,17 +13,15 @@ class Filters(MongoDB):
super().__init__(self.db_name)
def save_filter(
- self,
- chat_id: int,
- keyword: str,
- filter_reply: str,
- msgtype: int = Types.TEXT,
- fileid="",
+ self,
+ chat_id: int,
+ keyword: str,
+ filter_reply: str,
+ msgtype: int = Types.TEXT,
+ 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..b8ad9dbfc720b4569b363f53ed40829ee33555e0 100644
--- a/Powers/database/flood_db.py
+++ b/Powers/database/flood_db.py
@@ -1,9 +1,6 @@
from threading import RLock
-from traceback import format_exc
-from Powers import LOGGER
from Powers.database import MongoDB
-from Powers.utils.msg_types import Types
INSERTION_LOCK = RLock()
@@ -16,29 +13,14 @@ class Floods(MongoDB):
super().__init__(self.db_name)
def save_flood(
- self,
- chat_id: int,
- limit: int,
- within: int,
- action: str,
+ self,
+ chat_id: int,
+ limit: int,
+ within: int,
+ 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 +29,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/greetings_db.py b/Powers/database/greetings_db.py
index 3a00e44505369c2dc9a018f722fa403442d1ed52..6d5fdd29a49f7396d79cd11640cbc72dfdec2c4f 100644
--- a/Powers/database/greetings_db.py
+++ b/Powers/database/greetings_db.py
@@ -1,6 +1,5 @@
from threading import RLock
-from Powers import LOGGER
from Powers.database import MongoDB
INSERTION_LOCK = RLock()
diff --git a/Powers/database/locks_db.py b/Powers/database/locks_db.py
index 222ecbc098e8316020c9a258c378fb986f964abc..c4a9fc7b63a00333f251863b15e2bc5697630c60 100644
--- a/Powers/database/locks_db.py
+++ b/Powers/database/locks_db.py
@@ -1,6 +1,5 @@
from threading import RLock
-from Powers import LOGGER
from Powers.database import MongoDB
INSERTION_LOCK = RLock()
@@ -30,15 +29,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 +43,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,43 +57,48 @@ 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:
- to_return = {
- "anti_channel": False,
- "anti_fwd": {
- "user": False,
- "chat": False
- },
- "anti_links": False,
- "bot": False
- }
- curr = self.find_all({"chat_id": chat})
- if not curr:
- return None
+ if not (curr := self.find_all({"chat_id": chat})):
+ return None
+ to_return = {
+ "anti_channel": False,
+ "anti_fwd": {
+ "user": False,
+ "chat": False
+ },
+ "anti_links": False,
+ "bot": False
+ }
+ 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:
- 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
+ continue
+ return to_return
def merge_u_and_c(self, chat: int, locktype: str):
if locktype == "anti_fwd_u":
@@ -119,8 +119,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..96c5c29196741d0a6637b6b31153924660732fd5 100644
--- a/Powers/database/notes_db.py
+++ b/Powers/database/notes_db.py
@@ -15,18 +15,17 @@ class Notes(MongoDB):
super().__init__(self.db_name)
def save_note(
- self,
- chat_id: int,
- note_name: str,
- note_value: str,
- msgtype: int = Types.TEXT,
- fileid="",
+ self,
+ chat_id: int,
+ note_name: str,
+ note_value: str,
+ msgtype: int = Types.TEXT,
+ fileid="",
):
with INSERTION_LOCK:
- curr = self.find_one(
- {"chat_id": chat_id, "note_name": note_name},
- )
- if curr:
+ if curr := self.find_one(
+ {"chat_id": chat_id, "note_name": note_name},
+ ):
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(
- {"chat_id": chat_id, "note_name": note_name},
- )
- if curr:
+ if curr := self.find_one(
+ {"chat_id": chat_id, "note_name": note_name},
+ ):
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(
- {"chat_id": chat_id, "note_name": note_name},
- )
- if curr:
+ if curr := self.find_one(
+ {"chat_id": chat_id, "note_name": note_name},
+ ):
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..9505b1377e2081794ead4623204b278db6289a6d 100644
--- a/Powers/database/support_db.py
+++ b/Powers/database/support_db.py
@@ -1,6 +1,5 @@
from threading import RLock
-from Powers import LOGGER
from Powers.database import MongoDB
INSERTION_LOCK = RLock()
@@ -30,8 +29,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 +42,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/database/warns_db.py b/Powers/database/warns_db.py
index c7117db76b2cce844a20e00e2edbc04c14d4add2..2508807cebac8fafe3706720746d07c9748b157e 100644
--- a/Powers/database/warns_db.py
+++ b/Powers/database/warns_db.py
@@ -94,7 +94,7 @@ class Warns(MongoDB):
)
collection.update(
{"chat_id": data["chat_id"],
- "user_id": data["user_id"]},
+ "user_id": data["user_id"]},
{key: val},
)
diff --git a/Powers/plugins/__init__.py b/Powers/plugins/__init__.py
index aa74eba62fe2fd143b067f7944d3f6b9dfff3f82..0c13e6cb960ea5677a7eda68f01d7a02d8446554 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
@@ -13,6 +13,7 @@ async def all_plugins():
]
return sorted(all_plugs)
+
from sys import exit as exiter
from pymongo import MongoClient
@@ -36,6 +37,4 @@ 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..f5b8cbf02306f2c089c3071414f95902fe184921 100644
--- a/Powers/plugins/admin.py
+++ b/Powers/plugins/admin.py
@@ -15,8 +15,7 @@ from Powers import DEV_USERS, LOGGER, OWNER_ID, SUDO_USERS, WHITELIST_USERS
from Powers.bot_class import Gojo
from Powers.database.approve_db import Approve
from Powers.database.reporting_db import Reporting
-from Powers.utils.caching import (ADMIN_CACHE, TEMP_ADMIN_CACHE_BLOCK,
- admin_cache_reload)
+from Powers.utils.caching import (admin_cache_reload)
from Powers.utils.custom_filters import admin_filter, command, promote_filter
from Powers.utils.extract_user import extract_user
from Powers.utils.parser import mention_html
@@ -25,7 +24,7 @@ from Powers.utils.parser import mention_html
@Gojo.on_message(command("adminlist"))
async def adminlist_show(_, m: Message):
global ADMIN_CACHE
- if m.chat.type not in [ChatType.SUPERGROUP,ChatType.GROUP]:
+ if m.chat.type not in [ChatType.SUPERGROUP, ChatType.GROUP]:
return await m.reply_text(
text="This command is made to be used in groups only!",
)
@@ -64,12 +63,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}
"
)
@@ -78,7 +77,6 @@ async def adminlist_show(_, m: Message):
return
-
@Gojo.on_message(command("zombies") & admin_filter)
async def zombie_clean(c: Gojo, m: Message):
zombie = 0
@@ -95,27 +93,28 @@ 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!")
await wait.delete()
- txt=f"{zombie} Zombies found and {zombie - failed} has been banned!\n{failed} zombies' are immune to me",
+ txt = f"{zombie} Zombies found and {zombie - failed} has been banned!\n{failed} zombies' are immune to me",
await m.reply_animation("https://graph.org/file/02a1dcf7788186ffb36cb.mp4", caption=txt)
return
+
@Gojo.on_message(command("admincache"))
async def reload_admins(_, m: Message):
global TEMP_ADMIN_CACHE_BLOCK
- if m.chat.type not in [ChatType.SUPERGROUP,ChatType.GROUP]:
+ if m.chat.type not in [ChatType.SUPERGROUP, ChatType.GROUP]:
return await m.reply_text(
"This command is made to be used in groups only!",
)
SUPPORT_STAFF = DEV_USERS.union(SUDO_USERS).union(WHITELIST_USERS)
if (
- (m.chat.id in set(TEMP_ADMIN_CACHE_BLOCK.keys()))
- and (m.from_user.id not in SUPPORT_STAFF)
- and TEMP_ADMIN_CACHE_BLOCK[m.chat.id] == "manualblock"
+ (m.chat.id in set(TEMP_ADMIN_CACHE_BLOCK.keys()))
+ and (m.from_user.id not in SUPPORT_STAFF)
+ and TEMP_ADMIN_CACHE_BLOCK[m.chat.id] == "manualblock"
):
await m.reply_text("Can only reload admin cache once per 10 mins!")
return
@@ -194,9 +193,9 @@ async def fullpromote_usr(c: Gojo, m: Message):
if m.chat.type in [ChatType.SUPERGROUP, ChatType.GROUP]:
title = "Gojo" # Default fullpromote title
if len(m.text.split()) == 3 and not m.reply_to_message:
- title = " ".join(m.text.split()[2:16]) # trim title to 16 characters
+ title = " ".join(m.text.split()[2:16]) # trim title to 16 characters
elif len(m.text.split()) >= 2 and m.reply_to_message:
- title = " ".join(m.text.split()[1:16]) # trim title to 16 characters
+ title = " ".join(m.text.split()[1:16]) # trim title to 16 characters
try:
await c.set_administrator_title(m.chat.id, user_id, title)
@@ -297,9 +296,9 @@ async def promote_usr(c: Gojo, m: Message):
if m.chat.type in [ChatType.SUPERGROUP, ChatType.GROUP]:
title = "Itadori" # Deafult title
if len(m.text.split()) >= 3 and not m.reply_to_message:
- title = " ".join(m.text.split()[2:16]) # trim title to 16 characters
+ title = " ".join(m.text.split()[2:16]) # trim title to 16 characters
elif len(m.text.split()) >= 2 and m.reply_to_message:
- title = " ".join(m.text.split()[1:16]) # trim title to 16 characters
+ title = " ".join(m.text.split()[1:16]) # trim title to 16 characters
try:
await c.set_administrator_title(m.chat.id, user_id, title)
except RPCError as e:
@@ -308,7 +307,7 @@ async def promote_usr(c: Gojo, m: Message):
except Exception as e:
LOGGER.error(e)
LOGGER.error(format_exc())
-
+
await m.reply_text(
("{promoter} promoted {promoted} in chat {chat_title}!").format(
promoter=(await mention_html(m.from_user.first_name, m.from_user.id)),
@@ -406,7 +405,8 @@ async def demote_usr(c: Gojo, m: Message):
"Cannot act on this user, maybe I wasn't the one who changed their permissions."
)
except BotChannelsNa:
- await m.reply_text("May be the user is bot and due to telegram restrictions I can't demote them. Please do it manually")
+ await m.reply_text(
+ "May be the user is bot and due to telegram restrictions I can't demote them. Please do it manually")
except RPCError as ef:
await m.reply_text(
f"Some error occured, report it using `/bug` \n Error: {ef}
"
@@ -419,7 +419,7 @@ async def demote_usr(c: Gojo, m: Message):
@Gojo.on_message(command("invitelink"))
async def get_invitelink(c: Gojo, m: Message):
# Bypass the bot devs, sudos and owner
-
+
DEV_LEVEL = DEV_USERS
if m.from_user.id not in DEV_LEVEL:
user = await m.chat.get_member(m.from_user.id)
@@ -466,6 +466,7 @@ async def setgtitle(_, m: Message):
f"Successfully Changed Group Title From {m.chat.title} To {gtit}",
)
+
@Gojo.on_message(command("setgdes") & admin_filter)
async def setgdes(_, m: Message):
user = await m.chat.get_member(m.from_user.id)
@@ -499,9 +500,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,11 +536,9 @@ 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)
+ await m.chat.set_photo(photo, video=is_vid)
except Exception as e:
remove(photo)
return await m.reply_text(f"Error: {e}")
@@ -586,5 +584,3 @@ __HELP__ = """
**Example:**
`/promote @username`: this promotes a user to admin."""
-
-
diff --git a/Powers/plugins/afk.py b/Powers/plugins/afk.py
index 58bced21298ab116d036355ad3ab10363a2095e6..caf1cb003557c920ac21a51fe7ddb4b5137319d5 100644
--- a/Powers/plugins/afk.py
+++ b/Powers/plugins/afk.py
@@ -30,40 +30,42 @@ back = [
"{first} is now finally back from the dead"
]
-@Gojo.on_message(command(["afk","brb"]) & ~filters.private)
+
+@Gojo.on_message(command(["afk", "brb"]) & ~filters.private)
async def going_afk(c: Gojo, m: Message):
user = m.from_user.id
chat = m.chat.id
afk = AFK()
text, data_type, content = await get_afk_type(m)
-
- time = str(datetime.now()).rsplit(".",1)[0]
+
+ time = str(datetime.now()).rsplit(".", 1)[0]
if len(m.command) == 1:
text = choice(res)
elif len(m.command) > 1:
- text = m.text.markdown.split(None,1)[1]
+ text = m.text.markdown.split(None, 1)[1]
if not data_type:
data_type = Types.TEXT
- afk.insert_afk(chat,user,str(time),text,data_type,content)
+ afk.insert_afk(chat, user, str(time), text, data_type, content)
await m.reply_text(f"{m.from_user.mention} is now AFK")
return
-async def get_hours(hour:str):
+
+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,19 +76,12 @@ 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
-
- is_afk = afk.check_afk(chat,user)
- is_rep_afk = False
- if rep_user:
- is_rep_afk = afk.check_afk(chat,rep_user)
+ rep_user = repl.from_user.id if repl and repl.from_user else False
+ is_afk = afk.check_afk(chat, user)
+ is_rep_afk = afk.check_afk(chat, rep_user) if rep_user else False
if is_rep_afk and rep_user != user:
- con = afk.get_afk(chat,rep_user)
+ con = afk.get_afk(chat, rep_user)
time = till_date(con["time"])
media = con["media"]
media_type = con["media_type"]
@@ -96,7 +91,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)}"
@@ -104,22 +99,22 @@ async def afk_checker(c: Gojo, m: Message):
reason += f"\n{con['reason'].format(first=repl.from_user.first_name)}"
txt = reason
- if media_type == Types.TEXT:
- await (await send_cmd(c,media_type))(
+ if media_type == Types.TEXT:
+ await (await send_cmd(c, media_type))(
chat,
txt,
parse_mode=PM.MARKDOWN,
reply_to_message_id=m.id,
)
else:
- await (await send_cmd(c,media_type))(
+ await (await send_cmd(c, media_type))(
chat,
media,
txt,
parse_mode=PM.MARKDOWN,
reply_to_message_id=repl.id
)
-
+
if is_afk:
txt = False
try:
@@ -127,10 +122,10 @@ async def afk_checker(c: Gojo, m: Message):
except Exception:
pass
- if txt and txt in ["afk","brb"]:
+ if txt and txt in ["afk", "brb"]:
raise ContinuePropagation
else:
- con = afk.get_afk(chat,user)
+ con = afk.get_afk(chat, user)
time = till_date(con["time"])
tim_ = datetime.now() - time
tim_ = str(tim_).split(",")
@@ -138,15 +133,16 @@ async def afk_checker(c: Gojo, m: Message):
if len(tim_) == 1:
tims = tim
elif len(tim_) == 2:
- tims = tim_[0] + " " + tim
- txt = back_.format(first=m.from_user.mention) + f"\n\nAfk for: {tims}"
+ tims = f"{tim_[0]} {tim}"
+ txt = f"{back_.format(first=m.from_user.mention)}\n\nAfk for: {tims}"
await m.reply_text(txt)
- afk.delete_afk(chat,user)
+ afk.delete_afk(chat, user)
raise ContinuePropagation
+
__PLUGIN__ = "afk"
-_DISABLE_CMDS_ = ["afk","brb"]
+_DISABLE_CMDS_ = ["afk", "brb"]
__alt_name__ = ["brb"]
@@ -155,4 +151,4 @@ __HELP__ = """
• /afk (/brb) [reason | reply to a message]
`reply to a message` can be any media or text
-"""
\ No newline at end of file
+"""
diff --git a/Powers/plugins/antispam.py b/Powers/plugins/antispam.py
index eb278055653ecdcc3b390810aee3aaef727507e7..f2e6349bf6f2e52f595ffc34ca58fff40af1eb73 100644
--- a/Powers/plugins/antispam.py
+++ b/Powers/plugins/antispam.py
@@ -18,6 +18,7 @@ from Powers.utils.parser import mention_html
# Initialize
db = GBan()
+
@Gojo.on_message(command(["gban", "globalban"], sudo_cmd=True))
async def gban(c: Gojo, m: Message):
if len(m.text.split()) == 1:
@@ -72,7 +73,7 @@ async def gban(c: Gojo, m: Message):
try:
await c.ban_chat_member(m.chat.id, user_id)
except Exception as e:
- await m.reply_text(f"Failed to ban this user\n{e}")
+ await m.reply_text(f"Failed to ban this user\n{e}")
except UserIsBlocked:
LOGGER.error("Could not send PM Message, user blocked bot")
except PeerIdInvalid:
@@ -170,14 +171,13 @@ async def gban_list(_, m: Message):
document=f, caption="Here are all the globally banned geys!\n\n"
)
-
return
+
__PLUGIN__ = "global"
__alt_name__ = ["antispam", "global"]
-
__HELP__ = """
**Global**
@@ -186,4 +186,4 @@ __HELP__ = """
• /ungban [reply to user | user id | username]: Remove the user from the global ban watchlist.
• /numgbans : Give number of users who are banned globally.
• /gbanlist : Give list of globally banned users.
-"""
\ No newline at end of file
+"""
diff --git a/Powers/plugins/approve.py b/Powers/plugins/approve.py
index f84822f4d9efaee2396660732f7bc13a01fdc5a1..2642a7666261a11c5de539bd5323bdcc36e39ea1 100644
--- a/Powers/plugins/approve.py
+++ b/Powers/plugins/approve.py
@@ -3,7 +3,6 @@ from pyrogram.enums import ChatMemberStatus as CMS
from pyrogram.errors import PeerIdInvalid, RPCError, UserNotParticipant
from pyrogram.types import CallbackQuery, Message
-from Powers import LOGGER
from Powers.bot_class import Gojo
from Powers.database.approve_db import Approve
from Powers.utils.custom_filters import admin_filter, command, owner_filter
@@ -44,8 +43,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}",
)
@@ -223,7 +221,6 @@ _DISABLE_CMDS_ = ["approval"]
__alt_name__ = ["approved"]
-
__HELP__ = """
**Apporve**
diff --git a/Powers/plugins/auto_join.py b/Powers/plugins/auto_join.py
index 52c6d4fc18ec7d33ba7de49e1d8f18e635888959..77e8cf95226e549377c345dac2c1bef651b6155d 100644
--- a/Powers/plugins/auto_join.py
+++ b/Powers/plugins/auto_join.py
@@ -34,33 +34,25 @@ async def accept_join_requests(c: Gojo, m: Message):
return
if len(split) == 1:
txt = "**USAGE**\n/joinreq [on | off]"
- await m.reply_text(txt)
- 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"]:
+ 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)
+ 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)
@@ -101,11 +91,12 @@ async def join_request_handler(c: Gojo, j: ChatJoinRequest):
return
if join_type == "auto" or user in SUPPORT_STAFF:
try:
- await c.approve_chat_join_request(chat,user)
+ await c.approve_chat_join_request(chat, user)
await c.send_message(chat, f"Accepted join request of the {userr.mention}")
return
except Exception as ef:
- await c.send_message(chat,f"Some error occured while approving request, report it using `/bug`\nError: {ef}
")
+ 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())
return
@@ -114,20 +105,21 @@ async def join_request_handler(c: Gojo, j: ChatJoinRequest):
txt += f"Name: {userr.full_name}"
txt += f"Mention: {userr.mention}"
txt += f"Id: {user}"
- txt += f"Scam: {'True' if userr.is_scam else 'False'}"
+ txt += f"Scam: {'True' if userr.is_scam else 'False'}"
if userr.username:
- txt+= f"Username: @{userr.username}"
+ txt += f"Username: @{userr.username}"
kb = [
[
- ikb("Accept",f"accept_joinreq_uest_{user}"),
- ikb("Decline",f"decline_joinreq_uest_{user}")
+ ikb("Accept", f"accept_joinreq_uest_{user}"),
+ ikb("Decline", f"decline_joinreq_uest_{user}")
]
]
- await c.send_message(chat,txt,reply_markup=ikm(kb))
+ await c.send_message(chat, txt, reply_markup=ikm(kb))
return
+
@Gojo.on_callback_query(filters.regex("^accept_joinreq_uest_") | filters.regex("^decline_joinreq_uest_"))
-async def accept_decline_request(c:Gojo, q: CallbackQuery):
+async def accept_decline_request(c: Gojo, q: CallbackQuery):
user_id = q.from_user.id
chat = q.message.chat.id
try:
@@ -138,7 +130,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,39 +139,41 @@ 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:
- await c.approve_chat_join_request(chat,user)
- await q.answer(f"Accepted join request of the {userr.mention if userr else user}",True)
+ await c.approve_chat_join_request(chat, user)
+ await q.answer(f"Accepted join request of the {userr.mention if userr else user}", True)
await q.edit_message_text(f"Accepted join request of the {userr.mention if userr else user}")
except Exception as ef:
- await c.send_message(chat,f"Some error occured while approving request, report it using `/bug`\nError: {ef}
")
+ 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)
+ await c.decline_chat_join_request(chat, user)
await q.answer(f"DECLINED: {user}")
await q.edit_message_text()
except Exception as ef:
- await c.send_message(chat,f"Some error occured while approving request, report it using `/bug`\nError: {ef}
")
+ 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())
return
+
__PLUGIN__ = "auto join"
__alt_name__ = ["join_request"]
-
__HELP__ = """
**Auto join request**
**Admin commands:**
• /joinreq [on | off]: To switch on auto accept join request
• /joinreqmode [auto | manual]: `auto` to accept join request automatically and `manual` to get notified when new join request is available
-"""
\ No newline at end of file
+"""
diff --git a/Powers/plugins/bans.py b/Powers/plugins/bans.py
index 69b035b8d6ceec5ca0e9fd61b772f9d29e8a5c87..dfcbac96c34e5617383fe464a3be132f153f5e8a 100644
--- a/Powers/plugins/bans.py
+++ b/Powers/plugins/bans.py
@@ -44,7 +44,7 @@ async def tban_usr(c: Gojo, m: Message):
await m.reply_text(
text="This user is in my support staff, cannot restrict them."
)
-
+
await m.stop_propagation()
r_id = m.reply_to_message.id if m.reply_to_message else m.id
@@ -86,10 +86,11 @@ async def tban_usr(c: Gojo, m: Message):
await m.chat.ban_member(
user_id,
until_date=bantime)
- t_t=f"{admin} banned {banned} in {chat_title}!",
+ t_t = f"{admin} banned {banned} in {chat_title}!",
txt = t_t
if type(t_t) is tuple:
- txt = t_t[0] # Done this bcuz idk why t_t is tuple type data. SO now if it is tuple this will get text from it
+ txt = t_t[
+ 0] # Done this bcuz idk why t_t is tuple type data. SO now if it is tuple this will get text from it
if reason:
txt += f"\nReason: {reason}"
if time_val:
@@ -114,14 +115,14 @@ async def tban_usr(c: Gojo, m: Message):
parse_mode=enums.ParseMode.HTML,
)
except Exception:
-
+
await m.reply_text(
reply_to_message_id=r_id,
text=txt,
reply_markup=keyboard,
parse_mode=enums.ParseMode.HTML,
)
- await c.send_message(MESSAGE_DUMP,f"#REMOVE from BAN_GFIS\n{anim}")
+ await c.send_message(MESSAGE_DUMP, f"#REMOVE from BAN_GFIS\n{anim}")
# await m.reply_text(txt, reply_markup=keyboard,
# reply_to_message_id=r_id)
except ChatAdminRequired:
@@ -175,7 +176,7 @@ async def stban_usr(c: Gojo, m: Message):
await m.reply_text(
text="This user is in my support staff, cannot restrict them."
)
-
+
await m.stop_propagation()
if m.reply_to_message and len(m.text.split()) >= 2:
@@ -266,7 +267,7 @@ async def dtban_usr(c: Gojo, m: Message):
if user_id in SUPPORT_STAFF:
await m.reply_text(text="I am not going to ban one of my support staff")
-
+
await m.stop_propagation()
if m.reply_to_message and len(m.text.split()) >= 2:
@@ -329,13 +330,13 @@ async def dtban_usr(c: Gojo, m: Message):
parse_mode=enums.ParseMode.HTML,
)
except Exception:
-
+
await m.reply_text(
txt,
reply_markup=keyboard,
parse_mode=enums.ParseMode.HTML,
)
- await c.send_message(MESSAGE_DUMP,f"#REMOVE from BAN_GFIS\n{anim}")
+ await c.send_message(MESSAGE_DUMP, f"#REMOVE from BAN_GFIS\n{anim}")
# await c.send_message(m.chat.id, txt, reply_markup=keyboard)
except ChatAdminRequired:
await m.reply_text(text="I'm not admin or I don't have rights.")
@@ -395,7 +396,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,13 +425,13 @@ 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,
parse_mode=enums.ParseMode.HTML,
)
- await c.send_message(MESSAGE_DUMP,f"#REMOVE from KICK_GFIS\n{kickk}")
+ await c.send_message(MESSAGE_DUMP, f"#REMOVE from KICK_GFIS\n{kickk}")
await m.chat.unban_member(user_id)
except ChatAdminRequired:
await m.reply_text(text="I'm not admin or I don't have rights.")
@@ -483,7 +484,7 @@ async def skick_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:
@@ -554,7 +555,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,12 +583,12 @@ 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,
)
- await c.send_message(MESSAGE_DUMP,f"#REMOVE from KICK_GFIS\n{kickk}")
+ await c.send_message(MESSAGE_DUMP, f"#REMOVE from KICK_GFIS\n{kickk}")
await m.chat.unban_member(user_id)
except ChatAdminRequired:
await m.reply_text(text="I'm not admin or I don't have rights.")
@@ -641,7 +642,7 @@ async def unban_usr(c: Gojo, m: Message):
try:
statu = (await m.chat.get_member(user_id)).status
- if statu not in [enums.ChatMemberStatus.BANNED,enums.ChatMemberStatus.RESTRICTED]:
+ if statu not in [enums.ChatMemberStatus.BANNED, enums.ChatMemberStatus.RESTRICTED]:
await m.reply_text("User is not banned in this chat\nOr using this command as reply to his message")
return
except Exception as e:
@@ -752,7 +753,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 +791,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)
@@ -816,8 +814,8 @@ async def dban_usr(c: Gojo, m: Message):
m.chat.id, animation=str(animm), caption=txt, reply_markup=keyboard
)
except Exception:
- await c.send_message(m.chat.id,txt,enums.ParseMode.HTML,reply_markup=keyboard)
- await c.send_messagea(MESSAGE_DUMP,f"#REMOVE from BAN_GIFS\n{animm}")
+ await c.send_message(m.chat.id, txt, enums.ParseMode.HTML, reply_markup=keyboard)
+ await c.send_messagea(MESSAGE_DUMP, f"#REMOVE from BAN_GIFS\n{animm}")
except ChatAdminRequired:
await m.reply_text(text="I'm not admin or I don't have rights.")
except PeerIdInvalid:
@@ -924,14 +922,14 @@ async def ban_usr(c: Gojo, m: Message):
parse_mode=enums.ParseMode.HTML,
)
except Exception:
-
+
await m.reply_text(
reply_to_message_id=r_id,
text=txt,
reply_markup=keyboard,
parse_mode=enums.ParseMode.HTML,
)
- await c.send_message(MESSAGE_DUMP,f"#REMOVE from BAN_GFIS\n{anim}")
+ await c.send_message(MESSAGE_DUMP, f"#REMOVE from BAN_GFIS\n{anim}")
except ChatAdminRequired:
await m.reply_text(text="I'm not admin or I don't have rights.")
except PeerIdInvalid:
@@ -970,14 +968,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,11 +987,9 @@ 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)
+ mem = await c.get_chat_member(m.chat.id, m.from_user.id)
if mem.status in [enums.ChatMemberStatus.ADMINISTRATOR, enums.ChatMemberStatus.OWNER]:
try:
await c.promote_chat_member(
diff --git a/Powers/plugins/birthday.py b/Powers/plugins/birthday.py
index ddaccb545589fb46970b3b263bb3296db480a902..9c772900ccfc2b3531248666061f1cc5e8629c99 100644
--- a/Powers/plugins/birthday.py
+++ b/Powers/plugins/birthday.py
@@ -8,7 +8,7 @@ from pyrogram.types import InlineKeyboardButton as IKB
from pyrogram.types import InlineKeyboardMarkup as IKM
from pyrogram.types import Message
-from Powers import BDB_URI, LOGGER, TIME_ZONE
+from Powers import BDB_URI, LOGGER
from Powers.bot_class import Gojo
from Powers.database.chats_db import Chats
@@ -18,9 +18,9 @@ if BDB_URI:
from Powers.utils.custom_filters import command
-def give_date(date,form = "%d/%m/%Y"):
- datee = datetime.strptime(date,form).date()
- return datee
+def give_date(date, form="%d/%m/%Y"):
+ return datetime.strptime(date, form).date()
+
@Gojo.on_message(command("remember"))
async def remember_me(c: Gojo, m: Message):
@@ -29,38 +29,24 @@ async def remember_me(c: Gojo, m: Message):
return
splited = m.text.split()
if len(splited) == 1:
- await m.reply_text("**USAGE**:\n/remember [username or user id or reply to user] [DOB]\nDOB should be in format of dd/mm/yyyy\nYear is optional it is not necessary to pass it")
+ await m.reply_text(
+ "**USAGE**:\n/remember [username or user id or reply to user] [DOB]\nDOB should be in format of dd/mm/yyyy\nYear is optional it is not necessary to pass it")
return
if len(splited) != 2 and m.reply_to_message:
- await m.reply_text("**USAGE**:\n/remember [username or user id or reply to user] [DOB]\nDOB should be in format of dd/mm/yyyy\nYear is optional it is not necessary to pass it")
+ await m.reply_text(
+ "**USAGE**:\n/remember [username or user id or reply to user] [DOB]\nDOB should be in format of dd/mm/yyyy\nYear is optional it is not necessary to pass it")
return
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
- if len(DOB) == 3:
- is_correct = (len(DOB[2]) == 4)
- if len(DOB[0]) != 2 and len(DOB[1]) !=2 and not is_correct:
+ is_correct = (len(DOB[2]) == 4) if len(DOB) == 3 else False
+ if len(DOB[0]) != 2 and len(DOB[1]) != 2 and not is_correct:
await m.reply_text("DOB should be in format of dd/mm/yyyy\nYear is optional it is not necessary to pass it")
return
try:
@@ -72,15 +58,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}/{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}
+ 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:
@@ -97,26 +82,26 @@ async def remember_me(c: Gojo, m: Message):
LOGGER.error(format_exc())
return
-@Gojo.on_message(command(["removebday","rmbday"]))
+
+@Gojo.on_message(command(["removebday", "rmbday"]))
async def who_are_you_again(c: Gojo, m: Message):
if not BDB_URI:
await m.reply_text("BDB_URI is not configured")
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:
- bday_info.delete_one({"user_id":user})
+ 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
-@Gojo.on_message(command(["nextbdays","nbdays","birthdays","bdays"]))
+
+@Gojo.on_message(command(["nextbdays", "nbdays", "birthdays", "bdays"]))
async def who_is_next(c: Gojo, m: Message):
if not BDB_URI:
await m.reply_text("BDB_URI is not configured")
@@ -133,28 +118,27 @@ 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:
await xx.delete()
- await m.reply_text("There are no upcoming birthdays of any user in this chat:/\nEither all the birthdays are passed or no user from this chat have registered their birthday")
+ await m.reply_text(
+ "There are no upcoming birthdays of any user in this chat:/\nEither all the birthdays are passed or no user from this chat have registered their birthday")
return
txt = "🎊 Upcomming Birthdays Are 🎊\n"
for i in users:
DOB = give_date(i["dob"])
dete = date(curr.year, DOB.month, DOB.day)
- leff = (dete - curr).days
+ leff = (dete - curr).days
txt += f"`{i['user_id']}` : {leff} days left\n"
txt += "\n\nYou can use /info [user id] to get info about the user"
await xx.delete()
await m.reply_text(txt)
return
-@Gojo.on_message(command(["getbday","gbday","mybirthday","mybday"]))
+
+@Gojo.on_message(command(["getbday", "gbday", "mybirthday", "mybday"]))
async def cant_recall_it(c: Gojo, m: Message):
if not BDB_URI:
await m.reply_text("BDB_URI is not configured")
@@ -165,27 +149,27 @@ async def cant_recall_it(c: Gojo, m: Message):
user = m.reply_to_message.from_user.id
men = m.reply_to_message.from_user.mention
try:
- result = bday_info.find_one({"user_id":user})
+ result = bday_info.find_one({"user_id": user})
if not result:
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
-
- curr = datetime.now().date()
+
+ curr = datetime.now().date()
u_dob = give_date(result["dob"])
formatted = str(u_dob.strftime('%d' + '%B %Y'))[2:-5]
day = int(result["dob"].split('/')[0])
suffix = {1: 'st', 2: 'nd', 3: 'rd'}.get(day % 10, 'th')
bday_on = f"{day}{suffix} {formatted}"
- if (u_dob.day,u_dob.month) < (curr.day,curr.month):
+ if (u_dob.day, u_dob.month) < (curr.day, curr.month):
next_b = date(curr.year + 1, u_dob.month, u_dob.day)
days_left = (next_b - curr).days
txt = f"{men} 's birthday is passed 🫤\nDays left until next one {abs(days_left)}"
txt += f"\nBirthday on: {bday_on}"
txt += f"\n\nDate of birth: {result['dob']}"
- elif (u_dob.day,u_dob.month) == (curr.day,curr.month):
+ elif (u_dob.day, u_dob.month) == (curr.day, curr.month):
txt = f"Today is {men}'s birthday."
else:
u_dobm = date(curr.year, u_dob.month, u_dob.day)
@@ -193,11 +177,12 @@ async def cant_recall_it(c: Gojo, m: Message):
txt = f"User's birthday is coming🥳\nDays left: {abs(days_left)}"
txt += f"\nBirthday on: {bday_on}"
txt += f"\n\nDate of birth: {result['dob']}"
- txt+= "\n\n**NOTE**:\nDOB may be wrong if user haven't entered his/her birth year"
+ txt += "\n\n**NOTE**:\nDOB may be wrong if user haven't entered his/her birth year"
await m.reply_text(txt)
return
-@Gojo.on_message(command(["settingbday","sbday"]))
+
+@Gojo.on_message(command(["settingbday", "sbday"]))
async def chat_birthday_settings(c: Gojo, m: Message):
if not BDB_URI:
await m.reply_text("BDB_URI is not configured")
@@ -206,20 +191,21 @@ async def chat_birthday_settings(c: Gojo, m: Message):
await m.reply_text("Use in groups")
return
chats = m.chat.id
- c_in = bday_cinfo.find_one({"chat_id":chats})
+ c_in = bday_cinfo.find_one({"chat_id": chats})
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")
]
]
)
- await m.reply_text("Do you want to wish members for their birthday in the group?",reply_markup=kb)
+ await m.reply_text("Do you want to wish members for their birthday in the group?", reply_markup=kb)
return
+
@Gojo.on_callback_query(filters.regex(r"^switchh_(yes|no)$"))
-async def switch_on_off(c:Gojo, q: CallbackQuery):
+async def switch_on_off(c: Gojo, q: CallbackQuery):
user = (await q.message.chat.get_member(q.from_user.id)).status
await q.message.chat.get_member(q.from_user.id)
if user not in [ChatMemberStatus.ADMINISTRATOR, ChatMemberStatus.OWNER]:
@@ -227,16 +213,16 @@ async def switch_on_off(c:Gojo, q: CallbackQuery):
return
data = q.data.split("_")[1]
chats = q.message.chat.id
- query = {"chat_id":chats}
+ query = {"chat_id": chats}
if data == "yes":
bday_cinfo.delete_one(query)
elif data == "no":
bday_cinfo.insert_one(query)
- await q.edit_message_text(f"Done! I will {'wish' if data == 'yes' else 'not wish'}",reply_markup=IKM([[IKB("Close", "f_close")]]))
+ await q.edit_message_text(f"Done! I will {'wish' if data == 'yes' else 'not wish'}",
+ reply_markup=IKM([[IKB("Close", "f_close")]]))
return
-
__PLUGIN__ = "birthday"
__HELP__ = """
diff --git a/Powers/plugins/blacklist.py b/Powers/plugins/blacklist.py
index 768a5e4b13f82934905e0db739c3869e363307a8..6a35a6a5df12c390f5175a81fb8899137a732e0e 100644
--- a/Powers/plugins/blacklist.py
+++ b/Powers/plugins/blacklist.py
@@ -4,7 +4,6 @@ from pyrogram import filters
from pyrogram.enums import ChatMemberStatus as CMS
from pyrogram.types import CallbackQuery, Message
-from Powers import LOGGER
from Powers.bot_class import Gojo
from Powers.database.blacklist_db import Blacklist
from Powers.utils.custom_filters import command, owner_filter, restrict_filter
@@ -53,13 +52,13 @@ async def add_blacklist(_, m: Message):
if already_added_words:
rep_text = (
- ", ".join([f"{i}
" for i in bl_words])
- + " already added in blacklist, skipped them!"
+ ", ".join([f"{i}
" for i in bl_words])
+ + " already added in blacklist, skipped them!"
)
trigger = ", ".join(f"{i}
" for i in bl_words)
await m.reply_text(
text=f"Added {trigger}
in blacklist words!"
- + (f"\n{rep_text}" if rep_text else ""),
+ + (f"\n{rep_text}" if rep_text else ""),
)
await m.stop_propagation()
@@ -110,13 +109,13 @@ async def rm_blacklist(_, m: Message):
if non_found_words:
rep_text = (
- "Could not find " + ", ".join(f"{i}
" for i in non_found_words)
- ) + " in blcklisted words, skipped them."
+ "Could not find " + ", ".join(f"{i}
" for i in non_found_words)
+ ) + " in blcklisted words, skipped them."
bl_words = ", ".join(f"{i}
" for i in bl_words)
await m.reply_text(
text=f"Removed {bl_words} from blacklist words!"
- + (f"\n{rep_text}" if rep_text else ""),
+ + (f"\n{rep_text}" if rep_text else ""),
)
await m.stop_propagation()
@@ -134,8 +133,8 @@ async def set_bl_action(_, m: Message):
if action not in valid_actions:
await m.reply_text(
(
- "Choose a valid blacklist action from "
- + ", ".join(f"{i}
" for i in valid_actions)
+ "Choose a valid blacklist action from "
+ + ", ".join(f"{i}
" for i in valid_actions)
),
)
diff --git a/Powers/plugins/captcha.py b/Powers/plugins/captcha.py
index c288e4c497954f9085173c7d5735d47603f576f8..2c89b7cbb63b30d164b14b5b4c0283a313e0a95f 100644
--- a/Powers/plugins/captcha.py
+++ b/Powers/plugins/captcha.py
@@ -3,7 +3,6 @@ from random import choice, shuffle
from traceback import format_exc
from typing import List
-import pyrogram
from pyrogram import filters
from pyrogram.enums import ChatMemberStatus as CMS
from pyrogram.enums import ParseMode as PM
@@ -32,20 +31,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 +50,23 @@ 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
+ await m.reply_text(
+ f"Current captcha verification methode is {capatcha_type}\nAvailable methodes:\n■ qr\n■ image")
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,20 +130,20 @@ 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,
reply_markup=keyboard,
parse_mode=PM.HTML,
)
- await c.send_message(MESSAGE_DUMP,f"#REMOVE from BAN_GFIS\n{anim}")
+ 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
@@ -201,24 +192,16 @@ async def on_chat_members_updatess(c: Gojo, m: Message):
continue
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":
+ captcha_type = "image" # I am not going to apply qr captcha in this update
+ 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)
@@ -227,26 +210,31 @@ async def on_chat_members_updatess(c: Gojo, m: Message):
kb = ikm(
[
[
- IKB(rand[0], ini+rand[0])
+ IKB(rand[0], ini + rand[0])
],
[
- IKB(rand[1], ini+rand[1])
+ IKB(rand[1], ini + rand[1])
],
[
- IKB(rand[2], ini+rand[2])
+ IKB(rand[2], ini + rand[2])
],
[
- IKB(rand[3], ini+rand[3])
+ IKB(rand[3], ini + rand[3])
],
[
- IKB(rand[4], ini+rand[4])
+ IKB(rand[4], ini + rand[4])
]
]
)
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..7ab5b936a0424744858d64329ea4bd39bbfcbc4d 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,12 +84,11 @@ 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"
- + "\n".join(f"{i}
" for i in bl_chats)
+ "These Chats are Blacklisted:\n"
+ + "\n".join(f"{i}
" for i in bl_chats)
),
)
@@ -103,8 +100,6 @@ async def list_blacklist_chats(_, m: Message):
__PLUGIN__ = "Chat blacklist"
-
-
__HELP__ = """
**Chat blacklist**
@@ -112,4 +107,4 @@ __HELP__ = """
• /blchat [space separated id or username of chats]: Add chats to black list if given or the current chat.
• /rmblchat [space separated id or username of chats]: Remove chats from black list if given or the current chat.
• /blchats: Give the list of blacklisted chats
-"""
\ No newline at end of file
+"""
diff --git a/Powers/plugins/dev.py b/Powers/plugins/dev.py
index c64056b6bf6636b854bfda1bd4822060d2fee598..f1c751dedf3d3ff0a170f505a519880713131833 100644
--- a/Powers/plugins/dev.py
+++ b/Powers/plugins/dev.py
@@ -8,7 +8,6 @@ from sys import executable
from time import gmtime, strftime, time
from traceback import format_exc
-from pyrogram import filters
from pyrogram.errors import (ChannelInvalid, ChannelPrivate, ChatAdminRequired,
EntityBoundsInvalid, FloodWait, MessageTooLong,
PeerIdInvalid, RPCError)
@@ -31,23 +30,23 @@ from Powers.utils.parser import mention_markdown
def can_change_type(curr, to_user):
- if curr == "dev" and to_user in ["whitelist","sudo"]:
+ if curr == "dev" and to_user in ["whitelist", "sudo"]:
return True
elif curr == "sudo" and to_user == "whitelist":
return True
else:
return False
+
@Gojo.on_message(command(["addsupport"]))
-async def add_support(c: Gojo, m:Message):
+async def add_support(c: Gojo, m: Message):
support = SUPPORTS()
curr_user = support.get_support_type(m.from_user.id)
if not curr_user:
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:
@@ -59,26 +58,25 @@ async def add_support(c: Gojo, m:Message):
except IndexError:
await m.reply_text("**USAGE**\n/addsupport [reply to message | user id] [dev | sudo | whitelist]")
return
- if to not in ["dev","sudo","whitelist"]:
+ if to not in ["dev", "sudo", "whitelist"]:
await m.reply_text("**USAGE**\n/addsupport [reply to message | user id] [dev | sudo | whitelist]")
return
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(
[
[
- IKB("Yes",f"change_support_type:{to}"),
- IKB("No","change_support_type:no")
+ IKB("Yes", f"change_support_type:{to}"),
+ IKB("No", "change_support_type:no")
]
]
)
- 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
+ await m.reply_text(f"This is user is already in {curr} users\nDo you want to make him {to} user?",
+ reply_markup=kb)
else:
- support.insert_support_user(userr,to)
+ support.insert_support_user(userr, to)
if to == "dev":
DEV_USERS.add(userr)
elif to == "sudo":
@@ -86,34 +84,31 @@ 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(
[
[
- IKB("Yes",f"change_support_type:{to}"),
- IKB("No","change_support_type:no")
+ IKB("Yes", f"change_support_type:{to}"),
+ IKB("No", "change_support_type:no")
]
]
)
- 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
+ await m.reply_text(f"This is user is already in {curr} users\nDo you want to make him {to} user?",
+ reply_markup=kb)
else:
- support.insert_support_user(userr,to)
+ 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:
- userr,_,_ = extract_user(user)
+ userr, _, _ = extract_user(user)
except Exception:
await m.reply_text("Tell the user to start me first")
return
@@ -121,53 +116,51 @@ async def add_support(c: Gojo, m:Message):
try:
to = m.command[2].lower()
except IndexError:
- await m.reply_text("**USAGE**\n/addsupport [reply to message | user id | username] [dev | sudo | whitelist]")
+ await m.reply_text(
+ "**USAGE**\n/addsupport [reply to message | user id | username] [dev | sudo | whitelist]")
return
- if to not in ["dev","sudo","whitelist"]:
+ if to not in ["dev", "sudo", "whitelist"]:
await m.reply_text("**USAGE**\n/addsupport [reply to message | user id] [dev | sudo | whitelist]")
return
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(
[
[
- IKB("Yes",f"change_support_type:{to}"),
- IKB("No","change_support_type:no")
+ IKB("Yes", f"change_support_type:{to}"),
+ IKB("No", "change_support_type:no")
]
]
)
- 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
+ await m.reply_text(f"This is user is already in {curr} users\nDo you want to make him {to} user?",
+ reply_markup=kb)
else:
- support.insert_support_user(userr,to)
+ 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(
[
[
- IKB("Yes",f"change_support_type:{to}"),
- IKB("No","change_support_type:no")
+ IKB("Yes", f"change_support_type:{to}"),
+ IKB("No", "change_support_type:no")
]
]
)
- 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
+ await m.reply_text(f"This is user is already in {curr} users\nDo you want to make him {to} user?",
+ reply_markup=kb)
else:
- support.insert_support_user(userr,to)
+ 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 +170,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:
@@ -190,7 +181,7 @@ async def rm_support(c: Gojo, m: Message):
curr = int(split[1])
except Exception:
try:
- curr,_,_ = extract_user(m)
+ curr, _, _ = extract_user(m)
except Exception:
await m.reply_text("Dunno who u r talking abt")
return
@@ -198,7 +189,7 @@ async def rm_support(c: Gojo, m: Message):
await m.reply_text("**USAGE**\n/rmsupport [reply to user | user id | username]")
return
to_user = support.get_support_type(curr)
- can_user = can_change_type(curr_user,to_user)
+ can_user = can_change_type(curr_user, to_user)
if m.from_user.id == int(OWNER_ID) or can_user:
support.delete_support_user(curr)
DEV_USERS.discard(curr)
@@ -209,6 +200,7 @@ async def rm_support(c: Gojo, m: Message):
await m.reply_text("Sorry you can't do that...")
return
+
@Gojo.on_message(command("ping", sudo_cmd=True))
async def ping(_, m: Message):
start = time()
@@ -217,18 +209,20 @@ async def ping(_, m: Message):
await replymsg.edit_text(f"Pong!\n{delta_ping * 1000:.3f} ms")
return
+
"""
['Metadata-Version', 'Name', 'Version', 'Summary', 'Home-page', 'Author', 'Author-email', 'License', 'Download-URL', 'Project-URL', 'Project-URL', 'Project-URL', 'Project-URL', 'Keywords', 'Platform', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Requires-Python', 'Description-Content-Type', 'License-File', 'License-File', 'License-File', 'Requires-Dist', 'Requires-Dist', 'Description']
"""
+
@Gojo.on_message(command(["minfo", "moduleinfo"], dev_cmd=True))
async def check_module_info(_, m: Message):
if len(m.command) != 2:
await m.reply_text("**USAGE**\n/minfo [module name]")
return
-
+
module = m.command[-1]
try:
@@ -236,7 +230,7 @@ async def check_module_info(_, m: Message):
except PackageNotFoundError:
await m.reply_text(f"No module found with name {module}")
return
-
+
name = minfo["Name"]
version = minfo["Version"]
summary = minfo["Summary"]
@@ -262,7 +256,6 @@ Here are the info about the module **{name}**
await m.reply_text(txt, disable_web_page_preview=True)
return
-
@Gojo.on_message(command("logs", dev_cmd=True))
async def send_log(c: Gojo, m: Message):
@@ -292,12 +285,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)
@@ -308,6 +297,7 @@ async def neofetch_stats(_, m: Message):
await m.delete()
return
+
HARMFUL = [
"base64",
"bash",
@@ -325,7 +315,7 @@ HARMFUL = [
"SSH_CLIENT",
"SSH_CONNECTION"
"SSH"
-
+
]
@@ -345,17 +335,15 @@ async def evaluate_code(c: Gojo, m: Message):
await c.send_message(
MESSAGE_DUMP,
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()
@@ -385,8 +373,8 @@ async def evaluate_code(c: Gojo, m: Message):
for i in evaluation.split(None):
ev = i.strip()
if (
- (ev.startswith(initial) or ev.endswith(end))
- or (BOT_TOKEN in ev)
+ (ev.startswith(initial) or ev.endswith(end))
+ or (BOT_TOKEN in ev)
) and m.from_user.id != OWNER_ID:
evaluation = "Bhaag ja bsdk"
await c.send_message(
@@ -398,27 +386,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"
@@ -443,8 +429,6 @@ async def aexec(code, c, m):
return await locals()["__aexec"](c, m)
-
-
@Gojo.on_message(command(["exec", "sh"], dev_cmd=True))
async def execution(c: Gojo, m: Message):
protect = BOT_TOKEN.split(":")
@@ -456,55 +440,36 @@ 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:
- if OwO.startswith(initial) or OwO.endswith(end):
- out = "You can't access them"
- break
+ if OwO.startswith(initial) or OwO.endswith(end):
+ out = "You can't access them"
+ 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"
@@ -525,38 +490,41 @@ async def execution(c: Gojo, m: Message):
await sm.delete()
return
-async def stop_and_send_logger(c:Gojo,is_update=False):
+
+async def stop_and_send_logger(c: Gojo, is_update=False):
runtime = strftime("%Hh %Mm %Ss", gmtime(time() - UPTIME))
LOGGER.info("Uploading logs before stopping...!\n")
- # Send Logs to MESSAGE_DUMP and LOG_CHANNEL
+ # Send Logs to MESSAGE_DUMP and LOG_CHANNEL
await c.send_document(
- MESSAGE_DUMP,
- document=LOGFILE,
- caption=(
- f"{'Updating and Restarting'if is_update else 'Restarting'} The Bot !\n\n" f"Uptime: {runtime}\n" f"{LOG_DATETIME}
"
- ),
- )
+ MESSAGE_DUMP,
+ document=LOGFILE,
+ caption=(
+ f"{'Updating and Restarting' if is_update else 'Restarting'} The Bot !\n\n" f"Uptime: {runtime}\n" f"{LOG_DATETIME}
"
+ ),
+ )
if MESSAGE_DUMP:
# LOG_CHANNEL is not necessary
await c.send_document(
- MESSAGE_DUMP,
- document=LOGFILE,
- caption=f"Uptime: {runtime}",
- )
+ MESSAGE_DUMP,
+ document=LOGFILE,
+ caption=f"Uptime: {runtime}",
+ )
MongoDB.close()
LOGGER.info(
- f"""Bot Stopped.
+ f"""Bot Stopped.
Logs have been uploaded to the MESSAGE_DUMP Group!
Runtime: {runtime}s\n
""",
- )
+ )
return
+
@Gojo.on_message(command(["restart", "update"], owner_cmd=True))
-async def restart_the_bot(c:Gojo,m:Message):
+async def restart_the_bot(c: Gojo, m: Message):
try:
cmds = m.command
- await m.reply_text(f"Restarting{' and updating ' if cmds[0] == 'update' else ' '}the bot...\nType `/ping` after few minutes")
+ await m.reply_text(
+ f"Restarting{' and updating ' if cmds[0] == 'update' else ' '}the bot...\nType `/ping` after few minutes")
if cmds[0] == "update":
try:
out = subp.check_output(["git", "pull"]).decode("UTF-8")
@@ -566,7 +534,7 @@ async def restart_the_bot(c:Gojo,m:Message):
except Exception as e:
return await m.reply_text(str(e))
m = await m.reply_text("**Updated with main branch, restarting now.**")
- await stop_and_send_logger(c,True)
+ await stop_and_send_logger(c, True)
if cmds[0] == "restart":
await stop_and_send_logger(c)
execvp(executable, [executable, "-m", "Powers"])
@@ -576,6 +544,7 @@ async def restart_the_bot(c:Gojo,m:Message):
LOGGER.error(format_exc())
return
+
@Gojo.on_message(command("chatlist", dev_cmd=True))
async def chats(c: Gojo, m: Message):
exmsg = await m.reply_text(text="Exporting Charlist...")
@@ -685,14 +654,15 @@ async def chat_broadcast(c: Gojo, m: Message):
return
-@Gojo.on_message(command(["forward","fwd"],dev_cmd=True))
+
+@Gojo.on_message(command(["forward", "fwd"], dev_cmd=True))
async def forward_type_broadcast(c: Gojo, m: Message):
repl = m.reply_to_message
if not repl:
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 +684,7 @@ async def forward_type_broadcast(c: Gojo, m: Message):
peers = user
else:
peers = alll
-
+
xx = await m.reply_text("Broadcasting...")
failed = 0
@@ -725,8 +695,7 @@ 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"
+ 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"
await m.reply_text(txt)
@@ -737,10 +706,8 @@ async def forward_type_broadcast(c: Gojo, m: Message):
return
-
__PLUGIN__ = "devs"
-
__HELP__ = """
**DEV and SUDOERS commands**
diff --git a/Powers/plugins/disable.py b/Powers/plugins/disable.py
index a616edeb135133fdb8f2e0588fbe6790a48d7ed2..2bae2aef52d66088b0ed068cc7e153de26a3fa1f 100644
--- a/Powers/plugins/disable.py
+++ b/Powers/plugins/disable.py
@@ -5,7 +5,7 @@ from pyrogram.enums import ChatMemberStatus as CMS
from pyrogram.types import (CallbackQuery, InlineKeyboardButton,
InlineKeyboardMarkup, Message)
-from Powers import HELP_COMMANDS, LOGGER
+from Powers import HELP_COMMANDS
from Powers.bot_class import Gojo
from Powers.database.disable_db import Disabling
from Powers.utils.custom_filters import (admin_filter, can_change_filter,
@@ -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)
@@ -147,7 +146,6 @@ __PLUGIN__ = "disable able"
__alt_name__ = ["disable commands", "disable"]
-
__HELP__ = """
**Disable commands**
@@ -160,4 +158,4 @@ __HELP__ = """
**Owner command:**
• /enableall : Enable all the disabled commands.
-"""
\ No newline at end of file
+"""
diff --git a/Powers/plugins/filters.py b/Powers/plugins/filters.py
index 222dbc3a23db8e25fc2577b349b50f289b943bd9..6c079b916fa8b9f7386647af3f8f6a4780659a81 100644
--- a/Powers/plugins/filters.py
+++ b/Powers/plugins/filters.py
@@ -6,7 +6,7 @@ from pyrogram import filters
from pyrogram.enums import ChatMemberStatus as CMS
from pyrogram.enums import ParseMode as PM
from pyrogram.errors import RPCError
-from pyrogram.types import CallbackQuery, InlineKeyboardMarkup, Message
+from pyrogram.types import CallbackQuery, Message
from Powers.bot_class import LOGGER, Gojo
from Powers.database.filters_db import Filters
@@ -44,7 +44,6 @@ async def view_filters(_, m: Message):
@Gojo.on_message(command(["filter", "addfilter"]) & admin_filter & ~filters.bot)
async def add_filter(_, m: Message):
-
args = m.text.split(" ", 1)
all_filters = db.get_all_filters(m.chat.id)
actual_filters = {j for i in all_filters for j in i.split("|")}
@@ -95,8 +94,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 +135,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):
@@ -239,10 +236,10 @@ async def send_filter_reply(c: Gojo, m: Message, trigger: str):
return
elif msgtype in (
- Types.STICKER,
- Types.VIDEO_NOTE,
- Types.CONTACT,
- Types.ANIMATED_STICKER,
+ Types.STICKER,
+ Types.VIDEO_NOTE,
+ Types.CONTACT,
+ Types.ANIMATED_STICKER,
):
await (await send_cmd(c, msgtype))(
m.chat.id,
@@ -268,7 +265,6 @@ async def send_filter_reply(c: Gojo, m: Message, trigger: str):
@Gojo.on_message(filters.text & filters.group & ~filters.bot, group=69)
async def filters_watcher(c: Gojo, m: Message):
-
chat_filters = db.get_all_filters(m.chat.id)
actual_filters = {j for i in chat_filters for j in i.split("|")}
diff --git a/Powers/plugins/flood.py b/Powers/plugins/flood.py
index 0216ffe1da5b48863fc9fb78bb4f29b3396274d2..dd5e7d032fc2c62408854ebf1fcbae4c69f684c7 100644
--- a/Powers/plugins/flood.py
+++ b/Powers/plugins/flood.py
@@ -20,38 +20,25 @@ from Powers.utils.extras import BAN_GIFS, KICK_GIFS, MUTE_GIFS
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(
+
+close_kb = InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
@@ -147,20 +134,19 @@ limit_kb = InlineKeyboardMarkup(
]
)
-@Gojo.on_message(command(['floodaction','actionflood']) & admin_filter)
+
+@Gojo.on_message(command(['floodaction', 'actionflood']) & admin_filter)
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}",
@@ -170,28 +156,30 @@ async def flood_action(c: Gojo, m: Message):
await m.reply_text("Switch on the flood protection first.")
return
+
@Gojo.on_message(command(['isflood', 'flood']) & ~filters.bot)
async def flood_on_off(c: Gojo, m: Message):
- if m.chat.type == CT.PRIVATE:
- return await m.reply_text("This command is ment to be used in groups.")
+ if m.chat.type == CT.PRIVATE:
+ return await m.reply_text("This command is ment to be used in groups.")
Flood = Floods()
c_id = m.chat.id
is_flood = Flood.is_chat(c_id)
c_id = m.chat.id
if is_flood:
- saction = is_flood[2]
- slimit = is_flood[0]
- 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")
+ saction = is_flood[2]
+ slimit = is_flood[0]
+ 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 for this chat.")
+
@Gojo.on_message(command(['setflood']) & ~filters.bot & admin_filter)
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.")
@@ -201,22 +189,24 @@ async def flood_set(c: Gojo, m: Message):
if len(split) == 1:
c_id = m.chat.id
- if is_flood:
+ if is_flood:
saction = is_flood[2]
slimit = is_flood[0]
- 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")
+ 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:
- if is_flood:
+ if is_flood:
saction = is_flood[2]
slimit = is_flood[0]
swithin = is_flood[1]
- await m.reply_text(f"Flood is on for this chat\n**Action**:{saction}\n**Messages**:{slimit} within {swithin} sec")
+ await m.reply_text(
+ f"Flood is on for this chat\n**Action**:{saction}\n**Messages**:{slimit} within {swithin} sec")
return
if split[1].lower() in off_key:
x = Flood.rm_flood(c_id)
@@ -231,6 +221,7 @@ async def flood_set(c: Gojo, m: Message):
await m.reply_text("**Usage:**\n `/setflood on/off`")
return
+
@Gojo.on_callback_query(filters.regex("^f_"))
async def callbacks(c: Gojo, q: CallbackQuery):
SUPPORT_STAFF = DEV_USERS.union(SUDO_USERS).union(WHITELIST_USERS)
@@ -241,8 +232,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 +241,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 +269,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 +293,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 +314,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(
@@ -347,9 +332,10 @@ async def callbacks(c: Gojo, q: CallbackQuery):
await q.answer(
"You don't have enough permission to do this!\nStay in your limits!",
show_alert=True,
- )
+ )
return
+
@Gojo.on_callback_query(filters.regex("^un_"))
async def reverse_callbacks(c: Gojo, q: CallbackQuery):
data = q.data.split("_")
@@ -367,7 +353,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:
@@ -394,61 +380,63 @@ async def reverse_callbacks(c: Gojo, q: CallbackQuery):
await q.message.edit_text(f"{q.from_user.mention} unmuted {whoo.mention}!")
return
+
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 : [[],[]]}}
+ z = {c_id: {u_id: [[], []]}}
dic.update(z)
-
+
try:
- dic[c_id] # access and check weather the c_id present or not
+ dic[c_id] # access and check weather the c_id present or not
except KeyError:
- z = {c_id : {u_id : [[],[]]}}
- dic.update(z)
+ z = {c_id: {u_id: [[], []]}}
+ dic.update(z)
try:
- dic[c_id][u_id]
+ dic[c_id][u_id]
except KeyError:
- z = {u_id : [[],[]]}
- dic[c_id].update(z) # make the dic something like {c_id : {u_id : [[for time],[for msg]]}}
-
+ 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"]]})
-
+ 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:
+ if y - x <= within:
action = action.split("_")
if len(action) == 2:
try:
to_do = action[0]
- for_tim = int(action[1].replace("min",""))
- except:
+ for_tim = int(action[1].replace("min", ""))
+ 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 +454,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 +476,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 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 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
+ )
+ 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":
@@ -560,7 +526,7 @@ async def flood_watcher(c: Gojo, m: Message):
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
@@ -569,16 +535,17 @@ async def flood_watcher(c: Gojo, m: Message):
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
-
+
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
+ d = datetime.now() + timedelta(
+ seconds=31) # will automatically unban user after 31 seconds kind of fail safe if unban members doesn't work properly
await m.chat.ban_member(u_id, until_date=d)
success = await c.unban_chat_member(m.chat.id, u_id)
txt = f"Don't dare to spam here if I am around! Nothing can escape my 6 eyes\nAction: {'kicked' if success else 'banned for 30 seconds'}\nReason: Spaming"
@@ -656,23 +623,23 @@ async def flood_watcher(c: Gojo, m: Message):
dic[c_id][u_id][1].clear()
dic[c_id][u_id][0].clear()
return
- elif y-x > within:
- try:
- dic[c_id][u_id][1].clear()
- dic[c_id][u_id][0].clear()
- return
- except Exception:
- pass
+ elif y - x > within:
+ try:
+ dic[c_id][u_id][1].clear()
+ dic[c_id][u_id][0].clear()
+ return
+ except Exception:
+ pass
else:
return
__PLUGIN__ = "flood"
__alt_name__ = [
- "anit-flood",
- "flood",
- "spam",
- "anti-spam",
+ "anit-flood",
+ "flood",
+ "spam",
+ "anti-spam",
]
__HELP__ = """
**Anti Flood**
@@ -686,4 +653,3 @@ __HELP__ = """
**Example:**
`/setflood on`
"""
-
diff --git a/Powers/plugins/formatting.py b/Powers/plugins/formatting.py
index 2d4bcddf7003f3f8988b5ddaa7227df77c1e5eae..64fec15586061355ebd1492237fdc473433ee4f0 100644
--- a/Powers/plugins/formatting.py
+++ b/Powers/plugins/formatting.py
@@ -4,7 +4,6 @@ from pyrogram import enums, filters
from pyrogram.errors import MediaCaptionTooLong
from pyrogram.types import CallbackQuery, Message
-from Powers import LOGGER
from Powers.bot_class import Gojo
from Powers.utils.custom_filters import command
from Powers.utils.extras import StartPic
@@ -59,6 +58,7 @@ If you would like to send buttons on the same row, use the :same
fo
[button 3](buttonurl://example.com)
This will show button 1 and 2 on the same line, while 3 will be underneath."""
+
async def get_splited_formatting(msg, page=1):
msg = msg.split("\n")
l = len(msg)
@@ -71,7 +71,7 @@ async def get_splited_formatting(msg, page=1):
new_msg += f"{i}\n"
kb = [
[
- ("Next page ▶️", f"next_format_{page+1}")
+ ("Next page ▶️", f"next_format_{page + 1}")
]
]
else:
@@ -81,38 +81,39 @@ async def get_splited_formatting(msg, page=1):
new_msg += f"{i}\n"
kb = [
[
- ("◀️ Previous page", f"next_format_{page-1}")
+ ("◀️ Previous page", f"next_format_{page - 1}")
]
]
else:
for i in msg[first:last]:
new_msg += f"{i}\n"
kb = [
- [
- ("◀️ Previous page", f"next_format_{page-1}"),
- ("Next page ▶️", f"next_format_{page+1}")
- ]
+ [
+ ("◀️ Previous page", f"next_format_{page - 1}"),
+ ("Next page ▶️", f"next_format_{page + 1}")
]
-
+ ]
kb = ikb(kb, True, "back.formatting")
return new_msg, kb
+
@Gojo.on_callback_query(filters.regex(r"^next_format_.*[0-9]$"))
async def change_formatting_page(c: Gojo, q: CallbackQuery):
page = q.data.split("_")[-1]
txt, kb = await get_splited_formatting(md_txt, int(page))
- await q.edit_message_caption(txt, reply_markup=kb,parse_mode=enums.ParseMode.HTML,)
+ await q.edit_message_caption(txt, reply_markup=kb, parse_mode=enums.ParseMode.HTML, )
return
+
@Gojo.on_callback_query(filters.regex("^formatting."))
async def get_formatting_info(c: Gojo, q: CallbackQuery):
cmd = q.data.split(".")[1]
kb = ikb([[("Back", "back.formatting")]])
if cmd == "md_formatting":
-
+
try:
await q.edit_message_caption(
caption=md_txt,
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..bae32f145895b7a7514c0f414ece18bf55593fbc 100644
--- a/Powers/plugins/greetings.py
+++ b/Powers/plugins/greetings.py
@@ -26,11 +26,11 @@ gdb = GBan()
ChatType = enums.ChatType
-async def escape_mentions_using_curly_brackets_wl(
- user: User,
- m: Message,
- text: str,
- parse_words: list,
+async def escape_mentions_using_curly_brackets_wl(
+ user: User,
+ m: Message,
+ text: str,
+ parse_words: list,
) -> str:
teks = await escape_invalid_curly_brackets(text, parse_words)
if teks:
@@ -157,7 +157,7 @@ async def save_wlcm(_, m: Message):
await m.reply_text("Please provide some data for this to reply with!")
return
- db.set_welcome_text(text,msgtype,file)
+ db.set_welcome_text(text, msgtype, file)
await m.reply_text("Saved welcome!")
return
@@ -195,7 +195,7 @@ async def save_gdbye(_, m: Message):
await m.reply_text("Please provide some data for this to reply with!")
return
- db.set_goodbye_text(text,msgtype,file)
+ db.set_goodbye_text(text, msgtype, file)
await m.reply_text("Saved goodbye!")
return
@@ -206,7 +206,7 @@ async def resetgb(_, m: Message):
if m and not m.from_user:
return
text = "Sad to see you leaving {first}.\nTake Care!"
- db.set_goodbye_text(text,None)
+ db.set_goodbye_text(text, None)
await m.reply_text("Ok Done!")
return
@@ -217,7 +217,7 @@ async def resetwlcm(_, m: Message):
if m and not m.from_user:
return
text = "Hey {first}, welcome to {chatname}!"
- db.set_welcome_text(text,None)
+ db.set_welcome_text(text, None)
await m.reply_text("Done!")
return
@@ -232,6 +232,7 @@ async def cleannnnn(_, m: Message):
except Exception:
pass
+
@Gojo.on_message(filters.group & filters.new_chat_members & ~captcha_filter, group=69)
async def member_has_joined(c: Gojo, m: Message):
users: List[User] = m.new_chat_members
@@ -256,7 +257,7 @@ async def member_has_joined(c: Gojo, m: Message):
)
continue
if user.is_bot:
- continue # ignore bots
+ continue # ignore bots
except ChatAdminRequired:
continue
status = db.get_welcome_status()
@@ -273,78 +274,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 +286,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
@@ -450,14 +446,14 @@ async def welcome(c: Gojo, m: Message):
button = await build_keyboard(button)
button = ikb(button) if button else None
if not UwU:
- await c.send_message(
+ await c.send_message(
m.chat.id,
text=tek,
reply_markup=button,
disable_web_page_preview=True,
)
- elif UwU:
- await (await send_cmd(c,mtype))(
+ else:
+ await (await send_cmd(c, mtype))(
m.chat.id,
UwU,
caption=tek,
@@ -512,14 +508,14 @@ async def goodbye(c: Gojo, m: Message):
button = await build_keyboard(button)
button = ikb(button) if button else None
if not UwU:
- await c.send_message(
+ await c.send_message(
m.chat.id,
text=tek,
reply_markup=button,
disable_web_page_preview=True,
)
- elif UwU:
- await (await send_cmd(c,mtype))(
+ else:
+ await (await send_cmd(c, mtype))(
m.chat.id,
UwU,
caption=tek,
@@ -527,6 +523,7 @@ async def goodbye(c: Gojo, m: Message):
)
return
+
__PLUGIN__ = "greetings"
__alt_name__ = ["welcome", "goodbye", "cleanservice"]
diff --git a/Powers/plugins/info.py b/Powers/plugins/info.py
index c3698ef57f2653272bf61b11d1b0e5e8b567843d..00c50b9a8b9d8b2f5e6378819c35f2ef0d57d85e 100644
--- a/Powers/plugins/info.py
+++ b/Powers/plugins/info.py
@@ -22,13 +22,13 @@ async def count(c: Gojo, chat):
try:
administrator = []
async for admin in c.get_chat_members(
- chat_id=chat, filter=enums.ChatMembersFilter.ADMINISTRATORS
+ chat_id=chat, filter=enums.ChatMembersFilter.ADMINISTRATORS
):
administrator.append(admin)
total_admin = administrator
bot = []
async for tbot in c.get_chat_members(
- chat_id=chat, filter=enums.ChatMembersFilter.BOTS
+ chat_id=chat, filter=enums.ChatMembersFilter.BOTS
):
bot.append(tbot)
@@ -36,7 +36,7 @@ async def count(c: Gojo, chat):
bot_admin = 0
ban = []
async for banned in c.get_chat_members(
- chat, filter=enums.ChatMembersFilter.BANNED
+ chat, filter=enums.ChatMembersFilter.BANNED
):
ban.append(banned)
@@ -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 = 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,29 +107,29 @@ 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
status = user.status
last_date = "Unable to fetch"
if is_bot is True:
- last_date = "Targeted user is a bot"
+ last_date = "Targeted user is a bot"
if status == enums.UserStatus.RECENTLY:
- last_date = "User was seen recently"
+ last_date = "User was seen recently"
if status == enums.UserStatus.LAST_WEEK:
- last_date = "User was seen last week"
+ last_date = "User was seen last week"
if status == enums.UserStatus.LAST_MONTH:
- last_date = "User was seen last month"
+ last_date = "User was seen last month"
if status == enums.UserStatus.LONG_AGO:
- last_date = "User was seen long ago or may be I am blocked by the user :("
+ last_date = "User was seen long ago or may be I am blocked by the user :("
if status == enums.UserStatus.ONLINE:
- last_date = "User is online"
- if status == enums.UserStatus.OFFLINE:
- try:
- last_date = datetime.fromtimestamp(user.status.date).strftime("%Y-%m-%d %H:%M:%S")
- except Exception:
- last_date = "User is offline"
+ last_date = "User is online"
+ if status == enums.UserStatus.OFFLINE:
+ try:
+ last_date = datetime.fromtimestamp(user.status.date).strftime("%Y-%m-%d %H:%M:%S")
+ except Exception:
+ last_date = "User is offline"
caption = f"""
⚡️ Extracted User info From Telegram ⚡️
@@ -173,10 +173,10 @@ async def chat_info(c: Gojo, chat, already=False):
GetFullChannel(
channel=chat_r
)
- )
+ )
u_name = ll.chats[0].usernames
except Exception:
- pass
+ pass
except Exception:
try:
chat_r = await c.resolve_peer(chat)
@@ -186,7 +186,7 @@ async def chat_info(c: Gojo, chat, already=False):
GetFullChannel(
channel=chat_r
)
- )
+ )
u_name = ll.chats[0].usernames
except Exception:
pass
@@ -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:
@@ -285,9 +282,10 @@ async def info_func(c: Gojo, message: Message):
LOGGER.error(format_exc())
except Exception as e:
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")
+ 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())
@@ -303,7 +301,7 @@ async def chat_info_func(c: Gojo, message: Message):
if len(splited) == 1:
if message.reply_to_message and message.reply_to_message.sender_chat:
chat = message.reply_to_message.sender_chat.id
- else:
+ else:
chat = message.chat.id
else:
@@ -311,20 +309,19 @@ async def chat_info_func(c: Gojo, message: Message):
try:
chat = int(chat)
- except (ValueError, Exception) as ef:
- if "invalid literal for int() with base 10:" in str(ef):
- chat = str(chat)
- if chat.startswith("https://"):
- chat = '@'+chat.split("/")[-1]
- else:
+ except Exception as ef:
+ if "invalid literal for int() with base 10:" not in str(ef):
return await message.reply_text(
f"Got and exception {ef}\n**Usage:**/chinfo [USERNAME|ID]"
)
+ chat = str(chat)
+ if chat.startswith("https://"):
+ chat = '@' + chat.split("/")[-1]
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..cba1b635fddc62e0c73091cb5b11d3e026b90f52 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,20 +452,30 @@ 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):
+ 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
elif m.automatic_forward:
return True
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 +506,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..1e7ec74b327f6f108d3c1f428e97d577bc0e183f 100644
--- a/Powers/plugins/muting.py
+++ b/Powers/plugins/muting.py
@@ -40,7 +40,6 @@ async def tmute_usr(c: Gojo, m: Message):
SUPPORT_STAFF = DEV_USERS.union(SUDO_USERS).union(WHITELIST_USERS)
if user_id in SUPPORT_STAFF:
-
await m.reply_text(
text="This user is in my support staff, cannot restrict them."
)
@@ -109,8 +108,8 @@ async def tmute_usr(c: Gojo, m: Message):
reply_to_message_id=r_id,
)
except Exception:
- await m.reply_text(txt,reply_markup=keyboard, reply_to_message_id=r_id)
- await c.send_message(MESSAGE_DUMP,f"#REMOVE from MUTE_GIFS\n{mutt}")
+ await m.reply_text(txt, reply_markup=keyboard, reply_to_message_id=r_id)
+ await c.send_message(MESSAGE_DUMP, f"#REMOVE from MUTE_GIFS\n{mutt}")
except ChatAdminRequired:
await m.reply_text(text="I'm not admin or I don't have rights.")
except RightForbidden:
@@ -150,7 +149,6 @@ async def dtmute_usr(c: Gojo, m: Message):
SUPPORT_STAFF = DEV_USERS.union(SUDO_USERS).union(WHITELIST_USERS)
if user_id in SUPPORT_STAFF:
-
await m.reply_text(
text="This user is in my support staff, cannot restrict them."
)
@@ -217,8 +215,8 @@ async def dtmute_usr(c: Gojo, m: Message):
reply_markup=keyboard,
)
except Exception:
- await m.reply_text(txt,reply_markup=keyboard)
- await c.send_message(MESSAGE_DUMP,f"#REMOVE from MUTE_GIFS\n{mutt}")
+ await m.reply_text(txt, reply_markup=keyboard)
+ await c.send_message(MESSAGE_DUMP, f"#REMOVE from MUTE_GIFS\n{mutt}")
except ChatAdminRequired:
await m.reply_text(text="I'm not admin or I don't have rights.")
except RightForbidden:
@@ -346,7 +344,6 @@ async def mute_usr(c: Gojo, m: Message):
SUPPORT_STAFF = DEV_USERS.union(SUDO_USERS).union(WHITELIST_USERS)
if user_id in SUPPORT_STAFF:
-
await m.reply_text(
text="This user is in my support staff, cannot restrict them."
)
@@ -390,8 +387,8 @@ async def mute_usr(c: Gojo, m: Message):
reply_to_message_id=r_id,
)
except Exception:
- await m.reply_text(txt,reply_markup=keyboard, reply_to_message_id=r_id)
- await c.send_message(MESSAGE_DUMP,f"#REMOVE from MUTE_GIFS\n{mutt}")
+ await m.reply_text(txt, reply_markup=keyboard, reply_to_message_id=r_id)
+ await c.send_message(MESSAGE_DUMP, f"#REMOVE from MUTE_GIFS\n{mutt}")
except ChatAdminRequired:
await m.reply_text(text="I'm not admin or I don't have rights.")
except RightForbidden:
@@ -479,13 +476,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
@@ -496,7 +487,6 @@ async def dmute_usr(c: Gojo, m: Message):
await m.reply_text("Huh, why would I mute myself?")
return
-
SUPPORT_STAFF = DEV_USERS.union(SUDO_USERS).union(WHITELIST_USERS)
if user_id in SUPPORT_STAFF:
await m.reply_text(
@@ -542,8 +532,8 @@ async def dmute_usr(c: Gojo, m: Message):
reply_markup=keyboard,
)
except Exception:
- await m.reply_text(txt,reply_markup=keyboard)
- await c.send_message(MESSAGE_DUMP,f"#REMOVE from MUTE_GIFS\n{mutt}")
+ await m.reply_text(txt, reply_markup=keyboard)
+ await c.send_message(MESSAGE_DUMP, f"#REMOVE from MUTE_GIFS\n{mutt}")
except ChatAdminRequired:
await m.reply_text(text="I'm not admin or I don't have rights.")
except RightForbidden:
@@ -577,7 +567,7 @@ async def unmute_usr(c: Gojo, m: Message):
return
try:
statu = (await m.chat.get_member(user_id)).status
- if statu not in [enums.ChatMemberStatus.BANNED,enums.ChatMemberStatus.RESTRICTED]:
+ if statu not in [enums.ChatMemberStatus.BANNED, enums.ChatMemberStatus.RESTRICTED]:
await m.reply_text("User is not muted in this chat\nOr using this command as reply to his message")
return
except Exception as e:
diff --git a/Powers/plugins/notes.py b/Powers/plugins/notes.py
index a62cc3896a73a752adb37dd212de61f8364e0d52..af422fb55ccd7c712763b2e362b6d39302f04594 100644
--- a/Powers/plugins/notes.py
+++ b/Powers/plugins/notes.py
@@ -73,7 +73,6 @@ async def get_note_func(c: Gojo, m: Message, note_name, priv_notes_status):
return
if priv_notes_status:
-
note_hash = next(i[1] for i in db.get_all_notes(m.chat.id) if i[0] == note_name)
await reply_text(
f"Click on the button to get the note {note_name}
",
@@ -150,10 +149,10 @@ async def get_note_func(c: Gojo, m: Message, note_name, priv_notes_status):
)
return
elif msgtype in (
- Types.STICKER,
- Types.VIDEO_NOTE,
- Types.CONTACT,
- Types.ANIMATED_STICKER,
+ Types.STICKER,
+ Types.VIDEO_NOTE,
+ Types.CONTACT,
+ Types.ANIMATED_STICKER,
):
await (await send_cmd(c, msgtype))(
m.chat.id,
@@ -192,7 +191,7 @@ async def get_note_func(c: Gojo, m: Message, note_name, priv_notes_status):
reply_markup=button,
reply_to_message_id=reply_msg_id,
)
-
+
except Exception as e:
await m.reply_text(f"Error in notes: {e}")
return
@@ -222,10 +221,10 @@ async def get_raw_note(c: Gojo, m: Message, note: str):
teks, parse_mode=enums.ParseMode.DISABLED, reply_to_message_id=msg_id
)
elif msgtype in (
- Types.STICKER,
- Types.VIDEO_NOTE,
- Types.CONTACT,
- Types.ANIMATED_STICKER,
+ Types.STICKER,
+ Types.VIDEO_NOTE,
+ Types.CONTACT,
+ Types.ANIMATED_STICKER,
):
await (await send_cmd(c, msgtype))(
m.chat.id,
@@ -241,7 +240,7 @@ async def get_raw_note(c: Gojo, m: Message, note: str):
parse_mode=enums.ParseMode.DISABLED,
reply_to_message_id=msg_id,
)
-
+
return
@@ -267,7 +266,6 @@ async def hash_get(c: Gojo, m: Message):
@Gojo.on_message(command("get") & filters.group & ~filters.bot)
async def get_note(c: Gojo, m: Message):
-
if len(m.text.split()) == 2:
priv_notes_status = db_settings.get_privatenotes(m.chat.id)
note = ((m.text.split())[1]).lower()
@@ -290,7 +288,6 @@ async def get_note(c: Gojo, m: Message):
@Gojo.on_message(command(["privnotes", "privatenotes"]) & admin_filter & ~filters.bot)
async def priv_notes(_, m: Message):
-
chat_id = m.chat.id
if len(m.text.split()) == 2:
option = (m.text.split())[1]
@@ -323,9 +320,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(
[
[
@@ -355,7 +350,6 @@ async def local_notes(c: Gojo, m: Message):
@Gojo.on_message(command("clear") & admin_filter & ~filters.bot)
async def clear_note(_, m: Message):
-
if len(m.text.split()) <= 1:
await m.reply_text("What do you want to clear?")
return
@@ -372,7 +366,6 @@ async def clear_note(_, m: Message):
@Gojo.on_message(command("clearall") & owner_filter & ~filters.bot)
async def clear_allnote(_, m: Message):
-
all_notes = {i[0] for i in db.get_all_notes(m.chat.id)}
if not all_notes:
await m.reply_text("No notes are there in this chat")
diff --git a/Powers/plugins/pin.py b/Powers/plugins/pin.py
index 58ac70a04e734ee300717684705ad762499f807b..5fe1aad25996607efdd66e6109b3481260862919 100644
--- a/Powers/plugins/pin.py
+++ b/Powers/plugins/pin.py
@@ -5,7 +5,7 @@ from pyrogram.errors import ChatAdminRequired, RightForbidden, RPCError
from pyrogram.filters import regex
from pyrogram.types import CallbackQuery, Message
-from Powers import LOGGER, SUPPORT_GROUP
+from Powers import LOGGER
from Powers.bot_class import Gojo
from Powers.database.pins_db import Pins
from Powers.utils.custom_filters import admin_filter, command
@@ -18,15 +18,14 @@ 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
@@ -69,11 +68,11 @@ async def unpin_message(c: Gojo, m: Message):
try:
if m.reply_to_message:
await m.reply_to_message.unpin()
-
+
await m.reply_text(text="Unpinned last message.")
else:
m_id = (await c.get_chat(m.chat.id)).pinned_message.id
- await c.unpin_chat_message(m.chat.id,m_id)
+ await c.unpin_chat_message(m.chat.id, m_id)
await m.reply_text(text="Unpinned last pinned message!")
except ChatAdminRequired:
await m.reply_text(text="I'm not admin or I don't have rights.")
@@ -162,8 +161,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 +170,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/purge.py b/Powers/plugins/purge.py
index bd4864b6fc04bf3294eefe80772f195c4bf07e8d..4b0020d006411ab0053bc034c5cde05c85875adf 100644
--- a/Powers/plugins/purge.py
+++ b/Powers/plugins/purge.py
@@ -4,14 +4,12 @@ from pyrogram.enums import ChatType
from pyrogram.errors import MessageDeleteForbidden, RPCError
from pyrogram.types import Message
-from Powers import SUPPORT_GROUP
from Powers.bot_class import Gojo
from Powers.utils.custom_filters import admin_filter, command
@Gojo.on_message(command("purge") & admin_filter)
async def purge(c: Gojo, m: Message):
-
if m.chat.type != ChatType.SUPERGROUP:
await m.reply_text(text="Cannot purge messages in a basic group")
return
@@ -21,7 +19,7 @@ async def purge(c: Gojo, m: Message):
def divide_chunks(l: list, n: int = 100):
for i in range(0, len(l), n):
- yield l[i : i + n]
+ yield l[i: i + n]
# Dielete messages in chunks of 100 messages
m_list = list(divide_chunks(message_ids))
@@ -58,7 +56,6 @@ async def purge(c: Gojo, m: Message):
@Gojo.on_message(command("spurge") & admin_filter)
async def spurge(c: Gojo, m: Message):
-
if m.chat.type != ChatType.SUPERGROUP:
await m.reply_text(text="Cannot purge messages in a basic group")
return
@@ -68,7 +65,7 @@ async def spurge(c: Gojo, m: Message):
def divide_chunks(l: list, n: int = 100):
for i in range(0, len(l), n):
- yield l[i : i + n]
+ yield l[i: i + n]
# Dielete messages in chunks of 100 messages
m_list = list(divide_chunks(message_ids))
@@ -101,7 +98,6 @@ async def spurge(c: Gojo, m: Message):
command("del") & admin_filter,
)
async def del_msg(c: Gojo, m: Message):
-
if m.chat.type != ChatType.SUPERGROUP:
return
diff --git a/Powers/plugins/report.py b/Powers/plugins/report.py
index dacb246a95bb1c60d8097f63a41398560c866582..989dd412bb8a43cb6894de229260fb3f293ab6c1 100644
--- a/Powers/plugins/report.py
+++ b/Powers/plugins/report.py
@@ -58,7 +58,6 @@ async def report_setting(_, m: Message):
@Gojo.on_message(command("report") & filters.group)
async def report_watcher(c: Gojo, m: Message):
-
if m.chat.type not in [ChatType.SUPERGROUP, ChatType.GROUP]:
return
@@ -76,7 +75,7 @@ async def report_watcher(c: Gojo, m: Message):
if reported_user.id == me.id:
await m.reply_text("Nice try.")
return
-
+
SUPPORT_STAFF = DEV_USERS.union(SUDO_USERS).union(WHITELIST_USERS)
if reported_user.id in SUPPORT_STAFF:
await m.reply_text("Uh? You reporting my support team?")
@@ -118,7 +117,6 @@ async def report_watcher(c: Gojo, m: Message):
],
)
-
await m.reply_text(
(
f"{(await mention_html(m.from_user.first_name, m.from_user.id))} "
@@ -129,7 +127,7 @@ async def report_watcher(c: Gojo, m: Message):
async for admin in c.get_chat_members(m.chat.id, filter=cmf.ADMINISTRATORS):
if (
- admin.user.is_bot or admin.user.is_deleted
+ admin.user.is_bot or admin.user.is_deleted
): # can't message bots or deleted accounts
continue
if Reporting(admin.user.id).get_settings():
diff --git a/Powers/plugins/rules.py b/Powers/plugins/rules.py
index a2a22ef94dc861e7d589a364d816d20303d0734f..016feab31be410bf8a0a98d612aa5a8cc2150b86 100644
--- a/Powers/plugins/rules.py
+++ b/Powers/plugins/rules.py
@@ -1,7 +1,6 @@
from pyrogram import filters
from pyrogram.types import CallbackQuery, Message
-from Powers import LOGGER
from Powers.bot_class import Gojo
from Powers.database.rules_db import Rules
from Powers.utils.custom_filters import admin_filter, command
@@ -25,9 +24,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 +73,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..fc2da31f317467a1f39a47a8ac5b063eaf73cf3b 100644
--- a/Powers/plugins/scheduled_jobs.py
+++ b/Powers/plugins/scheduled_jobs.py
@@ -16,13 +16,15 @@ from pyrogram.enums import ChatMemberStatus
from Powers.utils.extras import birthday_wish
-def give_date(date,form = "%d/%m/%Y"):
- datee = datetime.strptime(date,form).date()
- return datee
+def give_date(date, form="%d/%m/%Y"):
+ return datetime.strptime(date, form).date()
+
scheduler = AsyncIOScheduler()
scheduler.timezone = TIME_ZONE
-scheduler_time = time(0,0,0)
+scheduler_time = time(0, 0, 0)
+
+
async def send_wishish(JJK: Client):
c_list = Chats.list_chats_by_id()
blist = list(bday_info.find())
@@ -38,16 +40,16 @@ 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:
+ if int(agee / 10) == 1:
suf = "th"
else:
- suffix.get((agee%10), "th")
+ 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"])
+ U = await JJK.get_chat_member(chat_id=j, user_id=i["user_id"])
wish = choice(birthday_wish)
- if U.status in [ChatMemberStatus.MEMBER,ChatMemberStatus.ADMINISTRATOR, ChatMemberStatus.OWNER]:
- xXx = await JJK.send_message(j,f"Happy {agee} birthday {U.user.mention}🥳\n{wish}")
+ if U.status in [ChatMemberStatus.MEMBER, ChatMemberStatus.ADMINISTRATOR, ChatMemberStatus.OWNER]:
+ xXx = await JJK.send_message(j, f"Happy {agee} birthday {U.user.mention}🥳\n{wish}")
try:
await xXx.pin()
except Exception:
@@ -55,6 +57,7 @@ async def send_wishish(JJK: Client):
except Exception:
pass
+
""""
from datetime import date, datetime
@@ -72,4 +75,3 @@ else:
print(days_left)
print(x.year - timm.year)
"""
-
diff --git a/Powers/plugins/search.py b/Powers/plugins/search.py
index 1e0ee22697f97adc16a12afc1bb6a908d848c537..98428fd995b56d0fb63a2d91b0db59ed85b52aee 100644
--- a/Powers/plugins/search.py
+++ b/Powers/plugins/search.py
@@ -14,12 +14,13 @@ from Powers.utils.custom_filters import command
from Powers.utils.http_helper import *
from Powers.utils.kbhelpers import ikb
-#have to add youtube
+# have to add youtube
gsearch = GoogleSearch()
anisearch = AnimeSearch()
stsearch = StackSearch()
+
@Gojo.on_message(command('google'))
async def g_search(c: Gojo, m: Message):
split = m.text.split(None, 1)
@@ -157,6 +158,7 @@ async def anime_search(c: Gojo, m: Message):
LOGGER.error(format_exc())
return
+
@Gojo.on_message(command('stack'))
async def stack_search(c: Gojo, m: Message):
split = m.text.split(None, 1)
@@ -233,17 +235,15 @@ 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"]))
+
+@Gojo.on_message(command(["images", "imgs"]))
async def get_image_search(_, m: Message):
# Credits: https://t.me/NovaXMod
# https://t.me/NovaXMod/98
@@ -258,17 +258,15 @@ 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()
except Exception:
await ab.edit("Error occurred while sending images. Please try again.")
-__PLUGIN__ = "search"
+__PLUGIN__ = "search"
__alt_name__ = [
"google",
diff --git a/Powers/plugins/start.py b/Powers/plugins/start.py
index 95e3ad5c6665973a649a57e25c60a0f36790f5e7..1f26dc16957ec0cf50b1f40aebd8fb076aca0e73 100644
--- a/Powers/plugins/start.py
+++ b/Powers/plugins/start.py
@@ -1,4 +1,3 @@
-import os
from random import choice
from time import gmtime, strftime, time
@@ -67,14 +66,13 @@ async def close_admin_callback(_, q: CallbackQuery):
command("start") & (filters.group | filters.private),
)
async def start(c: Gojo, m: Message):
-
if m.chat.type == ChatType.PRIVATE:
if len(m.text.strip().split()) > 1:
arg = m.text.split(None, 1)[1]
help_option = arg.lower()
if help_option.startswith("note") and (
- help_option not in ("note", "notes")
+ help_option not in ("note", "notes")
):
await get_private_note(c, m, help_option)
return
@@ -127,13 +125,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:
@@ -229,7 +227,7 @@ You can use {", ".join(PREFIX_HANDLER)} as your prefix handler
@Gojo.on_message(command("help"))
async def help_menu(c: Gojo, m: Message):
if len(m.text.split()) >= 2:
- textt = m.text.replace(" ", "_",).replace("_", " ", 1)
+ textt = m.text.replace(" ", "_", ).replace("_", " ", 1)
help_option = (textt.split(None)[1]).lower()
help_msg, help_kb = await get_help_msg(c, m, help_option)
@@ -299,7 +297,7 @@ Commands available:
return
-async def get_divided_msg(plugin_name: str, page:int=1, back_to_do = None):
+async def get_divided_msg(plugin_name: str, page: int = 1, back_to_do=None):
msg = HELP_COMMANDS[plugin_name]["help_msg"]
msg = msg.split("\n")
l = len(msg)
@@ -313,7 +311,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,32 +324,38 @@ 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]$"))
async def helppp_page_iter(c: Gojo, q: CallbackQuery):
data = q.data.split("_")
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 +427,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:
@@ -442,7 +449,8 @@ async def give_bot_staffs(c: Gojo, q: CallbackQuery):
except RPCError:
pass
- await q.edit_message_caption(reply, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("« Back", "start_back")]]))
+ await q.edit_message_caption(reply,
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("« Back", "start_back")]]))
return
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..c08c1652cc8fd4b3cccb3444cbaac70a7676afc4 100644
--- a/Powers/plugins/stickers.py
+++ b/Powers/plugins/stickers.py
@@ -1,4 +1,3 @@
-import os
from random import choice
from traceback import format_exc
@@ -13,19 +12,15 @@ from pyrogram.types import InlineKeyboardMarkup as IKM
from pyrogram.types import Message
from Powers import LOGGER
-from Powers.bot_class import Gojo
from Powers.utils.custom_filters import command
from Powers.utils.sticker_help import *
from Powers.utils.string import encode_decode
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:
+@Gojo.on_message(command(["stickerinfo", "stinfo"]))
+async def give_st_info(c: Gojo, m: Message):
+ 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
@@ -44,15 +39,13 @@ Emoji : {st_in.emoji}
Pack name : {st_in.set_name}
"""
kb = IKM([[IKB("➕ Add sticker to pack", url=f"https://t.me/addstickers/{st_in.set_name}")]])
- await m.reply_text(st_to_gib,reply_markup=kb)
+ await m.reply_text(st_to_gib, reply_markup=kb)
return
-@Gojo.on_message(command(["stickerid","stid"]))
+
+@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
@@ -61,18 +54,22 @@ async def sticker_id_gib(c: Gojo, m: Message):
@Gojo.on_message(command(["kang", "steal"]))
-async def kang(c:Gojo, m: Message):
+async def kang(c: Gojo, m: Message):
if not m.reply_to_message:
return await m.reply_text("Reply to a sticker or image to kang it.")
- elif not (m.reply_to_message.animation or m.reply_to_message.sticker or m.reply_to_message.photo or (m.reply_to_message.document and m.reply_to_message.document.mime_type.split("/")[0]in["image","video"])):
+ elif not (m.reply_to_message.animation or m.reply_to_message.sticker or m.reply_to_message.photo or (
+ m.reply_to_message.document and m.reply_to_message.document.mime_type.split("/")[0] in ["image", "video"])):
return await m.reply_text("Reply to a sticker or image to kang it.")
if not m.from_user:
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
+ is_requ = bool(
+ m.reply_to_message.sticker
+ and (
+ m.reply_to_message.sticker.is_animated
+ or m.reply_to_message.sticker.is_video
+ )
+ )
# Find the proper emoji
args = m.text.split()
if len(args) > 1:
@@ -81,23 +78,38 @@ async def kang(c:Gojo, m: Message):
try:
sticker_emoji = m.reply_to_message.sticker.emoji
if not sticker_emoji:
- ran = ["🤣", "😑", "😁", "👍", "🔥", "🙈", "🙏", "😍", "😘", "😱", "☺️", "🙃", "😌", "🤧", "😐", "😬", "🤩", "😀", "🙂", "🥹", "🥺", "🫥", "🙄", "🫡", "🫠", "🤫", "😓", "🥵", "🥶", "😤", "😡", "🤬", "🤯", "🥴", "🤢", "🤮", "💀", "🗿", "💩", "🤡", "🫶", "🙌", "👐", "✊", "👎", "🫰", "🤌", "👌", "👀", "💃", "🕺", "👩❤️💋👩", "👩❤️💋👨","👨❤️👨", "💑", "👩❤️👩", "👩❤️👨", "💏", "👨❤️💋👨", "😪", "😴", "😭", "🥸", "🤓", "🫤", "😮", "😧", "😲", "🥱", "😈", "👿", "🤖", "👾", "🙌", "🥴", "🥰", "😇", "🤣" ,"😂", "😜", "😎"]
+ ran = ["🤣", "😑", "😁", "👍", "🔥", "🙈", "🙏", "😍", "😘", "😱", "☺️", "🙃", "😌", "🤧", "😐", "😬", "🤩", "😀", "🙂",
+ "🥹", "🥺", "🫥", "🙄", "🫡", "🫠", "🤫", "😓", "🥵", "🥶", "😤", "😡", "🤬", "🤯", "🥴", "🤢", "🤮", "💀", "🗿",
+ "💩", "🤡", "🫶", "🙌", "👐", "✊", "👎", "🫰", "🤌", "👌", "👀", "💃", "🕺", "👩❤️💋👩", "👩❤️💋👨",
+ "👨❤️👨", "💑", "👩❤️👩", "👩❤️👨", "💏", "👨❤️💋👨", "😪", "😴", "😭", "🥸", "🤓", "🫤", "😮", "😧", "😲",
+ "🥱", "😈", "👿", "🤖", "👾", "🙌", "🥴", "🥰", "😇", "🤣", "😂", "😜", "😎"]
sticker_emoji = choice(ran)
except Exception:
- ran = ["🤣", "😑", "😁", "👍", "🔥", "🙈", "🙏", "😍", "😘", "😱", "☺️", "🙃", "😌", "🤧", "😐", "😬", "🤩", "😀", "🙂", "🥹", "🥺", "🫥", "🙄", "🫡", "🫠", "🤫", "😓", "🥵", "🥶", "😤", "😡", "🤬", "🤯", "🥴", "🤢", "🤮", "💀", "🗿", "💩", "🤡", "🫶", "🙌", "👐", "✊", "👎", "🫰", "🤌", "👌", "👀", "💃", "🕺", "👩❤️💋👩", "👩❤️💋👨","👨❤️👨", "💑", "👩❤️👩", "👩❤️👨", "💏", "👨❤️💋👨", "😪", "😴", "😭", "🥸", "🤓", "🫤", "😮", "😧", "😲", "🥱", "😈", "👿", "🤖", "👾", "🙌", "🥴", "🥰", "😇", "🤣" ,"😂", "😜", "😎"]
+ ran = ["🤣", "😑", "😁", "👍", "🔥", "🙈", "🙏", "😍", "😘", "😱", "☺️", "🙃", "😌", "🤧", "😐", "😬", "🤩", "😀", "🙂", "🥹",
+ "🥺", "🫥", "🙄", "🫡", "🫠", "🤫", "😓", "🥵", "🥶", "😤", "😡", "🤬", "🤯", "🥴", "🤢", "🤮", "💀", "🗿", "💩", "🤡",
+ "🫶", "🙌", "👐", "✊", "👎", "🫰", "🤌", "👌", "👀", "💃", "🕺", "👩❤️💋👩", "👩❤️💋👨", "👨❤️👨", "💑",
+ "👩❤️👩", "👩❤️👨", "💏", "👨❤️💋👨", "😪", "😴", "😭", "🥸", "🤓", "🫤", "😮", "😧", "😲", "🥱", "😈", "👿", "🤖",
+ "👾", "🙌", "🥴", "🥰", "😇", "🤣", "😂", "😜", "😎"]
sticker_emoji = choice(ran)
else:
edit = await msg.reply_text("No emoji provided choosing a random emoji")
- ran = ["🤣", "😑", "😁", "👍", "🔥", "🙈", "🙏", "😍", "😘", "😱", "☺️", "🙃", "😌", "🤧", "😐", "😬", "🤩", "😀", "🙂", "🥹", "🥺", "🫥", "🙄", "🫡", "🫠", "🤫", "😓", "🥵", "🥶", "😤", "😡", "🤬", "🤯", "🥴", "🤢", "🤮", "💀", "🗿", "💩", "🤡", "🫶", "🙌", "👐", "✊", "👎", "🫰", "🤌", "👌", "👀", "💃", "🕺", "👩❤️💋👩", "👩❤️💋👨","👨❤️👨", "💑", "👩❤️👩", "👩❤️👨", "💏", "👨❤️💋👨", "😪", "😴", "😭", "🥸", "🤓", "🫤", "😮", "😧", "😲", "🥱", "😈", "👿", "🤖", "👾", "🙌", "🥴", "🥰", "😇", "🤣" ,"😂", "😜", "😎"]
+ ran = ["🤣", "😑", "😁", "👍", "🔥", "🙈", "🙏", "😍", "😘", "😱", "☺️", "🙃", "😌", "🤧", "😐", "😬", "🤩", "😀", "🙂", "🥹", "🥺",
+ "🫥", "🙄", "🫡", "🫠", "🤫", "😓", "🥵", "🥶", "😤", "😡", "🤬", "🤯", "🥴", "🤢", "🤮", "💀", "🗿", "💩", "🤡", "🫶", "🙌",
+ "👐", "✊", "👎", "🫰", "🤌", "👌", "👀", "💃", "🕺", "👩❤️💋👩", "👩❤️💋👨", "👨❤️👨", "💑", "👩❤️👩", "👩❤️👨",
+ "💏", "👨❤️💋👨", "😪", "😴", "😭", "🥸", "🤓", "🫤", "😮", "😧", "😲", "🥱", "😈", "👿", "🤖", "👾", "🙌", "🥴", "🥰",
+ "😇", "🤣", "😂", "😜", "😎"]
sticker_emoji = choice(ran)
await edit.delete()
await msg.edit_text(f"Makeing a sticker with {sticker_emoji} emoji")
# Get the corresponding fileid, resize the file if necessary
try:
- if is_requ or m.reply_to_message.animation or m.reply_to_message.video or m.reply_to_message.photo or (m.reply_to_message.document and m.reply_to_message.document.mime_type.split("/")[0] in ["video","image"]):
+ if is_requ or m.reply_to_message.animation or m.reply_to_message.video or m.reply_to_message.photo or (
+ m.reply_to_message.document and m.reply_to_message.document.mime_type.split("/")[0] in ["video",
+ "image"]):
# telegram doesn't allow animated and video sticker to be kanged as we do for normal stickers
- if m.reply_to_message.animation or m.reply_to_message.video or (m.reply_to_message.document and m.reply_to_message.document.mime_type.split("/")[0] == "video"):
+ if m.reply_to_message.animation or m.reply_to_message.video or (
+ m.reply_to_message.document and m.reply_to_message.document.mime_type.split("/")[0] == "video"):
path = await Vsticker(c, m.reply_to_message)
SIZE = os.path.getsize(path)
if SIZE > 261120:
@@ -105,7 +117,7 @@ async def kang(c:Gojo, m: Message):
os.remove(path)
return
elif is_requ:
- path = await m.reply_to_message.download()
+ path = await m.reply_to_message.download()
else:
sizee = (await get_file_size(m.reply_to_message)).split()
if (sizee[1] == "mb" and int(sizee[0]) > 10) or sizee[1] == "gb":
@@ -120,7 +132,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 +140,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,11 +163,12 @@ 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}"
- 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")
+ 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
- sticker_set = await get_sticker_set_by_name(c,packname)
+ sticker_set = await get_sticker_set_by_name(c, packname)
if not sticker_set:
try:
sticker_set = await create_sticker_set(
@@ -173,14 +186,14 @@ async def kang(c:Gojo, m: Message):
volume += 1
continue
try:
- await add_sticker_to_set(c,sticker_set,sticker)
+ await add_sticker_to_set(c, sticker_set, sticker)
packname_found = True
except StickerEmojiInvalid:
return await msg.edit("[ERROR]: INVALID_EMOJI_IN_ARGUMENT")
kb = IKM(
[
[
- IKB("➕ Add Pack ➕",url=f"t.me/addstickers/{packname}")
+ IKB("➕ Add Pack ➕", url=f"t.me/addstickers/{packname}")
]
]
)
@@ -219,34 +232,36 @@ async def kang(c:Gojo, m: Message):
LOGGER.error(format_exc())
return
+
@Gojo.on_message(command(["rmsticker", "removesticker"]))
async def remove_sticker_from_pack(c: Gojo, m: Message):
if not m.reply_to_message or not m.reply_to_message.sticker:
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}")
+ await to_modify.edit_text(
+ f"Successfully removed [sticker]({m.reply_to_message.link}) from {sticker_set.set.title}")
except Exception as e:
await to_modify.delete()
await m.reply_text(f"Failed to remove sticker due to:\n{e}\nPlease report this bug using `/bug`")
LOGGER.error(e)
LOGGER.error(format_exc())
return
-
-@Gojo.on_message(command(["mmfb","mmfw","mmf"]))
+
+@Gojo.on_message(command(["mmfb", "mmfw", "mmf"]))
async def memify_it(c: Gojo, m: Message):
if not m.reply_to_message:
await m.reply_text("Invalid type.")
@@ -261,7 +276,7 @@ async def memify_it(c: Gojo, m: Message):
kb = IKM(
[
[
- IKB("Join for memes",url="https://t.me/memesofdank")
+ IKB("Join for memes", url="https://t.me/memesofdank")
]
]
)
@@ -269,21 +284,16 @@ 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()
+ 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
- output = await draw_meme(path,meme,is_sticker,fiil)
+ 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)
- await xNx.reply_sticker(output[1],reply_markup=kb)
+ xNx = await m.reply_photo(output[0], reply_markup=kb)
+ await xNx.reply_sticker(output[1], reply_markup=kb)
try:
os.remove(output[0])
os.remove(output[1])
@@ -292,63 +302,72 @@ async def memify_it(c: Gojo, m: Message):
LOGGER.error(format_exc())
return
-@Gojo.on_message(command(["getsticker","getst"]))
+
+@Gojo.on_message(command(["getsticker", "getst"]))
async def get_sticker_from_file(c: Gojo, m: Message):
Caption = f"Converted by:\n@{c.me.username}"
repl = m.reply_to_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:
upp = await repl.download()
- up = tgs_to_gif(upp,True)
+ up = tgs_to_gif(upp, True)
await x.delete()
- await m.reply_animation(up,caption=Caption)
- os.remove(up)
- return
+ await m.reply_animation(up, caption=Caption)
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
+ await m.reply_animation(up, caption=Caption)
else:
upp = await repl.download()
- up = toimage(upp,is_direc=True)
+ 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)
+ up = tosticker(upp, is_direc=True)
await x.delete()
await m.reply_sticker(up)
os.remove(up)
return
-
+
elif to_vid:
- up = await Vsticker(c,repl)
+ up = await Vsticker(c, repl)
await x.delete()
await m.reply_sticker(up)
os.remove(up)
return
+
@Gojo.on_message(command(["rmsticker", "rmst", "removesticker"]))
async def remove_from_MY_pack(c: Gojo, m: Message):
if not m.reply_to_message or not m.reply_to_message.sticker:
await m.reply_text("Please reply to a sticker to remove it from your pack")
return
-
+
sticker = m.reply_to_message.sticker
sticker_set = await get_sticker_set_by_name(c, sticker.set_name)
@@ -366,10 +385,11 @@ async def remove_from_MY_pack(c: Gojo, m: Message):
LOGGER.error(format_exc(e))
return
+
@Gojo.on_message(command(["getmypacks", "mypacks", "mysets", "stickerset", "stset"]))
async def get_my_sticker_sets(c: Gojo, m: Message):
to_del = await m.reply_text("Please wait while I fetch all the sticker set I have created for you.")
-
+
txt, kb = await get_all_sticker_packs(c, m.from_user.id)
await to_del.delete()
@@ -378,6 +398,7 @@ async def get_my_sticker_sets(c: Gojo, m: Message):
return
await m.reply_text(txt, reply_markup=kb)
+
@Gojo.on_message(command(["q", "ss"]))
async def quote_the_msg(_, m: Message):
if not m.reply_to_message:
@@ -386,12 +407,9 @@ async def quote_the_msg(_, m: Message):
to_edit = await m.reply_text("Genrating quote...")
- 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...")
@@ -415,7 +433,7 @@ async def quote_the_msg(_, m: Message):
if m.reply_to_message.from_user.emoji_status:
emoji_status = str(m.reply_to_message.from_user.emoji_status.custom_emoji_id)
- msg_data.append(
+ msg_data = [
{
"entities": get_msg_entities(m.reply_to_message),
"avatar": True,
@@ -427,8 +445,7 @@ async def quote_the_msg(_, m: Message):
"text": m.reply_to_message.text,
"replyMessage": reply_message,
}
- )
-
+ ]
status, path = quotify(msg_data)
if not status:
@@ -439,26 +456,27 @@ async def quote_the_msg(_, m: Message):
await to_edit.delete()
os.remove(path)
+
@Gojo.on_callback_query(filters.regex(r"^stickers_.*"))
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__ = [
"sticker",
diff --git a/Powers/plugins/utils.py b/Powers/plugins/utils.py
index fb33c9b03ca1a48bf411da189f9f61dcaaa3a348..9b9f7abb8fb639abc87297243c6d4a9136b91d11 100644
--- a/Powers/plugins/utils.py
+++ b/Powers/plugins/utils.py
@@ -23,7 +23,6 @@ from Powers.utils.parser import mention_html
@Gojo.on_message(command("wiki"))
async def wiki(_, m: Message):
-
if len(m.text.split()) <= 1:
return await m.reply_text(
text="Please check help on how to use this this command."
@@ -81,6 +80,7 @@ async def gdpr_remove(_, m: Message):
)
await m.stop_propagation()
+
@Gojo.on_message(
command("lyrics") & (filters.group | filters.private),
)
@@ -102,22 +102,19 @@ async def get_lyrics(_, m: Message):
em = await m.reply_text(text=f"Finding lyrics for {song_name}...")
try:
if artist:
- song = genius_lyrics.search_song(query,artist)
+ song = genius_lyrics.search_song(query, artist)
else:
song = genius_lyrics.search_song(query)
except Exception as e:
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
+ reply = reply.split("\n", 1)[1]
+ artist = artist or song.artist
else:
reply = "Couldn't find any lyrics for that song!"
else:
@@ -136,12 +133,10 @@ async def get_lyrics(_, m: Message):
return
-
@Gojo.on_message(
command("id") & (filters.group | filters.private),
)
async def id_info(c: Gojo, m: Message):
-
ChatType = enums.ChatType
user_id, _, _ = await extract_user(c, m)
try:
@@ -150,7 +145,8 @@ async def id_info(c: Gojo, m: Message):
await m.reply_text(txt, parse_mode=enums.ParseMode.HTML)
return
elif m.chat.type in [ChatType.SUPERGROUP, ChatType.GROUP] and not m.reply_to_message:
- await m.reply_text(text=f"This Group's ID is {m.chat.id}
\nYour ID {m.from_user.id}
")
+ await m.reply_text(
+ text=f"This Group's ID is {m.chat.id}
\nYour ID {m.from_user.id}
")
return
elif m.chat.type == ChatType.PRIVATE and not m.reply_to_message:
@@ -187,15 +183,15 @@ Forwarder - {fwd_sender} ({fwd_id}
)""",
parse_mode=enums.ParseMode.HTML,
)
elif m.chat.type == ChatType.PRIVATE:
- text=f"Your ID is {m.chat.id}
."
+ text = f"Your ID is {m.chat.id}
."
if m.reply_to_message:
if m.forward_from:
- text+=f"Forwarded from user ID {m.forward_from.id}
."
+ text += f"Forwarded from user ID {m.forward_from.id}
."
elif m.forward_from_chat:
- text+=f"Forwarded from user ID {m.forward_from_chat.id}
."
+ text += f"Forwarded from user ID {m.forward_from_chat.id}
."
await m.reply_text(text)
else:
- text=f"Chat ID {m.chat.id}
\nYour ID {m.from_user.id}
"
+ text = f"Chat ID {m.chat.id}
\nYour ID {m.from_user.id}
"
await m.reply_text(text)
return
@@ -221,9 +217,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}"
@@ -234,12 +228,13 @@ async def github(_, m: Message):
except Exception as e:
return await m.reply_text(f"ERROR:\n`{e}`")
if r.status_code != 200:
- await m.reply_text(f"{username} this user is not available on github\nMake sure you have given correct username")
+ await m.reply_text(
+ f"{username} this user is not available on github\nMake sure you have given correct username")
return
r = r.json()
avtar = r.get("avatar_url", None)
if avtar:
- avtar = avtar.rsplit("=",1)
+ avtar = avtar.rsplit("=", 1)
avtar.pop(-1)
avtar.append("5")
avtar = "=".join(avtar)
@@ -250,10 +245,10 @@ async def github(_, m: Message):
following = r.get("following", 0)
public_repos = r.get("public_repos", 0)
bio = r.get("bio", None)
- created_at = r.get("created_at", "NA").replace("T", " ").replace("Z","")
+ created_at = r.get("created_at", "NA").replace("T", " ").replace("Z", "")
location = r.get("location", None)
email = r.get("email", None)
- updated_at = r.get("updated_at", "NA").replace("T", " ").replace("Z","")
+ updated_at = r.get("updated_at", "NA").replace("T", " ").replace("Z", "")
blog = r.get("blog", None)
twitter = r.get("twitter_username", None)
@@ -304,6 +299,7 @@ headers = {
"content-type": "application/json",
}
+
def paste(content: str):
data = {"content": content}
resp = resp_post(f"{BASE}api/v1/pastes", data=json.dumps(data), headers=headers)
@@ -336,7 +332,7 @@ async def paste_func(_, message: Message):
return await m.edit("Only text files can be pasted.")
doc = await message.reply_to_message.download()
- exe = doc.rsplit(".",1)[-1]
+ exe = doc.rsplit(".", 1)[-1]
async with aiofiles.open(doc, mode="r") as f:
fdata = await f.read()
content = fdata
@@ -350,13 +346,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}")
@@ -364,7 +360,7 @@ async def paste_func(_, message: Message):
async def tr(_, message):
trl = Translator()
if message.reply_to_message and (
- message.reply_to_message.text or message.reply_to_message.caption
+ message.reply_to_message.text or message.reply_to_message.caption
):
if len(message.text.split()) == 1:
target_lang = "en"
@@ -392,6 +388,7 @@ async def tr(_, message):
f"Translated: from {detectlang} to {target_lang} \n``{tekstr.text}``
",
)
+
@Gojo.on_message(command("bug"))
async def reporting_query(c: Gojo, m: Message):
repl = m.reply_to_message
@@ -404,17 +401,18 @@ async def reporting_query(c: Gojo, m: Message):
txt = "#BUG\n"
txt += repl.text.html
txt += f"\nReported by: {m.from_user.id} ({m.from_user.mention})"
- kb = InlineKeyboardMarkup([[InlineKeyboardButton("Update channel",url=f"https://t.me/{SUPPORT_GROUP}")],[InlineKeyboardButton("Report on github",url="https://github.com/Gojo-Bots/Gojo_Satoru/issues/new/choose")]])
+ kb = InlineKeyboardMarkup([[InlineKeyboardButton("Update channel", url=f"https://t.me/{SUPPORT_GROUP}")], [
+ InlineKeyboardButton("Report on github", url="https://github.com/Gojo-Bots/Gojo_Satoru/issues/new/choose")]])
try:
- z = await c.send_message(MESSAGE_DUMP,txt,parse_mode=enums.ParseMode.HTML)
+ z = await c.send_message(MESSAGE_DUMP, txt, parse_mode=enums.ParseMode.HTML)
except Exception:
txt = repl.text.html
- z = await c.send_message(MESSAGE_DUMP,txt,parse_mode=enums.ParseMode.HTML)
+ z = await c.send_message(MESSAGE_DUMP, txt, parse_mode=enums.ParseMode.HTML)
await z.reply_text(f"#BUG\nReported by: {m.from_user.id} ({m.from_user.mention})")
await repl.delete()
- await m.reply_photo(photo="./extras/Fire.jpg",caption="Successfully reported your bug",reply_markup=kb)
+ await m.reply_photo(photo="./extras/Fire.jpg", caption="Successfully reported your bug", reply_markup=kb)
ppost = z.link
- await c.send_message(OWNER_ID,f"New bug report\n{ppost}",disable_web_page_preview=True)
+ await c.send_message(OWNER_ID, f"New bug report\n{ppost}", disable_web_page_preview=True)
return
@@ -439,7 +437,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..0944777b1bcf4bff2792aa19b31df56265302b12 100644
--- a/Powers/plugins/warns.py
+++ b/Powers/plugins/warns.py
@@ -6,7 +6,7 @@ from pyrogram.types import (CallbackQuery, ChatPermissions,
InlineKeyboardButton, InlineKeyboardMarkup,
Message)
-from Powers import DEV_USERS, LOGGER, SUDO_USERS, TIME_ZONE, WHITELIST_USERS
+from Powers import DEV_USERS, SUDO_USERS, TIME_ZONE, WHITELIST_USERS
from Powers.bot_class import Gojo
from Powers.database.rules_db import Rules
from Powers.database.users_db import Users
@@ -23,20 +23,11 @@ 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
-
- if not len(m.command) > 1 and not m.reply_to_message:
+ r_id = m.id
+ reason = m.text.split(None, 2)[2] if len(m.text.split()) >= 3 else None
+ 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
@@ -69,32 +60,30 @@ 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']}!"
f"\nReason for last warn:\n{reason}"
if reason
else "\n"
- f"{(await mention_html(user_first_name, user_id))} has been {action}!"
+ f"{(await mention_html(user_first_name, user_id))} has been {action}!"
),
reply_to_message_id=r_id,
)
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}",
@@ -135,8 +124,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
@@ -172,7 +160,6 @@ async def reset_warn(c: Gojo, m: Message):
@Gojo.on_message(command("warns") & filters.group)
async def list_warns(c: Gojo, m: Message):
-
user_id, user_first_name, _ = await extract_user(c, m)
if user_id == c.me.id:
@@ -202,7 +189,7 @@ async def list_warns(c: Gojo, m: Message):
if not warns:
await m.reply_text("This user has no warns!")
return
- msg = f"{(await mention_html(user_first_name,user_id))} has {num_warns}/{warn_settings['warn_limit']} warns!\n\nReasons:\n"
+ msg = f"{(await mention_html(user_first_name, user_id))} has {num_warns}/{warn_settings['warn_limit']} warns!\n\nReasons:\n"
msg += "\n".join([("- No reason" if i is None else f" - {i}") for i in warns])
await m.reply_text(msg)
return
@@ -212,8 +199,7 @@ async def list_warns(c: Gojo, m: Message):
command(["rmwarn", "removewarn"]) & restrict_filter,
)
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!",
)
@@ -250,7 +236,7 @@ async def remove_warn(c: Gojo, m: Message):
_, num_warns = warn_db.remove_warn(user_id)
await m.reply_text(
(
- f"{(await mention_html(user_first_name,user_id))} now has {num_warns} warnings!\n"
+ f"{(await mention_html(user_first_name, user_id))} now has {num_warns} warnings!\n"
"Their last warn was removed."
),
)
@@ -259,7 +245,6 @@ async def remove_warn(c: Gojo, m: Message):
@Gojo.on_callback_query(filters.regex("^warn."))
async def remove_last_warn_btn(c: Gojo, q: CallbackQuery):
-
try:
admins_group = {i[0] for i in ADMIN_CACHE[q.message.chat.id]}
except KeyError:
@@ -273,20 +258,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 +279,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/watchers.py b/Powers/plugins/watchers.py
index ef5fb6c00c302461bd1f81f191af9b9f2d677f84..4a8a6fc009e85b93c438435a7afdbb46dc38d00a 100644
--- a/Powers/plugins/watchers.py
+++ b/Powers/plugins/watchers.py
@@ -15,7 +15,6 @@ from Powers.database.blacklist_db import Blacklist
from Powers.database.group_blacklist import BLACKLIST_CHATS
from Powers.database.pins_db import Pins
from Powers.database.warns_db import Warns, WarnSettings
-from Powers.supports import get_support_staff
from Powers.utils.caching import ADMIN_CACHE, admin_cache_reload
from Powers.utils.parser import mention_html
from Powers.utils.regex_utils import regex_searcher
@@ -23,6 +22,7 @@ from Powers.utils.regex_utils import regex_searcher
# Initialise
gban_db = GBan()
+
@Gojo.on_message(filters.linked_channel)
async def antichanpin_cleanlinked(c: Gojo, m: Message):
try:
@@ -115,13 +115,12 @@ async def bl_watcher(_, m: Message):
return
await m.reply_text(
(
- f"{(await mention_html(m.from_user.first_name, m.from_user.id))} warned {num}/{warn_settings['warn_limit']}\n"
- # f"Last warn was for:\n{warn_reason}"
- f"Last warn was for:\n{warn_reason.format(trigger)}"
+ f"{(await mention_html(m.from_user.first_name, m.from_user.id))} warned {num}/{warn_settings['warn_limit']}\n" +
+ "Last warn was for:\n{}".format(warn_reason.format(trigger))
),
)
return
-
+
SUPPORT_STAFF = DEV_USERS.union(SUDO_USERS).union(WHITELIST_USERS)
if m.from_user.id in SUPPORT_STAFF:
# Don't work on Support Staff!
@@ -156,7 +155,7 @@ async def bl_watcher(_, m: Message):
if match:
try:
await perform_action_blacklist(m, action, trigger)
-
+
await m.delete()
except RPCError as ef:
LOGGER.error(ef)
@@ -167,11 +166,10 @@ async def bl_watcher(_, m: Message):
return
-
@Gojo.on_message(filters.user(list(ANTISPAM_BANNED)) & filters.group, 5)
async def gban_watcher(c: Gojo, m: Message):
from Powers import SUPPORT_GROUP
-
+
if m and not m.from_user:
return
@@ -191,8 +189,8 @@ async def gban_watcher(c: Gojo, m: Message):
text=f"This user ({user_gbanned}) has been banned globally!\n\nTo get unbanned, appeal at @{SUPPORT_GROUP}")
return
except (ChatAdminRequired, UserAdminInvalid):
- pass # For now just ignore the user in future will let the admins know once or after few times think abt it later
-
+ pass # For now just ignore the user in future will let the admins know once or after few times think abt it later
+
except RPCError as ef:
await c.send_message(
MESSAGE_DUMP,
@@ -202,8 +200,6 @@ async def gban_watcher(c: Gojo, m: Message):
)
-
-
@Gojo.on_message(filters.chat(BLACKLIST_CHATS))
async def bl_chats_watcher(c: Gojo, m: Message):
from Powers import SUPPORT_GROUP
diff --git a/Powers/plugins/web_con.py b/Powers/plugins/web_con.py
index ba1a8f3177b8c8522dcfbea454b7686a3efc5abb..8b8ed189ed82926a41747fdb345bf3826a3a8250 100644
--- a/Powers/plugins/web_con.py
+++ b/Powers/plugins/web_con.py
@@ -1,21 +1,16 @@
import asyncio
-import os
-import shutil
-from traceback import format_exc
from pyrogram import filters
from pyrogram.types import CallbackQuery
from pyrogram.types import InlineKeyboardButton as IKB
-from pyrogram.types import InlineKeyboardMarkup as IKM
from pyrogram.types import InputMediaPhoto, InputMediaVideo, Message
-from Powers import LOGGER, RMBG, genius_lyrics, is_genius_lyrics, is_rmbg
-from Powers.bot_class import Gojo
+from Powers import RMBG, genius_lyrics, is_rmbg
from Powers.utils.custom_filters import command
from Powers.utils.http_helper import *
from Powers.utils.sticker_help import toimage
from Powers.utils.web_helpers import *
-from Powers.utils.web_scrapper import INSTAGRAM, SCRAP_DATA
+from Powers.utils.web_scrapper import INSTAGRAM
# @Gojo.on_message(command(["songname","insong","songinfo","whichsong","rsong","reversesong"]))
# • /whichsong (/songname, /songinfo, /insong, /rsong, /reversesong) : Reply to file to get the song playing in it.
@@ -105,7 +100,8 @@ 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):
@@ -116,44 +112,45 @@ async def lyrics_for_song(c: Gojo, q: CallbackQuery):
except IndexError:
artist = None
if artist:
- song = genius_lyrics.search_song(song,artist)
- elif not artist:
+ song = genius_lyrics.search_song(song, artist)
+ else:
song = genius_lyrics.search_song(song)
artist = song.artist
if not song.lyrics:
- await q.answer("‼️ No lyrics found ‼️",True)
+ await q.answer("‼️ No lyrics found ‼️", True)
return
header = f"{songe.capitalize()} by {artist}"
if song.lyrics:
await q.answer("Fetching lyrics")
- reply = song.lyrics.split("\n",1)[1]
+ 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 = ''
new_kb = [
[
- IKB("Next",f"lyrics_next_{songe}{art}")
+ IKB("Next", f"lyrics_next_{songe}{art}")
]
[
- IKB("Close","f_close")
+ IKB("Close", "f_close")
]
]
else:
cap = f"{header}\n{reply}"
new_kb = [
[
- IKB("Close","f_close")
+ IKB("Close", "f_close")
]
]
- await q.message.reply_to_message.reply_text(cap,reply_markup=new_kb)
+ await q.message.reply_to_message.reply_text(cap, reply_markup=new_kb)
await q.message.delete()
return
+
@Gojo.on_callback_query(filters.regex("^lyrics_next_") | filters.regex("^lyrics_prev_"))
async def lyrics_for_song_next(c: Gojo, q: CallbackQuery):
split = q.data.split("_")
@@ -162,43 +159,37 @@ 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:]
+ songe = genius_lyrics.search_song(song, artist)
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 = [
- [
- IKB("Next",f"lyrics_prev_{song}{art}")
- ]
- [
- IKB("Close","f_close")
- ]
+ [
+ IKB("Next", f"lyrics_prev_{song}{art}")
+ ]
+ [
+ IKB("Close", "f_close")
]
+ ]
await q.edit_message_text(next_part, reply_markup=new_kb)
-@Gojo.on_message(command(["removebackground","removebg","rmbg"]))
+@Gojo.on_message(command(["removebackground", "removebg", "rmbg"]))
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")
@@ -216,10 +207,10 @@ async def remove_background(c: Gojo, m: Message):
file = toimage(filee)
else:
file = await reply.download()
- finfo = {'image_file':open(file,'rb')}
- Data = {'size':'auto'}
- Headers = {'X-Api-Key':RMBG}
- result = resp_post(URL,files=finfo,data=Data,headers=Headers)
+ finfo = {'image_file': open(file, 'rb')}
+ Data = {'size': 'auto'}
+ Headers = {'X-Api-Key': RMBG}
+ result = resp_post(URL, files=finfo, data=Data, headers=Headers)
await to_edit.delete()
contentType = result.headers.get("content-type")
if result.status_code != 200:
@@ -231,11 +222,8 @@ 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'
- with open(to_path,'wb') as out:
+ 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:
await m.reply_sticker(to_path)
@@ -248,25 +236,23 @@ async def remove_background(c: Gojo, m: Message):
await asyncio.sleep(5)
return
-@Gojo.on_message(command(["song","yta"]))
+
+@Gojo.on_message(command(["song", "yta"]))
async def song_down_up(c: Gojo, m: Message):
try:
- splited = m.text.split(None,1)[1].strip()
+ splited = m.text.split(None, 1)[1].strip()
except IndexError:
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 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}")
@@ -274,25 +260,23 @@ async def song_down_up(c: Gojo, m: Message):
LOGGER.error(format_exc())
return
-@Gojo.on_message(command(["vsong","ytv"]))
+
+@Gojo.on_message(command(["vsong", "ytv"]))
async def video_down_up(c: Gojo, m: Message):
try:
- splited = m.text.split(None,1)[1].strip()
+ splited = m.text.split(None, 1)[1].strip()
except IndexError:
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 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}")
@@ -300,14 +284,15 @@ async def video_down_up(c: Gojo, m: Message):
LOGGER.error(format_exc())
return
-@Gojo.on_message(command(["ig","instagram","insta"]))
+
+@Gojo.on_message(command(["ig", "instagram", "insta"]))
async def download_instareels(c: Gojo, m: Message):
try:
reel_ = m.command[1]
except IndexError:
await m.reply_text("Give me an instagram link to download it...")
return
-
+
insta = INSTAGRAM(reel_)
if not insta.is_correct_url():
@@ -320,14 +305,14 @@ async def download_instareels(c: Gojo, m: Message):
if content["code"] == 69 or content["message"] != "success":
return await m.reply_text(content["message"])
-
+
try:
medias = content["content"]["mediaUrls"]
to_delete = await to_edit.edit_text("Found media in the link trying to download and upload them please wait")
to_send = []
- for media in medias:
+ for media in medias:
if media["type"] == "image":
to_send.append(InputMediaPhoto(media["url"]))
else:
@@ -336,12 +321,12 @@ async def download_instareels(c: Gojo, m: Message):
await m.reply_media_group(to_send)
await to_delete.delete()
# shutil.rmtree("./scrapped/")
-
+
except KeyError:
await to_edit.delete()
await m.reply_text("Failed to fetch any media from given url")
return
-
+
__PLUGIN__ = "web support"
diff --git a/Powers/supports.py b/Powers/supports.py
index e9ee9b7451dc3e2e3885967aaa0454362057a0f4..2ba6655d391af653ab1e3cbd1d56a3290a98c721 100644
--- a/Powers/supports.py
+++ b/Powers/supports.py
@@ -1,4 +1,4 @@
-from Powers import DEV_USERS, OWNER_ID, SUDO_USERS, WHITELIST_USERS
+from Powers import OWNER_ID, WHITELIST_USERS
from Powers.database.support_db import SUPPORTS
@@ -12,6 +12,7 @@ async def load_support_users():
support.insert_support_user(int(i), "whitelist")
return
+
def get_support_staff(want="all"):
"""
dev, sudo, whitelist, dev_level, sudo_level, all
@@ -32,7 +33,8 @@ 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/admin_check.py b/Powers/utils/admin_check.py
index ca799beeef7b3f4aec0fcb2a5462ef9df6801163..2b6b77f61d20290b73a13319eea2e0a6836f7d4d 100644
--- a/Powers/utils/admin_check.py
+++ b/Powers/utils/admin_check.py
@@ -69,7 +69,7 @@ async def owner_check(m: Message or CallbackQuery) -> bool:
if user_id in SUDO_LEVEL:
return True
-
+
try:
user = await m.chat.get_member(user_id)
except Exception:
diff --git a/Powers/utils/caching.py b/Powers/utils/caching.py
index 1e82eef85894b47112ddadd5323f8a4626d335ef..7c94f932b8804cbe2e70c3b9e8c77c38707cd08f 100644
--- a/Powers/utils/caching.py
+++ b/Powers/utils/caching.py
@@ -7,8 +7,6 @@ from pyrogram.enums import ChatMembersFilter
from pyrogram.types import CallbackQuery
from pyrogram.types.messages_and_media.message import Message
-from Powers import LOGGER
-
THREAD_LOCK = RLock()
# admins stay cached for 30 mins
diff --git a/Powers/utils/captcha_helper.py b/Powers/utils/captcha_helper.py
index 366185ccdfa0bc14f8aa46a632faaf90aee0cb1b..6cdcfc8a728d518f340d807c279c6ca4540edd05 100644
--- a/Powers/utils/captcha_helper.py
+++ b/Powers/utils/captcha_helper.py
@@ -13,7 +13,7 @@ async def get_qr_captcha(chat, user, username):
initial = f"t.me/{username}?start=qr_"
encode = f"{chat}:{user}"
encoded = await encode_decode(encode)
- final = initial+encoded
+ final = initial + encoded
qr = qrcode.make(final)
name = f"captcha_verification{chat}_{user}.png"
qr.save(name)
@@ -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)
@@ -52,4 +48,4 @@ async def get_image_captcha(chat, user):
cap = image.generate(str_)
image.write(str_, name)
- return name, str_
\ No newline at end of file
+ return name, str_
diff --git a/Powers/utils/custom_filters.py b/Powers/utils/custom_filters.py
index 9153a4f3100d6dd405f20b5ce952b8342864f102..1be5626c0292dadf094d43890453710d6c0469b0 100644
--- a/Powers/utils/custom_filters.py
+++ b/Powers/utils/custom_filters.py
@@ -21,11 +21,11 @@ from Powers.utils.caching import ADMIN_CACHE, admin_cache_reload
def command(
- commands: Union[str, List[str]],
- case_sensitive: bool = False,
- owner_cmd: bool = False,
- dev_cmd: bool = False,
- sudo_cmd: bool = False,
+ commands: Union[str, List[str]],
+ case_sensitive: bool = False,
+ owner_cmd: bool = False,
+ dev_cmd: bool = False,
+ sudo_cmd: bool = False,
):
async def func(flt, c: Gojo, m: Message):
if not m:
@@ -33,12 +33,12 @@ def command(
date = m.edit_date
if date:
- return False # reaction
+ return False # reaction
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:
@@ -81,19 +81,17 @@ def command(
# i.e. PM
user_status = CMS.OWNER
except RPCError:
- return False # Avoid RPCError while checking for user status
+ return False # Avoid RPCError while checking for user status
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:
@@ -215,7 +213,7 @@ async def restrict_check_func(_, __, m: Message or CallbackQuery):
m = m.message
if (
- m.chat.type not in [ChatType.SUPERGROUP, ChatType.GROUP]
+ m.chat.type not in [ChatType.SUPERGROUP, ChatType.GROUP]
):
return False
@@ -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):
@@ -378,19 +369,21 @@ async def flood_check_filter(_, __, m: Message):
elif u_id in admin_group:
return False
-
+
elif u_id in {i[0] for i in app_users}:
return False
else:
return True
+
async def captcha_filt(_, __, m: Message):
try:
return CAPTCHA().is_captcha(m.chat.id)
- except:
+ except Exception:
return False
+
captcha_filter = create(captcha_filt)
flood_filter = create(flood_check_filter)
afk_filter = create(afk_check_filter)
diff --git a/Powers/utils/extract_user.py b/Powers/utils/extract_user.py
index 6a9662edfe8c4c1258d3028d074b955637aebf4b..afe6c6280a6bd01ec3bc5ce4b756e7df34b463d0 100644
--- a/Powers/utils/extract_user.py
+++ b/Powers/utils/extract_user.py
@@ -30,14 +30,14 @@ async def extract_user(c: Gojo, m: Message) -> Tuple[int, str, str]:
elif required_entity.type in (entity.MENTION, entity.PHONE_NUMBER):
# new long user ids are identified as phone_number
user_found = m.text[
- required_entity.offset: (
- required_entity.offset + required_entity.length
- )
- ]
+ required_entity.offset: (
+ required_entity.offset + required_entity.length
+ )
+ ]
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/extras.py b/Powers/utils/extras.py
index 432e425219262845a0ce487e615587dfd36c7b2f..f6b5600434ba5c17dc1f41ced411b2ac3580cdb9 100644
--- a/Powers/utils/extras.py
+++ b/Powers/utils/extras.py
@@ -513,7 +513,6 @@ TOSS = (
"Tails",
)
-
DECIDE = ("Yes.", "No.", "Maybe.", "Who the hell cares?",
"No one give a damn about it")
@@ -554,7 +553,6 @@ INSULT_STRINGS = [
"`If you think you are an idiot..............then you are absolutely right...`",
]
-
BAN_GIFS = [
"https://tenor.com/bqhVe.gif",
"https://tenor.com/bsHe5.gif",
@@ -600,7 +598,6 @@ KICK_GIFS = [
"https://media.giphy.com/media/y9pfUqY3uaT1MPXxYM/giphy.gif",
]
-
MUTE_GIFS = [
"https://media.giphy.com/media/MpCxz9VLh6t8ceRb0r/giphy.gif",
"https://media.giphy.com/media/HWl1atKEPAWcw/giphy.gif",
@@ -708,7 +705,6 @@ StartPic = [
"https://graph.org/file/f377781fe8a1fe09fea55.jpg",
]
-
birthday_wish = [
"Wishing you a happy birthday filled with love and joy.",
"Hope your birthday is as wonderful as you are.",
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..db30fc0aa441f7e80a84c25ef2ad10e079e25a11 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",
),
],
- ],
+ ]
)
@@ -168,10 +160,10 @@ async def get_private_note(c: Gojo, m: Message, help_option: str):
await m.reply_text(teks, quote=True, disable_web_page_preview=True)
return
elif msgtype in (
- Types.STICKER,
- Types.VIDEO_NOTE,
- Types.CONTACT,
- Types.ANIMATED_STICKER,
+ Types.STICKER,
+ Types.VIDEO_NOTE,
+ Types.CONTACT,
+ Types.ANIMATED_STICKER,
):
await (await send_cmd(c, msgtype))(m.chat.id, getnotes["fileid"])
else:
@@ -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..b77a387fc245847ee780d04014fc7d5f6e482a7b 100644
--- a/Powers/utils/sticker_help.py
+++ b/Powers/utils/sticker_help.py
@@ -49,23 +49,23 @@ 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}"
- sticker_set = await get_sticker_set_by_name(c,packname)
+ 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
break
@@ -75,8 +75,8 @@ async def get_all_sticker_packs(c: Gojo, user_id: int, offset: int = 1, limit: i
packnum += 1
else:
page = await encode_decode(f"1_{user_id}")
- b64_next = await encode_decode(f"{offset+1}_{user_id}")
- b64_prev = await encode_decode(f"{offset-1}_{user_id}")
+ b64_next = await encode_decode(f"{offset + 1}_{user_id}")
+ b64_prev = await encode_decode(f"{offset - 1}_{user_id}")
if (packnum > (packnum + limit - 1)) and offset >= 2:
kb = [
@@ -85,21 +85,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 +111,7 @@ async def get_all_sticker_packs(c: Gojo, user_id: int, offset: int = 1, limit: i
]
kb = ikm(kb)
break
-
+
return txt, kb
@@ -130,7 +130,7 @@ async def runcmd(cmd: str) -> Tuple[str, str, int, int]:
async def get_sticker_set_by_name(
- client: Gojo, name: str
+ client: Gojo, name: str
) -> raw.base.messages.StickerSet:
try:
return await client.invoke(
@@ -144,13 +144,13 @@ async def get_sticker_set_by_name(
async def create_sticker_set(
- client: Gojo,
- owner: int,
- title: str,
- short_name: str,
- stickers: List[raw.base.InputStickerSetItem],
- animated: bool = False,
- video: bool = False
+ client: Gojo,
+ owner: int,
+ title: str,
+ short_name: str,
+ stickers: List[raw.base.InputStickerSetItem],
+ animated: bool = False,
+ video: bool = False
) -> raw.base.messages.StickerSet:
return await client.invoke(
raw.functions.stickers.CreateStickerSet(
@@ -163,9 +163,9 @@ async def create_sticker_set(
async def add_sticker_to_set(
- client: Gojo,
- stickerset: raw.base.messages.StickerSet,
- sticker: raw.base.InputStickerSetItem,
+ client: Gojo,
+ stickerset: raw.base.messages.StickerSet,
+ sticker: raw.base.InputStickerSetItem,
) -> raw.base.messages.StickerSet:
return await client.invoke(
raw.functions.stickers.AddStickerToSet(
@@ -178,12 +178,11 @@ async def add_sticker_to_set(
async def create_sticker(
- sticker: raw.base.InputDocument, emoji: str
+ sticker: raw.base.InputDocument, emoji: str
) -> raw.base.InputStickerSetItem:
return raw.types.InputStickerSetItem(document=sticker, emoji=emoji)
-
async def resize_file_to_sticker_size(file_path: str, length: int = 512, width: int = 512) -> str:
im = Image.open(file_path)
STICKER_DIMENSIONS = (length, width)
@@ -205,7 +204,7 @@ async def resize_file_to_sticker_size(file_path: str, length: int = 512, width:
else:
im.thumbnail(STICKER_DIMENSIONS)
- file_pathh = f"{scrap_dir}r{str(time()).replace('.','_')}.png"
+ file_pathh = f"{scrap_dir}r{str(time()).replace('.', '_')}.png"
im.save(file_pathh)
os.remove(file_path)
return file_pathh
@@ -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'"
@@ -248,7 +244,7 @@ async def Vsticker(c: Gojo, file: Message):
async def upload_document(
- client: Gojo, file_path: str, chat_id: int
+ client: Gojo, file_path: str, chat_id: int
) -> raw.base.InputDocument:
media = await client.invoke(
raw.functions.messages.UploadMedia(
@@ -274,7 +270,7 @@ async def upload_document(
async def get_document_from_file_id(
- file_id: str,
+ file_id: str,
) -> raw.base.InputDocument:
decoded = FileId.decode(file_id)
return raw.types.InputDocument(
@@ -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..5608ccd5d16552b6899e1a13bfced9da5264f3f2 100644
--- a/Powers/utils/string.py
+++ b/Powers/utils/string.py
@@ -5,7 +5,7 @@ from re import compile as compile_re
from typing import List
from pyrogram.enums import ChatType
-from pyrogram.types import InlineKeyboardButton, Message
+from pyrogram.types import Message
from Powers import TIME_ZONE
from Powers.utils.parser import escape_markdown
@@ -46,7 +46,6 @@ 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] == "\\":
@@ -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
@@ -121,9 +119,9 @@ async def escape_invalid_curly_brackets(text: str, valids: List[str]) -> str:
async def escape_mentions_using_curly_brackets(
- m: Message,
- text: str,
- parse_words: list,
+ m: Message,
+ text: str,
+ parse_words: list,
) -> str:
if m.chat.type in [ChatType.SUPERGROUP, ChatType.GROUP, ChatType.CHANNEL]:
chat_name = escape(m.chat.title)
@@ -166,7 +164,7 @@ async def split_quotes(text: str):
if text[counter] == "\\":
counter += 1
elif text[counter] == text[0] or (
- text[0] == SMART_OPEN and text[counter] == SMART_CLOSE
+ text[0] == SMART_OPEN and text[counter] == SMART_CLOSE
):
break
counter += 1
@@ -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..ad7fa126099182d78c723ca75f2f8addf549d70c 100644
--- a/Powers/utils/web_helpers.py
+++ b/Powers/utils/web_helpers.py
@@ -12,12 +12,12 @@ from yt_dlp import YoutubeDL
from Powers import youtube_dir
from Powers.bot_class import LOGGER, Gojo
-from Powers.utils.http_helper import *
from Powers.utils.sticker_help import resize_file_to_sticker_size
from Powers.utils.web_scrapper import SCRAP_DATA
backUP = "https://artfiles.alphacoders.com/160/160160.jpeg"
+
def readable_time(seconds: int) -> str:
count = 0
out_time = ""
@@ -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)
@@ -47,16 +47,17 @@ def readable_time(seconds: int) -> str:
def humanbytes(size: int):
if not size:
return ""
- power = 2**10
+ power = 2 ** 10
number = 0
dict_power_n = {0: " ", 1: "Ki", 2: "Mi", 3: "Gi", 4: "Ti"}
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
+ current: int, total: int, message: Message, start: float, process: str
):
now = time.time()
diff = now - start
@@ -67,67 +68,66 @@ 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 = (
- progress_str
- + "__{0}__ **𝗈𝖿** __{1}__\n**𝖲𝗉𝖾𝖾𝖽:** __{2}/s__\n**𝖤𝖳𝖠:** __{3}__".format(
- humanbytes(current),
- humanbytes(total),
- humanbytes(speed),
- readable_time(estimated_total_time / 1000),
- )
+ progress_str
+ + "__{0}__ **𝗈𝖿** __{1}__\n**𝖲𝗉𝖾𝖾𝖽:** __{2}/s__\n**𝖤𝖳𝖠:** __{3}__".format(
+ humanbytes(current),
+ humanbytes(total),
+ humanbytes(speed),
+ readable_time(estimated_total_time / 1000),
+ )
)
await message.edit_text(f"**{process} ...**\n\n{msg}")
async def get_file_size(file: Message):
if file.photo:
- size = file.photo.file_size/1024
+ size = file.photo.file_size / 1024
elif file.document:
- size = file.document.file_size/1024
+ size = file.document.file_size / 1024
elif file.video:
- size = file.video.file_size/1024
+ size = file.video.file_size / 1024
elif file.audio:
- size = file.audio.file_size/1024
+ size = file.audio.file_size / 1024
elif file.sticker:
- size = file.sticker.file_size/1024
+ size = file.sticker.file_size / 1024
elif file.animation:
- size = file.animation.file_size/1024
+ size = file.animation.file_size / 1024
elif file.voice:
- size = file.voice.file_size/1024
+ size = file.voice.file_size / 1024
elif file.video_note:
- size = file.video_note.file_size/1024
+ size = file.video_note.file_size / 1024
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"
+ size = size / 1024
+ 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.
@@ -145,13 +145,13 @@ async def song_search(query, max_results=1):
for i in results["result"]:
durr = i['duration'].split(":")
if len(durr) == 3:
- hour_to_sec = int(durr[0])*60*60
- minutes_to_sec = int(durr[1])*60
+ hour_to_sec = int(durr[0]) * 60 * 60
+ minutes_to_sec = int(durr[1]) * 60
total = hour_to_sec + minutes_to_sec + int(durr[2])
if len(durr) == 2:
- minutes_to_sec = int(durr[0])*60
+ 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,19 +163,18 @@ 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 = {
"format": "bestaudio",
"addmetadata": True,
@@ -196,22 +195,23 @@ song_opts = {
}
video_opts = {
- "format": "best",
- "addmetadata": True,
- "key": "FFmpegMetadata",
- "prefer_ffmpeg": True,
- "geo_bypass": True,
- "nocheckcertificate": True,
- "postprocessors": [
- {
- "key": "FFmpegVideoConvertor",
- "preferedformat": "mp4",
- }
- ],
- "outtmpl": "%(id)s.mp4",
- "quiet": True,
- "logtostderr": False,
- }
+ "format": "best",
+ "addmetadata": True,
+ "key": "FFmpegMetadata",
+ "prefer_ffmpeg": True,
+ "geo_bypass": True,
+ "nocheckcertificate": True,
+ "postprocessors": [
+ {
+ "key": "FFmpegVideoConvertor",
+ "preferedformat": "mp4",
+ }
+ ],
+ "outtmpl": "%(id)s.mp4",
+ "quiet": True,
+ "logtostderr": False,
+}
+
async def youtube_downloader(c: Gojo, m: Message, query: str, type_: str):
if type_ == "a":
@@ -258,7 +258,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 +276,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,11 +287,9 @@ 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 = info['title'].replace('/', '|').replace('\\', '|')
new_file = f"{youtube_dir}{new}.{ext}"
os.rename(file_name, new_file)
return True, new_file
@@ -308,7 +302,8 @@ Downloaded by: @{c.me.username}
await m.reply_text(file_path)
return
msg = await m.reply_text(upload_text)
- await m.reply_audio(file_path, caption=cap, reply_markup=kb, duration=vid_dur, thumb=thumb, title=f_name,performer=uploader, progress=progress, progress_args=(msg, time.time(), upload_text))
+ await m.reply_audio(file_path, caption=cap, reply_markup=kb, duration=vid_dur, thumb=thumb, title=f_name,
+ performer=uploader, progress=progress, progress_args=(msg, time.time(), upload_text))
await msg.delete()
os.remove(file_path)
return
@@ -318,7 +313,8 @@ Downloaded by: @{c.me.username}
await m.reply_text(file_path)
return
msg = await m.reply_text(upload_text)
- await m.reply_video(file_path, caption=cap, reply_markup=kb, duration=vid_dur, thumb=thumb, progress=progress, progress_args=(msg, time.time(), upload_text))
+ await m.reply_video(file_path, caption=cap, reply_markup=kb, duration=vid_dur, thumb=thumb, progress=progress,
+ progress_args=(msg, time.time(), upload_text))
await msg.delete()
os.remove(file_path)
return
diff --git a/Powers/utils/web_scrapper.py b/Powers/utils/web_scrapper.py
index 8eef1cdebfc7a68277c19ca703769de7a9ea7e9e..b5ba56d5a2ff662f9d55ab863acf8593587e1455 100644
--- a/Powers/utils/web_scrapper.py
+++ b/Powers/utils/web_scrapper.py
@@ -6,6 +6,7 @@ import httpx
from Powers import *
+
# import requests
# from selenium import webdriver
# from selenium.webdriver.chrome.options import Options
@@ -16,7 +17,6 @@ from Powers import *
# from selenium.webdriver.support.wait import WebDriverWait
-
class SCRAP_DATA:
"""Class to get and handel scrapped data"""
@@ -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,9 +221,10 @@ 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())
- return {"code": 69, "message": e}
\ No newline at end of file
+ return {"code": 69, "message": e}
diff --git a/Powers/vars.py b/Powers/vars.py
index 23562d3d6105b62a9a6d419a9942f67f1b625dd2..fdd8fe7cce4707c418e7c2681f98411ab58b3abb 100644
--- a/Powers/vars.py
+++ b/Powers/vars.py
@@ -7,6 +7,7 @@ env_file = f"{getcwd()}/.env"
config = Configuration(loaders=[Environment(), EnvFile(filename=env_file)])
is_env = path.isfile(env_file)
+
class Config:
"""Config class for variables."""
@@ -15,7 +16,7 @@ class Config:
API_ID = int(config("API_ID", default="123"))
API_HASH = config("API_HASH", default=None)
OWNER_ID = int(config("OWNER_ID", default=1344569458))
- MESSAGE_DUMP = int(config("MESSAGE_DUMP", default = "0")) # if not given owner id will be msg dump :)
+ MESSAGE_DUMP = int(config("MESSAGE_DUMP", default="0")) # if not given owner id will be msg dump :)
DEV_USERS = [
int(i)
for i in config(
@@ -51,8 +52,8 @@ class Config:
SUPPORT_CHANNEL = config("SUPPORT_CHANNEL", default="gojo_bots_network")
WORKERS = int(config("WORKERS", default=16))
TIME_ZONE = config("TIME_ZONE", default='Asia/Kolkata')
- BOT_USERNAME = "" # Leave it as it is
- BOT_ID = "" # Leave it as it is
+ BOT_USERNAME = "" # Leave it as it is
+ BOT_ID = "" # Leave it as it is
BOT_NAME = "" # Leave it as it is
diff --git a/requirements.txt b/requirements.txt
index d9c87424c57e2dbf6ca06e09aeb24124e8991a0c..6790f69c9c1f365b6b536c9c7ecd83197b89fc09 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -39,4 +39,4 @@ 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
+yt-dlp@git+https://github.com/HellBoy-OP/yt-dp-fork.git@af1fd12f675220df6793fc019dff320bc76e8080