Ver código fonte

Merge pull request #12 from thehamkercat/fix-flake8-warns

Fix flake8 warns
Akshay Rajput 5 anos atrás
pai
commit
893ae71dfc

+ 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)

+ 29 - 16
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
+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()
 
@@ -21,12 +23,21 @@ async def start_bot():
 
     for module in ALL_MODULES:
         imported_module = importlib.import_module("wbb.modules." + module)
-        if hasattr(imported_module, "__MODULE__") and imported_module.__MODULE__:
+        if (
+            hasattr(imported_module, "__MODULE__")
+            and imported_module.__MODULE__
+        ):
             if imported_module.__MODULE__.lower() in MOD_NOLOAD:
                 continue
             imported_module.__MODULE__ = imported_module.__MODULE__
-            if hasattr(imported_module, "__HELP__") and imported_module.__HELP__:
-                HELPABLE[imported_module.__MODULE__.lower()] = imported_module
+            if (
+                hasattr(imported_module, "__HELP__")
+                and imported_module.__HELP__
+            ):
+                HELPABLE[
+                    imported_module.__MODULE__.lower()
+                ] = imported_module
+
     bot_modules = ""
     j = 1
     for i in ALL_MODULES:
@@ -43,7 +54,7 @@ async def start_bot():
     print("+===============+===============+===============+===============+")
     print("Bot Started Successfully as {}!".format(botinfo.BOT_NAME))
     await idle()
-    
+
 
 @app.on_message(cust_filter.command("start"))
 async def start(client, message):
@@ -52,6 +63,7 @@ async def start(client, message):
         return
     await message.reply("Hi, try /help")
 
+
 @app.on_message(cust_filter.command("help"))
 async def help_command(_, message):
     if message.chat.type != "private":
