Selaa lähdekoodia

fix: fetching all users from db

TheHamkerCat 1 vuosi sitten
vanhempi
sitoutus
2f29119c2f
4 muutettua tiedostoa jossa 104 lisäystä ja 62 poistoa
  1. 5 3
      Dockerfile
  2. 65 38
      wbb/modules/karma.py
  3. 7 1
      wbb/modules/regex.py
  4. 27 20
      wbb/utils/functions.py

+ 5 - 3
Dockerfile

@@ -1,4 +1,4 @@
-FROM python:slim-bullseye
+FROM python:3.12-slim-bullseye
 WORKDIR /wbb
 RUN chmod 777 /wbb
 
@@ -6,10 +6,12 @@ RUN apt-get -qq update && apt-get -qq -y upgrade
 RUN DEBIAN_FRONTEND=noninteractive apt-get install -y git gcc build-essential
 ENV PYTHONUNBUFFERED=1
 
-# Copying All Source
-COPY . .
+COPY requirements.txt .
+
 RUN pip3 install -U pip setuptools wheel && pip3 install --no-cache-dir -U -r requirements.txt
 
+COPY . .
+
 # If u want to use /update feature, uncomment the following and edit
 #RUN git config --global user.email "your_email"
 #RUN git config --global user.name "git_username"

+ 65 - 38
wbb/modules/karma.py

@@ -40,7 +40,7 @@ from wbb.utils.dbfunctions import (
     update_karma,
 )
 from wbb.utils.filter_groups import karma_negative_group, karma_positive_group
-from wbb.utils.functions import get_user_id_and_usernames
+from wbb.utils.functions import get_specific_usernames
 
 __MODULE__ = "Karma"
 __HELP__ = """[UPVOTE] - Use upvote keywords like "+", "+1", "thanks", etc to upvote a message.
@@ -146,50 +146,77 @@ async def downvote(_, message):
 @capture_err
 async def command_karma(_, message):
     chat_id = message.chat.id
+    
     if not message.reply_to_message:
         m = await message.reply_text("Analyzing Karma...")
-        karma = await get_karmas(chat_id)
-        if not karma:
-            return await m.edit("No karma in DB for this chat.")
-        msg = f"Karma list of {message.chat.title}"
-        limit = 0
-        karma_dicc = {}
-        for i in karma:
-            user_id = await alpha_to_int(i)
-            user_karma = karma[i]["karma"]
-            karma_dicc[str(user_id)] = user_karma
-            karma_arranged = dict(
-                sorted(
-                    karma_dicc.items(),
-                    key=lambda item: item[1],
-                    reverse=True,
-                )
+        
+        try:
+            karma = await get_karmas(chat_id)
+            if not karma:
+                return await m.edit("No karma in DB for this chat.")
+            
+            karma_dicc = {}
+            for i in karma:
+                try:
+                    user_id = await alpha_to_int(i)
+                    user_karma = karma[i]["karma"]
+                    karma_dicc[str(user_id)] = user_karma
+                except Exception as e:
+                    continue
+            
+            if not karma_dicc:
+                return await m.edit("No karma in DB for this chat.")
+            
+            karma_sorted = sorted(
+                karma_dicc.items(),
+                key=lambda item: item[1],
+                reverse=True
             )
-        if not karma_dicc:
-            return await m.edit("No karma in DB for this chat.")
-        userdb = await get_user_id_and_usernames(app)
-        karma = {}
-        for user_idd, karma_count in karma_arranged.items():
-            if limit > 15:
-                break
-            if int(user_idd) not in list(userdb.keys()):
-                continue
-            username = userdb[int(user_idd)]
-            karma["@" + username] = ["**" + str(karma_count) + "**"]
-            limit += 1
-        await m.edit(section(msg, karma))
+            
+            try:
+                user_ids_needed = [int(uid) for uid, _ in karma_sorted]
+                userdb = await get_specific_usernames(app, user_ids_needed)
+            except Exception as e:
+                return await m.edit(f"Error fetching user data: {str(e)}")
+            
+            karma_display = {}
+            limit = 0
+            
+            for user_id_str, karma_count in karma_sorted:
+                if limit >= 15:
+                    break
+                
+                user_id_int = int(user_id_str)
+                
+                if user_id_int not in userdb:
+                    continue
+                
+                username = userdb[user_id_int]
+                karma_display[f"@{username}"] = [f"**{karma_count}**"]
+                limit += 1
+            
+            if not karma_display:
+                return await m.edit("No valid users found with karma.")
+            
+            msg = f"Karma list of {message.chat.title}"
+            await m.edit(section(msg, karma_display))
+            
+        except Exception as e:
+            await m.edit(f"An error occurred: {str(e)}")
+            rais
+    
     else:
         if not message.reply_to_message.from_user:
             return await message.reply("Anon user has no karma.")
-
+        
         user_id = message.reply_to_message.from_user.id
-        karma = await get_karma(chat_id, await int_to_alpha(user_id))
-        if karma:
-            karma = karma["karma"]
-            await message.reply_text(f"**Total Points**: __{karma}__")
-        else:
-            karma = 0
-            await message.reply_text(f"**Total Points**: __{karma}__")
+        try:
+            karma = await get_karma(chat_id, await int_to_alpha(user_id))
+            karma_value = karma["karma"] if karma else 0
+            await message.reply_text(f"**Total Points**: __{karma_value}__")
+        except Exception as e:
+            await message.reply_text(f"Error fetching karma: {str(e)}")
+
 
 
 @app.on_message(filters.command("karma_toggle") & ~filters.private)

+ 7 - 1
wbb/modules/regex.py

@@ -20,7 +20,10 @@ DELIMITERS = ("/", ":", "|", "_")
 async def sed(_, message):
     if not message.text:
         return
-    sed_result = separate_sed(message.text)
+
+    text_content = str(message.text)
+    sed_result = separate_sed(text_content)
+
     if message.reply_to_message:
         if message.reply_to_message.text:
             to_fix = message.reply_to_message.text
@@ -77,6 +80,9 @@ def infinite_checker(repl):
 
 
 def separate_sed(sed_string):
+    if not isinstance(sed_string, str):
+        sed_string = str(sed_string)
+
     if (
         len(sed_string) >= 3
         and sed_string[1] in DELIMITERS

+ 27 - 20
wbb/utils/functions.py

@@ -22,6 +22,8 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
 """
 
