Przeglądaj źródła

Many fixes and improvements

TheHamkerCat 5 lat temu
rodzic
commit
7e3e6b8770

+ 81 - 12
wbb/modules/chatbot.py

@@ -1,13 +1,17 @@
-from wbb import app, arq, BOT_ID
+from wbb import app, app2, arq, BOT_ID, SUDOERS, USERBOT_ID, USERBOT_USERNAME
 from wbb.core.decorators.errors import capture_err
 from wbb.utils.filter_groups import chatbot_group
 from pyrogram import filters
 
 
 __MODULE__ = "ChatBot"
-__HELP__ = "/chatbot [ON|OFF] To Enable Or Disable ChatBot In Your Chat."
+__HELP__ = """
+/chatbot [ON|OFF] To Enable Or Disable ChatBot In Your Chat.
+.chatbot [ON|OFF] To Do The Same For Userbot."""
+
+active_chats_bot = []
+active_chats_ubot = []
 
-active_chats = []
 
 # Enabled | Disable Chatbot
 
@@ -15,17 +19,17 @@ active_chats = []
 @app.on_message(filters.command("chatbot") & ~filters.edited)
 @capture_err
 async def chatbot_status(_, message):
-    global active_chats
+    global active_chats_bot
     if len(message.command) != 2:
-        await message.reply_text("/chatbot [ON|OFF]")
+        await message.reply_text("**Usage**\n/chatbot [ON|OFF]")
         return
     status = message.text.split(None, 1)[1]
     chat_id = message.chat.id
 
     if status == "ON" or status == "on" or status == "On":
-        if chat_id not in active_chats:
-            active_chats.append(chat_id)
-            text = "Chatbot Enabled Reply To Any Message" \
+        if chat_id not in active_chats_bot:
+            active_chats_bot.append(chat_id)
+            text = "Chatbot Enabled Reply To Any Message " \
                    + "Of Mine To Get A Reply"
             await message.reply_text(text)
             return
@@ -33,22 +37,22 @@ async def chatbot_status(_, message):
         return
 
     elif status == "OFF" or status == "off" or status == "Off":
-        if chat_id in active_chats:
-            active_chats.remove(chat_id)
+        if chat_id in active_chats_bot:
+            active_chats_bot.remove(chat_id)
             await message.reply_text("Chatbot Disabled!")
             return
         await message.reply_text("ChatBot Is Already Disabled.")
         return
 
     else:
-        await message.reply_text("/chatbot [ON|OFF]")
+        await message.reply_text("**Usage**\n/chatbot [ON|OFF]")
 
 
 @app.on_message(filters.text & filters.reply & ~filters.bot &
                 ~filters.via_bot & ~filters.forwarded, group=chatbot_group)
 @capture_err
 async def chatbot_talk(_, message):
-    if message.chat.id not in active_chats:
+    if message.chat.id not in active_chats_bot:
         return
     if not message.reply_to_message:
         return
@@ -58,3 +62,68 @@ async def chatbot_talk(_, message):
     luna = await arq.luna(query)
     response = luna.response
     await message.reply_text(response)
