Captain Ezio commited on
Commit
51e1c40
·
1 Parent(s): 518de8c
Powers/__init__.py CHANGED
@@ -13,6 +13,7 @@ from traceback import format_exc
13
  import lyricsgenius
14
  import pyrogram
15
  import pytz
 
16
 
17
  LOG_DATETIME = datetime.now().strftime("%d_%m_%Y-%H_%M_%S")
18
  LOGDIR = f"{__name__}/logs"
@@ -55,7 +56,7 @@ except Exception as ef:
55
  LOGGER.error(ef) # Print Error
56
  LOGGER.error(format_exc())
57
  sysexit(1)
58
- #time zone
59
  TIME_ZONE = pytz.timezone(Config.TIME_ZONE)
60
 
61
  path = "./Version"
@@ -126,7 +127,6 @@ SUDO_USERS = Config.SUDO_USERS
126
  WHITELIST_USERS = Config.WHITELIST_USERS
127
 
128
 
129
-
130
  defult_dev = [1344569458, 1432756163, 5294360309] + [int(OWNER_ID)]
131
 
132
  Defult_dev = set(defult_dev)
@@ -147,16 +147,17 @@ PREFIX_HANDLER = Config.PREFIX_HANDLER
147
  HELP_COMMANDS = {} # For help menu
148
  UPTIME = time() # Check bot uptime
149
 
150
- from apscheduler.schedulers.asyncio import AsyncIOScheduler
151
 
152
  scheduler = AsyncIOScheduler(timezone=TIME_ZONE)
153
 
 
154
  async def load_cmds(all_plugins):
155
  """Loads all the plugins in bot."""
156
  for single in all_plugins:
157
  # If plugin in NO_LOAD, skip the plugin
158
  if single.lower() in [i.lower() for i in Config.NO_LOAD]:
159
- LOGGER.warning(f"Not loading '{single}' s it's added in NO_LOAD list")
 
160
  continue
161
 
162
  imported_module = imp_mod(f"Powers.plugins.{single}")
@@ -197,6 +198,7 @@ async def load_cmds(all_plugins):
197
  LOGGER.warning(f"Not loading Plugins - {NO_LOAD}")
198
 
199
  return (
200
- ", ".join((i.split(".")[1]).capitalize() for i in list(HELP_COMMANDS.keys()))
 
201
  + "\n"
202
  )
 
13
  import lyricsgenius
14
  import pyrogram
15
  import pytz
16
+ from apscheduler.schedulers.asyncio import AsyncIOScheduler
17
 
18
  LOG_DATETIME = datetime.now().strftime("%d_%m_%Y-%H_%M_%S")
19
  LOGDIR = f"{__name__}/logs"
 
56
  LOGGER.error(ef) # Print Error
57
  LOGGER.error(format_exc())
58
  sysexit(1)
59
+ # time zone
60
  TIME_ZONE = pytz.timezone(Config.TIME_ZONE)
61
 
62
  path = "./Version"
 
127
  WHITELIST_USERS = Config.WHITELIST_USERS
128
 
129
 
 
130
  defult_dev = [1344569458, 1432756163, 5294360309] + [int(OWNER_ID)]
131
 
132
  Defult_dev = set(defult_dev)
 
147
  HELP_COMMANDS = {} # For help menu
148
  UPTIME = time() # Check bot uptime
149
 
 
150
 
151
  scheduler = AsyncIOScheduler(timezone=TIME_ZONE)
152
 
153
+
154
  async def load_cmds(all_plugins):
155
  """Loads all the plugins in bot."""
156
  for single in all_plugins:
157
  # If plugin in NO_LOAD, skip the plugin
158
  if single.lower() in [i.lower() for i in Config.NO_LOAD]:
159
+ LOGGER.warning(
160
+ f"Not loading '{single}' s it's added in NO_LOAD list")
161
  continue
162
 
163
  imported_module = imp_mod(f"Powers.plugins.{single}")
 
198
  LOGGER.warning(f"Not loading Plugins - {NO_LOAD}")
199
 
200
  return (
201
+ ", ".join((i.split(".")[1]).capitalize()
202
+ for i in list(HELP_COMMANDS.keys()))
203
  + "\n"
204
  )
Powers/__main__.py CHANGED
@@ -2,7 +2,5 @@ import uvloop # Comment it out if using on windows
2
  from Powers.bot_class import Gojo
3
 
4
  if __name__ == "__main__":
5
- uvloop.install() # Comment it out if using on windows
6
  Gojo().run()
7
-
8
-
 
2
  from Powers.bot_class import Gojo
3
 
4
  if __name__ == "__main__":
5
+ uvloop.install() # Comment it out if using on windows
6
  Gojo().run()
 
 
Powers/bot_class.py CHANGED
@@ -24,7 +24,6 @@ if MESSAGE_DUMP == -100 or not str(MESSAGE_DUMP).startswith("-100"):
24
  )
25
 
26
 
27
-
28
  class Gojo(Client):
29
  """Starts the Pyrogram Client on the Bot Token when we do 'python3 -m Powers'"""
30
 
@@ -45,10 +44,11 @@ class Gojo(Client):
45
  await super().start()
46
  await self.set_bot_commands(
47
  [
48
- BotCommand("start", "To check weather the bot is alive or not"),
 
49
  BotCommand("help", "To get help menu"),
50
  BotCommand("donate", "To buy me a coffee"),
51
- BotCommand("bug","To report bugs")
52
  ]
53
  )
54
  meh = await self.get_me() # Get bot info from pyrogram client
@@ -68,9 +68,11 @@ class Gojo(Client):
68
  cmd_list = await load_cmds(await all_plugins())
69
  await load_support_users()
70
  LOGGER.info(f"Plugins Loaded: {cmd_list}")
71
- scheduler.add_job(clean_my_db,'cron',[self],hour=3,minute=0,second=0)
 
72
  if BDB_URI:
73
- scheduler.add_job(send_wishish,'cron',[self],hour=0,minute=0,second=0)
 
74
  scheduler.start()
75
  # Send a message to MESSAGE_DUMP telling that the
76
  # bot has started and has loaded all plugins!
 
24
  )
25
 
26
 
 
27
  class Gojo(Client):
28
  """Starts the Pyrogram Client on the Bot Token when we do 'python3 -m Powers'"""
29
 
 
44
  await super().start()
45
  await self.set_bot_commands(
46
  [
47
+ BotCommand(
48
+ "start", "To check weather the bot is alive or not"),
49
  BotCommand("help", "To get help menu"),
50
  BotCommand("donate", "To buy me a coffee"),
51
+ BotCommand("bug", "To report bugs")
52
  ]
53
  )
54
  meh = await self.get_me() # Get bot info from pyrogram client
 
68
  cmd_list = await load_cmds(await all_plugins())
69
  await load_support_users()
70
  LOGGER.info(f"Plugins Loaded: {cmd_list}")
71
+ scheduler.add_job(clean_my_db, 'cron', [
72
+ self], hour=3, minute=0, second=0)
73
  if BDB_URI:
74
+ scheduler.add_job(send_wishish, 'cron', [
75
+ self], hour=0, minute=0, second=0)
76
  scheduler.start()
77
  # Send a message to MESSAGE_DUMP telling that the
78
  # bot has started and has loaded all plugins!
Powers/database/afk_db.py CHANGED
@@ -13,43 +13,45 @@ class AFK(MongoDB):
13
  def __init__(self) -> None:
14
  super().__init__(self.db_name)
15
 
16
- def insert_afk(self, chat_id, user_id, time, reason, media_type,media=None):
17
  with INSERTION_LOCK:
18
  curr = self.check_afk(chat_id=chat_id, user_id=user_id)
19
  if curr:
20
  if reason:
21
- self.update({"chat_id":chat_id,"user_id":user_id},{"reason":reason,"time":time})
 
22
  if media:
23
- self.update({"chat_id":chat_id,"user_id":user_id},{'media':media,'media_type':media_type,"time":time})
 
24
  return True
25
  else:
26
  self.insert_one(
27
  {
28
- "chat_id":chat_id,
29
- "user_id":user_id,
30
- "reason":reason,
31
- "time":time,
32
- "media":media,
33
- "media_type":media_type
34
  }
35
  )
36
  return True
37
 
38
  def check_afk(self, chat_id, user_id):
39
- curr = self.find_one({"chat_id":chat_id,"user_id":user_id})
40
  if curr:
41
  return True
42
  return False
43
-
44
  def get_afk(self, chat_id, user_id):
45
- curr = self.find_one({"chat_id":chat_id,"user_id":user_id})
46
  if curr:
47
  return curr
48
  return
49
-
50
  def delete_afk(self, chat_id, user_id):
51
  with INSERTION_LOCK:
52
- curr = self.check_afk(chat_id,user_id)
53
  if curr:
54
- self.delete_one({"chat_id":chat_id,"user_id":user_id})
55
- return
 
13
  def __init__(self) -> None:
14
  super().__init__(self.db_name)
15
 
16
+ def insert_afk(self, chat_id, user_id, time, reason, media_type, media=None):
17
  with INSERTION_LOCK:
18
  curr = self.check_afk(chat_id=chat_id, user_id=user_id)
19
  if curr:
20
  if reason:
21
+ self.update({"chat_id": chat_id, "user_id": user_id}, {
22
+ "reason": reason, "time": time})
23
  if media:
24
+ self.update({"chat_id": chat_id, "user_id": user_id}, {
25
+ 'media': media, 'media_type': media_type, "time": time})
26
  return True
27
  else:
28
  self.insert_one(
29
  {
30
+ "chat_id": chat_id,
31
+ "user_id": user_id,
32
+ "reason": reason,
33
+ "time": time,
34
+ "media": media,
35
+ "media_type": media_type
36
  }
37
  )
38
  return True
39
 
40
  def check_afk(self, chat_id, user_id):
41
+ curr = self.find_one({"chat_id": chat_id, "user_id": user_id})
42
  if curr:
43
  return True
44
  return False
45
+
46
  def get_afk(self, chat_id, user_id):
47
+ curr = self.find_one({"chat_id": chat_id, "user_id": user_id})
48
  if curr:
49
  return curr
50
  return
51
+
52
  def delete_afk(self, chat_id, user_id):
53
  with INSERTION_LOCK:
54
+ curr = self.check_afk(chat_id, user_id)
55
  if curr:
56
+ self.delete_one({"chat_id": chat_id, "user_id": user_id})
57
+ return
Powers/database/approve_db.py CHANGED
@@ -1,11 +1,16 @@
1
  from threading import RLock
 
2
  from Powers import LOGGER
3
  from Powers.database import MongoDB
 
4
  INSERTION_LOCK = RLock()
 
 
5
  class Approve(MongoDB):
6
  """Class for managing Approves in Chats in Bot."""
7
  # Database name to connect to to preform operations
8
  db_name = "approve"
 
9
  def __init__(self, chat_id: int) -> None:
10
  super().__init__(self.db_name)
11
  self.chat_id = chat_id
@@ -22,7 +27,6 @@ class Approve(MongoDB):
22
  else:
23
  j = False
24
  return j
25
-
26
 
27
  def add_approve(self, user_id: int, user_name: str):
28
  with INSERTION_LOCK:
@@ -33,6 +37,7 @@ class Approve(MongoDB):
33
  {"users": self.chat_info["users"]},
34
  )
35
  return True
 
36
  def remove_approve(self, user_id: int):
37
  with INSERTION_LOCK:
38
  if self.check_approve(user_id):
@@ -47,50 +52,61 @@ class Approve(MongoDB):
47
  {"users": self.chat_info["users"]},
48
  )
49
  return True
 
50
  def unapprove_all(self):
51
  with INSERTION_LOCK:
52
  return self.delete_one(
53
  {"_id": self.chat_id},
54
  )
 
55
  def clean_approve(self):
56
  with INSERTION_LOCK:
57
  return self.delete_one(
58
- {"_id":self.chat_id}
59
  )
 
60
  def list_approved(self):
61
  with INSERTION_LOCK:
62
  return self.chat_info["users"]
 
63
  def count_approved(self):
64
  with INSERTION_LOCK:
65
  return len(self.chat_info["users"])
 
66
  def load_from_db(self):
67
  return self.find_all()
 
68
  def __ensure_in_db(self):
69
  chat_data = self.find_one({"_id": self.chat_id})
70
  if not chat_data:
71
  new_data = {"_id": self.chat_id, "users": []}
72
  self.insert_one(new_data)
73
- LOGGER.info(f"Initialized Approve Document for chat {self.chat_id}")
 
74
  return new_data
75
  return chat_data
76
  # Migrate if chat id changes!
 
77
  def migrate_chat(self, new_chat_id: int):
78
  old_chat_db = self.find_one({"_id": self.chat_id})
79
  new_data = old_chat_db.update({"_id": new_chat_id})
80
  self.insert_one(new_data)
81
  self.delete_one({"_id": self.chat_id})
 
82
  @staticmethod
83
  def count_all_approved():
84
  with INSERTION_LOCK:
85
  collection = MongoDB(Approve.db_name)
86
  all_data = collection.find_all()
87
  return sum(len(i["users"]) for i in all_data if len(i["users"]) >= 1)
 
88
  @staticmethod
89
  def count_approved_chats():
90
  with INSERTION_LOCK:
91
  collection = MongoDB(Approve.db_name)
92
  all_data = collection.find_all()
93
  return sum(len(i["users"]) >= 1 for i in all_data)
 
94
  @staticmethod
95
  def repair_db(collection):
96
  all_data = collection.find_all()
 
1
  from threading import RLock
2
+
3
  from Powers import LOGGER
4
  from Powers.database import MongoDB
5
+
6
  INSERTION_LOCK = RLock()
7
+
8
+
9
  class Approve(MongoDB):
10
  """Class for managing Approves in Chats in Bot."""
11
  # Database name to connect to to preform operations
12
  db_name = "approve"
13
+
14
  def __init__(self, chat_id: int) -> None:
15
  super().__init__(self.db_name)
16
  self.chat_id = chat_id
 
27
  else:
28
  j = False
29
  return j
 
30
 
31
  def add_approve(self, user_id: int, user_name: str):
32
  with INSERTION_LOCK:
 
37
  {"users": self.chat_info["users"]},
38
  )
39
  return True
40
+
41
  def remove_approve(self, user_id: int):
42
  with INSERTION_LOCK:
43
  if self.check_approve(user_id):
 
52
  {"users": self.chat_info["users"]},
53
  )
54
  return True
55
+
56
  def unapprove_all(self):
57
  with INSERTION_LOCK:
58
  return self.delete_one(
59
  {"_id": self.chat_id},
60
  )
61
+
62
  def clean_approve(self):
63
  with INSERTION_LOCK:
64
  return self.delete_one(
65
+ {"_id": self.chat_id}
66
  )
67
+
68
  def list_approved(self):
69
  with INSERTION_LOCK:
70
  return self.chat_info["users"]
71
+
72
  def count_approved(self):
73
  with INSERTION_LOCK:
74
  return len(self.chat_info["users"])
75
+
76
  def load_from_db(self):
77
  return self.find_all()
78
+
79
  def __ensure_in_db(self):
80
  chat_data = self.find_one({"_id": self.chat_id})
81
  if not chat_data:
82
  new_data = {"_id": self.chat_id, "users": []}
83
  self.insert_one(new_data)
84
+ LOGGER.info(
85
+ f"Initialized Approve Document for chat {self.chat_id}")
86
  return new_data
87
  return chat_data
88
  # Migrate if chat id changes!
89
+
90
  def migrate_chat(self, new_chat_id: int):
91
  old_chat_db = self.find_one({"_id": self.chat_id})
92
  new_data = old_chat_db.update({"_id": new_chat_id})
93
  self.insert_one(new_data)
94
  self.delete_one({"_id": self.chat_id})
95
+
96
  @staticmethod
97
  def count_all_approved():
98
  with INSERTION_LOCK:
99
  collection = MongoDB(Approve.db_name)
100
  all_data = collection.find_all()
101
  return sum(len(i["users"]) for i in all_data if len(i["users"]) >= 1)
102
+
103
  @staticmethod
104
  def count_approved_chats():
105
  with INSERTION_LOCK:
106
  collection = MongoDB(Approve.db_name)
107
  all_data = collection.find_all()
108
  return sum(len(i["users"]) >= 1 for i in all_data)
109
+
110
  @staticmethod
111
  def repair_db(collection):
112
  all_data = collection.find_all()
Powers/database/autojoin_db.py CHANGED
@@ -15,36 +15,36 @@ class AUTOJOIN(MongoDB):
15
  def __init__(self) -> None:
16
  super().__init__(self.db_name)
17
 
18
- def load_autojoin(self, chat,mode="auto"):
19
  """
20
  type = auto or notify
21
  auto to auto accept join requests
22
  notify to notify the admins about the join requests
23
  """
24
- curr = self.find_one({"chat_id":chat,})
25
  if not curr:
26
  with INSERTION_LOCK:
27
- self.insert_one({"chat_id":chat,"type":mode})
28
  return True
29
  return False
30
 
31
- def get_autojoin(self,chat):
32
- curr = self.find_one({"chat_id":chat})
33
  if not curr:
34
  return False
35
  else:
36
  return curr["type"]
37
 
38
- def update_join_type(self,chat,mode):
39
- curr = self.find_one({"chat_id":chat})
40
  if curr:
41
- self.update({"chat_id":chat},{"type":mode})
42
- return
43
  else:
44
  return
45
 
46
- def remove_autojoin(self,chat):
47
- curr = self.find_one({"chat_id":chat})
48
  if curr:
49
- self.delete_one({"chat_id":chat})
50
- return
 
15
  def __init__(self) -> None:
16
  super().__init__(self.db_name)
17
 
18
+ def load_autojoin(self, chat, mode="auto"):
19
  """
20
  type = auto or notify
21
  auto to auto accept join requests
22
  notify to notify the admins about the join requests
23
  """
24
+ curr = self.find_one({"chat_id": chat, })
25
  if not curr:
26
  with INSERTION_LOCK:
27
+ self.insert_one({"chat_id": chat, "type": mode})
28
  return True
29
  return False
30
 
31
+ def get_autojoin(self, chat):
32
+ curr = self.find_one({"chat_id": chat})
33
  if not curr:
34
  return False
35
  else:
36
  return curr["type"]
