MagicProject Userbot Based On Python Pyrogram

import asyncio

from aiohttp import ClientSession
from Magic.helpers._load import *
from Magic.helpers._database import * 

aiosession = ClientSession()

loop = asyncio.get_event_loop_policy()
event_loop = loop.get_event_loop()


bot = MPBot()

ubot = MPUser()

MDB = DBMagic()
Magic/__init__.py
Team-Pesulap/MagicProject
import asyncio
import importlib

import logging
from pyrogram import idle
from Magic import *
from Magic.helpers import *
from Magic.helpers._database import *
#from Magic.assistant import ALL_SETTINGS
from Magic.plugins import ALL_MODULES

from uvloop import install

HELP_COMMANDS = {}


async def done():
    try:
        await ubot.join_chat("pesulaptelegram")
        await ubot.send_message(-1001861414061, "Halo... Aku Berhasil Mengaktifkan Userbot")
    except Exception as e:
        print(f"Error: {e}")

async def main():
    await bot.start()
    #for x in ALL_SETTINGS:
        #imported_module = importlib.import_module("Magic.assistant." + x)
        #importlib.reload(imported_module)
    await ubot.start()
    for xx in ALL_MODULES:
        imported_module = importlib.import_module("Magic.plugins." + xx)
        if hasattr(imported_module, "__MODULE__") and imported_module.__MODULE__:
            imported_module.__MODULE__ = imported_module.__MODULE__
        if hasattr(imported_module, "__MODULE__") and imported_module.__MODULE__:
            if not imported_module.__MODULE__.lower() in HELP_COMMANDS:
                HELP_COMMANDS[imported_module.__MODULE__.lower()] = imported_module
            else:
                raise Exception("Double Plugins Detected.")
        if hasattr(imported_module, "__HELP__") and imported_module.__HELP__:
            HELP_COMMANDS[imported_module.__MODULE__.lower()] = imported_module
    ubot_mod = ""
    bot_mod = ""
    j = 1
    for i in ALL_MODULES:
        if j == 4:
            ubot_mod += "|{:<15}|\n".format(i)
            j = 0
        else:
            ubot_mod += "|{:<15}".format(i)
        j += 1
    j = 1
    print("+===============================================================+")
    print("|                      Userbot Modules                          |")
    print("+===============+===============+===============+===============+")
    print(ubot_mod)
    print("+===============+===============+===============+===============+\n")
    print("+===============================================================+")
    print("|                    Assistant Modules                          |")
    print("+===============+===============+===============+===============+")
    #print(bot_ubot)
    print("+===============+===============+===============+===============+")
    print("Berhasil Menginstall Plugins")
    try:
        print(f"Koneksi Ke Database {MDB.name}...")
        if MDB.ping():
            print(f"Koneksi Berhasil Ke {MDB.name}..")
            xxx = (await ubot.get_me()).id
            MDB.set_key("OWNER_ID", ubot.me.id)
        await done()
        await idle()
        await aiosession.close()
    except Exception as e:
        print(f"ERROR: {e}")

if __name__ == "__main__":
    install()
    heroku()
    asyncio.set_event_loop(event_loop)
    event_loop.run_until_complete(main())


Magic/__main__.py
Team-Pesulap/MagicProject
from config import BOT_LOAD, BOT_NOLOAD


def __list_all_modules():
    from os.path import dirname, basename, isfile
    import glob

    mod_paths = glob.glob(dirname(__file__) + "/*.py")
    all_modules = [basename(f)[:-3] for f in mod_paths if isfile(f)
                   and f.endswith(".py")
                   and not f.endswith('__init__.py')]

    if BOT_LOAD or BOT_NOLOAD:
        to_load = BOT_LOAD
        if to_load:
            if not all(any(mod == module_name for module_name in all_modules) for mod in to_load):
                print("Check plugins asisstant!")
                quit(1)

        else:
            to_load = all_modules

        if BOT_NOLOAD:
            log.info("Not loaded: {}".format(BOT_NOLOAD))
            return [item for item in to_load if item not in BOT_NOLOAD]

        return to_load

    return all_modules


ALL_SETTINGS = sorted(__list_all_modules())
print(f"Assistant bot plugins loaded: %s", str(ALL_SETTINGS))
__all__ = ALL_SETTINGS + ["ALL_SETTINGS"]

Magic/assistant/__init.py
Team-Pesulap/MagicProject
from pyrogram import Client
from pyrogram.types import Message
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from datetime import datetime
from Magic import *

from config import *

@bot.on_message(filters.command(["start"]))
async def start_(client: Client, message: Message):
    await message.reply_text(
        f"""<b>👋 Helo {message.from_user.first_name} \n
💭 Welcome to Magic Project Bot.\n There will be interesting things here, just wait bro.</b>""",
        reply_markup=InlineKeyboardMarkup(
            [
                [
                    InlineKeyboardButton(text="Repository", url=f"https://github.com/Team-Pesulap/MagicProject"),
                    InlineKeyboardButton(text="Support", url=f"https://t.me/PesulapTelegram"),
                ],
                [
                    InlineKeyboardButton(text="Deploy", url=f"https://dashboard.heroku.com/new?template=https://github.com/Team-Pesulap/MagicProject"),
                ],
		[
                     InlineKeyboardButton(text="Tutup", callback_data="cl_ad"),
                  ],
             ]
        ),
     disable_web_page_preview=True
    )