+
+
+""" FOR USERBOT """
+
+
+@app2.on_message(filters.command("chatbot", prefixes=".") & ~filters.edited & filters.user(SUDOERS))
+@capture_err
+async def chatbot_status_ubot(_, message):
+    global active_chats_ubot
+    if len(message.text.split()) != 2:
+        await message.edit("**Usage**\n.chatbot [ON|OFF]")
+        return
+    status = message.text.split(None, 1)[1]
+    chat_id = message.chat.id
+    if status == "ON" or status == "on" or status == "On":
+        if chat_id not in active_chats_ubot:
+            active_chats_ubot.append(chat_id)
+            text = "Chatbot Enabled Reply To Any Message " \
+                   + "Of Mine To Get A Reply"
+            await message.edit(text)
+            return
+        await message.edit("ChatBot Is Already Enabled.")
+        return
+
+    elif status == "OFF" or status == "off" or status == "Off":
+        if chat_id in active_chats_bot:
+            active_chats_bot.remove(chat_id)
+            await message.edit("Chatbot Disabled!")
+            return
+        await message.edit("ChatBot Is Already Disabled.")
+        return
+
+    else:
+        await message.edit("**Usage**\n/chatbot [ON|OFF]")
+
+
+@app2.on_message(~filters.me & ~filters.private & filters.text & ~filters.edited, group=chatbot_group)
+@capture_err
+async def chatbot_talk_ubot(_, message):
+    if message.chat.id not in active_chats_ubot:
+        return
+    username = ("@" + str(USERBOT_USERNAME))
+    query = message.text
+    if message.reply_to_message:
+        if message.reply_to_message.from_user.id != USERBOT_ID and username not in query:
+            return
+    else:
+        if username not in query:
+            return
+    luna = await arq.luna(query)
+    response = luna.response
+    await message.reply_text(response)
+
+
+@app2.on_message(filters.text & filters.private & ~filters.me & ~filters.edited, group=(chatbot_group+1))
+@capture_err
+async def chatbot_talk_ubot_pm(_, message):
+    if message.chat.id not in active_chats_ubot:
+        return
+    query = message.text
+    await app2.send_chat_action(message.chat.id, "typing")
+    luna = await arq.luna(query)
+    response = luna.response
+    await message.reply_text(response)
+    await app2.send_chat_action(message.chat.id, "cancel")

+ 11 - 0
wbb/modules/inline.py

