Ejemplo n.º 1
0
async def remove_note(message: Message) -> None:
    """ delete note in current chat """
    if '-every' in message.flags:
        NOTES_DATA.clear()
        await asyncio.gather(
            NOTES_COLLECTION.drop(),
            message.edit("`Cleared All Notes in Every Chat !`", del_in=5))
        return
    if '-all' in message.flags:
        if message.chat.id in NOTES_DATA:
            del NOTES_DATA[message.chat.id]
            await asyncio.gather(
                NOTES_COLLECTION.delete_many({'chat_id': message.chat.id}),
                message.edit("`Cleared All Notes in This Chat !`", del_in=5))
        else:
            await message.err("Couldn't find notes in this chat!")
        return
    notename = message.input_str
    if not notename:
        out = "`Wrong syntax`\nNo arguements"
    elif await NOTES_COLLECTION.find_one_and_delete({
            'chat_id': message.chat.id,
            'name': notename
    }):
        out = "`Successfully deleted note:` **{}**".format(notename)
        _note_deleter(message.chat.id, notename)
    else:
        out = "`Couldn't find note:` **{}**".format(notename)
    await message.edit(text=out, del_in=3)
Ejemplo n.º 2
0
async def delete_filters(message: Message) -> None:
    """ delete filter in current chat """
    if '-every' in message.flags:
        FILTERS_DATA.clear()
        await asyncio.gather(
            FILTERS_COLLECTION.drop(),
            message.edit("`Cleared All Filters in Every Chat !`", del_in=5))
        return
    if '-all' in message.flags:
        if message.chat.id in FILTERS_DATA:
            del FILTERS_DATA[message.chat.id]
            await asyncio.gather(
                FILTERS_COLLECTION.delete_many({'chat_id': message.chat.id}),
                message.edit("`Cleared All Filters in This Chat !`", del_in=5))
        else:
            await message.err("Couldn't find filters in this chat!")
        return
    filter_ = message.input_str
    if not filter_:
        out = "`Wrong syntax`\nNo arguements"
    elif await FILTERS_COLLECTION.find_one_and_delete({
            'chat_id': message.chat.id,
            'name': filter_
    }):
        out = "`Successfully deleted filter:` **{}**".format(filter_)
        _filter_deleter(message.chat.id, filter_)
    else:
        out = "`Couldn't find filter:` **{}**".format(filter_)
    await message.edit(text=out, del_in=3)
Ejemplo n.º 3
0
async def gmute_at_entry(msg: Message):
    """ handle gmute """
    chat_id = msg.chat.id
    for user in msg.new_chat_members:
        user_id = user.id
        first_name = user.first_name
        gmuted = await GMUTE_USER_BASE.find_one({'user_id': user_id})
        if gmuted:
            await asyncio.gather(
                msg.client.restrict_chat_member(chat_id, user_id,
                                                ChatPermissions()),
                msg.reply(
                    r"\\**#xdecha_Antispam**//"
                    "\n\nGlobally Muted User Detected in this Chat.\n\n"
                    f"**User:** [{first_name}](tg://user?id={user_id})\n"
                    f"**ID:** `{user_id}`\n**Reason:** `{gmuted['reason']}`\n\n"
                    "**Quick Action:** Muted",
                    del_in=10),
                CHANNEL.log(
                    r"\\**#Antispam_Log**//"
                    "\n\n**GMuted User $SPOTTED**\n"
                    f"**User:** [{first_name}](tg://user?id={user_id})\n"
                    f"**ID:** `{user_id}`\n**Reason:** {gmuted['reason']}\n**Quick Action:** "
                    f"Muted in {msg.chat.title}"))
    msg.continue_propagation()