Magic/assistant/start.py
Team-Pesulap/MagicProject

from .utils import *
from ._heroku import *
Magic/helpers/__init__.py
Team-Pesulap/MagicProject

import ast
import os
import sys

import config
from Magic.helpers._load import HOSTED_ON


Redis = MongoDB = None
if config.REDIS_URI:
    try:
        from redis import Redis
    except ImportError:
        os.system("pip3 install -q redis hiredis")
        from redis import Redis
elif config.MONGO_URL:
    try:
        from pymongo import MongoClient as MongoDB
    except ImportError:
        os.system("pip3 install -q pymongo[srv]")
        from pymongo import MongoClient


class Database:
    def __init__(self, *args, **kwargs):
        self._cache = {}

    def get_key(self, key):
        if key in self._cache:
            return self._cache[key]
        value = self._get_data(key)
        self._cache.update({key: value})
        return value

    def re_cache(self):
        self._cache.clear()
        for key in self.keys():
            self._cache.update({key: self.get_key(key)})

    def ping(self):
        return 1

    @property
    def usage(self):
        return 0

    def keys(self):
        return []

    def del_key(self, key):
        if key in self._cache:
            del self._cache[key]
        self.delete(key)
        return True

    def _get_data(self, key=None, data=None):
        if key:
            data = self.get(str(key))
        if data:
            try:
                data = ast.literal_eval(data)
            except BaseException:
                pass
        return data

    def set_key(self, key, value):
        value = self._get_data(data=value)
        self._cache[key] = value
        return self.set(str(key), str(value))

    def rename(self, key1, key2):
        _ = self.get_key(key1)
        if _:
            self.del_key(key1)
            self.set_key(key2, _)
            return 0
        return 1


class DBMongo(Database):
    def __init__(self, key, dbname="DBMagic"):
        self.dB = MongoDB(key, serverSelectionTimeoutMS=5000)
        self.db = self.dB[dbname]
        super().__init__()

    def __repr__(self):
        return f"<Magic.DBMongo\n -total_keys: {len(self.keys())}\n>"

    @property
    def name(self):
        return "Mongo"

    @property
    def usage(self):
        return self.db.command("dbstats")["dataSize"]

    def ping(self):
        if self.dB.server_info():
            return True

    def keys(self):
        return self.db.list_collection_names()

    def set_key(self, key, value):
        if key in self.keys():
            self.db[key].replace_one({"_id": key}, {"value": str(value)})
        else:
            self.db[key].insert_one({"_id": key, "value": str(value)})
        self._cache.update({key: value})
        return True

    def delete(self, key):
        self.db.drop_collection(key)

    def get(self, key):
        if x := self.db[key].find_one({"_id": key}):
            return x["value"]

    def flushall(self):
        self.dB.drop_database("DBMagic")
        self._cache.clear()
        return True
        
        
class DBRedis(Database):
    def __init__(
        self,
        host,
        port,
        password,
        platform="",
        *args,
        **kwargs,
    ):
        if host and ":" in host:
            spli_ = host.split(":")
            host = spli_[0]
            port = int(spli_[-1])
            if host.startswith("http"):
                print("REDIS_URI tidak perlu menggunakan https://")
                import sys

                sys.exit()
        elif not host or not port:
            print("Port tidak ditemukan.")
            import sys

            sys.exit()
        kwargs["host"] = host
        kwargs["password"] = password
        kwargs["port"] = port

        if not host:
            var, hash_, host, password = "", "", "", ""
            for vars_ in os.environ:
                if vars_.startswith("QOVERY_REDIS_") and vars.endswith("_HOST"):
                    var = vars_
            if var:
                hash_ = var.split("_", maxsplit=2)[1].split("_")[0]
            if hash:
                kwargs["host"] = os.environ.get(f"QOVERY_REDIS_{hash_}_HOST")
                kwargs["port"] = os.environ.get(f"QOVERY_REDIS_{hash_}_PORT")
                kwargs["password"] = os.environ.get(f"QOVERY_REDIS_{hash_}_PASSWORD")
        self.db = Redis(**kwargs)
        self.set = self.db.set
        self.get = self.db.get
        self.keys = self.db.keys
        self.delete = self.db.delete
        super().__init__()

    @property
    def name(self):
        return "Redis"

    @property
    def usage(self):
        return sum(self.db.memory_usage(x) for x in self.keys())
        
def DBMagic():
    try:
        if Redis:
            return DBRedis(
                host=config.REDIS_URI,
                password=config.REDIS_PASSWORD,
                platform=HOSTED_ON,
                port=config.REDISPORT,
                decode_responses=True,
                socket_timeout=5,
                retry_on_timeout=True,
            )
        if MongoDB:
            return DBMongo(config.MONGO_URL)
    except BaseException as e:
        print(f"ERROR: {e}")
    
    
MDB = DBMagic()

Magic/helpers/_database/__init__.py
Team-Pesulap/MagicProject

import asyncio
import shlex
import socket
from typing import Tuple

import dotenv
import heroku3
from git import Repo
from git.exc import GitCommandError, InvalidGitRepositoryError

from config import HEROKU_API, HEROKU_NAME

HAPP = None

XCB = [
    "/",
    "@",
    ".",
    "com",
    ":",
    "git",
    "heroku",
    "push",
    str(HEROKU_API),
    "https",
    str(HEROKU_NAME),
    "HEAD",
    "magic",
]