@@ -20,6 +20,7 @@ __HELP__ = '''```
 - torrent [QUERY] - Torrent Search.
 - lyrics [QUERY] - Lyrics Search.
 - wiki [QUERY] - Wikipedia Search.
+- speedtest - Perform A Speedtest.
 - eval [CODE] - Execute Python Code.
 - gh_user [USERNAME | PROFILE_LINK] - Search A Github User.
 - gh_repo [REPO_LINK] - Search A Github Repo.
@@ -331,6 +332,16 @@ async def inline_query_handler(client, query):
                 results=answerss,
                 cache_time=2
             )
+
+        elif text.split()[0] == "speedtest":
+            answerss = await speedtest_init(query)
+            await client.answer_inline_query(
+                query.id,
+                results=answerss,
+                cache_time=2
+            )
+            return
+
     except Exception as e:
         print(str(e) + "InLine")
         return

+ 3 - 2
wbb/modules/music.py

@@ -107,8 +107,9 @@ async def jssong(_, message):
         await m.edit("Downloading")
         song = await download_song(slink)
         await m.edit("Uploading")
-        await message.reply_audio(audio=song, title=sname,
-                                  performer=ssingers)
+        await message.reply_audio(
+                audio=song, title=sname,
+                performer=ssingers, duration=int(songs[0].duration))
         os.remove(song)
         await m.delete()
     except Exception as e:

+ 5 - 34
wbb/modules/sudoers.py

@@ -2,7 +2,6 @@ import time
 import os
 import subprocess
 from pyrogram import filters
-import speedtest
 import psutil
 import asyncio
 from sys import version as pyver
@@ -21,7 +20,7 @@ from wbb.utils.dbfunctions import (
 
 
 __MODULE__ = "Sudoers"
-__HELP__ = '''/speedtest - To Perform A Speedtest.
+__HELP__ = '''
 /stats - To Check System Status.
 /gstats - To Check Bot's Global Stats.
 /gban - To Ban A User Globally.
@@ -29,36 +28,6 @@ __HELP__ = '''/speedtest - To Perform A Speedtest.
 /update - To Update And Restart The Bot
 /install - To Install A Module'''
 
-
-# SpeedTest Module
-
-
-def speed_convert(size):
-    power = 2 ** 10
-    zero = 0
-    units = {0: "", 1: "Kb/s", 2: "Mb/s", 3: "Gb/s", 4: "Tb/s"}
-    while size > power:
-        size /= power
-        zero += 1
-    return f"{round(size, 2)} {units[zero]}"
-
-
-@app.on_message(
-    filters.user(SUDOERS) & filters.command("speedtest")
-)
-@capture_err
-async def get_speedtest_result(_, message):
-    m = await message.reply_text("`Performing A Speedtest!`")
-    speed = speedtest.Speedtest()
-    i = speed.get_best_server()
-    j = speed.download()
-    k = speed.upload()
-    await m.edit(f'''
-**Download:** `{speed_convert(j)}`
-**Upload:** `{speed_convert(k)}`
-**Latency:** `{round((i["latency"]))} ms`
-''')
-
 # Stats Module
 
 
@@ -109,7 +78,8 @@ async def ban_globally(_, message):
             await message.reply_text("You want to ban a sudo user? GET REKT!!")
         else:
             served_chats = await get_served_chats()
-            m = await message.reply_text(f"**{user.mention} Will Be Banned  Globally In {len(served_chats)} Seconds.**")
+            m = await message.reply_text(f"**connecting to wbb network to perform a global ban of {user.mention}**\n"
+                                          + f" **this action should take about {len(served_chats)} seconds.**")
             await add_gban_user(user.id)
             number_of_chats = 0
             for served_chat in served_chats:
@@ -160,7 +130,8 @@ __**New Global Ban**__
             await message.reply_text("He's already gbanned, why bully him?")
         else:
             served_chats = await get_served_chats()
-            m = await message.reply_text(f"**{mention} Will Be Banned  Globally In {len(served_chats)} Seconds.**")
+            m = await message.reply_text(f"**connecting to wbb network to perform a global ban of {mention}**\n"
+                                          + f" **this action should take about {len(served_chats)} seconds.**")
             number_of_chats = 0
             for served_chat in served_chats:
                 try:

+ 21 - 4
wbb/utils/functions.py

@@ -1,5 +1,6 @@
 from PIL import Image, ImageDraw, ImageFont, ImageFilter
 from random import randint
+import speedtest
 
 
 def generate_captcha():
@@ -25,10 +26,10 @@ def generate_captcha():
     for _ in range(7):
         wrong_answers.append(gen_wrong_answer())
 
-    width = 120 * 4
-    height = 120
+    width = 80 * 4
+    height = 100
     correct_answer = ""
-    font = ImageFont.truetype("assets/arial.ttf", 90)
+    font = ImageFont.truetype("assets/arial.ttf", 55)
     file = f"assets/{randint(1000, 9999)}.jpg"
     image = Image.new('RGB', (width, height), (255, 255, 255))
     draw = ImageDraw.Draw(image)
@@ -42,7 +43,7 @@ def generate_captcha():
         letter = gen_letter()
         correct_answer += letter
         draw.text(
-            (120 * t + 32, 3),
+            (60 * t + 50, 15),
             letter,
             font=font,
             fill=rndColor2()
@@ -50,3 +51,19 @@ def generate_captcha():
     image = image.filter(ImageFilter.BLUR)
     image.save(file, 'jpeg')
     return [file, correct_answer, wrong_answers]
+
+
+async def test_speedtest():
+    def speed_convert(size):
+        power = 2 ** 10
+        zero = 0
+        units = {0: "", 1: "Kb/s", 2: "Mb/s", 3: "Gb/s", 4: "Tb/s"}
+        while size > power:
+            size /= power
+            zero += 1
+        return f"{round(size, 2)} {units[zero]}"
+    speed = speedtest.Speedtest()
+    info = speed.get_best_server()
+    download = speed.download()
+    upload = speed.upload()
+    return [speed_convert(download), speed_convert(upload), info]

+ 65 - 9
wbb/utils/inlinefuncs.py

@@ -6,23 +6,26 @@ from pyrogram.types import (
     InlineQueryResultArticle,
     InputTextMessageContent,
     InlineKeyboardButton,
-    InlineQueryResultPhoto
+    InlineQueryResultPhoto,
+    InputMediaPhoto
 )
 from googletrans import Translator
 from search_engine_parser import GoogleSearch
 from pykeyboard import InlineKeyboard
 from sys import version as pyver
 from motor import version as mongover
-from pyrogram import __version__ as pyrover
+from pyrogram import __version__ as pyrover, filters
 from time import time, ctime
 from wbb.modules.userbot import eval_executor_func
 from wbb.utils.fetch import fetch
+from wbb.utils.functions import test_speedtest
 from wbb.utils.formatter import convert_seconds_to_minutes as time_convert
 from wbb.utils.pastebin import paste
 from wbb.core.types.InlineQueryResult import InlineQueryResultCachedDocument
 from wbb import (
     arq, app, app2, USERBOT_USERNAME,
-    BOT_USERNAME, LOG_GROUP_ID, USERBOT_ID
+    BOT_USERNAME, LOG_GROUP_ID, USERBOT_ID,
+    SUDOERS
 )
 
 
@@ -120,11 +123,11 @@ async def urban_func(answers, text):
         limit += 1
         try:
             msg = f"""
-    **Query:** {text}
+**Query:** {text}
 
-    **Definition:** __{results[i].definition}__
+**Definition:** __{results[i].definition}__
 
-    **Example:** __{results[i].example}__"""
+**Example:** __{results[i].example}__"""
 
             answers.append(
                 InlineQueryResultArticle(
@@ -193,7 +196,7 @@ async def saavn_func(answers, text):
                 'Download | Play',
                 url=results[i].media_url
             )
-        )
+       )
         buttons_list.append(buttons)
         duration = await time_convert(results[i].duration)
         caption = f"""
@@ -405,7 +408,7 @@ async def lyrics_func(answers, text):
 
 
 async def eval_func(answers, text, user_id):
-    if user_id != USERBOT_ID:
+    if user_id not in SUDOERS:
         msg = "**ERROR**\n__THIS FEATURE IS ONLY FOR SUDO USERS__"
         answers.append(
             InlineQueryResultArticle(
@@ -517,7 +520,7 @@ async def github_repo_func(answers, text):
 
 
 async def tg_search_func(answers, text, user_id):
-    if user_id != USERBOT_ID:
+    if user_id not in SUDOERS:
         msg = "**ERROR**\n__THIS FEATURE IS ONLY FOR SUDO USERS__"
         answers.append(
             InlineQueryResultArticle(
@@ -628,3 +631,56 @@ __{data['answer']}__"""
         )
     )
     return answers
+
+
+async def speedtest_init(query):
+    answers = []
+    user_id = query.from_user.id
+    if user_id not in SUDOERS:
+        msg = "**ERROR**\n__THIS FEATURE IS ONLY FOR SUDO USERS__"
+        answers.append(
+            InlineQueryResultArticle(
+                title="ERROR",
+                description="THIS FEATURE IS ONLY FOR SUDO USERS",
+                input_message_content=InputTextMessageContent(msg)
+            ))
+        return answers
+    msg = "**Click The Button Below To Perform A Speedtest**"
+    button = InlineKeyboard(row_width=1)
+    button.add(InlineKeyboardButton(text="Test", callback_data="test_speedtest"))
+    answers.append(
+             InlineQueryResultArticle(
+                 title="Click Here",
+                 input_message_content=InputTextMessageContent(msg),
+                 reply_markup=button
+                 )
+             )
+    return answers
+
+""" callback query for the function above """
+
+
+@app.on_callback_query(filters.regex(f"test_speedtest"))
+async def test_speedtest_cq(_, cq):
+    if cq.from_user.id not in SUDOERS:
+        await cq.answer("This Isn't For You!")
+        return
+    inline_message_id = cq.inline_message_id
+    await app.edit_inline_text(
+            inline_message_id,
+            "**Testing**"
+    )
+    download, upload, info = await test_speedtest()
+    msg = f"""
+**Download:** `{download}`
+**Upload:** `{upload}`
+**Latency:** `{info['latency']} ms`
+**Country:** `{info['country']} [{info['cc']}]`
+**Latitude:** `{info['lat']}`
+**Longitude:** `{info['lon']}`
+"""
+    await app.edit_inline_text(
+            inline_message_id,
+            msg
+    )
+