소스 검색

Added Pipes

TheHamkerCat 5 년 전
부모
커밋
98a6c0e181
9개의 변경된 파일과 263개의 추가작업 그리고 156개의 파일을 삭제
  1. 4 14
      README.md
  2. 0 3
      wbb/modules/arq.py
  3. 0 106
      wbb/modules/bay.py
  4. 2 0
      wbb/modules/blacklist.py
  5. 6 3
      wbb/modules/misc.py
  6. 23 0
      wbb/modules/paste.py
  7. 157 0
      wbb/modules/pipes.py
  8. 70 30
      wbb/utils/dbfunctions.py
  9. 1 0
      wbb/utils/filter_groups.py

+ 4 - 14
README.md

@@ -63,17 +63,7 @@ $ python3 str_gen.py
 
 [![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy?template=https://github.com/thehamkercat/WilliamButcherBot/)
 
-## Features 
-
-* Group Management
-* Userbot [Including Ai PM PERMIT]
-* Music Downloading 
-* AI Chatbot
-* Web Scraping
-* Get Pictures/Wallpapers
-* Dictionary
-* Translation
-* Message Cryptography
-* Python Interpreter (Right In Your Telegram Chat!)
-* Nekobin (Paste Code/Text)
-* And Much More...
+
+## Note
+
+1. Support Chat: https://t.me/wbbsupport

+ 0 - 3
wbb/modules/arq.py

@@ -24,9 +24,6 @@ SOFTWARE.
 from wbb import app, arq, ARQ_API_BASE_URL
 from pyrogram import filters
 
-__MODULE__ = "ARQ"
-__HELP__ = "/arq - Stats Of ARQ API."
-
 
 @app.on_message(filters.command("arq"))
 async def arq_stats(_, message):

+ 0 - 106
wbb/modules/bay.py

@@ -1,106 +0,0 @@
-"""
-MIT License
-
-Copyright (c) 2021 TheHamkerCat
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-"""
-import os
-import requests
-import aiohttp
-import aiofiles
-from wbb import app, SUDOERS
-from pyrogram import filters
-from random import randint
-from wbb.core.decorators.errors import capture_err
-
-
-__MODULE__ = "BAYFILES"
-__HELP__ = """/url [URL] To upload a url to bayfiles. [SUDO ONLY]
-/tg To Upload a telegram file to bayfiles. [SUDO ONLY]"""
-
-
-@app.on_message(filters.command("url") & filters.user(SUDOERS))
-@capture_err
-async def url(_, message):
-    if len(message.command) != 2:
-        await message.reply_text("/url [url]")
-        return
-    m = await message.reply_text("Downloading")
-    lenk = message.text.split(None, 1)[1]
-    try:
-        filename = await download(lenk)
-        files = {'file': open(filename, 'rb')}
-        await m.edit("Uploading....")
-        r = requests.post("https://api.bayfiles.com/upload", files=files)
-        text = r.json()
-        output = f"""
-**status:** `{text['status']}`
-**link:** {text['data']['file']['url']['full']}
-**id:** `{text['data']['file']['metadata']['id']}`
-**name:** `{text['data']['file']['metadata']['name']}`
-**size:** `{text['data']['file']['metadata']['size']['readable']}`"""
-        await m.edit(output)
-        os.remove(filename)
-    except Exception as e:
-        print(str(e))
-        await m.edit(str(e))
-        return
-
-
-@app.on_message(filters.command("tg") & filters.user(SUDOERS))
-@capture_err
-async def tg(_, message):
-    if not message.reply_to_message:
-        await message.reply_text("Reply To A File With /tg To Upload")
-        return
-    if not message.reply_to_message.media:
-        await message.reply_text("Reply To A File With /tg To Upload")
-        return
-    m = await message.reply_text("Downloading Document.")
-    fn = await message.reply_to_message.download()
-    try:
-        files = {'file': open(fn, 'rb')}
-        await m.edit("Uploading....")
-        r = requests.post("https://api.bayfiles.com/upload", files=files)
-        text = r.json()
-        output = f"""
-**Status:** `{text['status']}`
-**Link:** {text['data']['file']['url']['full']}
-**ID:** `{text['data']['file']['metadata']['id']}`
-**Name:** `{text['data']['file']['metadata']['name']}`
-**Size:** `{text['data']['file']['metadata']['size']['readable']}`"""
-        await m.edit(output)
-        os.remove(fn)
-    except Exception as e:
-        print(str(e))
-        await m.edit(str(e))
-        return
-
-
-async def download(url):
-    ext = url.split(".")[-1]
-    filename = str(randint(1000, 9999)) + "." + ext
-    async with aiohttp.ClientSession() as session:
-        async with session.get(url) as resp:
-            if resp.status == 200:
-                f = await aiofiles.open(filename, mode='wb')
-                await f.write(await resp.read())
-                await f.close()
-    return filename

+ 2 - 0
wbb/modules/blacklist.py

@@ -104,6 +104,8 @@ async def blacklist_filters_re(_, message):
         return
     chat_id = message.chat.id
     user = message.from_user
+    if not user:
+        return
     if user.id in SUDOERS:
         return
     try:

+ 6 - 3
wbb/modules/misc.py

@@ -35,7 +35,8 @@ from wbb.utils.pastebin import paste
 from wbb.core.decorators.errors import capture_err
 
 __MODULE__ = "Misc"
-__HELP__ = '''/commit - Generate Funny Commit Messages
+__HELP__ = '''
+/commit - Generate Funny Commit Messages
 /runs  - Idk Test Yourself
 /id - Get Chat_ID or User_ID
 /random [Length] - Generate Random Complex Passwords
@@ -45,8 +46,10 @@ __HELP__ = '''/commit - Generate Funny Commit Messages
 /weather [City] - To Get Weather Info
 /tr [en] - Translate A Message
 /json [URL] - Get JSON Response From An API or Something.
-/ocr - Perform OCR on an image.
-#RTFM - Check it lol'''
+/ocr - Perform OCR On An Image.
+/arq - Statistics Of ARQ API.
+#RTFM - Check it lol
+'''
 
 
 @app.on_message(filters.command("commit") & ~filters.edited)

+ 23 - 0
wbb/modules/paste.py

@@ -1,3 +1,26 @@
+"""
+MIT License
+
+Copyright (c) 2021 TheHamkerCat
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+"""
 import os
 import asyncio
 from pyrogram import filters

+ 157 - 0
wbb/modules/pipes.py

@@ -0,0 +1,157 @@
+"""
+MIT License
+
+Copyright (c) 2021 TheHamkerCat
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+"""
+from wbb import app, app2, SUDOERS, MESSAGE_DUMP_CHAT, USERBOT_ID, BOT_ID
+from wbb.core.decorators.errors import capture_err
+from wbb.utils.filter_groups import pipes_group
+from wbb.utils.dbfunctions import is_pipe_active, activate_pipe, deactivate_pipe, show_pipes
+from pyrogram import filters
+from pyrogram.types import Message
+import asyncio
+
+__MODULE__ = "Pipes"
+__HELP__ = """
+**THIS MODULE IS ONLY FOR DEVS**
+
+Use this module to create a pipe that will forward messages of one chat/channel to another.
+
+
+/activate_pipe [FROM_CHAT_ID] [TO_CHAT_ID] [BOT|USERBOT]
+
+Active a pipe.
+
+choose 'BOT' or 'USERBOT' according to your needs, this will decide
+which client will fetch the message from 'FROM_CHAT'.
+
+
+/deactivate_pipe [FROM_CHAT_ID] [TO_CHAT_ID]
+
+Deactivete a pipe.
+
+
+/show_pipes
+
+Show all the active pipes.
+"""
+pipes_list_bot = []
+pipes_list_userbot = []
+
+
+async def load_pipes():
+    global pipes_list_bot, pipes_list_userbot
+    pipes_list_bot = []
+    pipes_list_userbot = []
+    pipes = await show_pipes()
+    for pipe in pipes:
+        if pipe['fetcher'] == "bot":
+            pipes_list_bot.append(pipe)
+            continue
+        pipes_list_userbot.append(pipe)
+
+loop = asyncio.get_running_loop()
+loop.create_task(load_pipes())
+
+
+@app.on_message(~filters.me, group=pipes_group)
+async def pipes_worker_bot(_, message: Message):
+    for pipe in pipes_list_bot:
+        if pipe['from_chat_id'] == message.chat.id:
+            await message.forward(pipe['to_chat_id'])
+
+
+@app2.on_message(~filters.me, group=pipes_group)
+async def pipes_worker_userbot(_, message: Message):
+    for pipe in pipes_list_userbot:
+        if pipe['from_chat_id'] == message.chat.id:
+            if not message.text:
+                m, temp = await asyncio.gather(
+                    app.listen(USERBOT_ID),
+                    message.copy(BOT_ID)
+                )
+                caption = f"Forwarded from `{pipe['from_chat_id']}`"
+                caption = f"{temp.caption}\n\n{caption}" if temp.caption else caption
+                await app.copy_message(
+                    pipe['to_chat_id'],
+                    USERBOT_ID,
+                    m.message_id,
+                    caption=caption
+                )
+                await asyncio.sleep(10)
+                await temp.delete()
+                return
+            caption = f"Forwarded from `{pipe['from_chat_id']}`"
+            await app.send_message(
+                pipe['to_chat_id'],
+                text=message.text + "\n\n" + caption
+            )
+
+
+@app.on_message(filters.command("activate_pipe") & filters.user(SUDOERS))
+async def activate_pipe_func(_, message: Message):
+    if len(message.command) != 4:
+        await message.reply_text("**Usage:**\n/activate_pipe [FROM_CHAT_ID] [TO_CHAT_ID] [BOT|USERBOT]")
+        return
+    text = message.text.strip().split()
+    from_chat = int(text[1])
+    to_chat = int(text[2])
+    fetcher = text[3].lower()
+    if fetcher != "bot" and fetcher != "userbot":
+        await message.reply_text("Wrong fetcher, see help menu.")
+        return
+    chat_id = message.chat.id
+    if await is_pipe_active(from_chat, to_chat):
+        await message.reply_text("This pipe is already active.")
+        return
+    await activate_pipe(from_chat, to_chat, fetcher)
+    await load_pipes()
+    await message.reply_text("Activated pipe.")
+
+
+@app.on_message(filters.command("deactivate_pipe") & filters.user(SUDOERS))
+async def deactivate_pipe_func(_, message: Message):
+    if len(message.command) != 3:
+        await message.reply_text("**Usage:**\n/deactivate_pipe [FROM_CHAT_ID] [TO_CHAT_ID]")
+        return
+    text = message.text.strip().split()
+    from_chat = int(text[1])
+    to_chat = int(text[2])
+    chat_id = message.chat.id
+    if not await is_pipe_active(from_chat, to_chat):
+        await message.reply_text("This pipe is already inactive.")
+        return
+    await deactivate_pipe(from_chat, to_chat)
+    await load_pipes()
+    await message.reply_text("Deactivated pipe.")
+
+
+@app.on_message(filters.command("pipes") & filters.user(SUDOERS))
+async def show_pipes_func(_, message: Message):
+    pipes = pipes_list_bot + pipes_list_userbot
+    if not pipes:
+        await message.reply_text("No pipe is active.")
+        return
+    text = ""
+    for count, pipe in enumerate(pipes, 1):
+        text += f"**Pipe:** `{count}`\n**From:** `{pipe['from_chat_id']}`\n" \
+                + f"**To:** `{pipe['to_chat_id']}`\n**Fetcher:** `{pipe['fetcher']}`\n\n"
+    await message.reply_text(text)

+ 70 - 30
wbb/utils/dbfunctions.py

@@ -39,6 +39,7 @@ welcomedb = db.welcome_text
 nsfwdb = db.nsfw
 captcha_cachedb = db.captcha_cache
 blacklist_filtersdb = db.blaclist_filters
+pipesdb = db.pipes
 
 """ Notes functions """
 
@@ -61,11 +62,9 @@ async def get_notes_count() -> dict:
 
 async def _get_notes(chat_id: int) -> Dict[str, int]:
     _notes = await notesdb.find_one({"chat_id": chat_id})
-    if _notes:
-        _notes = _notes["notes"]
-    else:
-        _notes = {}
-    return _notes
+    if not _notes:
+        return {}
+    return _notes["notes"]
 
 
 async def get_note_names(chat_id: int) -> List[str]:
@@ -139,11 +138,9 @@ async def get_filters_count() -> dict:
 
 async def _get_filters(chat_id: int) -> Dict[str, int]:
     _filters = await filtersdb.find_one({"chat_id": chat_id})
-    if _filters:
-        _filters = _filters['filters']
-    else:
-        _filters = {}
-    return _filters
+    if not _filters:
+        return []
+    return _filters['filters']
 
 
 async def get_filters_names(chat_id: int) -> List[str]:
@@ -235,11 +232,9 @@ async def get_warns_count() -> dict:
 
 async def get_warns(chat_id: int) -> Dict[str, int]:
     warns = await warnsdb.find_one({"chat_id": chat_id})
-    if warns:
-        warns = warns['warns']
-    else:
-        warns = {}
-    return warns
+    if not warns:
+        return {}
+    return warns['warns']
 
 
 async def get_warn(chat_id: int, name: str) -> Union[bool, dict]:
@@ -317,11 +312,9 @@ async def user_global_karma(user_id) -> int:
 
 async def get_karmas(chat_id: int) -> Dict[str, int]:
     karma = await karmadb.find_one({"chat_id": chat_id})
-    if karma:
-        karma = karma['karma']
-    else:
-        karma = {}
-    return karma
+    if not karma:
+        return {}
+    return karma['karma']
 
 
 async def get_karma(chat_id: int, name: str) -> Union[bool, dict]:
@@ -435,11 +428,9 @@ async def remove_gban_user(user_id: int):
 
 async def _get_lovers(chat_id: int):
     lovers = await coupledb.find_one({"chat_id": chat_id})
-    if lovers:
-        lovers = lovers["couple"]
-    else:
-        lovers = {}
-    return lovers
+    if not lovers:
+        return {}
+    return lovers["couple"]
 
 
 async def get_couple(chat_id: int, date: str):
@@ -629,11 +620,9 @@ async def get_blacklist_filters_count() -> dict:
 
 async def get_blacklisted_words(chat_id: int) -> List[str]:
     _filters = await blacklist_filtersdb.find_one({"chat_id": chat_id})
-    if _filters:
-        _filters = _filters['filters']
-    else:
-        _filters = []
-    return _filters
+    if not _filters:
+        return []
+    return _filters['filters']
 
 
 async def save_blacklist_filter(chat_id: int, word: str):
@@ -668,3 +657,54 @@ async def delete_blacklist_filter(chat_id: int, word: str) -> bool:
         return True
     return False
 
+""" PIPES SYSTEM """
+
+
+async def activate_pipe(from_chat_id: int, to_chat_id: int, fetcher: str):
+    pipes = await show_pipes()
+    pipe = {
+        "from_chat_id": from_chat_id,
+        "to_chat_id": to_chat_id,
+        "fetcher": fetcher
+    }
+    pipes.append(pipe)
+    return await pipesdb.update_one(
+        {"pipe": "pipe"},
+        {
+            "$set": {
+                "pipes": pipes
+            }
+        },
+        upsert=True
+    )
+
+
+async def deactivate_pipe(from_chat_id: int, to_chat_id: int):
+    pipes = await show_pipes()
+    if not pipes:
+        return
+    for pipe in pipes:
+        if pipe['from_chat_id'] == from_chat_id and pipe['to_chat_id'] == to_chat_id:
+            pipes.remove(pipe)
+    return await pipesdb.update_one(
+        {"pipe": "pipe"},
+        {
+            "$set": {
+                "pipes": pipes
+            }
+        },
+        upsert=True
+    )
+
+
+async def is_pipe_active(from_chat_id: int, to_chat_id: int) -> bool:
+    for pipe in await show_pipes():
+        if pipe['from_chat_id'] == from_chat_id and pipe['to_chat_id'] == to_chat_id:
+            return True
+
+
+async def show_pipes() -> list:
+    pipes = await pipesdb.find_one({"pipe": "pipe"})
+    if not pipes:
+        return []
+    return pipes['pipes']

+ 1 - 0
wbb/utils/filter_groups.py

@@ -30,3 +30,4 @@ welcome_captcha_group = 6
 antiflood_group = 7
 nsfw_detect_group = 8
 blacklist_filters_group = 9
+pipes_group = 10