Ejemplo n.º 4
0
async def add_sudo_cmd(message: Message):
    """ add sudo cmd """
    if '-all' in message.flags:
        await SUDO_CMDS_COLLECTION.drop()
        Config.ALLOWED_COMMANDS.clear()
        tmp_ = []
        for c_d in list(xdecha.manager.enabled_commands):
            t_c = c_d.lstrip(Config.CMD_TRIGGER)
            tmp_.append({'_id': t_c})
            Config.ALLOWED_COMMANDS.add(t_c)
        await asyncio.gather(
            SUDO_CMDS_COLLECTION.insert_many(tmp_),
            message.edit(f"**Added** all (`{len(tmp_)}`) commands to **SUDO** cmds!",
                         del_in=5, log=__name__))
        return
    cmd = message.input_str
    if not cmd:
        await message.err('input not found!')
        return
    cmd = cmd.lstrip(Config.CMD_TRIGGER)
    if cmd in Config.ALLOWED_COMMANDS:
        await message.edit(f"cmd : `{cmd}` already in **SUDO**!", del_in=5)
    elif cmd not in (c_d.lstrip(Config.CMD_TRIGGER)
                     for c_d in list(xdecha.manager.enabled_commands)):
        await message.edit(f"cmd : `{cmd}` 🤔, is that a command ?", del_in=5)
    else:
        Config.ALLOWED_COMMANDS.add(cmd)
        await asyncio.gather(
            SUDO_CMDS_COLLECTION.insert_one({'_id': cmd}),
            message.edit(f"cmd : `{cmd}` added to **SUDO**!", del_in=5, log=__name__))
Ejemplo n.º 5
0
async def del_sudo(message: Message):
    """ delete sudo user """
    if '-all' in message.flags:
        Config.SUDO_USERS.clear()
        await asyncio.gather(
            SUDO_USERS_COLLECTION.drop(),
            message.edit("**SUDO** users cleared!", del_in=5))
        return
    user_id = message.filtered_input_str
    if message.reply_to_message:
        user_id = message.reply_to_message.from_user.id
    if not user_id:
        await message.err(f'user: `{user_id}` not found!')
        return
    if isinstance(user_id, str) and user_id.isdigit():
        user_id = int(user_id)
    if not isinstance(user_id, int):
        await message.err('invalid type!')
        return
    if user_id not in Config.SUDO_USERS:
        await message.edit(f"user : `{user_id}` not in **SUDO**!", del_in=5)
    else:
        Config.SUDO_USERS.remove(user_id)
        await asyncio.gather(
            SUDO_USERS_COLLECTION.delete_one({'_id': user_id}),
            message.edit(f"user : `{user_id}` removed from **SUDO**!", del_in=5, log=__name__))
Ejemplo n.º 6
0
async def enable_userbot(message: Message):
    if message.flags:
        if '-all' in message.flags:
            Config.DISABLED_ALL = False
            Config.DISABLED_CHATS.clear()
            await asyncio.gather(
                DISABLED_CHATS.drop(),
                SAVED_SETTINGS.update_one({'_id': 'DISABLE_ALL_CHATS'},
                                          {"$set": {
                                              'on': False
                                          }},
                                          upsert=True),
                message.edit("**Enabled** all chats!", del_in=5))
        else:
            await message.err("invalid flag!")
    elif message.input_str:
        try:
            chat = await message.client.get_chat(message.input_str)
        except Exception as err:
            await message.err(str(err))
            return
        if chat.id not in Config.DISABLED_CHATS:
            await message.edit("this chat is already enabled!")
        else:
            Config.DISABLED_CHATS.remove(chat.id)
            await asyncio.gather(
                DISABLED_CHATS.delete_one({'_id': chat.id}),
                message.edit(
                    f"CHAT : `{chat.title}` removed from **DISABLED_CHATS**!",
                    del_in=5,
                    log=__name__))
    else:
        await message.err("chat_id not found!")
