浏览代码

Karma toggle

TheHamkerCat 5 年之前
父节点
当前提交
ea11d09856

+ 33 - 29
wbb/modules/anime.py

@@ -12,6 +12,7 @@ from wbb.core.decorators.errors import capture_err
 __MODULE__ = "Anime"
 __HELP__ = "•Anime uwu•\n\n/anime - search anime on AniList\n /manga - search manga on Anilist\n /char - search character on Anilist\n /nhentai ID - returns the nhentai in telegraph instant preview format."
 
+
 def shorten(description, info='anilist.co'):
     ms_g = ""
     if len(description) > 700:
@@ -43,8 +44,8 @@ def t(milliseconds: int) -> str:
 
 
 airing_query = '''
-    query ($id: Int,$search: String) { 
-      Media (id: $id, type: ANIME,search: $search) { 
+    query ($id: Int,$search: String) {
+      Media (id: $id, type: ANIME,search: $search) {
         id
         episodes
         title {
@@ -57,14 +58,14 @@ airing_query = '''
            airingAt
            timeUntilAiring
            episode
-        } 
+        }
       }
     }
     '''
 
 fav_query = """
-query ($id: Int) { 
-      Media (id: $id, type: ANIME) { 
+query ($id: Int) {
+      Media (id: $id, type: ANIME) {
         id
         title {
           romaji
@@ -76,8 +77,8 @@ query ($id: Int) {
 """
 
 anime_query = '''