@@ -74,7 +86,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):
@@ -84,11 +100,11 @@ async def help_parser(message, keyboard=None):
         "Hi {first_name}, I am {bot_name}".format(
             first_name=message.from_user.first_name,
             bot_name=botinfo.BOT_NAME,
-            commands=", ".join(Command),
         ),
         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,10 +133,9 @@ 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),
             ),
             reply_markup=InlineKeyboardMarkup(
                 paginate_modules(curr_page - 1, HELPABLE, "help")
@@ -131,10 +146,9 @@ 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),
             ),
             reply_markup=InlineKeyboardMarkup(
                 paginate_modules(next_page + 1, HELPABLE, "help")
@@ -144,10 +158,9 @@ 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),
             ),
             reply_markup=InlineKeyboardMarkup(
                 paginate_modules(0, HELPABLE, "help")

+ 2 - 1
wbb/modules/__init__.py

@@ -6,7 +6,8 @@ def __list_all_modules():
     from os.path import dirname, basename, isfile
     import glob
 
-    # This generates a list of modules in this folder for the * in __main__ to work.
+# This generates a list of modules in this
+# folder for the * in __main__ to work.
     mod_paths = glob.glob(dirname(__file__) + "/*.py")
     all_modules = [
         basename(f)[:-3]

+ 4 - 5
wbb/modules/admin.py

@@ -1,22 +1,21 @@
 import asyncio
-from pyrogram import Client, filters
 from wbb.utils import cust_filter
-from wbb import app, Command
+from wbb import app
 from wbb.utils.is_admin import is_admin
 
 
 __MODULE__ = "Admin"
 __HELP__ = '''
-/purge - Purge Messages From The Replied Message To The Last Message [Limit = 100]
+/purge - Purge Messages [Limit = 100]
 
 '''
 
+
 @app.on_message(cust_filter.command(commands=("purge")))
 async def purge(client, message):
     app.set_parse_mode("markdown")
     if message.chat.type not in (("supergroup", "channel")):
         return
-    
     admin = await is_admin(message)
 
     if not admin:
@@ -45,7 +44,7 @@ async def purge(client, message):
             )
 
     m = await message.reply_text(
-        f"```Purged!```"
+        "```Purged!```"
     )
     await asyncio.sleep(2)
     await m.delete()

+ 21 - 11
wbb/modules/bot_owner.py

@@ -1,7 +1,11 @@
 from wbb.utils import cust_filter, nekobin, formatter
-from wbb import app, Command, OWNER_ID, bot_start_time, NEOFETCH
+from wbb import app, OWNER_ID, bot_start_time, NEOFETCH
 from pyrogram import filters, types
-import re, speedtest, psutil, time, os
+import re
+import speedtest
+import psutil
+import time
+import os
 
 
 __MODULE__ = "BotOwner"
@@ -12,7 +16,8 @@ __HELP__ = '''
 
 '''
 
-#Logs Module
+# Logs Module
+
 
 @app.on_message(filters.user(OWNER_ID) & cust_filter.command("log"))
 async def logs_chat(client, message):
@@ -44,18 +49,20 @@ async def paste_log_neko(client, query):
         f = open("error.log", "r")
         data = await nekobin.neko(f.read())
         keyb = types.InlineKeyboardMarkup(
-            [[types.InlineKeyboardButton("pasted on nekobin", url=f"{data}")]]
+            [[types.InlineKeyboardButton("Pasted!", url=f"{data}")]]
         )
-        await query.message.edit_caption("Successfully Nekofied", reply_markup=keyb)
+        await query.message.edit_caption(
+                                            "Successfully Nekofied",
+                                            reply_markup=keyb
+                                        )
     else:
         await client.answer_callback_query(
             query.id, "'Blue Button Must Press', huh?", show_alert=True
         )
 
+# SpeedTest Module
 
 
-#SpeedTest Module
-
 def speed_convert(size):
     power = 2 ** 10
     zero = 0
@@ -66,7 +73,9 @@ def speed_convert(size):
     return f"{round(size, 2)} {units[zero]}"
 
 
-@app.on_message(filters.user(OWNER_ID) & cust_filter.command(commands=("speedtest")))
+@app.on_message(
+    filters.user(OWNER_ID) & cust_filter.command(commands=("speedtest"))
+)
 async def speeeed(client, message):
     app.set_parse_mode("markdown")
     m = await message.reply_text("```Performing A Speedtest!```")
@@ -80,10 +89,12 @@ Upload   - {speed_convert(z)}
 Latency  - {round((x["latency"]))} ms
 ```''')
 
+# Stats Module
 
-#Stats Module
 
-@app.on_message(filters.user(OWNER_ID) & cust_filter.command(commands=("stats")))
+@ app.on_message(
+    filters.user(OWNER_ID) & cust_filter.command(commands=("stats"))
+)
 async def stats(client, message):
     bot_uptime = int(time.time() - bot_start_time)
     cpu = psutil.cpu_percent(interval=0.5)
@@ -115,4 +126,3 @@ async def stats(client, message):
 {neofetch}
 ```''')
     await message.reply_text(stats)
-

+ 0 - 1
wbb/modules/commit.py

@@ -1,5 +1,4 @@
 from wbb import app
-from pyrogram import filters
 from wbb.utils import cust_filter, random_line
 
 __MODULE__ = "Commit"

+ 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)

+ 3 - 3
wbb/utils/__init__.py

@@ -1,3 +1,3 @@
-from .read_lines import random_line
-from .botinfo import get_info
-from .misc import paginate_modules
+from .read_lines import random_line  # noqa: F401
+from .botinfo import get_info        # noqa: F401
+from .misc import paginate_modules   # noqa: F401

+ 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:

+ 12 - 13
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()
             ]
@@ -67,13 +60,19 @@ def paginate_modules(page_n, module_dict, prefix, chat=None):
 
     # can only have a certain amount of buttons side by side
     if len(pairs) > 7:
-        pairs = pairs[modulo_page * 7 : 7 * (modulo_page + 1)] + [
+        pairs = pairs[modulo_page * 7: 7 * (modulo_page + 1)] + [
             (
                 EqInlineKeyboardButton(
-                    "<", callback_data="{}_prev({})".format(prefix, modulo_page)
+                    "<",
+                    callback_data="{}_prev({})".format(
+                        prefix, modulo_page
+                    ),
                 ),
                 EqInlineKeyboardButton(
-                    ">", callback_data="{}_next({})".format(prefix, modulo_page)
+                    ">",
+                    callback_data="{}_next({})".format(
+                        prefix, modulo_page
+                    ),
                 ),
             )
         ]