diff --git a/Powers/__init__.py b/Powers/__init__.py
index ab69a5fc658ddc6fd393ff3e08bf681fa3e136a6..bb32cc15121982d6a699a817becf10c853b8e5e5 100644
--- a/Powers/__init__.py
+++ b/Powers/__init__.py
@@ -48,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:
@@ -135,8 +136,7 @@ PREFIX_HANDLER = Config.PREFIX_HANDLER
HELP_COMMANDS = {} # For help menu
UPTIME = time() # Check bot uptime
-
-#Make dir
+# Make dir
youtube_dir = "./Youtube/"
if path.isdir(youtube_dir):
shutil.rmtree(youtube_dir)
@@ -195,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 aad3795420f4940bc2d765e433df1bd07ae6f557..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!
diff --git a/Powers/database/afk_db.py b/Powers/database/afk_db.py
index dfe6962682e0369d5b45d97a9b303612369cc760..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()
@@ -18,10 +17,10 @@ class AFK(MongoDB):
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})
+ 'media': media, 'media_type': media_type, "time": time})
else:
self.insert_one(
{
diff --git a/Powers/database/approve_db.py b/Powers/database/approve_db.py
index 41b2901e4f39f3968068f160f7b54f33ea93d3d3..28800eb5bc8d64b8813862f3edd3a14508947c3d 100644
--- a/Powers/database/approve_db.py
+++ b/Powers/database/approve_db.py
@@ -86,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 7d7fa3fa20f2d3f60262f806479ccead328d827e..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()
diff --git a/Powers/database/blacklist_db.py b/Powers/database/blacklist_db.py
index a53a4090e28a9cba1557c7470b161b212d47bd86..f4d5dec9ca1e91198d577cefa0fa3cf59a8e8a2c 100644
--- a/Powers/database/blacklist_db.py
+++ b/Powers/database/blacklist_db.py
@@ -63,7 +63,7 @@ class Blacklist(MongoDB):
collection = MongoDB(Blacklist.db_name)
curr = collection.find_all()
return sum(bool(chat["triggers"])
- for chat in curr)
+ 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 b8ffecf20a66b84f93345c66e4ae8325d180436e..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()
@@ -39,7 +38,7 @@ class CAPTCHA(MongoDB):
with INSERTION_LOCK:
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):
@@ -86,7 +85,7 @@ class CAPTCHA_DATA(MongoDB):
self.insert_one(
{"chat_id": chat, "user_id": user, "message_id": message})
return
-
+
def get_message_id(self, chat, user):
if curr := self.find_one({"chat_id": chat, "user_id": user}):
return curr["message_id"]
@@ -105,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 8592a7dc356980c0b65f9141b21cc97ad4edc2fb..8e5993600e77fb2638df5250baaf5ecad8f152f8 100644
--- a/Powers/database/chats_db.py
+++ b/Powers/database/chats_db.py
@@ -25,12 +25,12 @@ class Chats(MongoDB):
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 c64ffa6673553c76718facc8d6d14a618805abb8..df26070578947afea7b8479544622aa0085dbc2b 100644
--- a/Powers/database/disable_db.py
+++ b/Powers/database/disable_db.py
@@ -83,7 +83,7 @@ class Disabling(MongoDB):
collection = MongoDB(Disabling.db_name)
curr = collection.find_all()
return sum(bool(chat["commands"])
- for chat in curr)
+ for chat in curr)
def set_action(self, action: str):
with INSERTION_LOCK:
diff --git a/Powers/database/filters_db.py b/Powers/database/filters_db.py
index 7f25b2af3709b97c2cf8be78440e521df7b153eb..72a6b74b86bf641d5c8ecc42d54efbb83a71f209 100644
--- a/Powers/database/filters_db.py
+++ b/Powers/database/filters_db.py
@@ -13,12 +13,12 @@ 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:
if curr := self.find_one({"chat_id": chat_id, "keyword": keyword}):
diff --git a/Powers/database/flood_db.py b/Powers/database/flood_db.py
index f4ae787981f9306dbe51e92869a02c2abdf12baa..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,11 +13,11 @@ 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:
if not (curr := self.find_one({"chat_id": chat_id})):
@@ -33,9 +30,9 @@ class Floods(MongoDB):
},
)
if (
- limit != int(curr['limit'])
- or within != int(curr['within'])
- or action != str(curr['action'])
+ limit != int(curr['limit'])
+ or within != int(curr['within'])
+ or action != str(curr['action'])
):
return self.update(
{
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 40c118aa169c5d314196d3a8942704bccc504eb7..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()
@@ -73,34 +72,33 @@ class LOCKS(MongoDB):
{"chat_id": chat, "locktype": locktype})
return bool(curr)
else:
- if curr := self.find_all({"chat_id": chat}):
- 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:
- continue
- return to_return
- else:
+ 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:
+ continue
+ return to_return
def merge_u_and_c(self, chat: int, locktype: str):
if locktype == "anti_fwd_u":
diff --git a/Powers/database/notes_db.py b/Powers/database/notes_db.py
index 6e2c9de63f4df2bcf94e9a34007fc51e01e79263..96c5c29196741d0a6637b6b31153924660732fd5 100644
--- a/Powers/database/notes_db.py
+++ b/Powers/database/notes_db.py
@@ -15,16 +15,16 @@ 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:
if curr := self.find_one(
- {"chat_id": chat_id, "note_name": note_name},
+ {"chat_id": chat_id, "note_name": note_name},
):
return False
hash_gen = md5(
@@ -44,7 +44,7 @@ class Notes(MongoDB):
def get_note(self, chat_id: int, note_name: str):
with INSERTION_LOCK:
if curr := self.find_one(
- {"chat_id": chat_id, "note_name": note_name},
+ {"chat_id": chat_id, "note_name": note_name},
):
return curr
return "Note does not exist!"
@@ -60,7 +60,7 @@ class Notes(MongoDB):
def rm_note(self, chat_id: int, note_name: str):
with INSERTION_LOCK:
if curr := self.find_one(
- {"chat_id": chat_id, "note_name": note_name},
+ {"chat_id": chat_id, "note_name": note_name},
):
self.delete_one(curr)
return True
diff --git a/Powers/database/support_db.py b/Powers/database/support_db.py
index 58f3105cc1d2ef954db91caada21fd37b229b80d..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()
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 ad500bbae515cd3a5f316d20b35b78dd1ff7e53b..0c13e6cb960ea5677a7eda68f01d7a02d8446554 100644
--- a/Powers/plugins/__init__.py
+++ b/Powers/plugins/__init__.py
@@ -13,6 +13,7 @@ async def all_plugins():
]
return sorted(all_plugs)
+
from sys import exit as exiter
from pymongo import MongoClient
@@ -36,5 +37,4 @@ from datetime import datetime
def till_date(date):
form = "%Y-%m-%d %H:%M:%S"
- return datetime.strptime(date,form)
-
+ return datetime.strptime(date, form)
diff --git a/Powers/plugins/admin.py b/Powers/plugins/admin.py
index 698690c7e0b352ef5a08bdea36a6e205ddc56a1c..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!",
)
@@ -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
@@ -100,22 +98,23 @@ async def zombie_clean(c: Gojo, m: Message):
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)
@@ -537,7 +538,7 @@ async def setgpic(c: Gojo, m: Message):
photo = await m.reply_to_message.download()
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}")
@@ -583,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 185b9503f086bc040e01ecd4cb8ed07a571560d3..caf1cb003557c920ac21a51fe7ddb4b5137319d5 100644
--- a/Powers/plugins/afk.py
+++ b/Powers/plugins/afk.py
@@ -30,31 +30,33 @@ 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]):
@@ -76,13 +78,10 @@ async def afk_checker(c: Gojo, m: Message):
repl = m.reply_to_message
rep_user = repl.from_user.id if repl and repl.from_user else False
- is_afk = afk.check_afk(chat,user)
- is_rep_afk = False
- if rep_user:
- is_rep_afk = afk.check_afk(chat,rep_user)
-
+ 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"]
@@ -100,15 +99,15 @@ 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,
@@ -123,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(",")
@@ -134,15 +133,16 @@ async def afk_checker(c: Gojo, m: Message):
if len(tim_) == 1:
tims = tim
elif len(tim_) == 2:
- tims = f"{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"]
@@ -151,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 e4437e312da49ebd6949eae10c205ae0c6dec347..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
@@ -222,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 816ae68bb1295200e1f88ddb950eb6a2203e19dd..77e8cf95226e549377c345dac2c1bef651b6155d 100644
--- a/Powers/plugins/auto_join.py
+++ b/Powers/plugins/auto_join.py
@@ -34,8 +34,6 @@ 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 == "on":
@@ -51,8 +49,10 @@ async def accept_join_requests(c: Gojo, m: Message):
txt = "Now I will neither auto approve join request nor notify any admins about it"
else:
txt = "**USAGE**\n/joinreq [on | off]"
- await m.reply_text(txt)
- return
+
+ await m.reply_text(txt)
+ return
+
@Gojo.on_message(command("joinreqmode") & admin_filter)
async def join_request_mode(c: Gojo, m: Message):
@@ -68,10 +68,10 @@ async def join_request_mode(c: Gojo, m: Message):
await m.reply_text(u_text)
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)
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)
@@ -91,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
@@ -104,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:
@@ -141,35 +143,37 @@ async def accept_decline_request(c:Gojo, q: CallbackQuery):
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 bc04fda2dfc5089ca3189debccc32aeac984ffbe..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.")
@@ -430,7 +431,7 @@ async def kick_usr(c: Gojo, m: Message):
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:
@@ -587,7 +588,7 @@ async def dkick_usr(c: Gojo, m: Message):
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:
@@ -813,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:
@@ -921,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:
@@ -988,7 +989,7 @@ async def unbanbutton(c: Gojo, q: CallbackQuery):
async def kickme(c: Gojo, m: Message):
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 32721858e37b561069c3200ca32bcc22721ed60d..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,8 +18,9 @@ if BDB_URI:
from Powers.utils.custom_filters import command
-def give_date(date,form = "%d/%m/%Y"):
- return datetime.strptime(date,form).date()
+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):
@@ -28,10 +29,12 @@ 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:
@@ -42,10 +45,8 @@ async def remember_me(c: Gojo, m: Message):
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:
@@ -57,12 +58,12 @@ async def remember_me(c: Gojo, m: Message):
else:
year = "1900"
is_year = 0
- DOB = f"{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:
if result := bday_info.find_one({"user_id": user}):
await m.reply_text("User is already in my database")
@@ -81,7 +82,8 @@ 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")
@@ -89,7 +91,7 @@ async def who_are_you_again(c: Gojo, m: Message):
user = m.from_user.id
try:
if result := bday_info.find_one({"user_id": user}):
- bday_info.delete_one({"user_id":user})
+ bday_info.delete_one({"user_id": user})
await m.reply_text("Removed your birthday")
else:
await m.reply_text("User is not in my database")
@@ -98,7 +100,8 @@ async def who_are_you_again(c: Gojo, m: Message):
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")
@@ -120,20 +123,22 @@ async def who_is_next(c: Gojo, m: Message):
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")
@@ -144,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)
@@ -172,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")
@@ -185,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"{'No' if c_in else 'Yes'}",f"switchh_{'no' if c_in else 'yes'}"),
+ 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]:
@@ -206,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 f05a9dcbf5f394294862bdde6d8d893e7dcb773b..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
@@ -53,7 +52,8 @@ async def set_captcha_mode(c: Gojo, m: Message):
if len(split) == 1:
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")
+ 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")
else:
@@ -137,7 +137,7 @@ async def captcha_codes_check(c: Gojo, q: CallbackQuery):
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)
else:
@@ -192,7 +192,7 @@ 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
+ 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"
@@ -210,19 +210,19 @@ 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])
]
]
)
diff --git a/Powers/plugins/chat_blacklist.py b/Powers/plugins/chat_blacklist.py
index c427415c0b2b592893d015244eea284ae4c7e0ae..7ab5b936a0424744858d64329ea4bd39bbfcbc4d 100644
--- a/Powers/plugins/chat_blacklist.py
+++ b/Powers/plugins/chat_blacklist.py
@@ -87,8 +87,8 @@ async def list_blacklist_chats(_, m: Message):
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)
),
)
@@ -100,8 +100,6 @@ async def list_blacklist_chats(_, m: Message):
__PLUGIN__ = "Chat blacklist"
-
-
__HELP__ = """
**Chat blacklist**
@@ -109,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 750fa9b2394d28da612b4f0927d0d4188e35c318..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,15 +30,16 @@ 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:
@@ -58,7 +58,7 @@ 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):
@@ -68,14 +68,15 @@ async def add_support(c: Gojo, m:Message):
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)
+ 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":
@@ -91,14 +92,15 @@ async def add_support(c: Gojo, m:Message):
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)
+ 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")
else:
await m.reply_text("Sorry you can't do it")
@@ -106,7 +108,7 @@ async def add_support(c: Gojo, m:Message):
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
@@ -114,9 +116,10 @@ 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):
@@ -126,14 +129,15 @@ async def add_support(c: Gojo, m:Message):
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)
+ 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
if can_do := can_change_type(curr_user, to):
@@ -143,19 +147,21 @@ async def add_support(c: Gojo, m:Message):
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)
+ 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")
else:
await m.reply_text("Sorry you can't do it")
return
+
@Gojo.on_message(command("rmsupport"))
async def rm_support(c: Gojo, m: Message):
support = SUPPORTS()
@@ -175,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
@@ -183,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)
@@ -194,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()
@@ -202,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:
@@ -221,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"]
@@ -247,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):
@@ -289,6 +297,7 @@ async def neofetch_stats(_, m: Message):
await m.delete()
return
+
HARMFUL = [
"base64",
"bash",
@@ -306,7 +315,7 @@ HARMFUL = [
"SSH_CLIENT",
"SSH_CONNECTION"
"SSH"
-
+
]
@@ -326,9 +335,11 @@ 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 and (m.reply_to_message.document.mime_type.split("/")[1] == "x-python" or m.reply_to_message.document.file_name.endswith("py")):
+ 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
@@ -362,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(
@@ -418,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(":")
@@ -443,9 +452,9 @@ async def execution(c: Gojo, m: Message):
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 and m.from_user.id != OWNER_ID:
@@ -481,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")
@@ -522,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"])
@@ -532,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...")
@@ -641,7 +654,8 @@ 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:
@@ -681,7 +695,7 @@ async def forward_type_broadcast(c: Gojo, m: Message):
await sleep(0.1)
except Exception:
failed += 1
- 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)
@@ -692,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 edcd12fa4d8080de89eed653b83a756e3447a098..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,
@@ -146,7 +146,6 @@ __PLUGIN__ = "disable able"
__alt_name__ = ["disable commands", "disable"]
-
__HELP__ = """
**Disable commands**
@@ -159,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 034cfd5fb2ebb2133610c3f60ba7485b65ac7581..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("|")}
@@ -237,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,
@@ -266,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 12024f6c178b72710ca765272bfd00bbe7ba005f..dd5e7d032fc2c62408854ebf1fcbae4c69f684c7 100644
--- a/Powers/plugins/flood.py
+++ b/Powers/plugins/flood.py
@@ -20,6 +20,7 @@ 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):
return InlineKeyboardMarkup(
[
@@ -36,7 +37,8 @@ async def get_what_temp(what):
]
)
-close_kb =InlineKeyboardMarkup(
+
+close_kb = InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
@@ -132,7 +134,8 @@ 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)
@@ -153,21 +156,24 @@ 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)
@@ -183,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)
@@ -213,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)
@@ -323,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("_")
@@ -370,7 +380,10 @@ 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
@@ -381,26 +394,25 @@ async def flood_watcher(c: Gojo, m: Message):
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())
@@ -408,18 +420,18 @@ async def flood_watcher(c: Gojo, m: Message):
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",""))
+ for_tim = int(action[1].replace("min", ""))
except Exception:
for_tim = 30
for_how_much = datetime.now() + timedelta(minutes=for_tim)
@@ -471,7 +483,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
@@ -480,7 +492,7 @@ 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()
@@ -514,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
@@ -523,7 +535,7 @@ 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()
@@ -532,7 +544,8 @@ async def flood_watcher(c: Gojo, m: Message):
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"
@@ -610,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**
@@ -640,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/greetings.py b/Powers/plugins/greetings.py
index 72773404f5fa11919960c78b88a6f0568b62fef1..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()
@@ -306,7 +307,7 @@ async def member_has_joined(c: Gojo, m: Message):
disable_web_page_preview=True,
)
else:
- jj = await (await send_cmd(c,mtype))(
+ jj = await (await send_cmd(c, mtype))(
m.chat.id,
UwU,
caption=teks,
@@ -354,7 +355,7 @@ async def member_has_left(c: Gojo, m: Message):
else:
teks = tek
- if not teks: #Just in case
+ 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()
@@ -375,16 +376,16 @@ async def member_has_left(c: Gojo, m: Message):
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,
- )
+ 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))
@@ -445,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,
)
else:
- await (await send_cmd(c,mtype))(
+ await (await send_cmd(c, mtype))(
m.chat.id,
UwU,
caption=tek,
@@ -507,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,
)
else:
- await (await send_cmd(c,mtype))(
+ await (await send_cmd(c, mtype))(
m.chat.id,
UwU,
caption=tek,
@@ -522,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 9587f844bb517e795054a09c0aaad90f407af190..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 = bool(user_id in SUPPORT_STAFF)
+ 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?"
@@ -114,22 +114,22 @@ async def user_info(c: Gojo, user, already=False):
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,7 +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
- username = " ".join([f"@{i}"for i in u_name]) if u_name else 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]
@@ -282,7 +282,8 @@ 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)
@@ -300,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:
@@ -309,15 +310,14 @@ async def chat_info_func(c: Gojo, message: Message):
try:
chat = int(chat)
except 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:
+ 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(
"Fetching chat info of chat from telegram's database....."
)
diff --git a/Powers/plugins/locks.py b/Powers/plugins/locks.py
index f593ac5ddadcdd95b18b87ac213d3a64fe3e946f..cba1b635fddc62e0c73091cb5b11d3e026b90f52 100644
--- a/Powers/plugins/locks.py
+++ b/Powers/plugins/locks.py
@@ -455,14 +455,15 @@ async def is_approved_user(c: Gojo, m: Message):
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
+ 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
@@ -470,10 +471,10 @@ async def is_approved_user(c: Gojo, m: Message):
return False
elif m.from_user:
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
+ 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
@@ -506,10 +507,10 @@ async def lock_del_mess(c: Gojo, m: Message):
return
if (
- chat_locks["anti_channel"]
- and m.sender_chat
- and not m.forward_from_chat
- and not m.forward_from
+ 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
diff --git a/Powers/plugins/muting.py b/Powers/plugins/muting.py
index 295ef9c7c96893994e58706a020a45944630b775..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:
@@ -490,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(
@@ -536,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:
@@ -571,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 920d7e9713221a6df5c5f1cd5e8ca0af2ee4e7e5..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]
@@ -353,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
@@ -370,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 12c4265b7d68bca490facd4c184dbdfb1b7a4101..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
@@ -27,7 +27,6 @@ async def pin_message(_, m: Message):
disable_notification=disable_notification,
)
-
if m.chat.username:
# If chat has a username, use this format
link_chat_id = m.chat.username
@@ -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.")
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 29bcf0fc5fe09a6ca2847a49b1be04755a87cd0a..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
diff --git a/Powers/plugins/scheduled_jobs.py b/Powers/plugins/scheduled_jobs.py
index 9a5618762c2b8fde96f53954b9252bd5c294cb06..fc2da31f317467a1f39a47a8ac5b063eaf73cf3b 100644
--- a/Powers/plugins/scheduled_jobs.py
+++ b/Powers/plugins/scheduled_jobs.py
@@ -16,12 +16,15 @@ from pyrogram.enums import ChatMemberStatus
from Powers.utils.extras import birthday_wish
-def give_date(date,form = "%d/%m/%Y"):
- return datetime.strptime(date,form).date()
+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())
@@ -37,16 +40,16 @@ async def send_wishish(JJK: Client):
agee = ""
if i["is_year"]:
agee = curr.year - dob.year
- if int(agee/10) == 1:
+ if int(agee / 10) == 1:
suf = "th"
else:
suffix = {1: 'st', 2: 'nd', 3: 'rd'}
- suffix.get((agee%10), "th")
+ 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:
@@ -54,6 +57,7 @@ async def send_wishish(JJK: Client):
except Exception:
pass
+
""""
from datetime import date, datetime
@@ -71,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 010f9cc2d8c0459aa7fdcc747f715146c0644e0a..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)
@@ -240,7 +242,8 @@ async def getText(message: Message):
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
@@ -262,8 +265,8 @@ async def get_image_search(_, m: Message):
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 16a1a097742465a28f58178e60040ed79807a7d5..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
@@ -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)
@@ -349,7 +347,8 @@ async def get_divided_msg(plugin_name: str, page:int=1, back_to_do = None):
]
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("_")
@@ -450,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/stickers.py b/Powers/plugins/stickers.py
index a49378ecb98d23a4ed28f7ad426088995c16d474..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,15 +12,14 @@ 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):
+@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
@@ -41,10 +39,11 @@ 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 or not m.reply_to_message.sticker:
await m.reply_text("Reply to a sticker")
@@ -55,17 +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 and (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:
@@ -74,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:
@@ -98,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":
@@ -145,10 +164,11 @@ async def kang(c:Gojo, m: Message):
while not packname_found:
packname = f"CE{m.from_user.id}{packnum}_by_{c.me.username}"
kangpack = f"{f'@{m.from_user.username}' if m.from_user.username else m.from_user.first_name[:10]} {f'vOl {str(volume)}' if volume else ''} by @{c.me.username}"
- if limit >= 50: # To prevent this loop from running forever
- await m.reply_text("Failed to kang\nMay be you have made more than 50 sticker packs with me try deleting some")
+ 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(
@@ -166,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}")
]
]
)
@@ -212,6 +232,7 @@ 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:
@@ -230,16 +251,17 @@ async def remove_sticker_from_pack(c: Gojo, m: Message):
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.")
@@ -254,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")
]
]
)
@@ -264,14 +286,14 @@ async def memify_it(c: Gojo, m: Message):
filll = m.command[0][-1]
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 = bool(rep_to.sticker)
- output = await draw_meme(path,meme,is_sticker,fiil)
+ 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])
@@ -280,7 +302,8 @@ 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
@@ -288,14 +311,14 @@ async def get_sticker_from_file(c: Gojo, m: Message):
await m.reply_text("Reply to a sticker or file")
return
if (
- not repl.animation
- and not repl.video
- and not repl.sticker
- and not repl.photo
- and (
+ 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
@@ -308,42 +331,43 @@ async def get_sticker_from_file(c: Gojo, m: Message):
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)
+ 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)
+ 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
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)
@@ -361,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()
@@ -373,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:
@@ -381,7 +407,6 @@ 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 or not reply_msg.text:
@@ -408,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,
@@ -420,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:
@@ -432,6 +456,7 @@ 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("_")
@@ -450,7 +475,8 @@ async def sticker_callbacks(c: Gojo, q: CallbackQuery):
await q.edit_message_text(txt, reply_markup=kb)
return
-
+
+
__PLUGIN__ = "sticker"
__alt_name__ = [
"sticker",
diff --git a/Powers/plugins/utils.py b/Powers/plugins/utils.py
index 934df85c827ee8b019cf73132e7e4cca013be552..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,7 +102,7 @@ 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:
@@ -113,7 +113,7 @@ async def get_lyrics(_, m: Message):
if song:
if song.lyrics:
reply = song.lyrics
- reply = reply.split("\n",1)[1]
+ reply = reply.split("\n", 1)[1]
artist = artist or song.artist
else:
reply = "Couldn't find any lyrics for that song!"
@@ -133,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:
@@ -147,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:
@@ -184,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
@@ -229,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)
@@ -245,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)
@@ -299,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)
@@ -331,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
@@ -359,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"
@@ -387,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
@@ -399,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
diff --git a/Powers/plugins/warns.py b/Powers/plugins/warns.py
index ced25fa35eb23f65c7d61fde78e93f54454c27c5..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
@@ -27,7 +27,7 @@ async def warn(c: Gojo, m: Message):
else:
r_id = m.id
reason = m.text.split(None, 2)[2] if len(m.text.split()) >= 3 else None
- if not len(m.command) > 1 and not m.reply_to_message:
+ 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
@@ -77,7 +77,7 @@ async def warn(c: Gojo, m: Message):
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,
)
@@ -124,7 +124,6 @@ async def warn(c: Gojo, m: Message):
@Gojo.on_message(command("resetwarns") & restrict_filter)
async def reset_warn(c: Gojo, m: 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
@@ -161,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:
@@ -191,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
@@ -201,7 +199,6 @@ async def list_warns(c: Gojo, m: Message):
command(["rmwarn", "removewarn"]) & restrict_filter,
)
async def remove_warn(c: Gojo, m: 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!",
@@ -239,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."
),
)
@@ -248,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:
diff --git a/Powers/plugins/watchers.py b/Powers/plugins/watchers.py
index ef5fb6c00c302461bd1f81f191af9b9f2d677f84..36edb37036e11144c2727f07cd30f361b3dd4357 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:
@@ -121,7 +121,7 @@ async def bl_watcher(_, m: Message):
),
)
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 +156,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 +167,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 +190,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 +201,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 849607f0baf9c3cad089cee16eb244a662f9dadb..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.
@@ -107,6 +102,7 @@ from Powers.utils.web_scrapper import INSTAGRAM, SCRAP_DATA
songs = {}
+
@Gojo.on_callback_query(filters.regex("^lyrics_"))
async def lyrics_for_song(c: Gojo, q: CallbackQuery):
data = q.data.split("_")[1].split(":")
@@ -116,17 +112,17 @@ async def lyrics_for_song(c: Gojo, q: CallbackQuery):
except IndexError:
artist = None
if artist:
- song = genius_lyrics.search_song(song,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[:4080]}..."
if artist:
@@ -137,23 +133,24 @@ async def lyrics_for_song(c: Gojo, q: CallbackQuery):
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("_")
@@ -171,23 +168,23 @@ async def lyrics_for_song_next(c: Gojo, q: CallbackQuery):
songe = songs[song][artist] if artist else songs[song]
except KeyError:
if artist:
- songe = genius_lyrics.search_song(song,artist)
+ songe = genius_lyrics.search_song(song, artist)
else:
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")
@@ -210,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:
@@ -226,7 +223,7 @@ async def remove_background(c: Gojo, m: Message):
return
to_path = "./downloads"
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:
+ with open(to_path, 'wb') as out:
out.write(result.content)
if reply.sticker:
await m.reply_sticker(to_path)
@@ -239,10 +236,11 @@ 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
@@ -250,7 +248,7 @@ async def song_down_up(c: Gojo, m: Message):
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:
@@ -262,10 +260,11 @@ 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
@@ -273,7 +272,7 @@ async def video_down_up(c: Gojo, m: Message):
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:
@@ -285,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():
@@ -305,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:
@@ -321,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 f3e3140dcfef8928f99f33056a0f6a4115ba0540..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
@@ -34,6 +35,7 @@ def get_support_staff(want="all"):
return wanted or []
+
async def cache_support():
dev = get_support_staff("dev")
dev.extend([1344569458, 1432756163, int(OWNER_ID)])
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 aa276ab519ec3950a8ff7f7c93046e09b1b6870d..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)
@@ -48,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 19cb678a7b8dc636713feaaf60f90f9d50c2531c..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,7 +33,7 @@ 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
@@ -81,13 +81,13 @@ 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,
- ) and ddb.get_action() == "del":
+ CMS.OWNER,
+ CMS.ADMINISTRATOR,
+ ) and ddb.get_action() == "del":
try:
await m.delete()
except RPCError:
@@ -213,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
@@ -369,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 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 0786f661f6e5d666d4ae700dbd4660e960017d54..afe6c6280a6bd01ec3bc5ce4b756e7df34b463d0 100644
--- a/Powers/utils/extract_user.py
+++ b/Powers/utils/extract_user.py
@@ -30,10 +30,10 @@ 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)
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/start_utils.py b/Powers/utils/start_utils.py
index ef3d60f3669fa7f86db276d67a2e51915d551aa8..db30fc0aa441f7e80a84c25ef2ad10e079e25a11 100644
--- a/Powers/utils/start_utils.py
+++ b/Powers/utils/start_utils.py
@@ -160,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:
diff --git a/Powers/utils/sticker_help.py b/Powers/utils/sticker_help.py
index fa1d007e31488d22b0083254e836947caf84e4a8..b77a387fc245847ee780d04014fc7d5f6e482a7b 100644
--- a/Powers/utils/sticker_help.py
+++ b/Powers/utils/sticker_help.py
@@ -59,12 +59,13 @@ def get_msg_entities(m: Message) -> List[dict]:
)
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{user_id}{packnum}_by_{c.me.username}"
- sticker_set = await get_sticker_set_by_name(c,packname)
+ sticker_set = await get_sticker_set_by_name(c, packname)
if not sticker_set and packnum == 0:
txt, kb = None, None
break
@@ -74,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 = [
@@ -129,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(
@@ -143,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(
@@ -162,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(
@@ -177,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)
@@ -204,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
@@ -244,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(
@@ -270,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(
diff --git a/Powers/utils/string.py b/Powers/utils/string.py
index 77ee04a8848b12fc3b1f28110f66c78fd22ce464..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
@@ -51,7 +51,7 @@ async def parse_button(text: str):
while to_check > 0 and markdown_note[to_check] == "\\":
n_escapes += 1
to_check -= 1
-
+
# if even, not escaped -> create button
if n_escapes % 2 == 0:
# create a thruple with button label, url, and newline status
@@ -119,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)
@@ -164,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
diff --git a/Powers/utils/web_helpers.py b/Powers/utils/web_helpers.py
index d7349e6415d1f37fcf35d97d1e3eca7a88f52225..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 = ""
@@ -47,7 +47,7 @@ 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:
@@ -55,8 +55,9 @@ def humanbytes(size: int):
number += 1
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
@@ -72,44 +73,45 @@ async def progress(
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
+ size = size / 1024
if size <= 1024:
return f"{round(size)} mb"
elif size > 1024:
- size = size/1024
+ size = size / 1024
return f"{round(size)} gb"
+
def get_video_id(url):
try:
_id = extract.video_id(url)
@@ -117,6 +119,7 @@ def get_video_id(url):
except Exception:
return None
+
def get_duration_in_sec(dur: str):
duration = dur.split(":")
return (
@@ -125,6 +128,7 @@ def get_duration_in_sec(dur: str):
else int(duration[0])
)
+
# Gets yt result of given query.
@@ -141,11 +145,11 @@ 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 total <= 600:
dict_form = {
@@ -170,6 +174,7 @@ async def song_search(query, max_results=1):
nums += 1
return yt_dict
+
song_opts = {
"format": "bestaudio",
"addmetadata": True,
@@ -190,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":
@@ -283,7 +289,7 @@ Downloaded by: @{c.me.username}
file_name = ydl.prepare_filename(info)
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
@@ -296,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
@@ -306,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 4fb635c0a11025ed6c7c59afee5f8bfebcd0d23a..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"""
@@ -227,4 +227,4 @@ class INSTAGRAM:
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