37
 
38
+ def update_join_type(self, chat, mode):
39
+ curr = self.find_one({"chat_id": chat})
40
  if curr:
41
+ self.update({"chat_id": chat}, {"type": mode})
42
+ return
43
  else:
44
  return
45
 
46
+ def remove_autojoin(self, chat):
47
+ curr = self.find_one({"chat_id": chat})
48
  if curr:
49
+ self.delete_one({"chat_id": chat})
50
+ return
Powers/database/blacklist_db.py CHANGED
@@ -110,13 +110,14 @@ class Blacklist(MongoDB):
110
  "reason": "Automated blacklisted word: {{}}",
111
  }
112
  self.insert_one(new_data)
113
- LOGGER.info(f"Initialized Blacklist Document for chat {self.chat_id}")
 
114
  return new_data
115
  return chat_data
116
 
117
  def clean_blacklist(self):
118
  with INSERTION_LOCK:
119
- return self.delete_one({"_id":self.chat_id})
120
 
121
  # Migrate if chat id changes!
122
  def migrate_chat(self, new_chat_id: int):
 
110
  "reason": "Automated blacklisted word: {{}}",
111
  }
112
  self.insert_one(new_data)
113
+ LOGGER.info(
114
+ f"Initialized Blacklist Document for chat {self.chat_id}")
115
  return new_data
116
  return chat_data
117
 
118
  def clean_blacklist(self):
119
  with INSERTION_LOCK:
120
+ return self.delete_one({"_id": self.chat_id})
121
 
122
  # Migrate if chat id changes!
123
  def migrate_chat(self, new_chat_id: int):
Powers/database/captcha_db.py CHANGED
@@ -13,15 +13,15 @@ class CAPTCHA(MongoDB):
13
  def __init__(self) -> None:
14
  super().__init__(self.db_name)
15
 
16
- def insert_captcha(self, chat, captcha_type:str="qr", captcha_action:str = "mute"):
17
  with INSERTION_LOCK:
18
  curr = self.is_captcha(chat)
19
  if not curr:
20
  self.insert_one(
21
  {
22
- "chat_id":chat,
23
- "captcha_type":captcha_type,
24
- "captcha_action":captcha_action
25
  }
26
  )
27
  return
@@ -36,29 +36,31 @@ class CAPTCHA(MongoDB):
36
  with INSERTION_LOCK:
37
  curr = self.is_captcha(chat)
38
  if curr:
39
- self.update({"chat_id":chat},{"captcha_type":captcha_type})
40
  return
41
 
42
  def update_action(self, chat, captcha_action):
43
  with INSERTION_LOCK:
44
  curr = self.is_captcha(chat)
45
  if curr:
46
- self.update({"chat_id":chat},{"captcha_action":captcha_action})
 
47
  return
48
-
49
  def remove_captcha(self, chat):
50
  with INSERTION_LOCK:
51
  curr = self.is_captcha(chat)
52
  if curr:
53
- self.delete_one({"chat_id":chat})
54
  return
55
 
56
  def get_captcha(self, chat):
57
- curr = self.find_one({"chat_id":chat})
58
  if curr:
59
  return curr
60
  return False
61
 
 
62
  class CAPTCHA_DATA(MongoDB):
63
  """class to store captcha data"""
64
  db_name = "captcha_data"
@@ -67,47 +69,49 @@ class CAPTCHA_DATA(MongoDB):
67
  super().__init__(self.db_name)
68
 
69
  def load_cap_data(self, chat, user, data):
70
- curr = self.find_one({"chat_id":chat,"user_id":user})
71
  if not curr:
72
  with INSERTION_LOCK:
73
- self.insert_one({"chat_id":chat,"user_id":user,"data":data})
 
74
  return True
75
  else:
76
  return
77
 
78
  def get_cap_data(self, chat, user):
79
- curr = self.find_one({"chat_id":chat,"user_id":user})
80
  if curr:
81
  return curr["data"]
82
  else:
83
  return False
84
 
85
  def remove_cap_data(self, chat, user):
86
- curr = self.find_one({"chat_id":chat,"user_id":user})
87
  if curr:
88
  with INSERTION_LOCK:
89
- self.delete_one({"chat_id":chat,"user_id":user})
90
  return
91
 
92
  def store_message_id(self, chat, user, message):
93
- curr = self.find_one({"chat_id":chat,"user_id":user})
94
  if not curr:
95
  with INSERTION_LOCK:
96
- self.insert_one({"chat_id":chat,"user_id":user,"message_id":message})
 
97
  return
98
  else:
99
- return
100
-
101
  def is_already_data(self, chat, user):
102
- curr = self.find_one({"chat_id":chat,"user_id":user})
103
  if curr:
104
  return curr["message_id"]
105
  else:
106
  return False
107
 
108
  def del_message_id(self, chat, user):
109
- curr = self.find_one({"chat_id":chat,"user_id":user})
110
  if curr:
111
  with INSERTION_LOCK:
112
- self.delete_one({"chat_id":chat,"user_id":user})
113
- return
 
13
  def __init__(self) -> None:
14
  super().__init__(self.db_name)
15
 
16
+ def insert_captcha(self, chat, captcha_type: str = "qr", captcha_action: str = "mute"):
17
  with INSERTION_LOCK:
18
  curr = self.is_captcha(chat)
19
  if not curr:
20
  self.insert_one(
21
  {
22
+ "chat_id": chat,
23
+ "captcha_type": captcha_type,
24
+ "captcha_action": captcha_action
25
  }
26
  )
27
  return
 
36
  with INSERTION_LOCK:
37
  curr = self.is_captcha(chat)
38
  if curr:
39
+ self.update({"chat_id": chat}, {"captcha_type": captcha_type})
40
  return
41
 
42
  def update_action(self, chat, captcha_action):
43
  with INSERTION_LOCK:
44
  curr = self.is_captcha(chat)
45
  if curr:
46
+ self.update({"chat_id": chat}, {
47
+ "captcha_action": captcha_action})
48
  return
49
+
50
  def remove_captcha(self, chat):
51
  with INSERTION_LOCK:
52
  curr = self.is_captcha(chat)
53
  if curr:
54
+ self.delete_one({"chat_id": chat})
55
  return
56
 
57
  def get_captcha(self, chat):
58
+ curr = self.find_one({"chat_id": chat})
59
  if curr:
60
  return curr
61
  return False
62
 
63
+
64
  class CAPTCHA_DATA(MongoDB):
65
  """class to store captcha data"""
66
  db_name = "captcha_data"
 
69
  super().__init__(self.db_name)
70
 
71
  def load_cap_data(self, chat, user, data):
72
+ curr = self.find_one({"chat_id": chat, "user_id": user})
73
  if not curr:
74
  with INSERTION_LOCK:
75
+ self.insert_one(
76
+ {"chat_id": chat, "user_id": user, "data": data})
77
  return True
78
  else:
79
  return
80
 
81
  def get_cap_data(self, chat, user):
82
+ curr = self.find_one({"chat_id": chat, "user_id": user})
83
  if curr:
84
  return curr["data"]
85
  else:
86
  return False
87
 
88
  def remove_cap_data(self, chat, user):
89
+ curr = self.find_one({"chat_id": chat, "user_id": user})
90
  if curr:
91
  with INSERTION_LOCK:
92
+ self.delete_one({"chat_id": chat, "user_id": user})
93
  return
94
 
95
  def store_message_id(self, chat, user, message):
96
+ curr = self.find_one({"chat_id": chat, "user_id": user})
97
  if not curr:
98
  with INSERTION_LOCK:
99
+ self.insert_one(
100
+ {"chat_id": chat, "user_id": user, "message_id": message})
101
  return
102
  else:
103
+ return
104
+
105
  def is_already_data(self, chat, user):
106
+ curr = self.find_one({"chat_id": chat, "user_id": user})
107
  if curr:
108
  return curr["message_id"]
109
  else:
110
  return False
111
 
112
  def del_message_id(self, chat, user):
113
+ curr = self.find_one({"chat_id": chat, "user_id": user})
114
  if curr:
115
  with INSERTION_LOCK:
116
+ self.delete_one({"chat_id": chat, "user_id": user})
117
+ return
Powers/database/disable_db.py CHANGED
@@ -146,9 +146,11 @@ class Disabling(MongoDB):
146
  "commands": [],
147
  "action": "none",
148
  }
149
- DISABLED_CMDS[self.chat_id] = {"commands": [], "action": "none"}
 
150
  self.insert_one(new_data)
151
- LOGGER.info(f"Initialized Disabling Document for chat {self.chat_id}")
 
152
  return new_data
153
  DISABLED_CMDS[self.chat_id] = chat_data
154
  return chat_data
@@ -163,7 +165,7 @@ class Disabling(MongoDB):
163
 
164
  def clean_disable(self):
165
  with INSERTION_LOCK:
166
- return self.delete_one({"_id":self.chat_id})
167
 
168
  @staticmethod
169
  def repair_db(collection):
 
146
  "commands": [],
147
  "action": "none",
148
  }
149
+ DISABLED_CMDS[self.chat_id] = {
150
+ "commands": [], "action": "none"}
151
  self.insert_one(new_data)
152
+ LOGGER.info(
153
+ f"Initialized Disabling Document for chat {self.chat_id}")
154
  return new_data
155
  DISABLED_CMDS[self.chat_id] = chat_data
156
  return chat_data
 
165
 
166
  def clean_disable(self):
167
  with INSERTION_LOCK:
168
+ return self.delete_one({"_id": self.chat_id})
169
 
170
  @staticmethod
171
  def repair_db(collection):
Powers/database/filters_db.py CHANGED
@@ -71,7 +71,8 @@ class Filters(MongoDB):
71
  curr = self.find_all()
72
  if curr:
73
  return len(
74
- [z for z in (i["keyword"].split("|") for i in curr) if len(z) >= 2],
 
75
  )
76
  return 0
77
 
 
71
  curr = self.find_all()
72
  if curr:
73
  return len(
74
+ [z for z in (i["keyword"].split("|")
75
+ for i in curr) if len(z) >= 2],
76
  )
77
  return 0
78
 
Powers/database/flood_db.py CHANGED
@@ -7,6 +7,7 @@ from Powers.utils.msg_types import Types
7
 
8
  INSERTION_LOCK = RLock()
9
 
 
10
  class Floods(MongoDB):
11
  """Class to store flood limit and action of a chat"""
12
  db_name = "flood"
@@ -24,7 +25,7 @@ class Floods(MongoDB):
24
  with INSERTION_LOCK:
25
  curr = self.find_one({"chat_id": chat_id})
26
  if curr:
27
- if not(limit == int(curr['limit']) and within == int(curr['within']) and action == str(curr['action'])):
28
  return self.update(
29
  {
30
  "chat_id": chat_id
@@ -36,37 +37,37 @@ class Floods(MongoDB):
36
  }
37
  )
38
  else:
39
- return
40
  else:
41
  return self.insert_one(
42
  {
43
- "chat_id" : chat_id,
44
  "limit": limit,
45
  "within": within,
46
- "action" : action
47
  },
48
  )
49
-
50
  def is_chat(self, chat_id: int):
51
  with INSERTION_LOCK:
52
  curr = self.find_one({"chat_id": chat_id})
53
  if curr:
54
- action = [str(curr['limit']), str(curr['within']), str(curr['action'])]
 
55
  return action
56
  return False
57
-
58
  def get_action(self, chat_id: int):
59
  with INSERTION_LOCK:
60
  curr = self.find_one({"chat_id": chat_id})
61
  if curr:
62
  return curr['action']
63
  return "Flood haven't set"
64
-
65
  def rm_flood(self, chat_id: int):
66
  with INSERTION_LOCK:
67
  curr = self.find_one({"chat_id": chat_id})
68
  if curr:
69
- self.delete_one({"chat_id":chat_id})
70
  return True
71
  return False
72
-
 
7
 
8
  INSERTION_LOCK = RLock()
9
 
10
+
11
  class Floods(MongoDB):
12
  """Class to store flood limit and action of a chat"""
13
  db_name = "flood"
 
25
  with INSERTION_LOCK:
26
  curr = self.find_one({"chat_id": chat_id})
27
  if curr:
28
+ if not (limit == int(curr['limit']) and within == int(curr['within']) and action == str(curr['action'])):
29
  return self.update(
30
  {
31
  "chat_id": chat_id
 
37
  }
38
  )
39
  else:
40
+ return
41
  else:
42
  return self.insert_one(
43
  {
44
+ "chat_id": chat_id,
45
  "limit": limit,
46
  "within": within,
47
+ "action": action
48
  },
49
  )
50
+
51
  def is_chat(self, chat_id: int):
52
  with INSERTION_LOCK:
53
  curr = self.find_one({"chat_id": chat_id})
54
  if curr:
55
+ action = [str(curr['limit']), str(
56
+ curr['within']), str(curr['action'])]
57
  return action
58
  return False
59
+
60
  def get_action(self, chat_id: int):
61
  with INSERTION_LOCK:
62
  curr = self.find_one({"chat_id": chat_id})
63
  if curr:
64
  return curr['action']
65
  return "Flood haven't set"
66
+
67
  def rm_flood(self, chat_id: int):
68
  with INSERTION_LOCK:
69
  curr = self.find_one({"chat_id": chat_id})
70
  if curr:
71
+ self.delete_one({"chat_id": chat_id})
72
  return True
73
  return False
 
Powers/database/greetings_db.py CHANGED
@@ -45,6 +45,7 @@ class Greetings(MongoDB):
45
  def get_welcome_media(self):
46
  with INSERTION_LOCK:
47
  return self.chat_info["welcome_media"]
 
48
  def get_welcome_msgtype(self):
49
  with INSERTION_LOCK:
50
  return self.chat_info["welcome_mtype"]
@@ -78,32 +79,32 @@ class Greetings(MongoDB):
78
  with INSERTION_LOCK:
79
  return self.update({"_id": self.chat_id}, {"goodbye": status})
80
 
81
- def set_welcome_text(self, welcome_text: str, mtype,media=None):
82
  with INSERTION_LOCK:
83
  self.update(
84
  {"_id": self.chat_id},
85
- {"welcome_text": welcome_text,"welcome_mtype":mtype},
86
  )
87
  if media:
88
  self.update(
89
  {"_id": self.chat_id},
90
- {"welcome_media": media,"welcome_mtype":mtype}
91
  )
92
 
93
- return
94
 
95
- def set_goodbye_text(self, goodbye_text: str,mtype,media=None):
96
  with INSERTION_LOCK:
97
  self.update(
98
  {"_id": self.chat_id},
99
- {"goodbye_text": goodbye_text,"goodbye_mtype":mtype},
100
  )
101
  if media:
102
  self.update(
103
  {"_id": self.chat_id},
104
- {"goodbye_media": media,"goodbye_mtype":mtype}
105
  )
106
- return
107
 
108
  def set_current_cleanservice_settings(self, status: bool):
109
  with INSERTION_LOCK:
@@ -154,13 +155,14 @@ class Greetings(MongoDB):
154
  "welcome_text": "Hey {first}, welcome to {chatname}!",
155
  "welcome": True,
156
  "goodbye": True,
157
- "welcome_media":False,
158
- "welcome_mtype":False,
159
- "goodbye_media":False,
160
- "goodbye_mtype":False
161
  }
162
  self.insert_one(new_data)
163
- LOGGER.info(f"Initialized Greetings Document for chat {self.chat_id}")
 
164
  return new_data
165
  return chat_data
166
 
@@ -173,7 +175,7 @@ class Greetings(MongoDB):
173
 
174
  def clean_greetings(self):
175
  with INSERTION_LOCK:
176
- return self.delete_one({"_id":self.chat_id})
177
 
178
  @staticmethod
179
  def count_chats(query: str):
 
45
  def get_welcome_media(self):
46
  with INSERTION_LOCK:
47
  return self.chat_info["welcome_media"]
48
+
49
  def get_welcome_msgtype(self):
50
  with INSERTION_LOCK:
51
  return self.chat_info["welcome_mtype"]
 
79
  with INSERTION_LOCK:
80
  return self.update({"_id": self.chat_id}, {"goodbye": status})
81
 
82
+ def set_welcome_text(self, welcome_text: str, mtype, media=None):
83
  with INSERTION_LOCK:
84
  self.update(
85
  {"_id": self.chat_id},
86
+ {"welcome_text": welcome_text, "welcome_mtype": mtype},
87
  )
88
  if media:
89
  self.update(
90
  {"_id": self.chat_id},
91
+ {"welcome_media": media, "welcome_mtype": mtype}
92
  )
93
 
94
+ return
95
 
96
+ def set_goodbye_text(self, goodbye_text: str, mtype, media=None):
97
  with INSERTION_LOCK:
98
  self.update(
99
  {"_id": self.chat_id},
100
+ {"goodbye_text": goodbye_text, "goodbye_mtype": mtype},
101
  )
102
  if media:
103
  self.update(
104
  {"_id": self.chat_id},
105
+ {"goodbye_media": media, "goodbye_mtype": mtype}
106
  )
107
+ return
108
 
109
  def set_current_cleanservice_settings(self, status: bool):
110
  with INSERTION_LOCK:
 
155
  "welcome_text": "Hey {first}, welcome to {chatname}!",
156
  "welcome": True,
157
  "goodbye": True,
158
+ "welcome_media": False,
159
+ "welcome_mtype": False,
160
+ "goodbye_media": False,
161
+ "goodbye_mtype": False
162
  }
163
  self.insert_one(new_data)
164
+ LOGGER.info(
165
+ f"Initialized Greetings Document for chat {self.chat_id}")
166
  return new_data
167
  return chat_data
168
 
 
175
 
176
  def clean_greetings(self):
177
  with INSERTION_LOCK:
178
+ return self.delete_one({"_id": self.chat_id})
179
 
180
  @staticmethod
181
  def count_chats(query: str):
Powers/database/locks_db.py CHANGED
@@ -5,10 +5,13 @@ from Powers.database import MongoDB
5
 
6
  INSERTION_LOCK = RLock()
7
 
8
- lock_t = ["bot", "anti_c_send", "anti_fwd", "anti_fwd_u", "anti_fwd_c", "anti_links"]
 
 
 
9
  class LOCKS(MongoDB):
10
  """Class to store locks"""
11
-
12
  db_name = "locks"