Ejemplo n.º 7
0
async def rmwhitelist(message: Message):
    """ remove a user from whitelist """
    user_id, _ = message.extract_user_and_text
    if not user_id:
        await message.err("user-id not found")
        return
    get_mem = await message.client.get_user_dict(user_id)
    firstname = get_mem['fname']
    user_id = get_mem['id']
    found = await WHITELIST.find_one({'user_id': user_id})
    if not found:
        await message.err("User Not Found in My WhiteList")
        return
    await asyncio.gather(
        WHITELIST.delete_one({
            'firstname': firstname,
            'user_id': user_id
        }),
        message.edit(
            r"\\**#Removed_Whitelisted_User**//"
            f"\n\n**First Name:** [{firstname}](tg://user?id={user_id})\n"
            f"**User ID:** `{user_id}`"),
        CHANNEL.log(
            r"\\**#Antispam_Log**//"
            f"\n**User:** [{firstname}](tg://user?id={user_id})\n"
            f"**User ID:** `{user_id}`\n"
            f"**Chat:** {message.chat.title}\n"
            f"**Chat ID:** `{message.chat.id}`\n\n$RMWHITELISTED #id{user_id}")
    )
    LOG.info("WhiteListed %s", str(user_id))
Ejemplo n.º 8
0
async def quotecmd(message: Message):
    """quotecmd"""
    asyncio.get_event_loop().create_task(message.delete())
    args = message.input_str
    replied = message.reply_to_message
    async with xdecha.conversation('QuotLyBot') as conv:
        try:
            if replied and not args:
                await conv.forward_message(replied)
            else:
                if not args:
                    await message.err('input not found!')
                    return
                await conv.send_message(args)
        except YouBlockedUser:
            await message.edit('first **unblock** @QuotLyBot')
            return
        quote = await conv.get_response(mark_read=True)
        if not quote.sticker:
            await message.err('something went wrong!')
        else:
            message_id = replied.message_id if replied else None
            await xdecha.send_sticker(chat_id=message.chat.id,
                                      sticker=quote.sticker.file_id,
                                      reply_to_message_id=message_id)
Ejemplo n.º 9
0
async def handle_afk_incomming(message: Message) -> None:
    """ handle incomming messages when you afk """
    user_id = message.from_user.id
    chat = message.chat
    user_dict = await message.client.get_user_dict(user_id)
    afk_time = time_formatter(round(time.time() - TIME))
    coro_list = []
    if user_id in USERS:
        if not (USERS[user_id][0] + USERS[user_id][1]) % randint(2, 4):
            if REASON:
                out_str = (f"I'm still **AFK**.\nReason: <code>{REASON}</code>\n"
                           f"Last Seen: `{afk_time} ago`")
            else:
                out_str = choice(AFK_REASONS)
            coro_list.append(message.reply(out_str))
        if chat.type == 'private':
            USERS[user_id][0] += 1
        else:
            USERS[user_id][1] += 1
    else:
        if REASON:
            out_str = (f"I'm **AFK** right now.\nReason: <code>{REASON}</code>\n"
                       f"Last Seen: `{afk_time} ago`")
        else:
            out_str = choice(AFK_REASONS)
        coro_list.append(message.reply(out_str))
        if chat.type == 'private':
            USERS[user_id] = [1, 0, user_dict['mention']]
        else:
            USERS[user_id] = [0, 1, user_dict['mention']]
    if chat.type == 'private':
        coro_list.append(CHANNEL.log(
            f"#PRIVATE\n{user_dict['mention']} send you\n\n"
            f"{message.text}"))
    else:
        coro_list.append(CHANNEL.log(
            "#GROUP\n"
            f"{user_dict['mention']} tagged you in [{chat.title}](http://t.me/{chat.username})\n\n"
            f"{message.text}\n\n"
            f"[goto_msg](https://t.me/c/{str(chat.id)[4:]}/{message.message_id})"))
    coro_list.append(AFK_COLLECTION.update_one({'_id': user_id},
                                               {"$set": {
                                                   'pcount': USERS[user_id][0],
                                                   'gcount': USERS[user_id][1],
                                                   'men': USERS[user_id][2]}},
                                               upsert=True))
    await asyncio.gather(*coro_list)
Ejemplo n.º 10
0
async def convert_(message: Message):
    """ convert telegram files """
    await message.edit("`Trying to Convert ...`")
    if message.reply_to_message and message.reply_to_message.media:
        message.text = '' if message.reply_to_message.document else ". -d"
        await _handle_message(message)
    else:
        await message.edit("Please read `.help convert`", del_in=5)