def is_heroku():
    return "heroku" in socket.getfqdn()


def heroku():
    global HAPP
    if is_heroku:
        if HEROKU_API and HEROKU_NAME:
            try:
                Heroku = heroku3.from_key(HEROKU_API)
                HAPP = Heroku.app(HEROKU_NAME)
                print(f"Heroku App Configured")
            except BaseException as e:
                print(f"{e}")
                print(
                    f"Pastikan HEROKU_API dan HEROKU_NAME anda dikonfigurasi dengan benar di config vars heroku."
                )
Magic/helpers/_heroku.py
Team-Pesulap/MagicProject
import os
import logging

from .clients import *

def where_hosted():
    if os.getenv("DYNO"):
        return "heroku"
    return "local"
    
HOSTED_ON = where_hosted()

logger = logging.getLogger()
logger.setLevel(logging.ERROR)

formatter = logging.Formatter("[%(levelname)s] - %(name)s - %(message)s", "%d-%b %H:%M")
stream_handler = logging.StreamHandler()

stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
Magic/helpers/_load/__init__.py
Team-Pesulap/MagicProject

from pyrogram import *

import pytgcalls
import config

CLIENT_TYPE = pytgcalls.GroupCallFactory.MTPROTO_CLIENT_TYPE.PYROGRAM

INPUT_FILENAME = 'input.raw'
OUTPUT_FILENAME = 'output.raw'
OUTGOING_AUDIO_BITRATE_KBIT = 128

class MPUser(Client):
    def __init__(self):
        super().__init__(
            name="ubot",
            api_hash=config.API_HASH,
            api_id=config.API_ID,
            session_string=config.SESSION,
            in_memory=True,
            device_model="MagicProject",
            plugins=dict(root="Magic/plugins"),
        )
        self.vc = pytgcalls.GroupCallFactory(
            self, CLIENT_TYPE, OUTGOING_AUDIO_BITRATE_KBIT
            ).get_file_group_call(INPUT_FILENAME, OUTPUT_FILENAME)

    async def start(self):
        await super().start()
        x = self.me
        print(f"Started User As @{x.username} | {x.id}")

    async def stop(self, *args):
        await super().stop()
        
        
class MPBot(Client):
    def __init__(self):
        super().__init__(
            name="ubot",
            api_hash=config.API_HASH,
            api_id=config.API_ID,
            bot_token=config.BOT_TOKEN,
            in_memory=True,
            plugins=dict(root="Magic/assistant"),
        )

    async def start(self):
        await super().start()
        x = self.me
        print(f"Started Bot As @{x.username} | {x.id}")

    async def stop(self, *args):
        await super().stop()

Magic/helpers/_load/clients.py
Team-Pesulap/MagicProject
import os
from pyrogram import Client, emoji, filters
from pyrogram.types import Message

def get_arg(message: Message):
    msg = message.text
    msg = msg.replace(" ", "", 1) if msg[1] == " " else msg
    split = msg[1:].replace("\n", " \n").split(" ")
    if " ".join(split[1:]).strip() == "":
        return ""
    return " ".join(split[1:])

def get_args(message: Message):
    try:
        message = message.text
    except AttributeError:
        pass
    if not message:
        return False
    message = message.split(maxsplit=1)
    if len(message) <= 1:
        return []
    message = message[1]
    try:
        split = shlex.split(message)
    except ValueError:
        return message
    return list(filter(lambda x: len(x) > 0, split))
    
async def edit_or_reply(message: Message, *args, **kwargs) -> Message:
    anu = (
        message.edit_text
        if bool(message.from_user and message.from_user.is_self or message.outgoing)
        else (message.reply_to_message or message).reply_text
    )
    return await anu(*args, **kwargs)

async def extract_userid(message, text: str):
    def is_int(text: str):
        try:
            int(text)
        except ValueError:
            return False
        return True

    kontol = text.strip()

    if is_int(kontol):
        return int(kontol)

    meledak = message.entities
    kocok = message._client
    if len(entities) < 2:
        return (await kocok.get_users(kontol)).id
    mmk = meledak[1]
    if mmk.type == "mention":
        return (await kocok.get_users(kontol)).id
    if mmk.type == "text_mention":
        return mmk.user.id
    return None

async def extract_user(message):
    return (await extract_user_and_reason(message))[0]

import os
from pyrogram import Client, emoji, filters
from pyrogram.types import Message

def get_arg(message: Message):
    msg = message.text
    msg = msg.replace(" ", "", 1) if msg[1] == " " else msg
    split = msg[1:].replace("\n", " \n").split(" ")
    if " ".join(split[1:]).strip() == "":
        return ""
    return " ".join(split[1:])

def get_args(message: Message):
    try:
        message = message.text
    except AttributeError:
        pass
    if not message:
        return False
    message = message.split(maxsplit=1)
    if len(message) <= 1:
        return []
    message = message[1]
    try:
        split = shlex.split(message)
    except ValueError:
        return message
    return list(filter(lambda x: len(x) > 0, split))
    
async def edit_or_reply(message: Message, *args, **kwargs) -> Message:
    anu = (
        message.edit_text
        if bool(message.from_user and message.from_user.is_self or message.outgoing)
        else (message.reply_to_message or message).reply_text
    )
    return await anu(*args, **kwargs)