13
 
14
  def __init__(self) -> None:
@@ -20,21 +23,21 @@ class LOCKS(MongoDB):
20
  """
21
  if locktype == "all":
22
  for i in lock_t:
23
- curr = self.find_one({"chat_id":chat,"locktype":i})
24
- if curr:
25
- continue
26
- if i in ["anti_fwd_u", "anti_fwd_c"]:
27
- continue
28
- self.insert_one({"chat_id":chat,"locktype":i})
29
  return True
30
- curr = self.find_one({"chat_id":chat,"locktype":locktype})
31
  if curr:
32
  return False
33
  else:
34
  with INSERTION_LOCK:
35
- hmm = self.merge_u_and_c(chat,locktype)
36
  if not hmm:
37
- self.insert_one({"chat_id":chat,"locktype":locktype})
38
  return True
39
 
40
  def remove_lock_channel(self, chat: int, locktype: str):
@@ -43,40 +46,41 @@ class LOCKS(MongoDB):
43
  """
44
  if locktype == "all":
45
  for i in lock_t:
46
- curr = self.find_one({"chat_id":chat,"locktype":i})
47
- if curr:
48
- self.delete_one({"chat_id":chat,"locktype":i})
49
  return True
50
- curr = self.find_one({"chat_id":chat,"locktype":locktype})
51
  if curr:
52
  with INSERTION_LOCK:
53
- self.delete_one({"chat_id":chat,"locktype":locktype})
54
  return True
55
  else:
56
  return False
57
 
58
- def get_lock_channel(self, locktype: str="all", chat:int = 0):
59
  """
60
  locktypes: anti_c_send, anti_fwd, anti_fwd_u, anti_fwd_c, anti_links, bot
61
  """
62
- if locktype not in ["anti_c_send","anti_fwd","anti_fwd_u","anti_fwd_c","anti_links", "bot", "all"]:
63
  return False
64
  else:
65
  if locktype == "all":
66
  find = {}
67
  else:
68
- find = {"locktype":locktype}
69
  if chat:
70
  if find:
71
- curr = self.find_one({"chat_id":chat, "locktype":locktype})
 
72
  return bool(curr)
73
  else:
74
  to_return = []
75
  for i in lock_t:
76
- curr = self.find_one({"chat_id":chat, "locktype":i})
77
  to_return.append(bool(curr))
78
  return all(to_return)
79
- else:
80
  curr = self.find_all(find)
81
  if not curr:
82
  list_ = []
@@ -86,15 +90,15 @@ class LOCKS(MongoDB):
86
 
87
  def merge_u_and_c(self, chat: int, locktype: str):
88
  if locktype == "anti_fwd_u":
89
- curr = self.find_one({"chat_id":chat,"locktype":"anti_fwd_c"})
90
  elif locktype == "anti_fwd_c":
91
- curr = self.find_one({"chat_id":chat,"locktype":"anti_fwd_u"})
92
  else:
93
  return False
94
 
95
  if curr:
96
- self.delete_one({"chat_id":chat,"locktype":locktype})
97
- self.insert_one({"chat_id":chat,"locktype":"anti_fwd"})
98
  return True
99
  else:
100
  return False
@@ -103,9 +107,8 @@ class LOCKS(MongoDB):
103
  """
104
  locktypes: anti_c_send, anti_fwd, anti_fwd_u, anti_fwd_c, anti_links
105
  """
106
- curr = self.find_one({"chat_id":chat,"locktype":locktype})
107
  if curr:
108
  return True
109
  else:
110
  return False
111
-
 
5
 
6
  INSERTION_LOCK = RLock()
7
 
8
+ lock_t = ["bot", "anti_c_send", "anti_fwd",
9
+ "anti_fwd_u", "anti_fwd_c", "anti_links"]
10
+
11
+
12
  class LOCKS(MongoDB):
13
  """Class to store locks"""
14
+
15
  db_name = "locks"
16
 
17
  def __init__(self) -> None:
 
23
  """
24
  if locktype == "all":
25
  for i in lock_t:
26
+ curr = self.find_one({"chat_id": chat, "locktype": i})
27
+ if curr:
28
+ continue
29
+ if i in ["anti_fwd_u", "anti_fwd_c"]:
30
+ continue
31
+ self.insert_one({"chat_id": chat, "locktype": i})
32
  return True
33
+ curr = self.find_one({"chat_id": chat, "locktype": locktype})
34
  if curr:
35
  return False
36
  else:
37
  with INSERTION_LOCK:
38
+ hmm = self.merge_u_and_c(chat, locktype)
39
  if not hmm:
40
+ self.insert_one({"chat_id": chat, "locktype": locktype})
41
  return True
42
 
43
  def remove_lock_channel(self, chat: int, locktype: str):
 
46
  """
47
  if locktype == "all":
48
  for i in lock_t:
49
+ curr = self.find_one({"chat_id": chat, "locktype": i})
50
+ if curr:
51
+ self.delete_one({"chat_id": chat, "locktype": i})
52
  return True
53
+ curr = self.find_one({"chat_id": chat, "locktype": locktype})
54
  if curr:
55
  with INSERTION_LOCK:
56
+ self.delete_one({"chat_id": chat, "locktype": locktype})
57
  return True
58
  else:
59
  return False
60
 
61
+ def get_lock_channel(self, locktype: str = "all", chat: int = 0):
62
  """
63
  locktypes: anti_c_send, anti_fwd, anti_fwd_u, anti_fwd_c, anti_links, bot
64
  """
65
+ if locktype not in ["anti_c_send", "anti_fwd", "anti_fwd_u", "anti_fwd_c", "anti_links", "bot", "all"]:
66
  return False
67
  else:
68
  if locktype == "all":
69
  find = {}
70
  else:
71
+ find = {"locktype": locktype}
72
  if chat:
73
  if find:
74
+ curr = self.find_one(
75
+ {"chat_id": chat, "locktype": locktype})
76
  return bool(curr)
77
  else:
78
  to_return = []
79
  for i in lock_t:
80
+ curr = self.find_one({"chat_id": chat, "locktype": i})
81
  to_return.append(bool(curr))
82
  return all(to_return)
83
+ else:
84
  curr = self.find_all(find)
85
  if not curr:
86
  list_ = []
 
90
 
91
  def merge_u_and_c(self, chat: int, locktype: str):
92
  if locktype == "anti_fwd_u":
93
+ curr = self.find_one({"chat_id": chat, "locktype": "anti_fwd_c"})
94
  elif locktype == "anti_fwd_c":
95
+ curr = self.find_one({"chat_id": chat, "locktype": "anti_fwd_u"})
96
  else:
97
  return False
98
 
99
  if curr:
100
+ self.delete_one({"chat_id": chat, "locktype": locktype})
101
+ self.insert_one({"chat_id": chat, "locktype": "anti_fwd"})
102
  return True
103
  else:
104
  return False
 
107
  """
108
  locktypes: anti_c_send, anti_fwd, anti_fwd_u, anti_fwd_c, anti_links
109
  """
110
+ curr = self.find_one({"chat_id": chat, "locktype": locktype})
111
  if curr:
112
  return True
113
  else:
114
  return False
 
Powers/database/notes_db.py CHANGED
@@ -57,7 +57,8 @@ class Notes(MongoDB):
57
  def get_all_notes(self, chat_id: int):
58
  with INSERTION_LOCK:
59
  curr = self.find_all({"chat_id": chat_id})
60
- note_list = sorted([(note["note_name"], note["hash"]) for note in curr])
 
61
  return note_list
62
 
63
  def rm_note(self, chat_id: int, note_name: str):
@@ -124,9 +125,9 @@ class NotesSettings(MongoDB):
124
  self.update({"_id": chat_id}, {"privatenotes": False})
125
  return False
126
 
127
- def clean_notes(self,chat_id):
128
  with INSERTION_LOCK:
129
- return self.delete_one({"_id":chat_id})
130
 
131
  def list_chats(self):
132
  return self.find_all({"privatenotes": True})
 
57
  def get_all_notes(self, chat_id: int):
58
  with INSERTION_LOCK:
59
  curr = self.find_all({"chat_id": chat_id})
60
+ note_list = sorted([(note["note_name"], note["hash"])
61
+ for note in curr])
62
  return note_list
63
 
64
  def rm_note(self, chat_id: int, note_name: str):
 
125
  self.update({"_id": chat_id}, {"privatenotes": False})
126
  return False
127
 
128
+ def clean_notes(self, chat_id):
129
  with INSERTION_LOCK:
130
+ return self.delete_one({"_id": chat_id})
131
 
132
  def list_chats(self):
133
  return self.find_all({"privatenotes": True})
Powers/database/pins_db.py CHANGED
@@ -68,7 +68,7 @@ class Pins(MongoDB):
68
 
69
  def clean_pins(self):
70
  with INSERTION_LOCK:
71
- return self.delete_one({"_id":self.chat_id})
72
 
73
  # Migrate if chat id changes!
74
  def migrate_chat(self, new_chat_id: int):
 
68
 
69
  def clean_pins(self):
70
  with INSERTION_LOCK:
71
+ return self.delete_one({"_id": self.chat_id})
72
 
73
  # Migrate if chat id changes!
74
  def migrate_chat(self, new_chat_id: int):
Powers/database/reporting_db.py CHANGED
@@ -42,9 +42,11 @@ class Reporting(MongoDB):
42
  chat_data = self.find_one({"_id": self.chat_id})
43
  if not chat_data:
44
  chat_type = self.get_chat_type()
45
- new_data = {"_id": self.chat_id, "status": True, "chat_type": chat_type}
 
46
  self.insert_one(new_data)
47
- LOGGER.info(f"Initialized Language Document for chat {self.chat_id}")
 
48
  return new_data
49
  return chat_data
50
 
@@ -57,7 +59,7 @@ class Reporting(MongoDB):
57
 
58
  def clean_reporting(self):
59
  with INSERTION_LOCK:
60
- return self.delete_one({"_id":self.chat_id})
61
 
62
  @staticmethod
63
  def repair_db(collection):
 
42
  chat_data = self.find_one({"_id": self.chat_id})
43
  if not chat_data:
44
  chat_type = self.get_chat_type()
45
+ new_data = {"_id": self.chat_id,
46
+ "status": True, "chat_type": chat_type}
47
  self.insert_one(new_data)
48
+ LOGGER.info(
49
+ f"Initialized Language Document for chat {self.chat_id}")
50
  return new_data
51
  return chat_data
52
 
 
59
 
60
  def clean_reporting(self):
61
  with INSERTION_LOCK:
62
+ return self.delete_one({"_id": self.chat_id})
63
 
64
  @staticmethod
65
  def repair_db(collection):
Powers/database/rules_db.py CHANGED
@@ -68,7 +68,8 @@ class Rules(MongoDB):
68
  if not chat_data:
69
  new_data = {"_id": self.chat_id, "privrules": False, "rules": ""}
70
  self.insert_one(new_data)
71
- LOGGER.info(f"Initialized Language Document for chat {self.chat_id}")
 
72
  return new_data
73
  return chat_data
74
 
 
68
  if not chat_data:
69
  new_data = {"_id": self.chat_id, "privrules": False, "rules": ""}
70
  self.insert_one(new_data)
71
+ LOGGER.info(
72
+ f"Initialized Language Document for chat {self.chat_id}")
73
  return new_data
74
  return chat_data
75
 
Powers/database/support_db.py CHANGED
@@ -5,6 +5,7 @@ from Powers.database import MongoDB
5
 
6
  INSERTION_LOCK = RLock()
7
 
 
8
  class SUPPORTS(MongoDB):
9
  """
10
  class to store support users in database
@@ -12,7 +13,7 @@ class SUPPORTS(MongoDB):
12
  """
13
 
14
  db_name = "supports"
15
-
16
  def __init__(self) -> None:
17
  super().__init__(self.db_name)
18
 
@@ -22,49 +23,48 @@ class SUPPORTS(MongoDB):
22
  with INSERTION_LOCK:
23
  self.insert_one(
24
  {
25
- "user_id":user_id,
26
- "support_type":support_type
27
  }
28
  )
29
  return
30
 
31
- def update_support_user_type(self,user,new_type):
32
  curr = self.is_support_user(user)
33
  if curr:
34
  with INSERTION_LOCK:
35
  self.update(
36
  {
37
- "user_id":user
38
  },
39
  {
40
- "support_type":new_type
41
  }
42
  )
43
  return
44
 
45
-
46
  def is_support_user(self, user_id):
47
- curr = self.find_one({"user_id":user_id})
48
  if curr:
49
  return True
50
  return False
51
 
52
- def delete_support_user(self,user):
53
  curr = self.is_support_user(user)
54
  if curr:
55
  with INSERTION_LOCK:
56
- self.delete_one({"user_id":user})
57
  return
58
 
59
- def get_particular_support(self,support_type):
60
- curr = self.find_all({"support_type":support_type})
61
  if curr:
62
  return [i['user_id'] for i in curr]
63
  else:
64
  return []
65
 
66
- def get_support_type(self,user):
67
- curr = self.find_one({"user_id":user})
68
  if curr:
69
  return curr["support_type"]
70
- return False
 
5
 
6
  INSERTION_LOCK = RLock()
7
 
8
+
9
  class SUPPORTS(MongoDB):
10
  """
11
  class to store support users in database
 
13
  """
14
 
15
  db_name = "supports"
16
+
17
  def __init__(self) -> None:
18
  super().__init__(self.db_name)
19
 
 
23
  with INSERTION_LOCK:
24
  self.insert_one(
25
  {
26
+ "user_id": user_id,
27
+ "support_type": support_type
28
  }
29
  )
30
  return
31
 
32
+ def update_support_user_type(self, user, new_type):
33
  curr = self.is_support_user(user)
34
  if curr:
35
  with INSERTION_LOCK:
36
  self.update(
37
  {
38
+ "user_id": user
39
  },
40
  {
41
+ "support_type": new_type
42
  }
43
  )
44
  return
45
 
 
46
  def is_support_user(self, user_id):
47
+ curr = self.find_one({"user_id": user_id})
48
  if curr:
49
  return True
50
  return False
51
 
52
+ def delete_support_user(self, user):
53
  curr = self.is_support_user(user)
54
  if curr:
55
  with INSERTION_LOCK:
56
+ self.delete_one({"user_id": user})
57
  return
58
 
59
+ def get_particular_support(self, support_type):
60
+ curr = self.find_all({"support_type": support_type})
61
  if curr:
62
  return [i['user_id'] for i in curr]
63
  else:
64
  return []
65
 
66
+ def get_support_type(self, user):
67
+ curr = self.find_one({"user_id": user})
68
  if curr:
69
  return curr["support_type"]
70
+ return False
Powers/database/users_db.py CHANGED
@@ -67,7 +67,8 @@ class Users(MongoDB):
67
  def __ensure_in_db(self):
68
  chat_data = self.find_one({"_id": self.user_id})
69
  if not chat_data:
70
- new_data = {"_id": self.user_id, "username": "", "name": "unknown_till_now"}
 
71
  self.insert_one(new_data)
72
  LOGGER.info(f"Initialized User Document for {self.user_id}")
73
  return new_data
 
67
  def __ensure_in_db(self):
68
  chat_data = self.find_one({"_id": self.user_id})
69
  if not chat_data:
70
+ new_data = {"_id": self.user_id,
71
+ "username": "", "name": "unknown_till_now"}
72
  self.insert_one(new_data)
73
  LOGGER.info(f"Initialized User Document for {self.user_id}")
74
  return new_data
Powers/database/warns_db.py CHANGED
@@ -49,7 +49,7 @@ class Warns(MongoDB):
49
 
50
  def clean_warn(self):
51
  with INSERTION_LOCK:
52
- return self.delete_one({"chat_id":self.chat_id})
53
 
54
  def get_warns(self, user_id: int):
55
  with INSERTION_LOCK:
@@ -93,12 +93,14 @@ class Warns(MongoDB):
93
  f"Repairing Approve Database - setting '{key}:{val}' for {data['user_id']} in {data['chat_id']}",
94
  )
95
  collection.update(
96
- {"chat_id": data["chat_id"], "user_id": data["user_id"]},
 
97
  {key: val},
98
  )
99
 
100
  def __ensure_in_db(self, user_id: int):
101
- chat_data = self.find_one({"chat_id": self.chat_id, "user_id": user_id})
 
102
  if not chat_data:
103
  new_data = {
104
  "chat_id": self.chat_id,
@@ -107,7 +109,8 @@ class Warns(MongoDB):
107
  "num_warns": 0,
108
  }
109
  self.insert_one(new_data)
110
- LOGGER.info(f"Initialized Warn Document for {user_id} in {self.chat_id}")
 
111
  return new_data
112
  return chat_data
113
 
@@ -123,9 +126,11 @@ class WarnSettings(MongoDB):
123
  def __ensure_in_db(self):
124
  chat_data = self.find_one({"_id": self.chat_id})
125
  if not chat_data:
126
- new_data = {"_id": self.chat_id, "warn_mode": "none", "warn_limit": 3}
 
127
  self.insert_one(new_data)
128
- LOGGER.info(f"Initialized Warn Settings Document for {self.chat_id}")
 
129
  return new_data
130
  return chat_data
131
 
@@ -140,7 +145,7 @@ class WarnSettings(MongoDB):
140
 
141
  def clean_warns(self):
142
  with INSERTION_LOCK:
143
- return self.delete_one({"_id":self.chat_id})
144
 
145
  def get_warnmode(self):
146
  with INSERTION_LOCK:
 
49
 
50
  def clean_warn(self):
51
  with INSERTION_LOCK:
52
+ return self.delete_one({"chat_id": self.chat_id})
53
 
54
  def get_warns(self, user_id: int):
55
  with INSERTION_LOCK:
 
93
  f"Repairing Approve Database - setting '{key}:{val}' for {data['user_id']} in {data['chat_id']}",
94
  )
95
  collection.update(
96
+ {"chat_id": data["chat_id"],
97
+ "user_id": data["user_id"]},
98
  {key: val},
99
  )
100
 
101
  def __ensure_in_db(self, user_id: int):
102
+ chat_data = self.find_one(
103
+ {"chat_id": self.chat_id, "user_id": user_id})
104
  if not chat_data:
105
  new_data = {
106
  "chat_id": self.chat_id,
 
109
  "num_warns": 0,
110
  }