Ejemplo n.º 11
0
async def del_sudo_cmd(message: Message):
    """ delete sudo cmd """
    if '-all' in message.flags:
        Config.ALLOWED_COMMANDS.clear()
        await asyncio.gather(
            SUDO_CMDS_COLLECTION.drop(),
            message.edit("**SUDO** cmds cleared!", del_in=5))
        return
    cmd = message.filtered_input_str
    if not cmd:
        await message.err('input not found!')
        return
    if cmd not in Config.ALLOWED_COMMANDS:
        await message.edit(f"cmd : `{cmd}` not in **SUDO**!", del_in=5)
    else:
        Config.ALLOWED_COMMANDS.remove(cmd)
        await asyncio.gather(
            SUDO_CMDS_COLLECTION.delete_one({'_id': cmd}),
            message.edit(f"cmd : `{cmd}` removed from **SUDO**!", del_in=5, log=__name__))
Ejemplo n.º 12
0
async def active_afk(message: Message) -> None:
    """ turn on or off afk mode """
    global REASON, IS_AFK, TIME  # pylint: disable=global-statement
    IS_AFK = True
    TIME = time.time()
    REASON = message.input_str
    await asyncio.gather(
        CHANNEL.log(f"You went AFK! : `{REASON}`"),
        message.edit("`You went AFK!`", del_in=1),
        AFK_COLLECTION.drop(),
        SAVED_SETTINGS.update_one(
            {'_id': 'AFK'}, {"$set": {'on': True, 'data': REASON, 'time': TIME}}, upsert=True))
Ejemplo n.º 13
0
async def webss(message: Message):
    if Config.GOOGLE_CHROME_BIN is None:
        await message.err("need to install Google Chrome. Module Stopping")
        return
    link_match = match(r'\bhttps?://.*\.\S+', message.input_str)
    if not link_match:
        await message.err("`I need a valid link to take screenshots from.`")
        return
    link = link_match.group()
    await message.edit("`Processing ...`")
    chrome_options = webdriver.ChromeOptions()
    chrome_options.binary_location = Config.GOOGLE_CHROME_BIN
    chrome_options.add_argument('--ignore-certificate-errors')
    chrome_options.add_argument("--test-type")
    chrome_options.add_argument("--headless")
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')
    chrome_options.add_argument("--no-sandbox")
    chrome_options.add_argument('--disable-gpu')
    driver = webdriver.Chrome(chrome_options=chrome_options)
    driver.get(link)
    height = driver.execute_script(
        "return Math.max(document.body.scrollHeight, document.body.offsetHeight, "
        "document.documentElement.clientHeight, document.documentElement.scrollHeight, "
        "document.documentElement.offsetHeight);")
    width = driver.execute_script(
        "return Math.max(document.body.scrollWidth, document.body.offsetWidth, "
        "document.documentElement.clientWidth, document.documentElement.scrollWidth, "
        "document.documentElement.offsetWidth);")
    driver.set_window_size(width + 125, height + 125)
    wait_for = height / 1000
    await message.edit(f"`Generating screenshot of the page...`"
                       f"\n`Height of page = {height}px`"
                       f"\n`Width of page = {width}px`"
                       f"\n`Waiting ({int(wait_for)}s) for the page to load.`")
    await asyncio.sleep(int(wait_for))
    im_png = driver.get_screenshot_as_png()
    driver.close()
    message_id = message.message_id
    if message.reply_to_message:
        message_id = message.reply_to_message.message_id
    file_path = os.path.join(Config.DOWN_PATH, "webss.png")
    async with aiofiles.open(file_path, 'wb') as out_file:
        await out_file.write(im_png)
    await asyncio.gather(
        message.delete(),
        message.client.send_document(chat_id=message.chat.id,
                                     document=file_path,
                                     caption=link,
                                     reply_to_message_id=message_id))
    os.remove(file_path)
    driver.quit()
