Sfoglia il codice sorgente

Global Stats And Gbans

* Added global stats module

* Added Global bans

* Many other fixes
Akshay Rajput 5 anni fa
parent
commit
1e8bd827c9
4 ha cambiato i file con 245 aggiunte e 76 eliminazioni
  1. 61 20
      wbb/modules/global_stats.py
  2. 5 3
      wbb/modules/greetings.py
  3. 81 2
      wbb/modules/sudoers.py
  4. 98 51
      wbb/utils/dbfunctions.py

+ 61 - 20
wbb/modules/global_stats.py

@@ -2,17 +2,21 @@ from wbb import app
 from wbb.utils.filter_groups import global_stats_group
 from wbb.utils.errors import capture_err
 from wbb.utils.botinfo import BOT_ID, BOT_NAME
+from wbb.utils.fetch import fetch
 from wbb.utils.dbfunctions import (
         is_served_chat,
         get_served_chats,
         add_served_chat,
         remove_served_chat,
-        alpha_to_int_chat
+        get_notes_count,
+        get_filters_count,
+        get_warns_count,
+        get_karmas_count,
+        get_gbans_count
         )
-from pyrogram.errors.exceptions.bad_request_400 import UserNotParticipant
 from pyrogram import filters
 
-@app.on_message(filters.new_chat_members & filters.left_chat_member, group=global_stats_group)
+@app.on_message(filters.text, group=global_stats_group)
 @capture_err
 async def chat_watcher(_, message):
     chat_id = message.chat.id
@@ -21,32 +25,69 @@ async def chat_watcher(_, message):
     await add_served_chat(chat_id)
 
 
-@app.on_message(filters.command("global_stats") & ~filters.edited)
-@capture_err
 async def global_stats(_, message):
-    m = await app.send_message(message.chat.id, text="__**Analysing Stats, Might Take 10-30 Seconds.**__")
+    m = await app.send_message(
+            message.chat.id,
+            text="__**Analysing Stats, Might Take 10-30 Seconds.**__",
+            disable_web_page_preview=True
+            )
+    
+    ## For bot served chat and users count
+
     served_chats = []
     total_users = 0
     chats = await get_served_chats()
-    for chat in chats:
-        served_chats.append(await alpha_to_int_chat(chat))
+    for chat in chats: served_chats.append(chat["chat_id"])
     for served_chat in served_chats:
-        try:
-            await app.get_chat_member(served_chat, BOT_ID)
-        except UserNotParticipant:
+        try: await app.get_chat_member(served_chat, BOT_ID)
+        except Exception:
             await remove_served_chat(served_chat)
             served_chats.remove(served_chat)
             pass
     for i in served_chats:
-        total_users += int((await app.get_chat(i)).members_count)
+        mc = (await app.get_chat(i)).members_count
+        total_users += int(mc)
+    
+    # Gbans count
+    gbans = await get_gbans_count()
+    ## Notes count across chats
+    _notes = await get_notes_count()
+    notes_count = _notes["notes_count"]
+    notes_chats_count = _notes["chats_count"]
+
+    # Filters count across chats
+    _filters = await get_filters_count()
+    filters_count = _filters["filters_count"]
+    filters_chats_count = _filters["chats_count"]
+    
+    # Warns count across chats
+    _warns = await get_warns_count()
+    warns_count = _warns["warns_count"]
+    warns_chats_count = _warns["chats_count"]
+
+    # Karmas count across chats
+    _karmas = await get_karmas_count()
+    karmas_count = _karmas["karmas_count"]
+    karmas_chats_count = _karmas["chats_count"]
+
+    # Contributors/Developers count and commits on github
+    url = "https://api.github.com/repos/thehamkercat/williambutcherbot/contributors"
+    rurl = "https://github.com/thehamkercat/williambutcherbot"
+    developers = await fetch(url)
+    commits = 0
+    for developer in developers:
+        commits += developer['contributions']
+    developers = len(developers)
+
     # NOTE need to fix these
     msg = f"""**Global Stats of {BOT_NAME}**:
-0 gbanned users.                           
-0 blacklist triggers, across 0 chats.
-0 filters, across 0 chats.
-0 notes, across 0 chats.
-0 welcome messages are set.
-{total_users} users, across {len(served_chats)} chats.
-0 warns, across 0 chats."""
-    await m.edit(msg)
+**{gbans}** Globally banned users.
+**{total_users}** Users, Across **{len(served_chats)}** chats.
+**{filters_count}** Filters, Across **{filters_chats_count}** chats.
+**{notes_count}** Notes, Across **{notes_chats_count}** chats.
+**{warns_count}** Warns, Across **{warns_chats_count}** chats.
+**{karmas_count}** Karma, Across **{karmas_chats_count}** chats.
+**{developers}** Developers And **{commits}** Commits On **[Github]({rurl})**."""
+
+    await m.edit(msg, disable_web_page_preview=True)
 

+ 5 - 3
wbb/modules/greetings.py

@@ -17,6 +17,7 @@ from wbb.modules.admin import list_admins
 from pyrogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton, ChatPermissions, User
 from pyrogram.errors.exceptions.bad_request_400 import UserNotParticipant
 from wbb.utils.errors import capture_err
+from wbb.utils.dbfunctions import is_gbanned_user
 
 
 @app.on_message(filters.new_chat_members)
@@ -24,9 +25,10 @@ from wbb.utils.errors import capture_err
 async def welcome(_, message: Message):
     """Mute new member and send message with button"""
     for member in message.new_chat_members:
-        if member.is_bot:
-            continue  # ignore bots
-
+        if member.is_bot: continue  # ignore bots
+        if await is_gbanned_user(member.id):
+            await message.chat.kick_member(member.id)
+            continue
         text = (f"Welcome, {(member.mention())}\n**Are you human?**\n"
                 "You will be removed from this chat if you are not verified "
                 f"in {WELCOME_DELAY_KICK_SEC} seconds")

+ 81 - 2
wbb/modules/sudoers.py

@@ -3,16 +3,24 @@ import time
 from pyrogram import filters, types
 import speedtest
 import psutil
-from wbb.utils import nekobin, formatter
 from wbb import app, SUDOERS, bot_start_time
+from wbb.utils import nekobin, formatter
 from wbb.utils.errors import capture_err
+from wbb.utils.botinfo import BOT_ID
+from wbb.modules.global_stats import global_stats
+from wbb.utils.dbfunctions import (
+        is_gbanned_user,
+        add_gban_user,
+        remove_gban_user,
+        get_served_chats)
 
 
 __MODULE__ = "Sudoers"
 __HELP__ = '''/log - To Get Logs From Last Run.
 /speedtest - To Perform A Speedtest.
 /stats - To Check System Status.
-/song - To Download Songs From JioSaavn'''
+/global_stats - To Check Bot's Global Stats.
+/gban - To Ban A User Globally.'''
 
 
 # Logs Module
@@ -105,3 +113,74 @@ CPU: {cpu}%
 RAM: {mem}%
 Disk: {disk}%```''')
     await message.reply_text(stats)
+
+# Global Stats
+
+
+@app.on_message(
+        filters.command("global_stats") & filters.user(SUDOERS)
+        & ~filters.edited
+        )
+@capture_err
+async def g_stats(_, message):
+    await global_stats(_, message)
+
+# Gban
+
+
+@app.on_message(filters.command("gban") & filters.user(SUDOERS))
+@capture_err
+async def ban_globally(_, message):
+    if not message.reply_to_message:
+        await message.reply_to_message("Reply to a user's message to Gban.")
+        return
+    from_user_id = message.from_user.id
+    user_id = message.reply_to_message.from_user.id
+    mention = message.reply_to_message.from_user.mention
+    from_user_mention = message.from_user.mention
+    if user_id == from_user_id:
+        await message.reply_text("You want to gban yourself? FOOL!")
+    elif user_id == BOT_ID:
+        await message.reply_text("Should i gban myself? I'm not fool like you, HUMAN!")
+    elif user_id in SUDOERS:
+        await message.reply_text("You want to ban a sudo user? GET REKT!!")
+    else:
+        is_gbanned = is_gbanned_user(user_id)
+        if is_gbanned:
+            await message.reply_text("He's already gbanned, why bully him?")
+        else:
+            served_chats = await get_served_chats()
+            for served_chat in served_chats:
+                try: await app.kick_chat_member(served_chat, user_id)
+                except Exception: pass
+            await add_gban_user(user_id)
+            try: await app.send_message(
+            user_id, """Hello, You have been globally banned by {from_user_mention},
+You can appeal for this ban by talking to {from_user_mention} about this.""")
+            except Exception: pass
+            await message.reply_text(f"Banned {mention} Globally!")
+
+# Ungban
+
+@app.on_message(filters.command("ungban") & filters.user(SUDOERS))
+@capture_err
+async def unban_globally(_, message):
+    if not message.reply_to_message:
+        await message.reply_to_message("Reply to a user's message to ungban.")
+        return
+    from_user_id = message.from_user.id
+    user_id = message.reply_to_message.from_user.id
+    mention = message.reply_to_message.from_user.mention
+    if user_id == from_user_id:
+        await message.reply_text("You want to ungban yourself? FOOL!")
+    elif user_id == BOT_ID:
+        await message.reply_text("Should i ungban myself? But i'm not gbanned.")
+    elif user_id in SUDOERS:
+        await message.reply_text("Sudo users can't be gbanned/ungbanned.")
+    else:
+        is_gbanned = is_gbanned_user(user_id)
+        if not is_gbanned:
+            await message.reply_text("He's already free, why bully him?")
+        else:
+            await remove_gban_user(user_id)
+            await message.reply_text(f"Unbanned {mention} Globally!")

+ 98 - 51
wbb/utils/dbfunctions.py

@@ -6,12 +6,26 @@ notesdb = db.notes
 filtersdb = db.filters
 warnsdb = db.warns
 karmadb = db.karma
-usersdb = db.users
 chatsdb = db.chats
-
+gbansdb = db.gban
 
 """ Notes functions """
 
+async def get_notes_count() -> dict:
+    chats = notesdb.find({"chat_id": {"$lt": 0}})
+    if not chats: return {}
+    chats_count = 0
+    notes_count = 0
+    for chat in await chats.to_list(length=1000000000):
+        notes_name = await get_note_names(chat['chat_id'])
+        notes_count += len(notes_name)
+        chats_count += 1
+    return {
+            "chats_count": chats_count,
+            "notes_count": notes_count
+            }
+
+
 
 async def _get_notes(chat_id: int) -> Dict[str, int]:
     _notes = await notesdb.find_one({"chat_id": chat_id})
@@ -75,6 +89,22 @@ async def delete_note(chat_id: int, name: str) -> bool:
 """ Filters funcions """
 
 
+async def get_filters_count() -> dict:
+    chats = filtersdb.find({"chat_id": {"$lt": 0}})
+    if not chats: return {}
+    chats_count = 0
+    filters_count = 0
+    for chat in await chats.to_list(length=1000000000):
+        filters_name = await get_filters_names(chat['chat_id'])
+        filters_count += len(filters_name)
+        chats_count += 1
+    return {
+            "chats_count": chats_count,
+            "filters_count": filters_count
+            }
+
+
+
 async def _get_filters(chat_id: int) -> Dict[str, int]:
     _filters = await filtersdb.find_one({"chat_id": chat_id})
     if _filters:
@@ -144,14 +174,6 @@ async def int_to_alpha(user_id: int) -> str:
         text += alphabet[int(i)]
     return text
 
-async def int_to_alpha_chat(chat_id: int) -> str:
-    alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
-    text = ""
-    chat_id = str(chat_id)
-    chat_id = chat_id.replace("-", "")
-    for i in chat_id:
-        text += alphabet[int(i)]
-    return text
 
 async def alpha_to_int(user_id_alphabet: str) -> int:
     alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
@@ -163,15 +185,19 @@ async def alpha_to_int(user_id_alphabet: str) -> int:
     return user_id
 
 
-async def alpha_to_int_chat(chat_id_alphabet: str) -> int:
-    alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
-    chat_id = "-"
-    for i in chat_id_alphabet:
-        index = alphabet.index(i)
-        chat_id += str(index)
-    chat_id = int(chat_id)
-    return chat_id
-
+async def get_warns_count() -> dict:
+    chats = warnsdb.find({"chat_id": {"$lt": 0}})
+    if not chats: return {}
+    chats_count = 0
+    warns_count = 0
+    for chat in await chats.to_list(length=100000000):
+        for user in chat['warns']:
+            warns_count += chat['warns'][user]['warns']
+        chats_count += 1
+    return {
+            "chats_count": chats_count,
+            "warns_count": warns_count
+            }
 
 async def get_warns(chat_id: int) -> Dict[str, int]:
     warns = await warnsdb.find_one({"chat_id": chat_id})
@@ -225,6 +251,19 @@ async def remove_warns(chat_id: int, name: str) -> bool:
 
 """ Karma functions """
 
+async def get_karmas_count() -> dict:
+    chats = karmadb.find({"chat_id": {"$lt": 0}})
+    if not chats: return {}
+    chats_count = 0
+    karmas_count = 0
+    for chat in await chats.to_list(length=1000000):
+        for i in chat['karma']:
+            karmas_count += chat['karma'][i]['karma']
+        chats_count += 1
+    return {
+            "chats_count": chats_count,
+            "karmas_count": karmas_count
+            }
 
 async def get_karmas(chat_id: int) -> Dict[str, int]:
     karma = await karmadb.find_one({"chat_id": chat_id})
@@ -260,46 +299,54 @@ async def update_karma(chat_id: int, name: str, karma: dict):
 """ Chats log functions """
 
 async def is_served_chat(chat_id: int) -> bool:
-    chats = await chatsdb.find_one({"chats": "chats"})
-    if not chats: return False
-    chats = chats['chats']
-    for chat in chats:
-        if chat == await int_to_alpha_chat(chat_id): return True
+    chat = await chatsdb.find_one({"chat_id": chat_id})
+    if not chat: return False
+    return True
 
 
-async def get_served_chats():
-    chats = await chatsdb.find_one({"chats": "chats"})
-    if not chats: return {}
-    chats = chats['chats']
-    return chats
+async def get_served_chats() -> list:
+    chats = chatsdb.find({"chat_id": {'$lt': 0}})
+    if not chats: return []
+    chats_list = []
+    for chat in await chats.to_list(length=1000000000):
+        chats_list.append(chat)
+    return chats_list
 
 
 async def add_served_chat(chat_id: int):
     is_served = await is_served_chat(chat_id)
     if is_served: return
-    chats = await get_served_chats()
-    chats[await int_to_alpha_chat(chat_id)] = {"chat_id": chat_id}
-    await chatsdb.update_one(
-            {"chats": "chats"},
-            {
-                "$set": {
-                    "chats": chats
-                }
-            },
-            upsert=True
-            )
+    return await chatsdb.insert_one({"chat_id": chat_id})
+
 
 async def remove_served_chat(chat_id: int):
     is_served = await is_served_chat(chat_id)
     if not is_served: return
-    chats = await get_served_chats()
-    del chats[await int_to_alpha_chat(chat_id)]
-    await chatsdb.update_one(
-            {"chats": "chats"},
-            {
-                "$set": {
-                    "chats": chats
-                }
-            },
-            upsert=True
-            )
+    return await chatsdb.delete_one({"chat_id": chat_id})
+
+
+""" Gban functions """
+
+
+async def get_gbans_count() -> int:
+    users = gbansdb.find({"user_id": {"$gt": 0}})
+    users = await users.to_list(length=100000)
+    return len(users)
+
+
+async def is_gbanned_user(user_id: int) -> bool:
+    user = await gbansdb.find_one({"user_id": user_id})
+    if not user: return False
+    return True
+
+
+async def add_gban_user(user_id: int):
+    is_gbanned = await is_gbanned_user(user_id)
+    if is_gbanned: return
+    return await gbansdb.insert_one({"user_id": user_id})
+
+
+async def remove_gban_user(user_id: int):
+    is_gbanned = await is_gbanned_user(chat_id)
+    if not is_gbanned: return
+    return await gbansdb.delete_one({"user_id": user_id})