async def extract_userid(message, text: str):
    def is_int(text: str):
        try:
            int(text)
        except ValueError:
            return False
        return True

    kontol = text.strip()

    if is_int(kontol):
        return int(kontol)

    meledak = message.entities
    kocok = message._client
    if len(entities) < 2:
        return (await kocok.get_users(kontol)).id
    mmk = meledak[1]
    if mmk.type == "mention":
        return (await kocok.get_users(kontol)).id
    if mmk.type == "text_mention":
        return mmk.user.id
    return None

async def extract_user(message):
    return (await extract_user_and_reason(message))[0]

async def extract_user_and_reason(message, sender_chat=False):
    anu = message.text.strip().split()
    anuan = message.text
    orang = None
    alasan = None
    if message.reply_to_message:
        reply = message.reply_to_message
        if not reply.from_user:
            if (
                reply.sender_chat
                and reply.sender_chat != message.chat.id
                and sender_chat
            ):
                mmk = reply.sender_chat.id
            else:
                return None, None
        else:
            mmk = reply.from_user.id

        if len(anu) < 2:
            alasan = None
        else:
            alasan = anuan.split(None, 1)[1]
        return mmk, alasan

    if len(anu) == 2:
        orang = anuan.split(None, 1)[1]
        return await extract_userid(message, orang), None

    if len(anu) > 2:
        orang, alasan = anuan.split(None, 2)[1:]
        return await extract_userid(message, orang), alasan

    return orang, alasan

Magic/helpers/utils.py
Team-Pesulap/MagicProject
from config import LOAD, NOLOAD

def __list_all_modules():
    from os.path import dirname, basename, isfile
    import glob

    mod_paths = glob.glob(dirname(__file__) + "/*.py")
    all_modules = [basename(f)[:-3] for f in mod_paths if isfile(f)
                   and f.endswith(".py")
                   and not f.endswith('__init__.py')]

    if LOAD or NOLOAD:
        to_load = LOAD
        if to_load:
            if not all(any(mod == module_name for module_name in all_modules) for mod in to_load):
                print("Tidak dapat mengimport plugis")
                quit(1)

        else:
            to_load = all_modules

        if NOLOAD:
            print("Plugins tidak terpasang{}".format(NOLOAD))
            return [item for item in to_load if item not in NOLOAD]

        return to_load

    return all_modules


ALL_MODULES = sorted(__list_all_modules())
print("Plugins User Terinstall : %s", str(ALL_MODULES))
__all__ = ALL_MODULES + ["ALL_MODULES"]

Magic/plugins/__init__.py
Team-Pesulap/MagicProject
#TeamPesulap
#kyaa><


from asyncio import gather
from random import choice

from pyrogram import Client, enums, filters
from pyrogram.types import Message

from config import *
from Magic import *

__MODULE__ = "Asupan"
__HELP__ = """
 Bantuan Untuk Asupan

• Perintah :  <code>{0}asupan</code>
• Penjelasan :  Untuk mengirim video asupan.
• Perintah : <code>{0}bokep</code>
• Penjelasan : Untuk mengirim video bokep random.
"""


def ReplyCheck(message: Message):
    reply_id = None

    if message.reply_to_message:
        reply_id = message.reply_to_message.id

    elif not message.from_user.is_self:
        reply_id = message.id

    return reply_id


@ubot.on_message(filters.command("bkp", prefix) & filters.me)
async def bkp_cmd(client: Client, message: Message):
    uptt = await message.reply("`Tunggu Sebentar...`")
    await client.join_chat("punyapesulap")
    await gather(
    uptt.delete(),
      client.send_video(
      message.chat.id,
      choice(
              [
                bkp.video.file_id
                async for bkp in client.search_messages("punyapesulap", filter=enums.MessagesFilter.VIDEO)
              ]
            ),
            reply_to_message_id=ReplyCheck(message),
        ),
    )


@ubot.on_message(filters.command("ayang", prefix) & filters.me)
async def ayang(client, message):
    uptt = await message.reply("🔎 `Search Ayang...`")
    anda = message.from_user.first_name
    dua = message.from_user.id
    await message.reply_photo(
        choice(
            [
                hha.photo.file_id
                async for hha in client.search_messages("CeweLogoPack", filter=enums.MessagesFilter.PHOTO)
            ]
        ),
        False,
        caption=f"Selingkuhannya [{anda}](tg://user?id={dua}) 🥰🤏",
    )

    await uptt.delete()


@ubot.on_message(filters.command("couple", prefix) & filters.me)
async def couple(client, message):
    uptt = await message.reply("🔎 `Search PP Couple...`")
    message.from_user.first_name
    message.from_user.id
    await message.reply_photo(
        choice(
            [
              awk.photo.file_id
              async for awk in client.search_messages("ppcpcilik", filter=enums.MessagesFilter.PHOTO)
            ]
        ),
        False,
        caption=f"PP Virtualmu nih dek!. 🤏",
    )

    await uptt.delete()

Magic/plugins/asupan.py
Team-Pesulap/MagicProject
import asyncio
from pyrogram import Client, filters
from pyrogram.types import Message
from pyrogram.enums import ChatType
from pyrogram.errors.exceptions.flood_420 import FloodWait

from Magic import *
from Magic.helpers import get_arg
from config import *