Ejemplo n.º 14
0
async def disable_userbot(message: Message):
    if message.flags:
        if '-all' in message.flags:
            Config.DISABLED_ALL = True
            await asyncio.gather(
                SAVED_SETTINGS.update_one({'_id': 'DISABLE_ALL_CHATS'},
                                          {"$set": {
                                              'on': True
                                          }},
                                          upsert=True),
                message.edit("**Disabled** all chats!", del_in=5))
        else:
            await message.err("invalid flag!")
    else:
        chat = message.chat
        if message.input_str:
            try:
                chat = await message.client.get_chat(message.input_str)
            except Exception as err:
                await message.err(str(err))
                return
        if chat.id in Config.DISABLED_CHATS:
            await message.edit("this chat is already disabled!")
        elif chat.id == Config.LOG_CHANNEL_ID:
            await message.err("can't disabled log channel")
        else:
            Config.DISABLED_CHATS.add(chat.id)
            await asyncio.gather(
                DISABLED_CHATS.insert_one({
                    '_id': chat.id,
                    'title': chat.title
                }),
                message.edit(
                    f"CHAT : `{chat.title}` added to **DISABLED_CHATS**!",
                    del_in=5,
                    log=__name__))
Ejemplo n.º 15
0
async def add_sudo(message: Message):
    """ add sudo user """
    user_id = message.input_str
    if message.reply_to_message:
        user_id = message.reply_to_message.from_user.id
    if not user_id:
        await message.err(f'user: `{user_id}` not found!')
        return
    if isinstance(user_id, str) and user_id.isdigit():
        user_id = int(user_id)
    try:
        user = await message.client.get_user_dict(user_id)
    except PeerIdInvalid as p_e:
        await message.err(p_e)
        return
    if user['id'] in Config.SUDO_USERS:
        await message.edit(f"user : `{user['id']}` already in **SUDO**!", del_in=5)
    else:
        Config.SUDO_USERS.add(user['id'])
        await asyncio.gather(
            SUDO_USERS_COLLECTION.insert_one({'_id': user['id'], 'men': user['mention']}),
            message.edit(f"user : `{user['id']}` added to **SUDO**!", del_in=5, log=__name__))
Ejemplo n.º 16
0
async def ungmute_user(msg: Message):
    """ unmute a user globally """
    await msg.edit("`UnGMuting this User...`")
    user_id, _ = msg.extract_user_and_text
    if not user_id:
        await msg.err("user-id not found")
        return
    get_mem = await msg.client.get_user_dict(user_id)
    firstname = get_mem['fname']
    user_id = get_mem['id']
    found = await GMUTE_USER_BASE.find_one({'user_id': user_id})
    if not found:
        await msg.err("User Not Found in My GMute List")
        return
    await asyncio.gather(
        GMUTE_USER_BASE.delete_one({
            'firstname': firstname,
            'user_id': user_id
        }),
        msg.edit(r"\\**#UnGMuted_User**//"
                 f"\n\n**First Name:** [{firstname}](tg://user?id={user_id})\n"
                 f"**User ID:** `{user_id}`"))
    chats = [
        msg.chat
    ] if msg.client.is_bot else await msg.client.get_common_chats(user_id)
    for chat in chats:
        try:
            await chat.unban_member(user_id)
            await CHANNEL.log(
                r"\\**#Antispam_Log**//"
                f"\n**User:** [{firstname}](tg://user?id={user_id})\n"
                f"**User ID:** `{user_id}`\n"
                f"**Chat:** {chat.title}\n"
                f"**Chat ID:** `{chat.id}`\n\n$UNGMUTED #id{user_id}")
        except (ChatAdminRequired, UserAdminInvalid):
            pass
    LOG.info("UnGMuted %s", str(user_id))