111
  self.insert_one(new_data)
112
+ LOGGER.info(
113
+ f"Initialized Warn Document for {user_id} in {self.chat_id}")
114
  return new_data
115
  return chat_data
116
 
 
126
  def __ensure_in_db(self):
127
  chat_data = self.find_one({"_id": self.chat_id})
128
  if not chat_data:
129
+ new_data = {"_id": self.chat_id,
130
+ "warn_mode": "none", "warn_limit": 3}
131
  self.insert_one(new_data)
132
+ LOGGER.info(
133
+ f"Initialized Warn Settings Document for {self.chat_id}")
134
  return new_data
135
  return chat_data
136
 
 
145
 
146
  def clean_warns(self):
147
  with INSERTION_LOCK:
148
+ return self.delete_one({"_id": self.chat_id})
149
 
150
  def get_warnmode(self):
151
  with INSERTION_LOCK:
Powers/plugins/__init__.py CHANGED
@@ -38,3 +38,4 @@ def till_date(date):
38
  form = "%Y-%m-%d %H:%M:%S"
39
  z = datetime.strptime(date,form)
40
  return z
 
 
38
  form = "%Y-%m-%d %H:%M:%S"
39
  z = datetime.strptime(date,form)
40
  return z
41
+
Powers/plugins/captcha.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from random import shuffle
2
+ from traceback import format_exc
3
+
4
+ import pyrogram
5
+ from pyrogram import filters
6
+ from pyrogram.types import CallbackQuery, ChatMemberUpdated, ChatPermissions
7
+ from pyrogram.types import InlineKeyboardButton as IKB
8
+ from pyrogram.types import InlineKeyboardMarkup as ikm
9
+ from pyrogram.types import Message
10
+
11
+ from Powers import LOGGER
12
+ from Powers.bot_class import Gojo
13
+ from Powers.database.captcha_db import CAPTCHA, CAPTCHA_DATA
14
+ from Powers.supports import get_support_staff
15
+ from Powers.utils.captcha_helper import (genrator, get_image_captcha,
16
+ get_qr_captcha)
17
+ from Powers.utils.custom_filters import admin_filter, command
18
+
19
+
20
+ @Gojo.on_message(command("captcha") & admin_filter & ~filters.private)
21
+ async def start_captcha(c: Gojo, m: Message):
22
+ captcha = CAPTCHA()
23
+ split = m.command
24
+ if len(split) == 1:
25
+ is_cap = captcha.is_captcha(m.chat.id)
26
+ if is_cap:
27
+ txt = "Captcha verification is currently **on** for this chat"
28
+ else:
29
+ txt = "Captcha verification is currently **off** for this chat"
30
+ await m.reply_text(txt)
31
+ return
32
+ else:
33
+ on_off = split[1].lower()
34
+ if on_off in ["on", "yes", "enable"]:
35
+ captcha.insert_captcha(m.chat.id)
36
+ await m.reply_text("Captcha verification is now **on** for this chat")
37
+ return
38
+ elif on_off in ["off", "no", "disable"]:
39
+ captcha.remove_captcha(m.chat.id)
40
+ await m.reply_text("Captcha verification is now **off** for this chat")
41
+ return
42
+ else:
43
+ await m.reply_text("**USAGE**\n/captcha [on | yes | enable | off | no | disable]")
44
+ return
45
+
46
+
47
+ @Gojo.on_message(command("captchamode") & admin_filter & ~filters.private)
48
+ async def set_captcha_mode(c: Gojo, m: Message):
49
+ split = m.command
50
+ captcha = CAPTCHA()
51
+ if len(split) == 1:
52
+ curr = captcha.get_captcha(m.chat.id)
53
+ if curr:
54
+ capatcha_type = curr["captcha_type"]
55
+ await m.reply_text(f"Current captcha verification methode is {capatcha_type}\nAvailable methodes:\n■ qr\n■ image")
56
+ return
57
+ else:
58
+ await m.reply_text("Captcha verification is off for the current chat")
59
+ return
60
+ else:
61
+ type_ = split[1].lower()
62
+ if type_ == "qr":
63
+ captcha.update_type(m.chat.id, "qr")
64
+ await m.reply_text("Captcha verification is now changed to qr code")
65
+ return
66
+ elif type_ == "image":
67
+ captcha.update_type(m.chat.id, "image")
68
+ await m.reply_text("Captcha verication is now changed to image")
69
+ return
70
+ else:
71
+ await m.reply_text("**USAGE**\n/captchamode [qr | image]")
72
+ return
73
+
74
+
75
+ @Gojo.on_callback_query(filters.regex("^captcha_"))
76
+ async def captcha_codes_check(c: Gojo, q: CallbackQuery):
77
+ split = q.data.split("_")
78
+ chat = int(split[1])
79
+ user = int(split[2])
80
+ code = split[3]
81
+
82
+ if q.from_user.id != user:
83
+ await q.answer("Not for you BAKA!")
84
+ return
85
+
86
+ c_data = CAPTCHA_DATA()
87
+ code_ = c_data.get_cap_data(chat, user)
88
+
89
+ if code_ == code:
90
+ cap = "You guessed the captcha right...Now you can talk in the chat with no restrictions"
91
+ c_data.remove_cap_data(chat, user)
92
+ await q.answer(cap, True)
93
+ try:
94
+ await q.message.chat.unban_member(user)
95
+ except Exception as e:
96
+ await q.message.reply_text(f"Unable to unmute {q.from_user.mention} this user")
97
+ await q.message.reply_text(e)
98
+ return
99
+ await c.send_message(chat, f"{q.from_user.mention} now you are free to talk")
100
+ await q.message.delete()
101
+ return
102
+ else:
103
+ caps = q.message.caption.split(":")
104
+ tries = int(caps[1].strip()) - 1
105
+ caps.pop(-1)
106
+ caps.append(f" {tries}")
107
+ new_cap = ":".join(caps)
108
+ await q.answer(f"Wrong\nTries left: {tries}", True)
109
+ if not tries:
110
+ new_cap = f"You have zero tries left now. I am going to kick you know coz you failed to solve captcha...see yaa {q.from_user.mention}"
111
+ try:
112
+ await q.message.chat.ban_member(user)
113
+ except Exception as e:
114
+ await q.message.reply_text("Failed to kick member")
115
+ return
116
+ await q.message.delete()
117
+ await q.message.reply_text(new_cap)
118
+ await c.unban_chat_member(chat, user)
119
+
120
+ else:
121
+ await q.edit_message_caption(new_cap, reply_markup=q.message.reply_markup)
122
+ return
123
+
124
+
125
+ @Gojo.on_chat_member_updated(filters.group, group=3)
126
+ async def on_chat_members_updatess(c: Gojo, u: ChatMemberUpdated):
127
+ chat = u.chat.id
128
+
129
+ if u.new_chat_member:
130
+
131
+ user = u.new_chat_member.user.id
132
+ userr = u.new_chat_member.user
133
+
134
+ is_qr = CAPTCHA().is_captcha(chat)
135
+ if not is_qr:
136
+ return
137
+
138
+ captcha = CAPTCHA()
139
+ cap_data = CAPTCHA_DATA()
140
+
141
+ SUPPORT_STAFF = get_support_staff()
142
+ if user in SUPPORT_STAFF:
143
+ return
144
+
145
+ captcha_type = captcha.get_captcha(chat)
146
+
147
+ is_already = cap_data.is_already_data(chat, user)
148
+
149
+ mess = False
150
+ try:
151
+ if is_already:
152
+ mess = await c.get_messages(chat, int(is_already))
153
+ except Exception:
154
+ cap_data.del_message_id(chat, is_already)
155
+ mess = False
156
+ is_already = False
157
+
158
+ if is_already and not mess:
159
+ cap_data.del_message_id(chat, is_already)
160
+ return
161
+
162
+ try:
163
+ await c.restrict_chat_member(chat, user, ChatPermissions())
164
+ except Exception as e:
165
+ LOGGER.error(e)
166
+ LOGGER.error(format_exc())
167
+ return
168
+
169
+ if not is_already:
170
+ if captcha_type == "qr":
171
+ pic = await get_qr_captcha(chat, user)
172
+ cap = f"Please {userr.mention} scan this qr code with your phone to verify that you are human"
173
+ ms = await c.send_photo(chat, pic, caption=cap)
174
+ cap_data.store_message_id(chat, user, ms.id)
175
+ return
176
+ elif captcha_type == "image":
177
+ img, code = await get_image_captcha(chat, user)
178
+ cap = f"Please {userr.mention} please choose the correct code from the one given bellow\nYou have three tries if you get all three wrong u will be kicked from the chat.\nTries left: 3"
179
+ cap_data.load_cap_data(chat, user, code)
180
+ rand = [code]
181
+ while len(rand) != 5:
182
+ hehe = genrator()
183
+ rand.append(hehe)
184
+
185
+ shuffle(rand)
186
+
187
+ ini = f"captcha_{chat}_{user}_"
188
+
189
+ kb = ikm(
190
+ [
191
+ [
192
+ IKB(rand[0], ini+rand[0])
193
+ ],
194
+ [
195
+ IKB(rand[1], ini+rand[1])
196
+ ],
197
+ [
198
+ IKB(rand[2], ini+rand[2])
199
+ ],
200
+ [
201
+ IKB(rand[3], ini+rand[3])
202
+ ],
203
+ [
204
+ IKB(rand[4], ini+rand[4])
205
+ ]
206
+ ]
207
+ )
208
+ await c.send_photo(chat, img, caption=cap, reply_markup=kb)
209
+ return
210
+ elif is_already and mess:
211
+ kb = ikm(
212
+ [
213
+ [
214
+ IKB("Click here to verify", url=mess.link)
215
+ ]
216
+ ]
217
+ )
218
+ await c.send_message(f"{userr.mention} your verification is already pending", reply_markup=kb)
219
+ return
220
+ else:
221
+ await c.unban_chat_member(chat, user)
222
+ return
223
+
224
+
225
+ __PLUGIN__ = "captcha"
226
+
227
+ __HELP__ = """
228
+ • /captcha [on|yes|enable|off|no|disable] : To enable or disable captcha verification
229
+ • /captchamode [qr|image] : To change captcha mode
230
+ """
Powers/plugins/formatting.py CHANGED
@@ -73,10 +73,12 @@ This will show button 1 and 2 on the same line, while 3 will be underneath."""
73
  parse_mode=enums.ParseMode.HTML,
74
  )
75
  except MediaCaptionTooLong:
 
76
  await c.send_message(
77
  chat_id=q.message.chat.id,
78
  text=txt,
79
- parse_mode=enums.ParseMode.HTML,)
 
80
  elif cmd == "fillings":
81
  await q.edit_message_caption(
82
  caption="""<b>Fillings</b>
 
73
  parse_mode=enums.ParseMode.HTML,
74
  )
75
  except MediaCaptionTooLong:
76
+ kb = ikb([[("Back", "DELETEEEE")]])
77
  await c.send_message(
78
  chat_id=q.message.chat.id,
79
  text=txt,
80
+ parse_mode=enums.ParseMode.HTML,
81
+ reply_markup=kb)
82
  elif cmd == "fillings":
83
  await q.edit_message_caption(
84
  caption="""<b>Fillings</b>
Powers/plugins/locks.py CHANGED
@@ -6,7 +6,7 @@ from pyrogram import filters
6
  from pyrogram.enums import MessageEntityType as MET
7
  from pyrogram.enums import MessageServiceType as MST
8
  from pyrogram.errors import ChatAdminRequired, ChatNotModified, RPCError
9
- from pyrogram.types import ChatPermissions, Message
10
 
11
  from Powers import LOGGER
12
  from Powers.bot_class import Gojo
@@ -15,6 +15,7 @@ from Powers.database.locks_db import LOCKS
15
  from Powers.supports import get_support_staff
16
  from Powers.utils.caching import ADMIN_CACHE, admin_cache_reload
17
  from Powers.utils.custom_filters import command, restrict_filter
 
18
  from Powers.vars import Config
19
 
20
  l_t = """
@@ -37,6 +38,7 @@ l_t = """
37
  - `forwardc` = Forwarding from channel
38
  - `links | url` = Lock links"""
39
 
 
40
  @Gojo.on_message(command("locktypes"))
41
  async def lock_types(_, m: Message):
42
  await m.reply_text(
@@ -73,7 +75,8 @@ async def lock_perm(c: Gojo, m: Message):
73
  try:
74
  await c.set_chat_permissions(chat_id, ChatPermissions())
75
  lock.insert_lock_channel(m.chat.id, "all")
76
- LOGGER.info(f"{m.from_user.id} locked all permissions in {m.chat.id}")
 
77
  except ChatNotModified:
78
  pass
79
  except ChatAdminRequired:
@@ -82,7 +85,6 @@ async def lock_perm(c: Gojo, m: Message):
82
  await prevent_approved(m)
83
  return
84
 
85
-
86
  if lock_type == "msg":
87
  msg = False
88
  perm = "messages"
@@ -127,7 +129,7 @@ async def lock_perm(c: Gojo, m: Message):
127
  pin = False
128
  perm = "pin"
129
  elif lock_type == "bot":
130
- curr = lock.insert_lock_channel(m.chat.id,"bot")
131
  if not curr:
132
  await m.reply_text("It is already on")
133
  return
@@ -141,28 +143,28 @@ async def lock_perm(c: Gojo, m: Message):
141
  await m.reply_text("Locked links in the chat")
142
  return
143
  elif lock_type == "anonchannel":
144
- curr = lock.insert_lock_channel(m.chat.id,"anti_c_send")
145
  if not curr:
146
  await m.reply_text("It is already on")
147
  return
148
  await m.reply_text("Locked Send As Chat")
149
  return
150
  elif lock_type == "forwardall":
151
- curr = lock.insert_lock_channel(m.chat.id,"anti_fwd")
152
  if not curr:
153
  await m.reply_text("It is already on")
154
  return
155
  await m.reply_text("Locked Forward from user as well as channel")
156
  return
157
  elif lock_type == "forwardu":
158
- curr = lock.insert_lock_channel(m.chat.id,"anti_fwd_u")
159
  if not curr:
160
  await m.reply_text("It is already on")
161
  return
162
  await m.reply_text("Locked Forward message from user")
163
  return
164
  elif lock_type == "forwardc":
165
- curr = lock.insert_lock_channel(m.chat.id,"anti_fwd_c")
166
  if not curr:
167
  await m.reply_text("It is already on")
168
  return
@@ -182,7 +184,8 @@ Use /locktypes to get the lock types"""
182
  ChatPermissions(
183
  can_send_messages=msg,
184
  can_send_media_messages=media,
185
- can_send_other_messages=any([stickers, animations, games, inlinebots]),
 
186
  can_add_web_page_previews=webprev,
187
  can_send_polls=polls,
188
  can_change_info=info,
@@ -190,7 +193,8 @@ Use /locktypes to get the lock types"""
190
  can_pin_messages=pin,
191
  ),
192
  )
193
- LOGGER.info(f"{m.from_user.id} locked selected permissions in {m.chat.id}")
 
194
  except ChatNotModified:
195
  pass
196
  except ChatAdminRequired:
@@ -211,9 +215,9 @@ async def view_locks(_, m: Message):
211
  if val:
212
  return "✅"
213
  return "❌"
214
-
215
  lock = LOCKS()
216
- anon= lock.get_lock_channel("anti_c_send", m.chat.id)
217
  anti_f = lock.get_lock_channel("anti_fwd", m.chat.id)
218
  anti_f_u = lock.get_lock_channel("anti_fwd_u", m.chat.id)
219
  anti_f_c = lock.get_lock_channel("anti_fwd_c", m.chat.id)
@@ -294,8 +298,9 @@ async def unlock_perm(c: Gojo, m: Message):
294
  can_pin_messages=True,
295
  ),
296
  )
297
- lock.remove_lock_channel(m.chat.id,"all")
298
- LOGGER.info(f"{m.from_user.id} unlocked all permissions in {m.chat.id}")
 
299
  except ChatNotModified:
300
  pass
301
  except ChatAdminRequired:
@@ -315,7 +320,6 @@ async def unlock_perm(c: Gojo, m: Message):
315
  upin = get_uperm.can_pin_messages
316
  ustickers = uanimations = ugames = uinlinebots = None
317
 
318
-
319
  if unlock_type == "msg":
320
  umsg = True
321
  uperm = "messages"
@@ -360,21 +364,21 @@ async def unlock_perm(c: Gojo, m: Message):
360
  upin = True
361
  uperm = "pin"
362
  elif unlock_type == "bot":
363
- curr = lock.remove_lock_channel(m.chat.id,"bot")
364
  if not curr:
365
  m.reply_text("User already can add bots in the chat")
366
  return
367
  await m.reply_text("User are now allowed to add bots in the chat.")
368
  elif unlock_type == "anonchannel":
369
- curr = lock.remove_lock_channel(m.chat.id,"anti_c_send")
370
-
371
  if not curr:
372
  await m.reply_text("Send as chat is not allowed in this chat")
373
  return
374
  await m.reply_text("Send as chat is now enabled for this chat")
375
  return
376
  elif unlock_type in ["links", "url"]:
377
- curr = lock.remove_lock_channel(m.chat.id,"anti_links")
378
  if curr:
379
  await m.reply_text("Sending link is now allowed")
380
  return
@@ -382,33 +386,33 @@ async def unlock_perm(c: Gojo, m: Message):
382
  await m.reply_text("Sending link is not allowed")
383
  return
384
  elif unlock_type == "forwardall":
385
- curr = lock.remove_lock_channel(m.chat.id,"anti_fwd")
386
-
387
  if not curr:
388
  await m.reply_text("Forwarding content is not allowed in this chat")
389
  return
390
  await m.reply_text("Forwarding content is now enabled for this chat")
391
  return
392
-
393
  elif unlock_type == "forwardu":
394
- curr = lock.remove_lock_channel(m.chat.id,"anti_fwd_u")
395
-
396
  if not curr:
397
  await m.reply_text("Forwarding content from users is not allowed in this chat")
398
  return
399
-
400
  await m.reply_text("Forwarding content from users is now enabled for this chat")
401
  return
402
-
403
  elif unlock_type == "forwardc":
