Răsfoiți Sursa

Flakified some files and improved /repo module

TheHamkerCat 5 ani în urmă
părinte
comite
6d4a98c540
7 a modificat fișierele cu 69 adăugiri și 54 ștergeri
  1. 5 5
      wbb/__init__.py
  2. 15 8
      wbb/__main__.py
  3. 3 4
      wbb/modules/ping.py
  4. 27 5
      wbb/modules/repo.py
  5. 9 6
      wbb/utils/cust_filter.py
  6. 7 16
      wbb/utils/formatter.py
  7. 3 10
      wbb/utils/misc.py

+ 5 - 5
wbb/__init__.py

@@ -2,16 +2,16 @@ from pyrogram import Client
 from configparser import ConfigParser
 import logging
 import time
-import os
-
 
 
 f = open("error.log", "w")
 f.write("PEAK OF LOG FILE")
 
 LOG_FORMAT = (
-    "[%(asctime)s.%(msecs)03d] %(filename)s:%(lineno)s %(levelname)s: %(message)s"
-)
+    '''
+    [%(asctime)s.%(msecs)03d] %(filename)s:%(lineno)s
+    %(levelname)s: %(message)s'''
+    )
 
 logging.basicConfig(
     level=logging.INFO,
@@ -39,4 +39,4 @@ MOD_NOLOAD = config.get("mods", "noload_modules").split()
 bot_start_time = time.time()
 
 
-app = Client(":memory:")
+app = Client(":memory:", workers=16)

+ 15 - 8
wbb/__main__.py

@@ -1,12 +1,14 @@
 import asyncio
+import uvloop
 import re
+import importlib
 from pyrogram import filters, idle
 from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
-from wbb import app, MOD_NOLOAD, MOD_LOAD, Command
-from wbb.utils import random_line, get_info, paginate_modules, cust_filter, botinfo
-import importlib
+from wbb import app, MOD_NOLOAD, Command
+from wbb.utils import random_line, get_info, paginate_modules, cust_filter
+from wbb.utils import botinfo
 from wbb.modules import ALL_MODULES
-import uvloop
+
 
 loop = asyncio.get_event_loop()
 
@@ -74,7 +76,11 @@ async def help_command(_, message):
         await message.reply("Contact me in PM.", reply_markup=keyboard)
         return
     text, keyboard = await help_parser(message)
-    await message.reply(text, reply_markup=keyboard, disable_web_page_preview=True)
+    await message.reply(
+        text,
+        reply_markup=keyboard,
+        disable_web_page_preview=True
+        )
 
 
 async def help_parser(message, keyboard=None):
@@ -89,6 +95,7 @@ async def help_parser(message, keyboard=None):
         keyboard,
     )
 
+
 @app.on_callback_query(filters.regex(r"help_(.*?)"))
 async def help_button(c, q):
     mod_match = re.match(r"help_module\((.+?)\)", q.data)