Ejemplo n.º 17
0
async def gmute_user(msg: Message):
    """ Mute a user globally """
    await msg.edit("`Globally Muting this User...`")
    user_id, reason = msg.extract_user_and_text
    if not user_id:
        await msg.edit("`no valid user_id or message specified,`"
                       "`don't do .help gmute for more info. "
                       "Coz no one's gonna help ya`(。ŏ_ŏ) ⚠")
        return
    get_mem = await msg.client.get_user_dict(user_id)
    firstname = get_mem['fname']
    if not reason:
        await msg.edit(
            f"**#Aborted**\n\n**GMuting** of [{firstname}](tg://user?id={user_id}) "
            "`Aborted coz No reason of GMute provided by User`",
            del_in=5)
        return
    user_id = get_mem['id']
    if user_id == msg.from_user.id:
        await msg.err(r"LoL. Why would I GMuting myself ¯\(°_o)/¯")
        return
    if user_id in Config.SUDO_USERS:
        await msg.edit(
            "`That user is in my Sudo List, Hence I can't GMute him.`\n\n"
            "**Tip:** `Remove them from Sudo List and try again. (¬_¬)`",
            del_in=5)
        return
    found = await GMUTE_USER_BASE.find_one({'user_id': user_id})
    if found:
        await msg.edit(
            "**#Already_GMuted**\n\n`This User Already Exists in My GMute List.`\n"
            f"**Reason For GMute:** `{found['reason']}`")
        return
    await asyncio.gather(
        GMUTE_USER_BASE.insert_one({
            'firstname': firstname,
            'user_id': user_id,
            'reason': reason
        }),
        msg.edit(r"\\**#GMuted_User**//"
                 f"\n\n**First Name:** [{firstname}](tg://user?id={user_id})\n"
                 f"**User ID:** `{user_id}`\n**Reason:** `{reason}`"))
    chats = [
        msg.chat
    ] if msg.client.is_bot else await msg.client.get_common_chats(user_id)
    for chat in chats:
        try:
            await chat.restrict_member(user_id, ChatPermissions())
            await CHANNEL.log(
                r"\\**#Antispam_Log**//"
                f"\n**User:** [{firstname}](tg://user?id={user_id})\n"
                f"**User ID:** `{user_id}`\n"
                f"**Chat:** {chat.title}\n"
                f"**Chat ID:** `{chat.id}`\n"
                f"**Reason:** `{reason}`\n\n$GMUTE #id{user_id}")
        except (ChatAdminRequired, UserAdminInvalid):
            pass
    if msg.reply_to_message:
        await CHANNEL.fwd_msg(msg.reply_to_message)
        await CHANNEL.log(f'$GMUTE #prid{user_id} ⬆️')
    LOG.info("G-Muted %s", str(user_id))
Ejemplo n.º 18
0
async def check_and_send(message: Message, *args, **kwargs):
    replied = message.reply_to_message
    if replied:
        await asyncio.gather(message.delete(), replied.reply(*args, **kwargs))
    else:
        await message.edit(*args, **kwargs)