404
- curr = lock.remove_lock_channel(m.chat.id,"anti_fwd_c")
405
-
406
  if not curr:
407
  await m.reply_text("Forwarding content from channel is not allowed in this chat")
408
  return
409
  await m.reply_text("Forwarding content from channel is now enabled for this chat")
410
  return
411
-
412
  else:
413
  await m.reply_text(
414
  text="""Invalid Lock Type!
@@ -418,7 +422,8 @@ async def unlock_perm(c: Gojo, m: Message):
418
  return
419
 
420
  try:
421
- LOGGER.info(f"{m.from_user.id} unlocked selected permissions in {m.chat.id}")
 
422
  await c.set_chat_permissions(
423
  chat_id,
424
  ChatPermissions(
@@ -444,7 +449,8 @@ async def unlock_perm(c: Gojo, m: Message):
444
  await prevent_approved(m)
445
  return
446
 
447
- async def delete_messages(c:Gojo, m: Message):
 
448
  try:
449
  await m.delete()
450
  return
@@ -453,14 +459,15 @@ async def delete_messages(c:Gojo, m: Message):
453
  LOGGER.error(format_exc())
454
  return
455
 
456
- async def is_approved_user(c:Gojo, m: Message):
 
457
  approved_users = Approve(m.chat.id).list_approved()
458
  ul = [user[0] for user in approved_users]
459
  try:
460
  admins_group = {i[0] for i in ADMIN_CACHE[m.chat.id]}
461
  except KeyError:
462
  admins_group = await admin_cache_reload(m, "lock")
463
-
464
  SUDO_LEVEL = get_support_staff("sudo_level")
465
 
466
  if m.forward_from:
@@ -480,28 +487,28 @@ async def is_approved_user(c:Gojo, m: Message):
480
  return True
481
  return False
482
 
 
483
  @Gojo.on_message(filters.service & filters.group, 19)
484
  async def servicess(c: Gojo, m: Message):
485
  if m.service != MST.NEW_CHAT_MEMBERS:
486
  return
487
- approved = await is_approved_user(c,m)
488
  if approved:
489
  return
490
  for i in m.new_chat_members:
491
  if i.is_bot:
492
  try:
493
  timee = datetime.now() + timedelta(minutes=5)
494
- await m.chat.ban_member(i.id,until_date=timee)
495
  sleep(1)
496
  except Exception as ef:
497
  LOGGER.error(ef)
498
  LOGGER.error(format_exc())
499
  return
500
-
501
 
502
 
503
- @Gojo.on_message(filters.group & ~filters.me,18)
504
- async def lock_del_mess(c:Gojo, m: Message):
505
  lock = LOCKS()
506
  all_chats = lock.get_lock_channel()
507
  if not all_chats:
@@ -511,28 +518,29 @@ async def lock_del_mess(c:Gojo, m: Message):
511
  if m.sender_chat and not (m.forward_from_chat or m.forward_from):
512
  if m.sender_chat.id == m.chat.id:
513
  return
514
- await delete_messages(c,m)
515
  return
516
- is_approved = await is_approved_user(c,m)
517
  if is_approved:
518
  return
519
  entity = m.entities if m.text else m.caption_entities
520
  if entity:
521
  for i in entity:
522
  if i.type in [MET.URL or MET.TEXT_LINK]:
523
- await delete_messages(c,m)
524
  return
525
  elif m.forward_from or m.forward_from_chat:
526
- if lock.is_particular_lock(m.chat.id,"anti_fwd"):
527
- await delete_messages(c,m)
528
  return
529
- elif lock.is_particular_lock(m.chat.id,"anti_fwd_u") and not m.forward_from_chat:
530
- await delete_messages(c,m)
531
  return
532
- elif lock.is_particular_lock(m.chat.id,"anti_fwd_c") and m.forward_from_chat:
533
- await delete_messages(c,m)
534
  return
535
 
 
536
  async def prevent_approved(m: Message):
537
  approved_users = Approve(m.chat.id).list_approved()
538
  ul = [user[0] for user in approved_users]
@@ -553,7 +561,7 @@ __alt_name__ = ["grouplock", "lock", "grouplocks"]
553
  __buttons__ = [
554
  [
555
  ("Lock Types", "LOCK_TYPES"),
556
- ],]
557
 
558
  __HELP__ = """
559
  **Locks**
@@ -569,3 +577,21 @@ Allows you to lock and unlock permission types in the chat.
569
 
570
  **Example:**
571
  `/lock media`: this locks all the media messages in the chat."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  from pyrogram.enums import MessageEntityType as MET
7
  from pyrogram.enums import MessageServiceType as MST
8
  from pyrogram.errors import ChatAdminRequired, ChatNotModified, RPCError
9
+ from pyrogram.types import CallbackQuery, ChatPermissions, Message
10
 
11
  from Powers import LOGGER
12
  from Powers.bot_class import Gojo
 
15
  from Powers.supports import get_support_staff
16
  from Powers.utils.caching import ADMIN_CACHE, admin_cache_reload
17
  from Powers.utils.custom_filters import command, restrict_filter
18
+ from Powers.utils.kbhelpers import ikb
19
  from Powers.vars import Config
20
 
21
  l_t = """
 
38
  - `forwardc` = Forwarding from channel
39
  - `links | url` = Lock links"""
40
 
41
+
42
  @Gojo.on_message(command("locktypes"))
43
  async def lock_types(_, m: Message):
44
  await m.reply_text(
 
75
  try:
76
  await c.set_chat_permissions(chat_id, ChatPermissions())
77
  lock.insert_lock_channel(m.chat.id, "all")
78
+ LOGGER.info(
79
+ f"{m.from_user.id} locked all permissions in {m.chat.id}")
80
  except ChatNotModified:
81
  pass
82
  except ChatAdminRequired:
 
85
  await prevent_approved(m)
86
  return
87
 
 
88
  if lock_type == "msg":
89
  msg = False
90
  perm = "messages"
 
129
  pin = False
130
  perm = "pin"
131
  elif lock_type == "bot":
132
+ curr = lock.insert_lock_channel(m.chat.id, "bot")
133
  if not curr:
134
  await m.reply_text("It is already on")
135
  return
 
143
  await m.reply_text("Locked links in the chat")
144
  return
145
  elif lock_type == "anonchannel":
146
+ curr = lock.insert_lock_channel(m.chat.id, "anti_c_send")
147
  if not curr:
148
  await m.reply_text("It is already on")
149
  return
150
  await m.reply_text("Locked Send As Chat")
151
  return
152
  elif lock_type == "forwardall":
153
+ curr = lock.insert_lock_channel(m.chat.id, "anti_fwd")
154
  if not curr:
155
  await m.reply_text("It is already on")
156
  return
157
  await m.reply_text("Locked Forward from user as well as channel")
158
  return
159
  elif lock_type == "forwardu":
160
+ curr = lock.insert_lock_channel(m.chat.id, "anti_fwd_u")
161
  if not curr:
162
  await m.reply_text("It is already on")
163
  return
164
  await m.reply_text("Locked Forward message from user")
165
  return
166
  elif lock_type == "forwardc":
167
+ curr = lock.insert_lock_channel(m.chat.id, "anti_fwd_c")
168
  if not curr:
169
  await m.reply_text("It is already on")
170
  return
 
184
  ChatPermissions(
185
  can_send_messages=msg,
186
  can_send_media_messages=media,
187
+ can_send_other_messages=any(
188
+ [stickers, animations, games, inlinebots]),
189
  can_add_web_page_previews=webprev,
190
  can_send_polls=polls,
191
  can_change_info=info,
 
193
  can_pin_messages=pin,
194
  ),
195
  )
196
+ LOGGER.info(
197
+ f"{m.from_user.id} locked selected permissions in {m.chat.id}")
198
  except ChatNotModified:
199
  pass
200
  except ChatAdminRequired:
 
215
  if val:
216
  return "✅"
217
  return "❌"
218
+
219
  lock = LOCKS()
220
+ anon = lock.get_lock_channel("anti_c_send", m.chat.id)
221
  anti_f = lock.get_lock_channel("anti_fwd", m.chat.id)
222
  anti_f_u = lock.get_lock_channel("anti_fwd_u", m.chat.id)
223
  anti_f_c = lock.get_lock_channel("anti_fwd_c", m.chat.id)
 
298
  can_pin_messages=True,
299
  ),
300
  )
301
+ lock.remove_lock_channel(m.chat.id, "all")
302
+ LOGGER.info(
303
+ f"{m.from_user.id} unlocked all permissions in {m.chat.id}")
304
  except ChatNotModified:
305
  pass
306
  except ChatAdminRequired:
 
320
  upin = get_uperm.can_pin_messages
321
  ustickers = uanimations = ugames = uinlinebots = None
322
 
 
323
  if unlock_type == "msg":
324
  umsg = True
325
  uperm = "messages"
 
364
  upin = True
365
  uperm = "pin"
366
  elif unlock_type == "bot":
367
+ curr = lock.remove_lock_channel(m.chat.id, "bot")
368
  if not curr:
369
  m.reply_text("User already can add bots in the chat")
370
  return
371
  await m.reply_text("User are now allowed to add bots in the chat.")
372
  elif unlock_type == "anonchannel":
373
+ curr = lock.remove_lock_channel(m.chat.id, "anti_c_send")
374
+
375
  if not curr:
376
  await m.reply_text("Send as chat is not allowed in this chat")
377
  return
378
  await m.reply_text("Send as chat is now enabled for this chat")
379
  return
380
  elif unlock_type in ["links", "url"]:
381
+ curr = lock.remove_lock_channel(m.chat.id, "anti_links")
382
  if curr:
383
  await m.reply_text("Sending link is now allowed")
384
  return
 
386
  await m.reply_text("Sending link is not allowed")
387
  return
388
  elif unlock_type == "forwardall":
389
+ curr = lock.remove_lock_channel(m.chat.id, "anti_fwd")
390
+
391
  if not curr:
392
  await m.reply_text("Forwarding content is not allowed in this chat")
393
  return
394
  await m.reply_text("Forwarding content is now enabled for this chat")
395
  return
396
+
397
  elif unlock_type == "forwardu":
398
+ curr = lock.remove_lock_channel(m.chat.id, "anti_fwd_u")
399
+
400
  if not curr:
401
  await m.reply_text("Forwarding content from users is not allowed in this chat")
402
  return
403
+
404
  await m.reply_text("Forwarding content from users is now enabled for this chat")
405
  return
406
+
407
  elif unlock_type == "forwardc":
408
+ curr = lock.remove_lock_channel(m.chat.id, "anti_fwd_c")
409
+
410
  if not curr:
411
  await m.reply_text("Forwarding content from channel is not allowed in this chat")
412
  return
413
  await m.reply_text("Forwarding content from channel is now enabled for this chat")
414
  return
415
+
416
  else:
417
  await m.reply_text(
418
  text="""Invalid Lock Type!
 
422
  return
423
 
424
  try:
425
+ LOGGER.info(
426
+ f"{m.from_user.id} unlocked selected permissions in {m.chat.id}")
427
  await c.set_chat_permissions(
428
  chat_id,
429
  ChatPermissions(
 
449
  await prevent_approved(m)
450
  return
451
 
452
+
453
+ async def delete_messages(c: Gojo, m: Message):
454
  try:
455
  await m.delete()
456
  return
 
459
  LOGGER.error(format_exc())
460
  return
461
 
462
+
463
+ async def is_approved_user(c: Gojo, m: Message):
464
  approved_users = Approve(m.chat.id).list_approved()
465
  ul = [user[0] for user in approved_users]
466
  try:
467
  admins_group = {i[0] for i in ADMIN_CACHE[m.chat.id]}
468
  except KeyError:
469
  admins_group = await admin_cache_reload(m, "lock")
470
+
471
  SUDO_LEVEL = get_support_staff("sudo_level")
472
 
473
  if m.forward_from:
 
487
  return True
488
  return False
489
 
490
+
491
  @Gojo.on_message(filters.service & filters.group, 19)
492
  async def servicess(c: Gojo, m: Message):
493
  if m.service != MST.NEW_CHAT_MEMBERS:
494
  return
495
+ approved = await is_approved_user(c, m)
496
  if approved:
497
  return
498
  for i in m.new_chat_members:
499
  if i.is_bot:
500
  try:
501
  timee = datetime.now() + timedelta(minutes=5)
502
+ await m.chat.ban_member(i.id, until_date=timee)
503
  sleep(1)
504
  except Exception as ef:
505
  LOGGER.error(ef)
506
  LOGGER.error(format_exc())
507
  return
 
508
 
509
 
510
+ @Gojo.on_message(filters.group & ~filters.me, 18)
511
+ async def lock_del_mess(c: Gojo, m: Message):
512
  lock = LOCKS()
513
  all_chats = lock.get_lock_channel()
514
  if not all_chats:
 
518
  if m.sender_chat and not (m.forward_from_chat or m.forward_from):
519
  if m.sender_chat.id == m.chat.id:
520
  return
521
+ await delete_messages(c, m)
522
  return
523
+ is_approved = await is_approved_user(c, m)
524
  if is_approved:
525
  return
526
  entity = m.entities if m.text else m.caption_entities
527
  if entity:
528
  for i in entity:
529
  if i.type in [MET.URL or MET.TEXT_LINK]:
530
+ await delete_messages(c, m)
531
  return
532
  elif m.forward_from or m.forward_from_chat:
533
+ if lock.is_particular_lock(m.chat.id, "anti_fwd"):
534
+ await delete_messages(c, m)
535
  return
536
+ elif lock.is_particular_lock(m.chat.id, "anti_fwd_u") and not m.forward_from_chat:
537
+ await delete_messages(c, m)
538
  return
539
+ elif lock.is_particular_lock(m.chat.id, "anti_fwd_c") and m.forward_from_chat:
540
+ await delete_messages(c, m)
541
  return
542
 
543
+
544
  async def prevent_approved(m: Message):
545
  approved_users = Approve(m.chat.id).list_approved()
546
  ul = [user[0] for user in approved_users]
 
561
  __buttons__ = [
562
  [
563
  ("Lock Types", "LOCK_TYPES"),
564
+ ], ]
565
 
566
  __HELP__ = """
567
  **Locks**
 
577
 
578
  **Example:**
579
  `/lock media`: this locks all the media messages in the chat."""
580
+
581
+
582
+ @Gojo.on_callback_query(filters.regex("^LOCK_TYPES"))
583
+ async def lock_types_callback(c: Gojo, q: CallbackQuery):
584
+ data = q.data
585
+
586
+ if data == "LOCK_TYPES":
587
+ kb = ikb([[("Back", "LOCK_TYPES_back")]])
588
+ await q.edit_message_caption(
589
+ l_t,
590
+ reply_markup=kb
591
+ )
592
+ else:
593
+ kb = ikb([[("Lock Types", "LOCK_TYPES")]])
594
+ await q.edit_message_caption(
595
+ __HELP__,
596
+ reply_markup=kb
597
+ )
Powers/plugins/muting.py CHANGED
@@ -634,14 +634,14 @@ async def unmutebutton(c: Gojo, q: CallbackQuery):
634
  user_id = int(splitter[1])
635
  user = await q.message.chat.get_member(q.from_user.id)
636
 
637
- if not user:
638
  await q.answer(
639
  "You don't have enough permission to do this!\nStay in your limits!",
640
  show_alert=True,
641
  )
642
  return
643
 
644
- if not user.privileges.can_restrict_members and user.id != OWNER_ID:
645
  await q.answer(
646
  "You don't have enough permission to do this!\nStay in your limits!",
647
  show_alert=True,
 
634
  user_id = int(splitter[1])
635
  user = await q.message.chat.get_member(q.from_user.id)
636
 
637
+ if not user or not user.privileges:
638
  await q.answer(
639
  "You don't have enough permission to do this!\nStay in your limits!",
640
  show_alert=True,
641
  )
642
  return
643
 
644
+ if not user.privileges.can_restrict_members:
645
  await q.answer(
646
  "You don't have enough permission to do this!\nStay in your limits!",
647
  show_alert=True,
Powers/plugins/start.py CHANGED
@@ -1,3 +1,4 @@
 
1
  from random import choice
2
  from time import gmtime, strftime, time
3
 
@@ -19,6 +20,7 @@ from Powers.utils.kbhelpers import ikb
19
  from Powers.utils.parser import mention_html
20
  from Powers.utils.start_utils import (gen_cmds_kb, gen_start_kb, get_help_msg,
21
  get_private_note, get_private_rules)
 
22
  from Powers.vars import Config
23
 
24
 
@@ -33,7 +35,7 @@ Your donation might also me get me a new feature or two, which I wasn't able to
33
 
34
  All the fund would be put into my services such as database, storage and hosting!
35
 
36
- You can donate by contacting my owner: [Captain Ezio](http://t.me/iamgojoof6eyes)
37
  """
38
 
39
  LOGGER.info(f"{m.from_user.id} fetched donation text in {m.chat.id}")
@@ -76,13 +78,14 @@ async def start(c: Gojo, m: Message):
76
  ):
77
  await get_private_note(c, m, help_option)
78
  return
79
-
80
  if help_option.startswith("rules"):
81
- LOGGER.info(f"{m.from_user.id} fetched privaterules in {m.chat.id}")
 
82
  await get_private_rules(c, m, help_option)
83
  return
84
 
85
- help_msg, help_kb = await get_help_msg(m, help_option)
86
 
87
  if not help_msg:
88
  return
@@ -95,7 +98,7 @@ async def start(c: Gojo, m: Message):
95
  quote=True,
96
  )
97
  return
98
- if len(help_option.split("_",1)) == 2:
99
  if help_option.split("_")[1] == "help":
100
  await m.reply_photo(
101
  photo=str(choice(StartPic)),
@@ -105,10 +108,28 @@ async def start(c: Gojo, m: Message):
105
  quote=True,
106
  )
107
  return