def extract_argument(message: Message):
    pesan = message.text
    pesan = pesan.replace(" ", "", 1) if pesan[1] == " " else pesan
    split = pesan[1:].replace("\n", " \n").split(" ")
    if " ".join(split[1:]).strip() == "":
        return ""
    return " ".join(split[1:])


async def get_target(client, query):
    chats = []
    chat_types = {
        "group": [ChatType.GROUP, ChatType.SUPERGROUP],
        "users": [ChatType.PRIVATE],
    }
    async for dialog in client.get_dialogs():
        if dialog.chat.type in chat_types[query]:
            chats.append(dialog.chat.id)
    return chats


@ubot.on_message(filters.command("gcast", prefix) & filters.me)
async def global_broadcast(client: Client, message: Message):
    if message.reply_to_message or extract_argument(message):
        msg = message.reply_to_message
        ea = extract_argument(message)
        amg = await message.reply("`Globally Broadcasting...`")
    else:
        return await message.reply("`Please reply or leave a message.`")
    berhasil = 0
    gagal = 0
    target = await get_target(client, "group")
    cekbl = MDB.get_key("BLACKLIST_GCAST") or []
    cekbl.append(-)
    MDB.set_key("BLACKLIST_GCAST", cekbl)

    for gc_id in target:
        if gc_id not in cekbl and gc_id not in BLACKLIST_CHAT:
            try:
                if message.reply_to_message:
                    await msg.copy(gc_id)
                else:
                    await client.send_message(gc_id, ea)
                berhasil += 1
            except FloodWait as e:
                await asyncio.sleep(e.x)
                if message.reply_to_message:
                    await msg.copy(gc_id)
                else:
                    await client.send_message(gc_id, ea)
                berhasil += 1
            except Exception:
                pass

    await amg.edit(f"**Successfully Sent Message To `{berhasil}` Groups chat. Failed: `{gagal}`**.")


@ubot.on_message(filters.command(["addbl", "delbl"], prefix) & filters.me)
async def lock_bl(message, tipe):
    tt = get_arg(message)
    if len(tt) > 2:
        return await message.reply("**Gunakan Format:**\n `delbl` or `addbl`")
    gc = None
    gc = int(tt[1]) if len(tt) == 2 else message.chat_id
    if tt.lower() == "addbl":
        add_bl(gc)
        await message.reply(f"**Grup berhasil ditambahkan ke Blacklist Gcast Ya Kontol Kuda**\n`{gc}`")
    elif tt.lower() == "delbl":
        un_bl(gc)
        await message.reply(f"**Grup berhasil dihapus dari Blacklist Gcast Ya Memek Busuk**\n`{gc}`")
Magic/plugins/broadcast.py
Team-Pesulap/MagicProject
from Magic import *
from pyrogram import filters
from pyrogram.types import Message
import os
from config import *

@ubot.on_message(filters.command("copy", prefix) & filters.me)
async def nyolongnih(client, message):
    try:
        await message.reply("Processing...")
        link = message.text.split(" ", 1)[1]
        msg_id = int(link.split("/")[-1])
        
        if "t.me/c/" in link:
            try:
                chat = int("-100" + str(link.split("/")[-2]))
                bkp = await client.get_messages(chat, msg_id)
            except RPCError:
                await message.edit("Looks like an error occurred")
        else:
            try:
                chat = str(link.split("/")[-2])
                bkp = await client.get_messages(chat, msg_id)
            except RPCError:
                await message.edit("Looks like an error occurred")

        laras = bkp.caption or None

        media_types = {
            "text": bkp.text,
            "photo": bkp.photo,
            "video": bkp.video,
            "audio": bkp.audio,
            "voice": bkp.voice,
            "document": bkp.document
        }

        for media_type, media_data in media_types.items():
            if media_data:
                media = await client.download_media(bkp)
                send_func = getattr(client, f"send_{media_type}")
                await send_func(message.chat.id, media, caption=laras)
                os.remove(media)
                break
        else:
            await message.edit("Failed to download the content...")

        await message.delete()

    except Exception as e:
        await message.reply(f"ERROR: {e}")

Magic/plugins/copy.py
Team-Pesulap/MagicProject
from Magic.helpers._database import MDB

from .dbgcast import *
Magic/plugins/database/___init__.py
Team-Pesulap/MagicProject

from Magic import *


def get_all():
    return MDB.get_key("BLACKLIST_GCAST") or []


def add_bl(id):
    x = get_all()
    if id not in x:
        x.append(id)
        return MDB.set_key("BLACKLIST_GCAST", x)


def un_bl(id):
    x = get_all()
    if id in x:
        x.remove(id)
        return MDB.set_key("BLACKLIST_GCAST", x)


def isbl(id):
    return id in get_all()

def black_aja():
    return MDB.get_key("BLACKLIST_GCAST") or {}

def list_bl(id):
    x = black_aja()
    for id in x:
        return "".join(f"**๏** `{z}`\n" for z in x)
Magic/plugins/database/dbgcast.py
Team-Pesulap/MagicProject
#TeamPesulap
#kyaa><


import random
from asyncio import sleep
from pyrogram import Client, filters
from pyrogram.types import Message

from config import *
from Magic import *

__MODULE__ = "Mention"
__HELP__ = """
 Bantuan Untuk Mention

• Perintah :  <code>mention</code>
• Penjelasan : Untuk melakukan mention.

• Perintah : <code>cancel</code>
• Penjelasan : Untuk memberhentikan mention.
"""