Ejemplo n.º 19
0
async def gban_at_entry(message: Message):
    """ handle gbans """
    chat_id = message.chat.id
    for user in message.new_chat_members:
        user_id = user.id
        first_name = user.first_name
        if await WHITELIST.find_one({'user_id': user_id}):
            continue
        gbanned = await GBAN_USER_BASE.find_one({'user_id': user_id})
        if gbanned:
            if 'chat_ids' in gbanned:
                chat_ids = gbanned['chat_ids']
                chat_ids.append(chat_id)
            else:
                chat_ids = [chat_id]
            await asyncio.gather(
                message.client.kick_chat_member(chat_id, user_id),
                message.reply(
                    r"\\**#xdecha_Antispam**//"
                    "\n\nGlobally Banned User Detected in this Chat.\n\n"
                    f"**User:** [{first_name}](tg://user?id={user_id})\n"
                    f"**ID:** `{user_id}`\n**Reason:** `{gbanned['reason']}`\n\n"
                    "**Quick Action:** Banned",
                    del_in=10),
                CHANNEL.log(
                    r"\\**#Antispam_Log**//"
                    "\n\n**GBanned User $SPOTTED**\n"
                    f"**User:** [{first_name}](tg://user?id={user_id})\n"
                    f"**ID:** `{user_id}`\n**Reason:** {gbanned['reason']}\n**Quick Action:** "
                    f"Banned in {message.chat.title}"),
                GBAN_USER_BASE.update_one(
                    {
                        'user_id': user_id,
                        'firstname': first_name
                    }, {"$set": {
                        'chat_ids': chat_ids
                    }},
                    upsert=True))
        elif Config.ANTISPAM_SENTRY:
            async with aiohttp.ClientSession() as ses:
                async with ses.get(
                        f'https://api.cas.chat/check?user_id={user_id}'
                ) as resp:
                    res = json.loads(await resp.text())
            if res['ok']:
                reason = ' | '.join(
                    res['result']['messages']) if 'result' in res else None
                await asyncio.gather(
                    message.client.kick_chat_member(chat_id, user_id),
                    message.reply(
                        r"\\**#xdecha_Antispam**//"
                        "\n\nGlobally Banned User Detected in this Chat.\n\n"
                        "**$SENTRY CAS Federation Ban**\n"
                        f"**User:** [{first_name}](tg://user?id={user_id})\n"
                        f"**ID:** `{user_id}`\n**Reason:** `{reason}`\n\n"
                        "**Quick Action:** Banned",
                        del_in=10),
                    CHANNEL.log(
                        r"\\**#Antispam_Log**//"
                        "\n\n**GBanned User $SPOTTED**\n"
                        "**$SENRTY #CAS BAN**"
                        f"\n**User:** [{first_name}](tg://user?id={user_id})\n"
                        f"**ID:** `{user_id}`\n**Reason:** `{reason}`\n**Quick Action:**"
                        f" Banned in {message.chat.title}\n\n$AUTOBAN #id{user_id}"
                    ))
            elif Config.SPAM_WATCH_API:
                intruder = await _get_spamwatch_data(user_id)
                if intruder:
                    await asyncio.gather(
                        message.client.kick_chat_member(chat_id, user_id),
                        message.reply(
                            r"\\**#xdecha_Antispam**//"
                            "\n\nGlobally Banned User Detected in this Chat.\n\n"
                            "**$SENTRY SpamWatch Federation Ban**\n"
                            f"**User:** [{first_name}](tg://user?id={user_id})\n"
                            f"**ID:** `{user_id}`\n**Reason:** `{intruder.reason}`\n\n"
                            "**Quick Action:** Banned",
                            del_in=10),
                        CHANNEL.log(
                            r"\\**#Antispam_Log**//"
                            "\n\n**GBanned User $SPOTTED**\n"
                            "**$SENRTY #SPAMWATCH_API BAN**"
                            f"\n**User:** [{first_name}](tg://user?id={user_id})\n"
                            f"**ID:** `{user_id}`\n**Reason:** `{intruder.reason}`\n"
                            f"**Quick Action:** Banned in {message.chat.title}\n\n"
                            f"$AUTOBAN #id{user_id}"))
    message.continue_propagation()