108
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  try:
110
  cpt = f"""
111
- Hey [{m.from_user.first_name}](http://t.me/{m.from_user.username})! I am Gojo ✨.
112
  I'm here to help you manage your group(s)!
113
  Hit /help to find out more about how to use me in my full potential!
114
 
@@ -123,31 +144,31 @@ Join my [News Channel](https://t.me/gojo_bots_network) to get information on all
123
  except UserIsBlocked:
124
  LOGGER.warning(f"Bot blocked by {m.from_user.id}")
125
  else:
126
- kb = InlineKeyboardMarkup(
127
- [
128
- [
129
- InlineKeyboardButton(
130
- "Connect me to pm",
131
- url=f"https://{Config.BOT_USERNAME}.t.me/",
132
- ),
133
- ],
134
- ],
135
- )
136
-
137
- await m.reply_photo(
138
- photo=str(choice(StartPic)),
139
- caption="I'm alive :3",
140
- reply_markup=kb,
141
- quote=True,
142
- )
143
  return
144
 
145
 
146
  @Gojo.on_callback_query(filters.regex("^start_back$"))
147
- async def start_back(_, q: CallbackQuery):
148
  try:
149
  cpt = f"""
150
- Hey [{q.from_user.first_name}](http://t.me/{q.from_user.username})! I am Gojo ✨.
151
  I'm here to help you manage your group(s)!
152
  Hit /help to find out more about how to use me in my full potential!
153
 
@@ -164,12 +185,12 @@ Join my [News Channel](http://t.me/gojo_bots_network) to get information on all
164
 
165
 
166
  @Gojo.on_callback_query(filters.regex("^commands$"))
167
- async def commands_menu(_, q: CallbackQuery):
168
  ou = await gen_cmds_kb(q.message)
169
  keyboard = ikb(ou, True)
170
  try:
171
  cpt = f"""
172
- Hey **[{q.from_user.first_name}](http://t.me/{q.from_user.username})**! I am Gojo✨.
173
  I'm here to help you manage your group(s)!
174
  Commands available:
175
  × /start: Start the bot
@@ -194,14 +215,15 @@ You can use `$` and `!` in placec of `/` as your prefix handler
194
 
195
 
196
  @Gojo.on_message(command("help"))
197
- async def help_menu(_, m: Message):
198
  if len(m.text.split()) >= 2:
199
- textt = m.text.replace(" ","_",).replace("_"," ",1)
200
  help_option = (textt.split(None)[1]).lower()
201
- help_msg, help_kb = await get_help_msg(m, help_option)
202
 
203
  if not help_msg:
204
- LOGGER.error(f"No help_msg found for help_option - {help_option}!!")
 
205
  return
206
 
207
  LOGGER.info(
@@ -226,14 +248,14 @@ async def help_menu(_, m: Message):
226
  photo=str(choice(StartPic)),
227
  caption=f"Press the button below to get help for <i>{help_option}</i>",
228
  reply_markup=InlineKeyboardMarkup(
229
- [
230
  [
231
- InlineKeyboardButton(
232
- "Help",
233
- url=f"t.me/{Config.BOT_USERNAME}?start={help_option}",
234
- ),
 
 
235
  ],
236
- ],
237
  ),
238
  )
239
  else:
@@ -242,21 +264,21 @@ async def help_menu(_, m: Message):
242
  ou = await gen_cmds_kb(m)
243
  keyboard = ikb(ou, True)
244
  msg = f"""
245
- Hey **[{m.from_user.first_name}](http://t.me/{m.from_user.username})**!I am Gojo✨.
246
  I'm here to help you manage your group(s)!
247
  Commands available:
248
  × /start: Start the bot
249
  × /help: Give's you this message."""
250
  else:
251
  keyboard = InlineKeyboardMarkup(
252
- [
253
  [
254
- InlineKeyboardButton(
255
- "Help",
256
- url=f"t.me/{Config.BOT_USERNAME}?start=start_help",
257
- ),
 
 
258
  ],
259
- ],
260
  )
261
  msg = "Contact me in PM to get the list of possible commands."
262
 
@@ -268,6 +290,7 @@ Commands available:
268
 
269
  return
270
 
 
271
  @Gojo.on_callback_query(filters.regex("^bot_curr_info$"))
272
  async def give_curr_info(c: Gojo, q: CallbackQuery):
273
  start = time()
@@ -285,6 +308,7 @@ async def give_curr_info(c: Gojo, q: CallbackQuery):
285
  await q.answer(txt, show_alert=True)
286
  return
287
 
 
288
  @Gojo.on_callback_query(filters.regex("^plugins."))
289
  async def get_module_info(c: Gojo, q: CallbackQuery):
290
  module = q.data.split(".", 1)[1]
@@ -293,19 +317,21 @@ async def get_module_info(c: Gojo, q: CallbackQuery):
293
 
294
  help_kb = HELP_COMMANDS[f"plugins.{module}"]["buttons"]
295
  try:
296
- await q.edit_message_caption(
297
- caption=help_msg,
298
- parse_mode=enums.ParseMode.MARKDOWN,
299
- reply_markup=ikb(help_kb, True, todo="commands"),
300
- )
301
  except MediaCaptionTooLong:
302
- await c.send_message(chat_id=q.message.chat.id,text=help_msg,)
 
303
  await q.answer()
304
  return
305
 
306
  DEV_USERS = get_support_staff("dev")
307
  SUDO_USERS = get_support_staff("sudo")
308
 
 
309
  @Gojo.on_callback_query(filters.regex("^give_bot_staffs$"))
310
  async def give_bot_staffs(c: Gojo, q: CallbackQuery):
311
  try:
@@ -349,6 +375,11 @@ async def give_bot_staffs(c: Gojo, q: CallbackQuery):
349
  except RPCError:
350
  pass
351
 
352
- await q.edit_message_caption(reply,reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("« Back","start_back")]]))
353
  return
354
 
 
 
 
 
 
 
1
+ import os
2
  from random import choice
3
  from time import gmtime, strftime, time
4
 
 
20
  from Powers.utils.parser import mention_html
21
  from Powers.utils.start_utils import (gen_cmds_kb, gen_start_kb, get_help_msg,
22
  get_private_note, get_private_rules)
23
+ from Powers.utils.string import encode_decode
24
  from Powers.vars import Config
25
 
26
 
 
35
 
36
  All the fund would be put into my services such as database, storage and hosting!
37
 
38
+ You can donate by contacting my owner: [Captain D. Ezio](http://t.me/iamgojoof6eyes)
39
  """
40
 
41
  LOGGER.info(f"{m.from_user.id} fetched donation text in {m.chat.id}")
 
78
  ):
79
  await get_private_note(c, m, help_option)
80
  return
81
+
82
  if help_option.startswith("rules"):
83
+ LOGGER.info(
84
+ f"{m.from_user.id} fetched privaterules in {m.chat.id}")
85
  await get_private_rules(c, m, help_option)
86
  return
87
 
88
+ help_msg, help_kb = await get_help_msg(c, m, help_option)
89
 
90
  if not help_msg:
91
  return
 
98
  quote=True,
99
  )
100
  return
101
+ if len(help_option.split("_", 1)) == 2:
102
  if help_option.split("_")[1] == "help":
103
  await m.reply_photo(
104
  photo=str(choice(StartPic)),
 
108
  quote=True,
109
  )
110
  return
111
+ elif help_option.split("_", 1)[0] == "qrcaptcha":
112
+ decoded = encode_decode(
113
+ help_option.split("_", 1)[1], "decode")
114
+ decode = decoded.split(":")
115
+ chat = decode[0]
116
+ user = decode[1]
117
+ if m.from_user.id != int(user):
118
+ await m.reply_text("Not for you Baka")
119
+ return
120
+ try:
121
+ await c.unban_chat_member(int(chat), int(user))
122
+ try:
123
+ os.remove(f"captcha_verification{chat}_{user}.png")
124
+ except Exception:
125
+ pass
126
+ return
127
+ except Exception:
128
+ return
129
+
130
  try:
131
  cpt = f"""
132
+ Hey [{m.from_user.first_name}](http://t.me/{m.from_user.username})! I am {c.me.first_name} ✨.
133
  I'm here to help you manage your group(s)!
134
  Hit /help to find out more about how to use me in my full potential!
135
 
 
144
  except UserIsBlocked:
145
  LOGGER.warning(f"Bot blocked by {m.from_user.id}")
146
  else:
147
+ kb = InlineKeyboardMarkup(
148
+ [
149
+ [
150
+ InlineKeyboardButton(
151
+ "Connect me to pm",
152
+ url=f"https://{Config.BOT_USERNAME}.t.me/",
153
+ ),
154
+ ],
155
+ ],
156
+ )
157
+
158
+ await m.reply_photo(
159
+ photo=str(choice(StartPic)),
160
+ caption="I'm alive :3",
161
+ reply_markup=kb,
162
+ quote=True,
163
+ )
164
  return
165
 
166
 
167
  @Gojo.on_callback_query(filters.regex("^start_back$"))
168
+ async def start_back(c: Gojo, q: CallbackQuery):
169
  try:
170
  cpt = f"""
171
+ Hey [{q.from_user.first_name}](http://t.me/{q.from_user.username})! I am {c.me.first_name} ✨.
172
  I'm here to help you manage your group(s)!
173
  Hit /help to find out more about how to use me in my full potential!
174
 
 
185
 
186
 
187
  @Gojo.on_callback_query(filters.regex("^commands$"))
188
+ async def commands_menu(c: Gojo, q: CallbackQuery):
189
  ou = await gen_cmds_kb(q.message)
190
  keyboard = ikb(ou, True)
191
  try:
192
  cpt = f"""
193
+ Hey **[{q.from_user.first_name}](http://t.me/{q.from_user.username})**! I am {c.me.first_name}✨.
194
  I'm here to help you manage your group(s)!
195
  Commands available:
196
  × /start: Start the bot
 
215
 
216
 
217
  @Gojo.on_message(command("help"))
218
+ async def help_menu(c: Gojo, m: Message):
219
  if len(m.text.split()) >= 2:
220
+ textt = m.text.replace(" ", "_",).replace("_", " ", 1)
221
  help_option = (textt.split(None)[1]).lower()
222
+ help_msg, help_kb = await get_help_msg(c, m, help_option)
223
 
224
  if not help_msg:
225
+ LOGGER.error(
226
+ f"No help_msg found for help_option - {help_option}!!")
227
  return
228
 
229
  LOGGER.info(
 
248
  photo=str(choice(StartPic)),
249
  caption=f"Press the button below to get help for <i>{help_option}</i>",
250
  reply_markup=InlineKeyboardMarkup(
 
251
  [
252
+ [
253
+ InlineKeyboardButton(
254
+ "Help",
255
+ url=f"t.me/{Config.BOT_USERNAME}?start={help_option}",
256
+ ),
257
+ ],
258
  ],
 
259
  ),
260
  )
261
  else:
 
264
  ou = await gen_cmds_kb(m)
265
  keyboard = ikb(ou, True)
266
  msg = f"""
267
+ Hey **[{m.from_user.first_name}](http://t.me/{m.from_user.username})**!I am {c.me.first_name}✨.
268
  I'm here to help you manage your group(s)!
269
  Commands available:
270
  × /start: Start the bot
271
  × /help: Give's you this message."""
272
  else:
273
  keyboard = InlineKeyboardMarkup(
 
274
  [
275
+ [
276
+ InlineKeyboardButton(
277
+ "Help",
278
+ url=f"t.me/{Config.BOT_USERNAME}?start=start_help",
279
+ ),
280
+ ],
281
  ],
 
282
  )
283
  msg = "Contact me in PM to get the list of possible commands."
284
 
 
290
 
291
  return
292
 
293
+
294
  @Gojo.on_callback_query(filters.regex("^bot_curr_info$"))
295
  async def give_curr_info(c: Gojo, q: CallbackQuery):
296
  start = time()
 
308
  await q.answer(txt, show_alert=True)
309
  return
310
 
311
+
312
  @Gojo.on_callback_query(filters.regex("^plugins."))
313
  async def get_module_info(c: Gojo, q: CallbackQuery):
314
  module = q.data.split(".", 1)[1]
 
317
 
318
  help_kb = HELP_COMMANDS[f"plugins.{module}"]["buttons"]
319
  try:
320
+ await q.edit_message_caption(
321
+ caption=help_msg,
322
+ parse_mode=enums.ParseMode.MARKDOWN,
323
+ reply_markup=ikb(help_kb, True, todo="commands"),
324
+ )
325
  except MediaCaptionTooLong:
326
+ kb = ikb([[("Back", "DELETEEEE")]])
327
+ await c.send_message(chat_id=q.message.chat.id, text=help_msg, reply_markup=kb)
328
  await q.answer()
329
  return
330
 
331
  DEV_USERS = get_support_staff("dev")
332
  SUDO_USERS = get_support_staff("sudo")
333
 
334
+
335
  @Gojo.on_callback_query(filters.regex("^give_bot_staffs$"))
336
  async def give_bot_staffs(c: Gojo, q: CallbackQuery):
337
  try:
 
375
  except RPCError:
376
  pass
377
 
378
+ await q.edit_message_caption(reply, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("« Back", "start_back")]]))
379
  return
380
 
381
+
382
+ @Gojo.on_callback_query(filters.regex("^DELETEEEE$"))
383
+ async def delete_back(_, q: CallbackQuery):
384
+ await q.message.delete()
385
+ return
Powers/supports.py CHANGED
@@ -5,14 +5,15 @@ from Powers.database.support_db import SUPPORTS
5
  async def load_support_users():
6
  support = SUPPORTS()
7
  for i in DEV_USERS:
8
- support.insert_support_user(int(i),"dev")
9
  for i in SUDO_USERS:
10
- support.insert_support_user(int(i),"sudo")
11
  for i in WHITELIST_USERS:
12
- support.insert_support_user(int(i),"whitelist")
13
  return
14
 
15
- def get_support_staff(want = "all"):
 
16
  """
17
  dev, sudo, whitelist, dev_level, sudo_level, all
18
  """
@@ -21,7 +22,7 @@ def get_support_staff(want = "all"):
21
  sudo = support.get_particular_support("sudo")
22
  whitelist = support.get_particular_support("whitelist")
23
 
24
- if want in ["dev","dev_level"]:
25
  wanted = devs
26
  elif want == "sudo":
27
  wanted = sudo
@@ -32,4 +33,4 @@ def get_support_staff(want = "all"):
32
  else:
33
  wanted = list(set([int(OWNER_ID)] + devs + sudo + whitelist))
34
 
35
- return wanted
 
5
  async def load_support_users():
6
  support = SUPPORTS()
7
  for i in DEV_USERS:
8
+ support.insert_support_user(int(i), "dev")
9
  for i in SUDO_USERS:
10
+ support.insert_support_user(int(i), "sudo")
11
  for i in WHITELIST_USERS:
12
+ support.insert_support_user(int(i), "whitelist")
13
  return
14
 
15
+
16
+ def get_support_staff(want="all"):
17
  """
18
  dev, sudo, whitelist, dev_level, sudo_level, all
19
  """
 
22
  sudo = support.get_particular_support("sudo")
23
  whitelist = support.get_particular_support("whitelist")
24
 
25
+ if want in ["dev", "dev_level"]:
26
  wanted = devs
27
  elif want == "sudo":
28
  wanted = sudo
 
33
  else:
34
  wanted = list(set([int(OWNER_ID)] + devs + sudo + whitelist))
35
 
36
+ return wanted
Powers/utils/caching.py CHANGED
@@ -14,7 +14,8 @@ THREAD_LOCK = RLock()
14
  # admins stay cached for 30 mins
15
  ADMIN_CACHE = TTLCache(maxsize=512, ttl=(60 * 30), timer=perf_counter)
16
  # Block from refreshing admin list for 10 mins
17
- TEMP_ADMIN_CACHE_BLOCK = TTLCache(maxsize=512, ttl=(60 * 10), timer=perf_counter)
 
18
 
19
 
20
  async def admin_cache_reload(m: Message or CallbackQuery, status=None) -> List[int]:
 
14
  # admins stay cached for 30 mins
15
  ADMIN_CACHE = TTLCache(maxsize=512, ttl=(60 * 30), timer=perf_counter)
16
  # Block from refreshing admin list for 10 mins
17
+ TEMP_ADMIN_CACHE_BLOCK = TTLCache(
18
+ maxsize=512, ttl=(60 * 10), timer=perf_counter)
19
 
20
 
21
  async def admin_cache_reload(m: Message or CallbackQuery, status=None) -> List[int]:
Powers/utils/captcha_helper.py CHANGED
@@ -12,7 +12,8 @@ from Powers.vars import Config
12
  initial = f"t.me/{Config.BOT_USERNAME}?start=qrcaptcha_"
13
  captchaa = CAPTCHA_DATA()
14
 
15
- async def get_qr_captcha(chat,user):
 
16
  encode = f"{chat}:{user}"
17
  encoded = encode_decode(encode)
18
  final = initial+encoded
@@ -21,11 +22,13 @@ async def get_qr_captcha(chat,user):
21
  qr.save(name)
22
  return name
23
 
 
24
  def genrator():
25
- alpha = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
 
26
  rand_alpha = choice(alpha)
27
- if_ = randint(0,1)
28
-
29
  if if_:
30
  new_alpha = rand_alpha.upper()
31
  else:
@@ -33,24 +36,23 @@ def genrator():
33
 
34
  list_ = [new_alpha]
35
  while len(list_) != 4:
36
- xXx = randrange(0,9)
37
  list_.append(xXx)
38
 
39
  str_ = ""
40
  while len(str_) != 4:
41
  OwO = choice(list_)
42
- str_ += OwO
43
  return str_
44
 
45
- async def get_image_captcha(chat,user):
 
46
  str_ = genrator()
47
- captchaa.load_cap_data(chat,user,str_)
48
  name = f"captcha_img_{chat}_{user}.png"
49
- image = ImageCaptcha(280,90)
50
 
51
  cap = image.generate(str_)
52
- image.write(str_,name)
53
 
54
  return name, str_
55
-
56
-
 
12
  initial = f"t.me/{Config.BOT_USERNAME}?start=qrcaptcha_"
13
  captchaa = CAPTCHA_DATA()
14
 
15
+
16
+ async def get_qr_captcha(chat, user):
17
  encode = f"{chat}:{user}"
18
  encoded = encode_decode(encode)
19
  final = initial+encoded
 
22
  qr.save(name)
23
  return name
24
 
25
+
26
  def genrator():
27
+ alpha = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
28
+ "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
29
  rand_alpha = choice(alpha)
30
+ if_ = randint(0, 1)
31
+
32
  if if_:
33
  new_alpha = rand_alpha.upper()
34
  else:
 