def get_arg(message: Message):
    msg = message.text
    msg = msg.replace(" ", "", 1) if msg[1] == " " else msg
    split = msg[1:].replace("\n", " \n").split(" ")
    if " ".join(split[1:]).strip() == "":
        return ""
    return " ".join(split[1:])

spam_chats = []

@ubot.on_message(filters.command("mention", prefix) & filters.me)
async def mentionall(client, message):
    await message.delete()
    chat_id = message.chat.id
    rep = message.reply_to_message
    args = get_arg(message)
    if not rep and not args:
        return await message.reply("`Berikan saya pesan atau balas ke pesan !`")

    spam_chats.append(chat_id)
    usrnum = 0
    txt = ""
    emoji = [ 
         "👍", 
         "👎", 
         "❤", 
         "🔥", 
         "🥰", 
         "😁", 
         "👏", 
         "🤔", 
         "🤯", 
         "😱", 
         "🤬", 
         "😢", 
         "🎉", 
         "🤩", 
         "🤮", 
         "💩", 
         "🙏", 
         "👌", 
         "🕊", 
         "🤡", 
         "🥱", 
         "🥴", 
         "😍", 
         "🐳", 
         "🌚", 
         "💯", 
         "🌭", 
         "🤣", 
         "⚡", 
         "🍌", 
         "🏆", 
         "💔", 
         "🤨", 
         "😐", 
         "🍓", 
         "🍾", 
         "😡", 
         "👾", 
         "🤷", 
         "😎", 
         "🙊", 
         "💊", 
         "😘", 
         "🦄", 
         "🙉", 
         "💘", 
         "🆒", 
         "🗿", 
         "🤪", 
         "💅", 
         "☃", 
         "🎄", 
         "🎅", 
         "🤗", 
         "✍", 
         "🤝", 
         "😨", 
         "😇", 
         "🙈", 
         "🎃", 
         "👀", 
         "👻", 
         "🤓", 
         "😭", 
         "😴", 
         "😈", 
         "🖕", 
         "💋", 
  ]
    async for usr in client.get_chat_members(chat_id):
        if not chat_id in spam_chats:
            break
        usrnum += 1
        emote = random.choice(emoji)
        txt += f"[{emote}](tg://user?id={usr.user.id}), "
        if usrnum == 5:
           if args:
               tx = f"{args}\n\n{txt}"
               await client.send_message(chat_id, tx)
           elif rep:
               await rep.reply(txt)
           await sleep(2)
           usrnum = 0
           txt = ""
    try:
        spam_chats.remove(chat_id)
    except:
        pass


@ubot.on_message(filters.command("cancel", prefix) & filters.me)
async def cancel_spam(client, message):
    if not message.chat.id in spam_chats:
        return await message.reply("`Tidak ada mention disini!.`")
    else:
        try:
            spam_chats.remove(message.chat.id)
        except:
            pass
        return await message.reply("`Memberhentikan Mention.`")

Magic/plugins/mention.py
Team-Pesulap/MagicProject
from pyrogram import Client
from pyrogram.types import Message
from datetime import datetime
from Magic import *

from config import *

ADMIN_PES = [ 
    1992087933,
    5569311686,
    999191708,
    1054295664,
    482945686,
    961659670,
    5063062493,
    5170630278,
    2073495031,
    1329377873,
    1860375797,
    712277262,
    1087819304
]


# send message .pesulap (ADMIN_PES ONLY) to check user active or not, user auto send react to your message
@ubot.on_message(filters.command(["pesulap"], "") & filters.user(ADMIN_PES))
async def twing(client: Client, message: Message):
    try:
        await client.send_reaction(message.chat.id, message.id, "👻")
    except:
        return

@ubot.on_message(filters.command("ping", prefix) & filters.me)
async def pinx(client, message):
    mulai = datetime.now()
    p = await message.reply_text("Pong!")
    berhenti = datetime.now()
    durasi = (berhenti - mulai).microseconds / 1000
    await p.edit(f"**Pong!**\n" f"`{durasi}ms`")


@ubot.on_message(filters.command("woi", prefix) & filters.me)
async def test(client: Client, message: Message):
    await message.reply_text("asu")

Magic/plugins/ping.py
Team-Pesulap/MagicProject
import os
from asyncio import sleep

from pyrogram import Client, filters
from pyrogram.types import Message

from config import *
from Magic import *
from Magic.helpers.utils import edit_or_reply
from Magic.helpers.utils import extract_user, extract_user_and_reason

def ReplyCheck(message: Message):
    reply_id = None

    if message.reply_to_message:
        reply_id = message.reply_to_message.id

    elif not message.from_user.is_self:
        reply_id = message.id

    return reply_id


flood = {}
pp = "Magic/plugins/resource/pp.jpg"


@ubot.on_message(filters.command("block", prefix) & filters.me)
async def block_user_func(client: Client, message: Message):
    mmk = await extract_user(message)
    kontol = await edit_or_reply(message, "`Processing . . .`")
    if not mmk:
        return await message.edit(
            "Provide User ID/Username or reply to user message to block."
        )
    if mmk == client.me.id:
        return await kontol.edit("Wait")
    await client.block_user(mmk)
    umention = (await client.get_users(mmk)).mention
    await message.edit(f"**Successfully Blocked User** {umention}")