Ejemplo n.º 20
0
async def carbon_(message: Message):
    if Config.GOOGLE_CHROME_BIN is None:
        replied = message.reply_to_message
        if replied:
            text = replied.text
        else:
            text = message.text
        if not text:
            await message.err("need input text!")
            return
        await message.edit("`Creating a Carbon...`")
        async with xdecha.conversation("CarbonNowShBot", timeout=30) as conv:
            try:
                await conv.send_message(text)
            except YouBlockedUser:
                await message.edit('first **unblock** @CarbonNowShBot')
                return
            response = await conv.get_response(mark_read=True)
            while not response.reply_markup:
                response = await conv.get_response(mark_read=True)
            await response.click(x=random.randint(0, 2),
                                 y=random.randint(0, 8))
            response = await conv.get_response(mark_read=True)
            while not response.media:
                response = await conv.get_response(mark_read=True)
            caption = "\n".join(response.caption.split("\n")[0:2])
            file_id = response.document.file_id
            await asyncio.gather(
                message.delete(),
                xdecha.send_document(chat_id=message.chat.id,
                                     document=file_id,
                                     caption='`' + caption + '`',
                                     reply_to_message_id=replied.message_id
                                     if replied else None))
    else:
        input_str = message.filtered_input_str
        replied = message.reply_to_message
        theme = 'seti'
        lang = 'auto'
        red = message.flags.get('r', random.randint(0, 255))
        green = message.flags.get('g', random.randint(0, 255))
        blue = message.flags.get('b', random.randint(0, 255))
        alpha = message.flags.get('a', random.randint(0, 100))
        bg_ = f"rgba({red}, {green}, {blue}, {alpha})"
        if replied and (replied.text or
                        (replied.document
                         and 'text' in replied.document.mime_type)):
            message_id = replied.message_id
            if replied.document:
                await message.edit("`Downloading File...`")
                path_ = await message.client.download_media(
                    replied, file_name=Config.DOWN_PATH)
                async with aiofiles.open(path_) as file_:
                    code = await file_.read()
                os.remove(path_)
            else:
                code = replied.text
            if input_str:
                if '|' in input_str:
                    args = input_str.split('|')
                    if len(args) == 2:
                        theme = args[0].strip()
                        lang = args[1].strip()
                else:
                    theme = input_str
        elif input_str:
            message_id = message.message_id
            if '|' in input_str:
                args = input_str.split('|')
                if len(args) == 3:
                    theme = args[0].strip()
                    lang = args[1].strip()
                    code = args[2].strip()
                elif len(args) == 2:
                    theme = args[0].strip()
                    code = args[1].strip()
            else:
                code = input_str
        else:
            await message.err("need input text!")
            return
        await message.edit("`Creating a Carbon...`")
        code = quote_plus(code)
        await message.edit("`Processing... 20%`")
        carbon_path = os.path.join(Config.DOWN_PATH, "carbon.png")
        if os.path.isfile(carbon_path):
            os.remove(carbon_path)
        url = CARBON.format(theme=theme, lang=lang, code=code, bg=bg_)
        if len(url) > 2590:
            await message.err("input too large!")
            return
        chrome_options = webdriver.ChromeOptions()
        chrome_options.binary_location = Config.GOOGLE_CHROME_BIN
        chrome_options.add_argument("--headless")
        chrome_options.add_argument("--window-size=1920x1080")
        chrome_options.add_argument("--disable-dev-shm-usage")
        chrome_options.add_argument("--no-sandbox")
        chrome_options.add_argument("--disable-gpu")
        prefs = {'download.default_directory': Config.DOWN_PATH}
        chrome_options.add_experimental_option('prefs', prefs)
        driver = webdriver.Chrome(chrome_options=chrome_options)
        driver.get(url)
        await message.edit("`Processing... 40%`")
        driver.command_executor._commands["send_command"] = (  # pylint: disable=protected-access
            "POST", '/session/$sessionId/chromium/send_command')
        params = {
            'cmd': 'Page.setDownloadBehavior',
            'params': {
                'behavior': 'allow',
                'downloadPath': Config.DOWN_PATH
            }
        }
        driver.execute("send_command", params)
        # driver.find_element_by_xpath("//button[contains(text(),'Export')]").click()
        driver.find_element_by_id("export-menu").click()
        await asyncio.sleep(1)
        await message.edit("`Processing... 60%`")
        driver.find_element_by_xpath("//button[contains(text(),'4x')]").click()
        await asyncio.sleep(1)
        driver.find_element_by_xpath(
            "//button[contains(text(),'PNG')]").click()
        await message.edit("`Processing... 80%`")
        while not os.path.isfile(carbon_path):
            await asyncio.sleep(0.5)
        await message.edit("`Processing... 100%`")
        await message.edit("`Uploading Carbon...`")
        await asyncio.gather(
            message.delete(),
            message.client.send_photo(chat_id=message.chat.id,
                                      photo=carbon_path,
                                      reply_to_message_id=message_id))
        os.remove(carbon_path)
        driver.quit()