36
 
37
  list_ = [new_alpha]
38
  while len(list_) != 4:
39
+ xXx = randrange(0, 9)
40
  list_.append(xXx)
41
 
42
  str_ = ""
43
  while len(str_) != 4:
44
  OwO = choice(list_)
45
+ str_ += OwO
46
  return str_
47
 
48
+
49
+ async def get_image_captcha(chat, user):
50
  str_ = genrator()
51
+ captchaa.load_cap_data(chat, user, str_)
52
  name = f"captcha_img_{chat}_{user}.png"
53
+ image = ImageCaptcha(280, 90)
54
 
55
  cap = image.generate(str_)
56
+ image.write(str_, name)
57
 
58
  return name, str_
 
 
Powers/utils/custom_filters.py CHANGED
@@ -186,7 +186,7 @@ async def owner_check_func(_, __, m: Message or CallbackQuery):
186
 
187
  if m.chat.type not in [ChatType.SUPERGROUP, ChatType.GROUP]:
188
  return False
189
-
190
  if not m.from_user:
191
  return False
192
 
@@ -264,7 +264,6 @@ async def changeinfo_check_func(_, __, m):
264
  if m.sender_chat:
265
  return True
266
 
267
-
268
  user = await m.chat.get_member(m.from_user.id)
269
 
270
  if user.status in [CMS.ADMINISTRATOR, CMS.OWNER] and user.privileges.can_change_info:
@@ -304,16 +303,18 @@ async def can_pin_message_func(_, __, m):
304
 
305
  return status
306
 
 
307
  async def auto_join_check_filter(_, __, j: ChatJoinRequest):
308
  chat = j.chat.id
309
  aj = AUTOJOIN()
310
  join_type = aj.get_autojoin(chat)
311
-
312
  if not join_type:
313
  return False
314
  else:
315
  return True
316
 
 
317
  async def afk_check_filter(_, __, m: Message):
318
  if not m.from_user:
319
  return False
@@ -323,7 +324,7 @@ async def afk_check_filter(_, __, m: Message):
323
 
324
  if m.chat.type == ChatType.PRIVATE:
325
  return False
326
-
327
  afk = AFK()
328
  user = m.from_user.id
329
  chat = m.chat.id
@@ -334,16 +335,17 @@ async def afk_check_filter(_, __, m: Message):
334
  else:
335
  rep_user = False
336
 
337
- is_afk = afk.check_afk(chat,user)
338
  is_rep_afk = False
339
  if rep_user:
340
- is_rep_afk = afk.check_afk(chat,rep_user)
341
 
342
  if not is_rep_afk and not is_afk:
343
  return False
344
  else:
345
  return True
346
 
 
347
  async def flood_check_filter(_, __, m: Message):
348
  Flood = Floods()
349
  if not m.chat:
@@ -351,23 +353,23 @@ async def flood_check_filter(_, __, m: Message):
351
 
352
  if not m.from_user:
353
  return False
354
-
355
  if m.chat.type == ChatType.PRIVATE:
356
  return False
357
 
358
  u_id = m.from_user.id
359
  c_id = m.chat.id
360
  is_flood = Flood.is_chat(c_id)
361
-
362
  app_users = Approve(m.chat.id).list_approved()
363
  SUDO_LEVEL = set(SUDO_USERS + DEV_USERS + [int(OWNER_ID)])
364
-
365
  if not is_flood or u_id in SUDO_LEVEL:
366
  return False
367
-
368
  elif u_id in {i[0] for i in app_users}:
369
  return False
370
-
371
  else:
372
  return True
373
 
 
186
 
187
  if m.chat.type not in [ChatType.SUPERGROUP, ChatType.GROUP]:
188
  return False
189
+
190
  if not m.from_user:
191
  return False
192
 
 
264
  if m.sender_chat:
265
  return True
266
 
 
267
  user = await m.chat.get_member(m.from_user.id)
268
 
269
  if user.status in [CMS.ADMINISTRATOR, CMS.OWNER] and user.privileges.can_change_info:
 
303
 
304
  return status
305
 
306
+
307
  async def auto_join_check_filter(_, __, j: ChatJoinRequest):
308
  chat = j.chat.id
309
  aj = AUTOJOIN()
310
  join_type = aj.get_autojoin(chat)
311
+
312
  if not join_type:
313
  return False
314
  else:
315
  return True
316
 
317
+
318
  async def afk_check_filter(_, __, m: Message):
319
  if not m.from_user:
320
  return False
 
324
 
325
  if m.chat.type == ChatType.PRIVATE:
326
  return False
327
+
328
  afk = AFK()
329
  user = m.from_user.id
330
  chat = m.chat.id
 
335
  else:
336
  rep_user = False
337
 
338
+ is_afk = afk.check_afk(chat, user)
339
  is_rep_afk = False
340
  if rep_user:
341
+ is_rep_afk = afk.check_afk(chat, rep_user)
342
 
343
  if not is_rep_afk and not is_afk:
344
  return False
345
  else:
346
  return True
347
 
348
+
349
  async def flood_check_filter(_, __, m: Message):
350
  Flood = Floods()
351
  if not m.chat:
 
353
 
354
  if not m.from_user:
355
  return False
356
+
357
  if m.chat.type == ChatType.PRIVATE:
358
  return False
359
 
360
  u_id = m.from_user.id
361
  c_id = m.chat.id
362
  is_flood = Flood.is_chat(c_id)
363
+
364
  app_users = Approve(m.chat.id).list_approved()
365
  SUDO_LEVEL = set(SUDO_USERS + DEV_USERS + [int(OWNER_ID)])
366
+
367
  if not is_flood or u_id in SUDO_LEVEL:
368
  return False
369
+
370
  elif u_id in {i[0] for i in app_users}:
371
  return False
372
+
373
  else:
374
  return True
375
 
Powers/utils/extract_user.py CHANGED
@@ -30,7 +30,7 @@ async def extract_user(c: Gojo, m: Message) -> Tuple[int, str, str]:
30
  elif required_entity.type in (entity.MENTION, entity.PHONE_NUMBER):
31
  # new long user ids are identified as phone_number
32
  user_found = m.text[
33
- required_entity.offset : (
34
  required_entity.offset + required_entity.length
35
  )
36
  ]
 
30
  elif required_entity.type in (entity.MENTION, entity.PHONE_NUMBER):
31
  # new long user ids are identified as phone_number
32
  user_found = m.text[
33
+ required_entity.offset: (
34
  required_entity.offset + required_entity.length
35
  )
36
  ]
Powers/utils/extras.py CHANGED
@@ -514,7 +514,8 @@ TOSS = (
514
  )
515
 
516
 
517
- DECIDE = ("Yes.", "No.", "Maybe.", "Who the hell cares?", "No one give a damn about it")
 
518
 
519
  INSULT_STRINGS = [
520
  "`Owww ... Such a stupid idiot.`",
@@ -707,7 +708,7 @@ StartPic = [
707
  ]
708
 
709
 
710
- birthday_wish = [
711
  "Wishing you a happy birthday filled with love and joy.",
712
  "Hope your birthday is as wonderful as you are.",
713
  "Happy birthday to someone who deserves an exceptional day.",
@@ -783,4 +784,4 @@ birthday_wish = [
783
  "Happy birthday to someone who brings a smile to my face every day, may your day be as wonderful as you are.",
784
  "Sending you all my love and warmest wishes on your special day, may your year be filled with love and happiness.",
785
  "May your birthday be a time to appreciate all the people who make your life special, and cherish all the memories you've created.",
786
- "Wishing you a birthday that's as beautiful as you are, filled with joy and celebration.",]
 
514
  )
515
 
516
 
517
+ DECIDE = ("Yes.", "No.", "Maybe.", "Who the hell cares?",
518
+ "No one give a damn about it")
519
 
520
  INSULT_STRINGS = [
521
  "`Owww ... Such a stupid idiot.`",
 
708
  ]
709
 
710
 
711
+ birthday_wish = [
712
  "Wishing you a happy birthday filled with love and joy.",
713
  "Hope your birthday is as wonderful as you are.",
714
  "Happy birthday to someone who deserves an exceptional day.",
 
784
  "Happy birthday to someone who brings a smile to my face every day, may your day be as wonderful as you are.",
785
  "Sending you all my love and warmest wishes on your special day, may your year be filled with love and happiness.",
786
  "May your birthday be a time to appreciate all the people who make your life special, and cherish all the memories you've created.",
787
+ "Wishing you a birthday that's as beautiful as you are, filled with joy and celebration.", ]
Powers/utils/http_helper.py CHANGED
@@ -48,7 +48,7 @@ async def multipost(url: str, times: int, *args, **kwargs):
48
 
49
 
50
  def resp_get(url: str, *args, **kwargs):
51
- return requests.get(url, *args, **kwargs)
52
 
53
 
54
  def resp_post(url: str, *args, **kwargs):
 
48
 
49
 
50
  def resp_get(url: str, *args, **kwargs):
51
+ return requests.get(url, *args, **kwargs)
52
 
53
 
54
  def resp_post(url: str, *args, **kwargs):
Powers/utils/kbhelpers.py CHANGED
@@ -22,7 +22,8 @@ def ikb(rows=None, back=False, todo="start_back"):
22
  for row in rows:
23
  line = []
24
  for button in row:
25
- button = btn(*button) # Will make the kb which don't have "." in them
 
26
  line.append(button)
27
  lines.append(line)
28
  except TypeError:
@@ -32,7 +33,7 @@ def ikb(rows=None, back=False, todo="start_back"):
32
  button = btn(*button) # InlineKeyboardButton
33
  line.append(button)
34
  lines.append(line)
35
- if back:
36
  back_btn = [(btn("« Back", todo))]
37
  lines.append(back_btn)
38
  return InlineKeyboardMarkup(inline_keyboard=lines)
 
22
  for row in rows:
23
  line = []
24
  for button in row:
25
+ # Will make the kb which don't have "." in them
26
+ button = btn(*button)
27
  line.append(button)
28
  lines.append(line)
29
  except TypeError:
 
33
  button = btn(*button) # InlineKeyboardButton
34
  line.append(button)
35
  lines.append(line)
36
+ if back:
37
  back_btn = [(btn("« Back", todo))]
38
  lines.append(back_btn)
39
  return InlineKeyboardMarkup(inline_keyboard=lines)
Powers/utils/msg_types.py CHANGED
@@ -215,6 +215,7 @@ async def get_wlcm_type(m: Message):
215
 
216
  return text, data_type, content
217
 
 
218
  async def get_afk_type(m: Message):
219
  data_type = None
220
  content = None
 
215
 
216
  return text, data_type, content
217
 
218
+
219
  async def get_afk_type(m: Message):
220
  data_type = None
221
  content = None
Powers/utils/start_utils.py CHANGED
@@ -30,7 +30,7 @@ async def gen_cmds_kb(m: Message or CallbackQuery):
30
  cmds = sorted(list(HELP_COMMANDS.keys()))
31
  kb = [cmd.lower() for cmd in cmds]
32
 
33
- return [kb[i : i + 3] for i in range(0, len(kb), 3)]
34
 
35
 
36
  async def gen_start_kb(q: Message or CallbackQuery):
@@ -238,7 +238,7 @@ async def get_private_rules(_, m: Message, help_option: str):
238
  return ""
239
 
240
 
241
- async def get_help_msg(m: Message or CallbackQuery, help_option: str):
242
  """Helper function for getting help_msg and it's keyboard."""
243
  help_msg = None
244
  help_kb = None
@@ -266,12 +266,12 @@ async def get_help_msg(m: Message or CallbackQuery, help_option: str):
266
  f"{m.from_user.id} fetched help for {help_option} in {m.chat.id}",
267
  )
268
  else:
269
- if isinstance(m,CallbackQuery):
270
  mes = m.message
271
  else:
272
  mes = m
273
  help_msg = f"""
274
- Hey **[{mes.from_user.first_name}](http://t.me/{mes.from_user.username})**!I am Gojo✨.
275
  I'm here to help you manage your groups!
276
  Commands available:
277
  × /start: Start the bot
 
30
  cmds = sorted(list(HELP_COMMANDS.keys()))
31
  kb = [cmd.lower() for cmd in cmds]
32
 
33
+ return [kb[i: i + 3] for i in range(0, len(kb), 3)]
34
 
35
 
36
  async def gen_start_kb(q: Message or CallbackQuery):
 
238
  return ""
239
 
240
 
241
+ async def get_help_msg(c: Gojo, m: Message or CallbackQuery, help_option: str):
242
  """Helper function for getting help_msg and it's keyboard."""
243
  help_msg = None
244
  help_kb = None
 
266
  f"{m.from_user.id} fetched help for {help_option} in {m.chat.id}",
267
  )
268
  else:
269
+ if isinstance(m, CallbackQuery):
270
  mes = m.message
271
  else:
272
  mes = m