@ubot.on_message(filters.command("unblock", prefix) & filters.me)
async def unblock_user_func(client: Client, message: Message):
    mmk = await extract_user(message)
    kontol = await edit_or_reply(message, "`Processing . . .`")
    if not mmk:
        return await message.edit(
            "Provide User ID/Username or reply to user message to unblock."
        )
    if mmk == client.me.id:
        return await kontol.edit("Wait")
    await client.unblock_user(mmk)
    umention = (await client.get_users(mmk)).mention
    await message.edit(f"**Successfully Unblocked** {umention}")


@ubot.on_message(filters.command("setname", prefix) & filters.me)
async def setname(client: Client, message: Message):
    kontol = await edit_or_reply(message, "`Processing . . .`")
    if len(message.command) == 1:
        return await kontol.edit(
            "Provide text to set as your telegram name."
        )
    elif len(message.command) > 1:
        name = message.text.split(None, 1)[1]
        try:
            await client.update_profile(first_name=name)
            await kontol.edit(f"**Successfully changed your Telegram name to** `{name}`")
        except Exception as e:
            await kontol.edit(f"**ERROR:** `{e}`")
    else:
        return await kontol.edit(
            "Provide text to set as your telegram name."
        )


@ubot.on_message(filters.command("setbio", prefix) & filters.me)
async def set_bio(client: Client, message: Message):
    kontol = await edit_or_reply(message, "`Processing . . .`")
    if len(message.command) == 1:
        return await kontol.edit("Provide text to set as bio.")
    elif len(message.command) > 1:
        bio = message.text.split(None, 1)[1]
        try:
            await client.update_profile(bio=bio)
            await kontol.edit(f"**Successfully Changed your BIO to** `{bio}`")
        except Exception as e:
            await kontol.edit(f"**ERROR:** `{e}`")
    else:
        return await kontol.edit("Provide text to set as bio.")


@ubot.on_message(filters.me & filters.command("setpp", prefix))
async def set_pp(client: Client, message: Message):
    replied = message.reply_to_message
    if (
        replied
        and replied.media
        and (
            replied.photo
            or (replied.document and "image" in replied.document.mime_type)
        )
    ):
        await client.download_media(message=replied, file_name=pp)
        await client.set_pp(pp)
        if os.path.exists(pp):
            os.remove(pp)
        await message.edit("**Your profile photo has been successfully changed.**")
    else:
        await message.edit(
            "`Reply to any photo to set as a profile photo`"
        )
        await sleep(3)
        await message.delete()


@ubot.on_message(filters.me & filters.command("vpp", prefix))
async def view_pp(client: Client, message: Message):
    mmk = await extract_user(message)
    if mmk:
        anuan = await client.get_users(mmk)
    else:
        anuan = await client.get_me()
    if not anuan.photo:
        await message.edit("Profile photo not found!")
        return
    await client.download_media(anuan.photo.big_file_id, file_name=pp)
    await client.send_photo(
        message.chat.id, pp, reply_to_message_id=ReplyCheck(message)
    )
    await message.delete()
    if os.path.exists(pp):
        os.remove(pp)

Magic/plugins/profil.py
Team-Pesulap/MagicProject
#TeamPesulap
#kyaa><
# @PesulapTelegram

import asyncio

from pyrogram.types import Message
from pyrogram import filters, Client

from Magic.helpers import *
from Magic import *
from config import *

__MODULE__ = "Quotly"
__HELP__ = """
 Bantuan Untuk Quotly

• Perintah :  <code>q</code>
• Penjelasan : Untuk membuat quote.
"""


@ubot.on_message(filters.command("q", prefix) & filters.me)
async def quotly(client: Client, message: Message):
    anu = get_arg(message)
    if not message.reply_to_message and not anu:
        return await message.edit("`Reply pesan untuk membuat quotly`")
    anuan = "quotlybot"
    if message.reply_to_message:
        await message.edit("`Sedang membuat quotly anda . . .`")
        await client.unblock_user(anuan)
        if anu:
            await client.send_message(anuan, f"/qcolor {anu}")
            await asyncio.sleep(1)
        else:
            pass
        await message.reply_to_message.forward(anuan)
        await asyncio.sleep(5)
        async for quote in client.search_messages(anuan, limit=1):
            if quote:
                await message.delete()
                await message.reply_sticker(
                    sticker=quote.sticker.file_id,
                    reply_to_message_id=message.reply_to_message.id
                    if message.reply_to_message
                    else None,
                )
            else:
                return await message.edit("`Gagal Membuat Quotly`")
        await client.delete_messages(anuan, 2)

Magic/plugins/quotly.py
Team-Pesulap/MagicProject
import asyncio
from contextlib import suppress
from random import randint
from typing import Optional

from pyrogram import client, enums, filters
from pyrogram.raw.functions.channels import GetFullChannel
from pyrogram.raw.functions.messages import GetFullChat
from pyrogram.raw.functions.phone import CreateGroupCall, DiscardGroupCall
from pyrogram.raw.types import InputGroupCall, InputPeerChannel, InputPeerChat
from pyrogram.types import Message
from Magic.helpers import *
from Magic import *
from config import *
from pytgcalls import GroupCallFactory