-   query ($id: Int,$search: String) { 
-      Media (id: $id, type: ANIME,search: $search) { 
+   query ($id: Int,$search: String) {
+      Media (id: $id, type: ANIME,search: $search) {
         id
         idMal
         title {
@@ -103,7 +104,7 @@ anime_query = '''
           }
           trailer{
                id
-               site 
+               site
                thumbnail
           }
           averageScore
@@ -132,8 +133,8 @@ character_query = """
 """
 
 manga_query = """
-query ($id: Int,$search: String) { 
-      Media (id: $id, type: MANGA,search: $search) { 
+query ($id: Int,$search: String) {
+      Media (id: $id, type: MANGA,search: $search) {
         id
         title {
           romaji
@@ -155,11 +156,12 @@ query ($id: Int,$search: String) {
     }
 """
 
+
 def format_bytes(size):
     size = int(size)
     power = 1024
     n = 0
-    power_labels = {0 : '', 1: 'K', 2: 'M', 3: 'G', 4: 'T'}
+    power_labels = {0: '', 1: 'K', 2: 'M', 3: 'G', 4: 'T'}
     while size > power:
         size /= power
         n += 1
@@ -177,7 +179,8 @@ def calculate_eta(current, total, start_time):
     end_time = time.time()
     elapsed_time = end_time - start_time
     seconds = (elapsed_time * (total / current)) - elapsed_time
-    thing = ''.join(str(timedelta(seconds=seconds)).split('.')[:-1]).split(', ')
+    thing = ''.join(str(timedelta(seconds=seconds)
+                        ).split('.')[:-1]).split(', ')
     thing[-1] = thing[-1].rjust(8, '0')
     return ', '.join(thing)
 
@@ -217,17 +220,17 @@ async def anime_search(_, message):
         image = info.replace('anilist.co/anime/', 'img.anili.st/media/')
         if trailer:
             buttons = [
-                    [InlineKeyboardButton("More Info", url=info),
-                    InlineKeyboardButton("Trailer", url=trailer)]
-                    ]
+                [InlineKeyboardButton("More Info", url=info),
+                 InlineKeyboardButton("Trailer", url=trailer)]
+            ]
         else:
             buttons = [
-                    [InlineKeyboardButton("More Info", url=info)]
-                    ]
+                [InlineKeyboardButton("More Info", url=info)]
+            ]
         if image:
             try:
                 await message.reply_photo(image, caption=msg, reply_markup=InlineKeyboardMarkup(buttons))
-            except:
+            except Exception:
                 msg += f" [✔️️]({image})"
                 await message.edit(msg)
         else:
@@ -270,7 +273,7 @@ async def manga_search(_, message):
         if image:
             try:
                 await message.reply_photo(image, caption=ms_g)
-            except:
+            except Exception:
                 ms_g += f" [✔️️]({image})"
                 await message.reply(ms_g)
         else:
@@ -307,7 +310,8 @@ async def nhentai(_, message):
         await message.delete()
         return
     query = message.text.split(None, 1)[1]
-    title, tags, artist, total_pages, post_url, cover_image = nhentai_data(query)
+    title, tags, artist, total_pages, post_url, cover_image = nhentai_data(
+        query)
     await message.reply_text(
         f"<code>{title}</code>\n\n<b>Tags:</b>\n{tags}\n<b>Artists:</b>\n{artist}\n<b>Pages:</b>\n{total_pages}",
         reply_markup=InlineKeyboardMarkup(
@@ -334,9 +338,9 @@ def nhentai_data(noombers):
     artist = ''
     total_pages = res['num_pages']
     extensions = {
-        'j':'jpg',
-        'p':'png',
-        'g':'gif'
+        'j': 'jpg',
+        'p': 'png',
+        'g': 'gif'
     }
     for i, x in enumerate(pages):
         media_id = res["media_id"]
@@ -346,20 +350,20 @@ def nhentai_data(noombers):
         links.append(link)
 
     for i in info:
-        if i["type"]=="tag":
+        if i["type"] == "tag":
             tag = i['name']
             tag = tag.split(" ")
             tag = "_".join(tag)
-            tags+=f"#{tag} "
-        if i["type"]=="artist":
-            artist=f"{i['name']} "
+            tags += f"#{tag} "
+        if i["type"] == "artist":
+            artist = f"{i['name']} "
 
     post_content = "".join(f"<img src={link}><br>" for link in links)
 
     post = telegraph.create_page(
         f"{title}",
         html_content=post_content,
-        author_name="@WilliamButcherBot", 
+        author_name="@WilliamButcherBot",
         author_url="https://t.me/WilliamButcherBot"
     )
-    return title,tags,artist,total_pages,post['url'],links[0]
+    return title, tags, artist, total_pages, post['url'], links[0]

+ 1 - 0
wbb/modules/carbon.py

@@ -10,6 +10,7 @@ __HELP__ = "/carbon - Make Carbon Of Code."
 
 
 @app.on_message(filters.command("carbon"))
+@capture_err
 async def carbon_func(_, message):
     if not message.reply_to_message:
         await message.reply_text("Reply to a text message to make carbon.")

+ 39 - 39
wbb/modules/greetings.py

@@ -47,7 +47,7 @@ __MODULE__ = "Greetings"
 __HELP__ = """
 /captcha [ON|OFF] - Enable/Disable captcha.
 
-/set_welcome - Reply this to a message containing correct 
+/set_welcome - Reply this to a message containing correct
 format for a welcome message, check end of this message.
 
 /del_welcome - Delete the welcome message.
@@ -68,7 +68,7 @@ button2=[Github, https://github.com]
 
 **NOTES ->**
 
-for /rules, you can do /filter rules to a message 
+for /rules, you can do /filter rules to a message
 containing rules of your groups whenever a user
 sends /rules, he'll get the message
 """
@@ -88,12 +88,12 @@ async def welcome(_, message: Message):
         try:
             if member.id in SUDOERS:
                 continue  # ignore sudos
-            """if await is_gbanned_user(member.id):
+            if await is_gbanned_user(member.id):
                 await message.chat.kick_member(member.id)
                 await message.reply_text(f"{member.mention} was globally banned, and got removed,"
                                          + " if you think this is a false gban, you can appeal"
                                          + " for this ban in support chat.")
-               continue"""
+               continue
             if member.is_bot:
                 continue  # ignore bots
             await message.chat.restrict_member(member.id, ChatPermissions())
@@ -161,41 +161,41 @@ async def welcome(_, message: Message):
 
 
 async def send_welcome_message(callback_query, pending_user_id):
-        try:
-            raw_text = await get_welcome(callback_query.message.chat.id)
-        except TypeError:
-            return
-        raw_text = raw_text.strip().replace("`", "")
-        if not raw_text:
-            return
-        text = raw_text.split("~")[0].strip()
-        buttons_text_list = raw_text.split("~")[1].strip().splitlines()
-        if "{chat}" in text:
-            text = text.replace("{chat}", callback_query.message.chat.title)
-        if "{name}" in text:
-            text = text.replace("{name}", (await app.get_users(pending_user_id)).mention)
-        buttons = InlineKeyboard(row_width=2)
-        list_of_buttons = []
-        for button_string in buttons_text_list:
-            button_string = button_string.strip().split("=")[1].strip()
-            button_string = button_string.replace("[", "").strip()
-            button_string = button_string.replace("]", "").strip()
-            button_string = button_string.split(",")
-            button_text = button_string[0].strip()
-            button_url = button_string[1].strip()
-            list_of_buttons.append(
-                    InlineKeyboardButton(
-                        text=button_text,
-                        url=button_url
-                        )
-                    )
-        buttons.add(*list_of_buttons)
-        await app.send_message(
-                callback_query.message.chat.id,
-                text=text,
-                reply_markup=buttons,
-                disable_web_page_preview=True
-                )
+    try:
+        raw_text = await get_welcome(callback_query.message.chat.id)
+    except TypeError:
+        return
+    raw_text = raw_text.strip().replace("`", "")
+    if not raw_text:
+        return
+    text = raw_text.split("~")[0].strip()
+    buttons_text_list = raw_text.split("~")[1].strip().splitlines()
+    if "{chat}" in text:
+        text = text.replace("{chat}", callback_query.message.chat.title)
+    if "{name}" in text:
+        text = text.replace("{name}", (await app.get_users(pending_user_id)).mention)
+    buttons = InlineKeyboard(row_width=2)
+    list_of_buttons = []
+    for button_string in buttons_text_list:
+        button_string = button_string.strip().split("=")[1].strip()
+        button_string = button_string.replace("[", "").strip()
+        button_string = button_string.replace("]", "").strip()
+        button_string = button_string.split(",")
+        button_text = button_string[0].strip()
+        button_url = button_string[1].strip()
+        list_of_buttons.append(
+            InlineKeyboardButton(
+                text=button_text,
+                url=button_url
+            )
+        )
+    buttons.add(*list_of_buttons)
+    await app.send_message(
+        callback_query.message.chat.id,
+        text=text,
+        reply_markup=buttons,
+        disable_web_page_preview=True
+    )
 
 
 @app.on_callback_query(filters.regex("pressed_button"))

+ 31 - 1
wbb/modules/karma.py

@@ -24,7 +24,8 @@ SOFTWARE.
 from wbb import app
 from wbb.core.decorators.errors import capture_err
 from wbb.utils.dbfunctions import (update_karma, get_karma, get_karmas,
-                                   int_to_alpha, alpha_to_int)
+                                   int_to_alpha, alpha_to_int, is_karma_on,
+                                   karma_on, karma_off)
 from wbb.utils.filter_groups import karma_positive_group, karma_negative_group
 from pyrogram import filters
 
@@ -52,6 +53,8 @@ regex_downvote = r"^(\-|\-\-|\-1|👎)$"
 )
 @capture_err
 async def upvote(_, message):
+    if not await is_karma_on:
+        return
     if message.reply_to_message.from_user.id == message.from_user.id:
         return
     chat_id = message.chat.id
@@ -85,6 +88,8 @@ async def upvote(_, message):
 )
 @capture_err
 async def downvote(_, message):
+    if not await is_karma_on:
+        return
     if message.reply_to_message.from_user.id == message.from_user.id:
         return
     chat_id = message.chat.id
@@ -140,3 +145,28 @@ async def karma(_, message):
         else:
             karma = 0
             await message.reply_text(f'**Total Points**: __{karma}__')
+
+
+@app.on_message(filters.command("karma_toggle") & ~filters.private)
+@capture_err
+async def captcha_state(_, message):
+    usage = "**Usage:**\n/karma_toggle [ON|OFF]"
+    if len(message.command) != 2:
+        await message.reply_text(usage)
+        return
+    user_id = message.from_user.id
+    chat_id = message.chat.id
+    permissions = await member_permissions(chat_id, user_id)
+    if "can_restrict_members" not in permissions:
+        await message.reply_text("You don't have enough permissions.")
+        return
+    state = message.text.split(None, 1)[1].strip()
+    state = state.lower()
+    if state == "on":
+        await karma_on(chat_id)
+        await message.reply_text("Enabled karma system.")
+    elif state == "off":
+        await karma_off(chat_id)
+        await message.reply_text("Disabled karma system.")
+    else:
+        await message.reply_text(usage)

+ 0 - 1
wbb/modules/misc.py

@@ -24,7 +24,6 @@ SOFTWARE.
 import secrets
 import string
 import aiohttp
-import html
 from pyrogram import filters
 from googletrans import Translator
 from cryptography.fernet import Fernet

+ 5 - 5
wbb/modules/music.py

@@ -52,9 +52,9 @@ def get_file_extension_from_url(url):
     return basename.split(".")[-1]
 
 
-async def download_youtube_audio(url: str, m = 0):
+async def download_youtube_audio(url: str, m=0):
     global is_downloading
-    with youtube_dl.YoutubeDL({'format': 'bestaudio', 'writethumbnail': True,}) as ydl:
+    with youtube_dl.YoutubeDL({'format': 'bestaudio', 'writethumbnail': True, }) as ydl:
         info_dict = ydl.extract_info(url, download=False)
         if int(float(info_dict['duration'])) > 600:
             if m != 0:
@@ -100,9 +100,9 @@ async def music(_, message):
         await m.edit(str(e))
         return
     await message.reply_audio(
-            audio_file, duration=duration,
-            performer=performer, title=title, thumb=thumbnail_file
-            )
+        audio_file, duration=duration,
+        performer=performer, title=title, thumb=thumbnail_file
+    )
     await m.delete()
     os.remove(audio_file)
     os.remove(thumbnail_file)

+ 1 - 1
wbb/modules/pmpermit.py

@@ -146,7 +146,7 @@ async def pmpermit_cq(_, cq):
         else:
             flood2[str(user_id)] = 1
         if flood2[str(user_id)] > 5:
+            await app2.send_message(user_id, "SPAM DETECTED, USER BLOCKED.")
             await app2.block_user(user_id)
-            await message.reply_text("SPAM DETECTED, USER BLOCKED.")
             return
         await app2.send_message(user_id, "I'm busy right now, will approve you shortly, DO NOT SPAM.")

+ 0 - 1
wbb/modules/regex.py

@@ -26,7 +26,6 @@ import sre_constants
 from wbb import app
 from wbb.utils.filter_groups import regex_group
 from pyrogram import filters
-from wbb.core.decorators.errors import capture_err
 
 __MODULE__ = "Sed"
 __HELP__ = "**Usage:**\ns/foo/bar"

+ 0 - 1
wbb/modules/sudoers.py

@@ -27,7 +27,6 @@ import subprocess
 from pyrogram import filters
 import psutil
 import asyncio
-from sys import version as pyver
 from wbb import (
     app, SUDOERS, bot_start_time, BOT_ID, USERBOT_USERNAME, GBAN_LOG_GROUP_ID
 )

+ 17 - 16
wbb/modules/telegraph.py

@@ -1,5 +1,5 @@
-#Written by MaskedVirus | github.com/swatv3nub for William and SupMeta_bot
-#Kang with Proper Credits
+# Written by MaskedVirus | github.com/swatv3nub for William and SupMeta_bot
+# Kang with Proper Credits
 # Part of Pull Req #2 by @MaskedVirus | github.com/swatv3nub
 
 import os
@@ -11,11 +11,12 @@ from wbb.core.decorators.errors import capture_err
 __MODULE__ = "Telegraph"
 __HELP__ = """
 Paste Photo and Video to Telegraph
-Usage : 
+Usage:
 /tgphoto - reply to a photo
 /tgvideo - reply to a Video
 """
 
+
 @app.on_message(filters.command("tgphoto"))
 @capture_err
 async def tgphoto(client, message):
@@ -25,19 +26,19 @@ async def tgphoto(client, message):
     if not message.reply_to_message.photo:
         await message.reply_text("Works only for Photos")
         return
-    msg = await message.reply_text("`Uploading to Telegraph...`") 
+    msg = await message.reply_text("`Uploading to Telegraph...`")
     userid = str(message.chat.id)
     path = (f"./DOWNLOADS/{userid}.jpg")
     path = await client.download_media(message=message.reply_to_message, file_name=path)
     try:
-      tlink = upload_file(path)
-    except:
-      await msg.edit_text("Something went Wrong.") 
+        tlink = upload_file(path)
+    except Exception:
+        await msg.edit_text("Something went Wrong.")
     else:
-      await msg.edit_text(f"Successfully Uploaded to [Telegraph](https://telegra.ph{tlink[0]})")     
-      os.remove(path)
-   
-   
+        await msg.edit_text(f"Successfully Uploaded to [Telegraph](https://telegra.ph{tlink[0]})")
+        os.remove(path)
+
+
 @app.on_message(filters.command("tgvideo"))
 @capture_err
 async def tgvideo(client, message):
@@ -53,10 +54,10 @@ async def tgvideo(client, message):
         vid_path = (f"./DOWNLOADS/{userid}.mp4")
         vid_path = await client.download_media(message=message.reply_to_message, file_name=vid_path)
         try:
-          tlink = upload_file(vid_path)
-          await msg.edit_text(f"Successfully Uploaded to [Telegraph](https://telegra.ph{tlink[0]})")   
-          os.remove(vid_path)   
-        except:
-          await msg.edit_text("Something went Wrong.") 
+            tlink = upload_file(vid_path)
+            await msg.edit_text(f"Successfully Uploaded to [Telegraph](https://telegra.ph{tlink[0]})")
+            os.remove(vid_path)
+        except Exception:
+            await msg.edit_text("Something went Wrong.")
     else:
         await message.reply_text("Size Should Be Less Than 5 mb")

+ 1 - 0
wbb/utils/aiodownloader/__init__.py

@@ -1 +1,2 @@
 from .downloader import Handler
+Handler = Handler

+ 4 - 4
wbb/utils/aiodownloader/downloader.py

@@ -88,9 +88,9 @@ class Handler:
     Top level interface with the downloader. It creates the download jobs and handles them.
 
     :param loop: asyncio loop. if not provided asyncio.get_event_loop() will be used
-    :param session: aiohttp session to be used on all downloads. If not provided it will be 
-    created 
-    :param chunk_size: chunk bytes sizes to get from the file source. Defaults to 1024 bytes 
+    :param session: aiohttp session to be used on all downloads. If not provided it will be
+    created
+    :param chunk_size: chunk bytes sizes to get from the file source. Defaults to 1024 bytes
     """
 
     def __init__(self,
@@ -109,7 +109,7 @@ class Handler:
         Shortcut for creating a download job. It adds the session and the chunk size.
         :param file_url: url where the file is located
         :param save_path: save path for the download
-        :return: 
+        :return:
         """
 
         return DownloadJob(self._session, file_url, save_path, self._chunk_size)

+ 22 - 2
wbb/utils/dbfunctions.py

@@ -331,6 +331,27 @@ async def update_karma(chat_id: int, name: str, karma: dict):
     )
 
 
+async def is_karma_on(chat_id: int) -> bool:
+    chat = await karmadb.find_one({"chat_id": chat_id})
+    if not chat:
+        return True
+    return False
+
+
+async def karma_on(chat_id: int):
+    is_karma = await is_karma_on(chat_id)
+    if is_karma:
+        return
+    return await karmadb.delete_one({"chat_id": chat_id})
+
+
+async def karma_off(chat_id: int):
+    is_karma = await is_karma_on(chat_id)
+    if not is_karma:
+        return
+    return await karmadb.insert_one({"chat_id": chat_id})
+
+
 """ Chats log functions """
 
 
@@ -501,8 +522,7 @@ async def disapprove_pmpermit(user_id: int):
 """ WELCOME FUNCTIONS """
 
 
-
-async def get_welcome(chat_id: int)-> str:
+async def get_welcome(chat_id: int) -> str:
     text = await welcomedb.find_one({"chat_id": chat_id})
     return text['text']
 

+ 10 - 9
wbb/utils/inlinefuncs.py

@@ -63,7 +63,7 @@ async def inline_help_func(__HELP__):
         "wall", "yt", "torrent", "lyrics", "wiki",
         "speedtest", "eval", "music", "saavn", "deezer",
         "gh_repo", "gh_user", "search", "pastebin",
-        "nsfw_scan", "ytmusic"
+        "nsfw_scan", "ytmusic", "carbon"
     ]
     buttons.add(*[(InlineKeyboardButton(
         text=i, switch_inline_query_current_chat=i)) for i in keywords_list])
@@ -841,13 +841,13 @@ async def yt_music_func(answers, url, user_id):
         return answers
     title, performer, duration, audio, thumbnail = await download_youtube_audio(url)
     m = await app.send_audio(
-            MESSAGE_DUMP_CHAT,
-            audio,
-            title=title,
-            duration=duration,
-            performer=performer,
-            thumb=thumbnail
-            )
+        MESSAGE_DUMP_CHAT,
+        audio,
+        title=title,
+        duration=duration,
+        performer=performer,
+        thumb=thumbnail
+    )
     os.remove(audio)
     os.remove(thumbnail)
     answers.append(
@@ -888,7 +888,8 @@ async def carbon_inline_func(answers, link):
         os.remove(doc)
     image = await make_carbon(content)
     link = await paste(content)
-    carbon = await app.send_document(MESSAGE_DUMP_CHAT, image)  # To Pre-cache the media
+    # To Pre-cache the media
+    carbon = await app.send_document(MESSAGE_DUMP_CHAT, image)
     os.remove(image)
     buttons = InlineKeyboard(row_width=1)
     buttons.add(InlineKeyboardButton(text="Paste Link", url=link))