@@ -117,7 +124,7 @@ async def help_button(c, q):
     elif prev_match:
         curr_page = int(prev_match.group(1))
         await q.message.edit(
-            text="Hi {first_name}. I am {bot_name}, you can use commands with following prefixes{commands}".format(
+            text="Hi {first_name}. I am {bot_name}".format(
                 first_name=q.from_user.first_name,
                 bot_name=botinfo.BOT_NAME,
                 commands=", ".join(Command),
@@ -131,7 +138,7 @@ async def help_button(c, q):
     elif next_match:
         next_page = int(next_match.group(1))
         await q.message.edit(
-            text="Hi {first_name}. I am {bot_name}, you can use commands with following prefixes{commands}".format(
+            text="Hi {first_name}. I am {bot_name}".format(
                 first_name=q.from_user.first_name,
                 bot_name=botinfo.BOT_NAME,
                 commands=", ".join(Command),
@@ -144,7 +151,7 @@ async def help_button(c, q):
 
     elif back_match:
         await q.message.edit(
-            text="Hi {first_name}. I am {bot_name}, you can use commands with following prefixes{commands}".format(
+            text="Hi {first_name}. I am {bot_name}".format(
                 first_name=q.from_user.first_name,
                 bot_name=botinfo.BOT_NAME,
                 commands=", ".join(Command),

+ 3 - 4
wbb/modules/ping.py

@@ -1,12 +1,11 @@
-from wbb import app, Command
+from wbb import app
 from wbb.utils import cust_filter
 import requests
-import time
+
 __MODULE__ = "Ping"
 __HELP__ = " /ping - To Get Response Time From All TG Datacenters"
 
 
-
 @app.on_message(cust_filter.command(commands=("ping")))
 async def ping(client, message):
     app.set_parse_mode("markdown")
@@ -14,6 +13,6 @@ async def ping(client, message):
     result = ""
     for i in range(1, 6):
         dc = (f"https://cdn{i}.telesco.pe")
-        ping1 = round(requests.head(dc).elapsed.total_seconds() * 1000)   
+        ping1 = round(requests.head(dc).elapsed.total_seconds() * 1000)
         result += f'```DC{i} - {ping1}ms```'
     await m.edit(result)

+ 27 - 5
wbb/modules/repo.py

@@ -1,17 +1,39 @@
 from wbb import app
-from pyrogram import filters
 from wbb.utils import cust_filter
+import requests
 
 __MODULE__ = "Repo"
 __HELP__ = "/repo - To Get My Github Repository Link"
 
+api = 'https://api.github.com/repos/thehamkercat/' \
+      'WilliamButcherBot/stats/contributors'
+
+print(api)
+
 
 @app.on_message(cust_filter.command(commands=("repo")))
 async def repo(client, message):
     app.set_parse_mode("markdown")
-    await message.reply_text(f'''
-```👨‍💻 Developer``` - @TheHamkerCat
+    profile_url = []
+    username = []
 
-```🔗 Repo``` - github.com/thehamkercat/WilliamButcherBot
+# Get The List Of Usernames And Profile Url
+    for item in requests.get(api).json():
+        profile_url.append(f"{item['author']['html_url']}")
+        username.append(f"{item['author']['login']}")
 
-```❤️ PRs Are Always Welcomed```''', disable_web_page_preview=True)
+# Join Usernames And Profile Url For Markdown
+    no_of_contributors = len(username)
+    i = 0
+    n = 1
+    contributors = ""
+    while i < no_of_contributors:
+        contributors += f"[{n}. {username[i]}]({profile_url[i]})\n"
+        n += 1
+        i += 1
+
+    await message.reply_text(f'''
+```Devs and Contributors```
+{contributors}
+```Source Code```[Github](https://github.com/thehamkercat/WilliamButcherBot)
+''', disable_web_page_preview=True)

+ 9 - 6
wbb/utils/cust_filter.py

@@ -15,12 +15,15 @@ def command(
     case_sensitive: bool = False,
 ):
     """
-    This is a drop in replacement for the default cust_filter.command that is included
-    in Pyrogram. The Pyrogram one does not support /command@botname type commands,
-    so this custom filter enables that throughout all groups and private chats.
-    This filter works exactly the same as the original command filter even with support for multiple command
-    prefixes and case sensitivity.
-    Command arguments are given to user as message.command
+    This is a drop in replacement for the default
+    cust_filter.command that is included in Pyrogram.
+    The Pyrogram one does not support /command@botname
+    type commands, so this custom filter enables that
+    throughout all groups and private chats. This filter
+    works exactly the same as the original command filter
+    even with support for multiple command prefixes and
+    case sensitivity. Command arguments are given to user
+    as message.command
     """
 
     async def func(flt, _, message: Message):

+ 7 - 16
wbb/utils/formatter.py

@@ -1,4 +1,5 @@
-import time, math
+import time
+import math
 
 
 def time_formatter(seconds):
@@ -66,7 +67,10 @@ def get_readable_time(seconds: int) -> str:
     time_suffix_list = ["s", "m", "h", "days"]
     while count < 4:
         count += 1
-        remainder, result = divmod(seconds, 60) if count < 3 else divmod(seconds, 24)
+        if count < 3:
+            remainder, result = divmod(seconds, 60)
+        else:
+            remainder, result = divmod(seconds, 24)
         if seconds == 0 and remainder == 0:
             break
         time_list.append(int(result))
@@ -109,18 +113,6 @@ def extract_time(time_val):
     return bantime
 
 
-def make_time(time_val):
-    if int(time_val) == 0:
-        return "0"
-    if int(time_val) <= 3600:
-        bantime = str(int(time_val / 60)) + "m"
-    elif int(time_val) >= 3600 and time_val <= 86400:
-        bantime = str(int(time_val / 60 / 60)) + "h"
-    elif int(time_val) >= 86400:
-        bantime = str(int(time_val / 24 / 60 / 60)) + "d"
-    return bantime
-
-
 def extract_time_set(time_val):
     if not any(time_val.endswith(unit) for unit in ("m", "h", "d")):
         return False
@@ -128,7 +120,6 @@ def extract_time_set(time_val):
     time_num = time_val[:-1]  # type: str
     if not time_num.isdigit():
         return False
-
     if unit == "d":
         bantime = int(int(time_num) * 24 * 60 * 60)
     elif unit == "h":
@@ -156,7 +147,7 @@ def escape_invalid_curly_brackets(text, valids):  # sourcery skip
                         success = True
                         break
                     if success:
-                        new_text += text[idx : idx + len(v) + 2]
+                        new_text += text[idx: idx + len(v) + 2]
                         idx += len(v) + 2
                         continue
                     else:

+ 3 - 10
wbb/utils/misc.py

@@ -1,17 +1,8 @@
-import re
-
-# import requests
 from math import ceil
-
 from pyrogram.types import InlineKeyboardButton
 from wbb import MOD_LOAD, MOD_NOLOAD
 
 
-def cleanhtml(raw_html):
-    cleanr = re.compile("<.*?>")
-    return re.sub(cleanr, "", raw_html)
-
-
 class EqInlineKeyboardButton(InlineKeyboardButton):
     def __eq__(self, other):
         return self.text == other.text
@@ -29,7 +20,9 @@ def paginate_modules(page_n, module_dict, prefix, chat=None):
             [
                 EqInlineKeyboardButton(
                     x.__MODULE__,
-                    callback_data="{}_module({})".format(prefix, x.__MODULE__.lower()),
+                    callback_data="{}_module({})".format(
+                        prefix, x.__MODULE__.lower()
+                        ),
                 )
                 for x in module_dict.values()
             ]