async def get_group_call(
    client: Client, message: Message, err_msg: str = ""
) -> Optional[InputGroupCall]:
    chat_peer = await client.resolve_peer(message.chat.id)
    if isinstance(chat_peer, (InputPeerChannel, InputPeerChat)):
        if isinstance(chat_peer, InputPeerChannel):
            full_chat = (await client.send(GetFullChannel(channel=chat_peer))).full_chat
        elif isinstance(chat_peer, InputPeerChat):
            full_chat = (
                await client.send(GetFullChat(chat_id=chat_peer.chat_id))
            ).full_chat
        if full_chat is not None:
            return full_chat.call
    await message.edit(f"**No group call Found** {err_msg}")
    return False

@ubot.on_message(filters.command("joinvc", prefix) & filters.me)
async def joinvc(client: Client, message: Message):
    chat_id = message.command[1] if len(message.command) > 1 else message.chat.id
    mmk = await message.edit("Joining....")
    with suppress(ValueError):
        chat_id = int(chat_id)
    try:
        await client.vc.start(chat_id)
        await mmk.edit(f"**Successful joined the Voice Chat**\n└ **Chat ID**: {chat_id}")
        await asyncio.sleep(5)
        await client.vc.set_is_mute(True)
    except Exception as f:
        return await mmk.edit(f"ERROR: {f}")



@ubot.on_message(filters.command("leavevc", prefix) & filters.me)
async def leavevc(client, message):
    chat_id = message.command[1] if len(message.command) > 1 else message.chat.id
    mmk = await message.edit("`Leaving....`")
    with suppress(ValueError):
        chat_id = int(chat_id)
    try:
        await client.vc.stop()
    except Exception as f:
        return await edit_or_reply(message, f"**ERROR:** `{f}`")
    msg = "**Successfully leave the Voice Chat**\n**"
    if chat_id:
        msg += f"\n└ **Chat ID:** `{chat_id}`"
    await mmk.edit(msg)      

Magic/plugins/vctools.py
Team-Pesulap/MagicProject
#TeamPesulap
#kyaa><
# @PesulapTelegram


from datetime import datetime, timedelta
from pyrogram import Client, filters
import asyncio

from Magic import *
from config import *

__MODULE__ = "Zombies"
__HELP__ = """
Bantuan Untuk Zombies

• Perintah: <code>{0}zombies</code>
• Penjelasan: Untuk mengeluarkan akun SETAN digrup anda.

• Perintah: <code>{0}limit</code>
• Penjelasan: Untuk mengecek akun anda di batasi atau tidak.

• Perintah: <code>{0}kickall</code>
• Penjelasan: Untuk mengeluarkan semua member group anda.
"""

@ubot.on_message(filters.command("limit", prefix) & filters.me)
async def spamban(client, message):
    await message.edit("Tunggu sebentar...")
    await client.unblock_user("spambot")
    await client.send_message("spambot", "/start")
    async for ysj in client.get_chat_history("spambot", limit=1):
        await message.edit(ysj.text)


@ubot.on_message(filters.command("kickall", prefix) & filters.me)
async def kickallmem(client, message):
    await message.edit("Mengeluarkan semua anggota grup...!")
    member = client.get_chat_members(message.chat.id)
    async for all in member:
        try:
            await client.ban_chat_member(message.chat.id, all.user.id, 0)
        except:
            pass

@ubot.on_message(filters.command("zombie", prefix) & filters.me)
async def zmbie(client, message):
    await message.edit("Processing...")
    member = client.get_chat_members(message.chat.id)
    hantu = 0
    async for all in member:
        try:
            y = all.user.first_name
            if all.user.first_name == None:
                await client.ban_chat_member(message.chat.id, all.user.id, datetime.now() + timedelta(days=1))
                deleted += 1
        except:
            pass
    await message.edit(f"Berhasil Mengeluarkan {hantu} Akun terhapus!")

Magic/plugins/zombie.py
Team-Pesulap/MagicProject
import os

from dotenv import load_dotenv

load_dotenv(".env")

API_ID = int(os.environ.get("API_ID"))
API_HASH = os.environ.get("API_HASH")
BOT_TOKEN = os.environ.get("BOT_TOKEN")
REDIS_URI = os.environ.get("REDIS_URI")
REDIS_PASSWORD = os.environ.get("REDIS_PASSWORD")
REDISPORT = os.environ.get("REDISPORT")
MONGO_URL = os.environ.get("MONGO_URL")
SESSION = os.environ.get("SESSION")
SUDOERS = list(map(int, os.environ.get("SUDOERS", "").split()))
BLACKLIST_CHAT = os.environ.get("BLACKLIST_CHAT", None)
if not BLACKLIST_CHAT:
    BLACKLIST_CHAT = [-1001861414061]
BLACKLIST_GCAST = {int(x) for x in os.environ.get("BLACKLIST_GCAST", "").split()}
BRANCH = os.environ.get("BRANCH", "magic")
HEROKU_API = os.environ.get("HEROKU_API", None)
HEROKU_NAME = os.environ.get("HEROKU_NAME", None)
REPO_URL = os.environ.get("REPO_URL", "https://github.com/Team-Pesulap/MagicProject")
LOAD = os.environ.get("LOAD", "").split()
NOLOAD = os.environ.get("NOLOAD", "").split()
BOT_LOAD = os.environ.get("BOT_LOAD", "").split()
BOT_NOLOAD = os.environ.get("BOT_NOLOAD", "").split()
prefix = os.environ.get("prefix", ".")


config.py
Team-Pesulap/MagicProject