273
  help_msg = f"""
274
+ Hey **[{mes.from_user.first_name}](http://t.me/{mes.from_user.username})**!I am {c.me.first_name}✨.
275
  I'm here to help you manage your groups!
276
  Commands available:
277
  × /start: Start the bot
Powers/utils/sticker_help.py CHANGED
@@ -28,6 +28,7 @@ async def runcmd(cmd: str) -> Tuple[str, str, int, int]:
28
  process.pid,
29
  )
30
 
 
31
  async def get_sticker_set_by_name(
32
  client: Gojo, name: str
33
  ) -> raw.base.messages.StickerSet:
@@ -42,15 +43,14 @@ async def get_sticker_set_by_name(
42
  return None
43
 
44
 
45
-
46
  async def create_sticker_set(
47
  client: Gojo,
48
  owner: int,
49
  title: str,
50
  short_name: str,
51
  stickers: List[raw.base.InputStickerSetItem],
52
- animated:bool=False,
53
- video:bool=False
54
  ) -> raw.base.messages.StickerSet:
55
  return await client.invoke(
56
  raw.functions.stickers.CreateStickerSet(
@@ -85,11 +85,10 @@ async def create_sticker(
85
  return raw.types.InputStickerSetItem(document=sticker, emoji=emoji)
86
 
87
 
88
-
89
  STICKER_DIMENSIONS = (512, 512)
90
 
91
 
92
- async def resize_file_to_sticker_size(file_path: str,length:int=512,width:int=512) -> str:
93
  im = Image.open(file_path)
94
  if (im.width, im.height) < STICKER_DIMENSIONS:
95
  size1 = im.width
@@ -114,6 +113,7 @@ async def resize_file_to_sticker_size(file_path: str,length:int=512,width:int=51
114
  os.remove(file_path)
115
  return file_pathh
116
 
 
117
  async def tgs_to_gif(file, tgs=False, video=False):
118
  if tgs:
119
  cmd = f"lottie_convert.py '{file}' 'gojo_satoru.gif'"
@@ -123,12 +123,14 @@ async def tgs_to_gif(file, tgs=False, video=False):
123
  os.remove(file)
124
  return 'gojo_satoru.gif'
125
 
 
126
  async def webm_to_gif(file):
127
  cmd = f"ffmpeg -i '{file}' 'goJo.gif'"
128
  await runcmd(cmd)
129
  os.remove(file)
130
  return "goJo.gif"
131
-
 
132
  async def Vsticker(c: Gojo, file: Message):
133
  if file.animation:
134
  file = file.animation
@@ -155,7 +157,8 @@ async def upload_document(
155
  raw.functions.messages.UploadMedia(
156
  peer=await client.resolve_peer(chat_id),
157
  media=raw.types.InputMediaUploadedDocument(
158
- mime_type=client.guess_mime_type(file_path) or "application/zip",
 
159
  file=await client.save_file(file_path),
160
  attributes=[
161
  raw.types.DocumentAttributeFilename(
@@ -183,6 +186,7 @@ async def get_document_from_file_id(
183
  file_reference=decoded.file_reference,
184
  )
185
 
 
186
  async def remove_sticker(c: Gojo, stickerid: str) -> raw.base.messages.StickerSet:
187
  sticker = await get_document_from_file_id(stickerid)
188
  return await c.invoke(raw.functions.stickers.RemoveStickerFromSet(sticker=sticker))
@@ -237,7 +241,7 @@ async def draw_meme(image_path: str, text: str, sticker: bool, fiill: str) -> li
237
  stick_path = await resize_file_to_sticker_size(image_path)
238
 
239
  image1 = image_path
240
- image2 = tosticker(stick_path,f"@GojoSuperbot_{int(time())}.webp")
241
 
242
  image.save(image1)
243
  image.save(image2)
@@ -247,12 +251,10 @@ async def draw_meme(image_path: str, text: str, sticker: bool, fiill: str) -> li
247
  return [image1, image2]
248
 
249
 
250
-
251
-
252
  def toimage(image, filename=None, is_direc=False):
253
  filename = filename if filename else "gojo.jpg"
254
  if is_direc:
255
- os.rename(image,filename)
256
  return filename
257
  img = Image.open(image)
258
  if img.mode != "RGB":
@@ -265,11 +267,11 @@ def toimage(image, filename=None, is_direc=False):
265
  def tosticker(response, filename=None, is_direc=False):
266
  filename = filename if filename else "gojo.webp"
267
  if is_direc:
268
- os.rename(response,filename)
269
  return filename
270
  image = Image.open(response)
271
  if image.mode != "RGB":
272
  image.convert("RGB")
273
  image.save(filename, "webp")
274
  os.remove(response)
275
- return filename
 
28
  process.pid,
29
  )
30
 
31
+
32
  async def get_sticker_set_by_name(
33
  client: Gojo, name: str
34
  ) -> raw.base.messages.StickerSet:
 
43
  return None
44
 
45
 
 
46
  async def create_sticker_set(
47
  client: Gojo,
48
  owner: int,
49
  title: str,
50
  short_name: str,
51
  stickers: List[raw.base.InputStickerSetItem],
52
+ animated: bool = False,
53
+ video: bool = False
54
  ) -> raw.base.messages.StickerSet:
55
  return await client.invoke(
56
  raw.functions.stickers.CreateStickerSet(
 
85
  return raw.types.InputStickerSetItem(document=sticker, emoji=emoji)
86
 
87
 
 
88
  STICKER_DIMENSIONS = (512, 512)
89
 
90
 
91
+ async def resize_file_to_sticker_size(file_path: str, length: int = 512, width: int = 512) -> str:
92
  im = Image.open(file_path)
93
  if (im.width, im.height) < STICKER_DIMENSIONS:
94
  size1 = im.width
 
113
  os.remove(file_path)
114
  return file_pathh
115
 
116
+
117
  async def tgs_to_gif(file, tgs=False, video=False):
118
  if tgs:
119
  cmd = f"lottie_convert.py '{file}' 'gojo_satoru.gif'"
 
123
  os.remove(file)
124
  return 'gojo_satoru.gif'
125
 
126
+
127
  async def webm_to_gif(file):
128
  cmd = f"ffmpeg -i '{file}' 'goJo.gif'"
129
  await runcmd(cmd)
130
  os.remove(file)
131
  return "goJo.gif"
132
+
133
+
134
  async def Vsticker(c: Gojo, file: Message):
135
  if file.animation:
136
  file = file.animation
 
157
  raw.functions.messages.UploadMedia(
158
  peer=await client.resolve_peer(chat_id),
159
  media=raw.types.InputMediaUploadedDocument(
160
+ mime_type=client.guess_mime_type(
161
+ file_path) or "application/zip",
162
  file=await client.save_file(file_path),
163
  attributes=[
164
  raw.types.DocumentAttributeFilename(
 
186
  file_reference=decoded.file_reference,
187
  )
188
 
189
+
190
  async def remove_sticker(c: Gojo, stickerid: str) -> raw.base.messages.StickerSet:
191
  sticker = await get_document_from_file_id(stickerid)
192
  return await c.invoke(raw.functions.stickers.RemoveStickerFromSet(sticker=sticker))
 
241
  stick_path = await resize_file_to_sticker_size(image_path)
242
 
243
  image1 = image_path
244
+ image2 = tosticker(stick_path, f"@GojoSuperbot_{int(time())}.webp")
245
 
246
  image.save(image1)
247
  image.save(image2)
 
251
  return [image1, image2]
252
 
253
 
 
 
254
  def toimage(image, filename=None, is_direc=False):
255
  filename = filename if filename else "gojo.jpg"
256
  if is_direc:
257
+ os.rename(image, filename)
258
  return filename
259
  img = Image.open(image)
260
  if img.mode != "RGB":
 
267
  def tosticker(response, filename=None, is_direc=False):
268
  filename = filename if filename else "gojo.webp"
269
  if is_direc:
270
+ os.rename(response, filename)
271
  return filename
272
  image = Image.open(response)
273
  if image.mode != "RGB":
274
  image.convert("RGB")
275
  image.save(filename, "webp")
276
  os.remove(response)
277
+ return filename
Powers/utils/string.py CHANGED
@@ -1,3 +1,4 @@
 
1
  from datetime import datetime, timedelta
2
  from html import escape
3
  from re import compile as compile_re
@@ -9,7 +10,8 @@ from pyrogram.types import InlineKeyboardButton, Message
9
  from Powers import TIME_ZONE
10
  from Powers.utils.parser import escape_markdown
11
 
12
- BTN_URL_REGEX = compile_re(r"(\[([^\[]+?)\]\(buttonurl:(?:/{0,2})(.+?)(:same)?\))")
 
13
 
14
 
15
  async def extract_time(m: Message, time_val: str):
@@ -26,7 +28,7 @@ async def extract_time(m: Message, time_val: str):
26
  elif unit == "h":
27
  bantime = initial_time + timedelta(hours=int(time_num))
28
  elif unit == "d":
29
- bantime = initial_time + timedelta(days=int(time_num))
30
  else:
31
  # how even...?
32
  return ""
@@ -54,8 +56,9 @@ async def parse_button(text: str):
54
  # if even, not escaped -> create button
55
  if n_escapes % 2 == 0:
56
  # create a thruple with button label, url, and newline status
57
- buttons.append((match.group(2), match.group(3), bool(match.group(4))))
58
- note_data += markdown_note[prev : match.start(1)]
 
59
  prev = match.end(1)
60
  # if odd, escaped -> move along
61
  else:
@@ -98,7 +101,7 @@ async def escape_invalid_curly_brackets(text: str, valids: List[str]) -> str:
98
  success = True
99
  break
100
  if success:
101
- new_text += text[idx : idx + len(v) + 2]
102
  idx += len(v) + 2
103
  continue
104
  new_text += "{{"
@@ -173,7 +176,7 @@ async def split_quotes(text: str):
173
  # 1 to avoid starting quote, and counter is exclusive so avoids ending
174
  key = await remove_escapes(text[1:counter].strip())
175
  # index will be in range, or `else` would have been executed and returned
176
- rest = text[counter + 1 :].strip()
177
  if not key:
178
  key = text[0] + text[0]
179
  return list(filter(None, [key, rest]))
@@ -192,3 +195,25 @@ async def remove_escapes(text: str) -> str:
192
  else:
193
  res += text[counter]
194
  return res
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
  from datetime import datetime, timedelta
3
  from html import escape
4
  from re import compile as compile_re
 
10
  from Powers import TIME_ZONE
11
  from Powers.utils.parser import escape_markdown
12
 
13
+ BTN_URL_REGEX = compile_re(
14
+ r"(\[([^\[]+?)\]\(buttonurl:(?:/{0,2})(.+?)(:same)?\))")
15
 
16
 
17
  async def extract_time(m: Message, time_val: str):
 
28
  elif unit == "h":
29
  bantime = initial_time + timedelta(hours=int(time_num))
30
  elif unit == "d":
31
+ bantime = initial_time + timedelta(days=int(time_num))
32
  else:
33
  # how even...?
34
  return ""
 
56
  # if even, not escaped -> create button
57
  if n_escapes % 2 == 0:
58
  # create a thruple with button label, url, and newline status
59
+ buttons.append(
60
+ (match.group(2), match.group(3), bool(match.group(4))))
61
+ note_data += markdown_note[prev: match.start(1)]
62
  prev = match.end(1)
63
  # if odd, escaped -> move along
64
  else:
 
101
  success = True
102
  break
103
  if success:
104
+ new_text += text[idx: idx + len(v) + 2]
105
  idx += len(v) + 2
106
  continue
107
  new_text += "{{"
 
176
  # 1 to avoid starting quote, and counter is exclusive so avoids ending
177
  key = await remove_escapes(text[1:counter].strip())
178
  # index will be in range, or `else` would have been executed and returned
179
+ rest = text[counter + 1:].strip()
180
  if not key:
181
  key = text[0] + text[0]
182
  return list(filter(None, [key, rest]))
 
195
  else:
196
  res += text[counter]
197
  return res
198
+
199
+
200
+ async def encode_decode(string: str, to_do="encode"):
201
+ """
202
+ Function to encode or decode strings
203
+ string: string to be decoded or encoded
204
+ to_do: encode to encode the string or decode to decode the string
205
+ """
206
+ if to_do.lower() == "encode":
207
+ encodee = string.encode("ascii")
208
+ base64_ = base64.b64encode(encodee)
209
+ B64 = base64_.decode("ascii")
210
+
211
+ elif to_do.lower() == "decode":
212
+ decodee = string.encode("ascii")
213
+ base64_ = base64.b64decode(decodee)
214
+ B64 = base64_.decode("ascii")
215
+
216
+ else:
217
+ B64 = None
218
+
219
+ return B64
Powers/utils/web_helpers.py CHANGED
@@ -16,6 +16,7 @@ from Powers.utils.sticker_help import resize_file_to_sticker_size
16
 
17
  backUP = "https://artfiles.alphacoders.com/160/160160.jpeg"
18
 
 
19
  async def get_file_size(file: Message):
20
  if file.photo:
21
  size = file.photo.file_size/1024
@@ -33,7 +34,7 @@ async def get_file_size(file: Message):
33
  size = file.voice.file_size/1024
34
  elif file.video_note:
35
  size = file.video_note.file_size/1024
36
-
37
  if size <= 1024:
38
  return f"{round(size)} kb"
39
  elif size > 1024:
@@ -54,6 +55,8 @@ def get_duration_in_sec(dur: str):
54
  return dur
55
 
56
  # Gets yt result of given query.
 
 
57
  async def song_search(query, is_direct, max_results=1):
58
  yt_dict = {}
59
  try:
@@ -62,7 +65,7 @@ async def song_search(query, is_direct, max_results=1):
62
  query = vid["title"]
63
  else:
64
  query = query
65
- videos = VideosSearch(query,max_results)
66
  results = await videos.next()
67
  except Exception as e:
68
  LOGGER.error(e)
@@ -87,8 +90,8 @@ async def song_search(query, is_direct, max_results=1):
87
  "duration": i["accessibility"]['duration'],
88
  "DURATION": i["duration"],
89
  "published": i["publishedTime"],
90
- "uploader": i ["channel"]["name"]
91
- }
92
  try:
93
  thumb = {"thumbnail": i["richThumbnail"]["url"]}
94
  except Exception:
@@ -140,8 +143,7 @@ video_opts = {
140
  }"""
141
 
142
 
143
-
144
- async def youtube_downloader(c:Gojo,m:Message,query:str,is_direct:bool,type_:str):
145
  if type_ == "a":
146
  # opts = song_opts
147
  video = False
@@ -151,7 +153,7 @@ async def youtube_downloader(c:Gojo,m:Message,query:str,is_direct:bool,type_:str
151
  video = True
152
  song = False
153
  # ydl = yt_dlp.YoutubeDL(opts)
154
- dicti = await song_search(query, is_direct,1)
155
  if not dicti and type(dicti) != str:
156
  await m.reply_text("File with duration less than or equals to 10 minutes is allowed only")
157
  elif type(dicti) == str:
@@ -172,14 +174,14 @@ async def youtube_downloader(c:Gojo,m:Message,query:str,is_direct:bool,type_:str
172
  vid_dur = get_duration_in_sec(dicti["DURATION"])
173
  published_on = dicti["published"]
174
  if thumb:
175
- thumb_ = await c.send_photo(MESSAGE_DUMP,thumb)
176
  else:
177
- thumb_ = await c.send_photo(MESSAGE_DUMP,backUP)
178
  # FILE = ydl.extract_info(query,download=video)
179
  url = query
180
  thumb = await thumb_.download()
181
  if not thumb:
182
- thumb = await resize_file_to_sticker_size(thumb,320,320)
183
  await thumb_.delete()
184
  cap = f"""
185
  ⤷ Name: `{f_name}`
@@ -192,7 +194,7 @@ Downloaded by: @{c.me.username}
192
  kb = IKM(
193
  [
194
  [
195
- IKB(f"✘ {uploader.capitalize()} ✘",url=f"{up_url}")
196
  ],
197
  [
198
  IKB(f"✘ Youtube url ✘", url=f"{url}")
@@ -200,12 +202,12 @@ Downloaded by: @{c.me.username}
200
  ]
201
  )
202
  if song:
203
- audio_stream= yt.streams.filter(only_audio=True).first()
204
  f_path = audio_stream.download()
205
  # file_path = f"./youtube_downloads/{f_name.strip()}.mp3"
206
  file_path = f"./{f_name.strip()}.mp3"
207
- os.rename(f_path,file_path)
208
- await m.reply_audio(file_path,caption=cap,reply_markup=kb,duration=vid_dur,thumb=thumb,title=f_name)
209
  # os.remove(f_path)
210
  os.remove(file_path)
211
  os.remove(thumb)
@@ -214,7 +216,7 @@ Downloaded by: @{c.me.username}
214
  video_stream = yt.streams.get_highest_resolution()
215
  file_path = video_stream.download()
216
  # file_path = f"./youtube_downloads/{f_name}.mp4"
217
- await m.reply_video(file_path,caption=cap,reply_markup=kb,duration=vid_dur,thumb=thumb)
218
  os.remove(file_path)
219
  os.remove(thumb)
220
  return
 
16
 
17
  backUP = "https://artfiles.alphacoders.com/160/160160.jpeg"
18
 
19
+
20
  async def get_file_size(file: Message):
21
  if file.photo:
22
  size = file.photo.file_size/1024
 
34
  size = file.voice.file_size/1024
35
  elif file.video_note:
36
  size = file.video_note.file_size/1024
37
+
38
  if size <= 1024:
39
  return f"{round(size)} kb"
40
  elif size > 1024:
 
55
  return dur
56
 
57
  # Gets yt result of given query.
58
+
59
+
60
  async def song_search(query, is_direct, max_results=1):
61
  yt_dict = {}
62
  try:
 
65
  query = vid["title"]
66
  else:
67
  query = query
68
+ videos = VideosSearch(query, max_results)
69
  results = await videos.next()
70
  except Exception as e:
71
  LOGGER.error(e)
 
90
  "duration": i["accessibility"]['duration'],
91
  "DURATION": i["duration"],
92
  "published": i["publishedTime"],
93
+ "uploader": i["channel"]["name"]
94
+ }
95
  try:
96
  thumb = {"thumbnail": i["richThumbnail"]["url"]}
97
  except Exception:
 
143
  }"""
144
 
145
 
146
+ async def youtube_downloader(c: Gojo, m: Message, query: str, is_direct: bool, type_: str):
 
147
  if type_ == "a":
148
  # opts = song_opts
149
  video = False
 
153
  video = True
154
  song = False
155
  # ydl = yt_dlp.YoutubeDL(opts)
156
+ dicti = await song_search(query, is_direct, 1)
157
  if not dicti and type(dicti) != str:
158
  await m.reply_text("File with duration less than or equals to 10 minutes is allowed only")
159
  elif type(dicti) == str:
 
174
  vid_dur = get_duration_in_sec(dicti["DURATION"])
175
  published_on = dicti["published"]
176
  if thumb:
177
+ thumb_ = await c.send_photo(MESSAGE_DUMP, thumb)
178
  else:
179
+ thumb_ = await c.send_photo(MESSAGE_DUMP, backUP)
180
  # FILE = ydl.extract_info(query,download=video)
181
  url = query
182
  thumb = await thumb_.download()
183
  if not thumb:
184
+ thumb = await resize_file_to_sticker_size(thumb, 320, 320)
185
  await thumb_.delete()
186
  cap = f"""
187
  ⤷ Name: `{f_name}`
 
194
  kb = IKM(
195
  [
196
  [
197
+ IKB(f"✘ {uploader.capitalize()} ✘", url=f"{up_url}")
198
  ],
199
  [
200
  IKB(f"✘ Youtube url ✘", url=f"{url}")
 
202
  ]
203
  )
204
  if song:
205
+ audio_stream = yt.streams.filter(only_audio=True).first()
206
  f_path = audio_stream.download()
207
  # file_path = f"./youtube_downloads/{f_name.strip()}.mp3"
208
  file_path = f"./{f_name.strip()}.mp3"
209
+ os.rename(f_path, file_path)
210
+ await m.reply_audio(file_path, caption=cap, reply_markup=kb, duration=vid_dur, thumb=thumb, title=f_name)
211
  # os.remove(f_path)
212
  os.remove(file_path)
213
  os.remove(thumb)
 
216
  video_stream = yt.streams.get_highest_resolution()
217
  file_path = video_stream.download()
218
  # file_path = f"./youtube_downloads/{f_name}.mp4"
219
+ await m.reply_video(file_path, caption=cap, reply_markup=kb, duration=vid_dur, thumb=thumb)
220
  os.remove(file_path)
221
  os.remove(thumb)
222
  return
Powers/vars.py CHANGED
@@ -37,18 +37,18 @@ class Config:
37
  default="",
38
  ).split(None)
39
  ]
40
- GENIUS_API_TOKEN = config("GENIUS_API",default=None)
41
  # AuDD_API = config("AuDD_API",default=None)
42
- RMBG_API = config("RMBG_API",default=None)
43
  DB_URI = config("DB_URI", default="")
44
  DB_NAME = config("DB_NAME", default="gojo_satarou")
45
- BDB_URI = config("BDB_URI",default=None)
46
  NO_LOAD = config("NO_LOAD", default="").split()
47
  PREFIX_HANDLER = config("PREFIX_HANDLER", default="/").split()
48
  SUPPORT_GROUP = config("SUPPORT_GROUP", default="gojo_bots_network")
49
  SUPPORT_CHANNEL = config("SUPPORT_CHANNEL", default="gojo_bots_network")
50
  WORKERS = int(config("WORKERS", default=16))
51
- TIME_ZONE = config("TIME_ZONE",default='Asia/Kolkata')
52
  BOT_USERNAME = ""
53
  BOT_ID = ""
54
  BOT_NAME = ""
@@ -73,7 +73,7 @@ class Development:
73
  NO_LOAD = []
74
  GENIUS_API_TOKEN = ""
75
  RMBG_API = ""
76
- PREFIX_HANDLER = ["!", "/","$"]
77
  SUPPORT_GROUP = "SUPPORT_GROUP"
78
  SUPPORT_CHANNEL = "SUPPORT_CHANNEL"
79
  VERSION = "VERSION"
 
37
  default="",
38
  ).split(None)
39
  ]
40
+ GENIUS_API_TOKEN = config("GENIUS_API", default=None)
41
  # AuDD_API = config("AuDD_API",default=None)
42
+ RMBG_API = config("RMBG_API", default=None)
43
  DB_URI = config("DB_URI", default="")
44
  DB_NAME = config("DB_NAME", default="gojo_satarou")
45
+ BDB_URI = config("BDB_URI", default=None)
46
  NO_LOAD = config("NO_LOAD", default="").split()
47
  PREFIX_HANDLER = config("PREFIX_HANDLER", default="/").split()
48
  SUPPORT_GROUP = config("SUPPORT_GROUP", default="gojo_bots_network")
49
  SUPPORT_CHANNEL = config("SUPPORT_CHANNEL", default="gojo_bots_network")
50
  WORKERS = int(config("WORKERS", default=16))
51
+ TIME_ZONE = config("TIME_ZONE", default='Asia/Kolkata')
52
  BOT_USERNAME = ""
53
  BOT_ID = ""
54
  BOT_NAME = ""
 
73
  NO_LOAD = []
74
  GENIUS_API_TOKEN = ""
75
  RMBG_API = ""
76
+ PREFIX_HANDLER = ["!", "/", "$"]
77
  SUPPORT_GROUP = "SUPPORT_GROUP"
78
  SUPPORT_CHANNEL = "SUPPORT_CHANNEL"
79
  VERSION = "VERSION"