+import asyncio
+
 from asyncio import gather
 from datetime import datetime, timedelta
 from io import BytesIO
@@ -31,6 +33,7 @@ from random import randint
 from re import findall, search
 from re import sub as re_sub
 from sys import executable
+from typing import Dict
 
 import aiofiles
 import speedtest
@@ -378,23 +381,27 @@ async def get_data_and_name(replied_message, message):
     return data, name
 
 
-async def get_user_id_and_usernames(client) -> dict:
-    with client.storage.conn:
-        query = """
-        SELECT usernames.id, usernames.username
-        FROM usernames
-        WHERE usernames.id IN (
-            SELECT peers.id
-            FROM peers
-            WHERE peers.type IN ("user", "bot") AND username IS NOT NULL
-        )
-        """
-        result = client.storage.conn.execute(query).fetchall()
-
-    users_ = {}
-    for row in result:
-        user_id = row[0]
-        username = row[1]
-        users_[user_id] = username
-
-    return users_
+async def get_specific_usernames(client, user_ids: list) -> Dict[int, str]:
+    def _fetch_users():
+        ids_str = ','.join(str(uid) for uid in user_ids)
+
+        with client.storage.conn:
+            query = f"""
+            SELECT usernames.id, usernames.username
+            FROM usernames
+            WHERE usernames.id IN ({ids_str})
+            AND username IS NOT NULL
+            """
+            result = client.storage.conn.execute(query).fetchall()
+
+        users_ = {}
+        for row in result:
+            users_[row[0]] = row[1]
+        return users_
+
+    try:
+        users = await asyncio.to_thread(_fetch_users)
+        return users
+    except Exception as e:
+        print(f"Error fetching users: {e}")
+        return {}