Ejemplo n.º 1
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.º 2
0
 async def func(_, __, m: Message) -> bool:
     text = m.text or m.caption
     bot_ = (await get_bot_info()).get("bot")
     username = "******" + bot_.uname if bot_ else ""
     pattern = comp_regex(f"(?i)^/start({username})?([\s]+)?$")
     m.matches = (list(pattern.finditer(text))
                  if text else None) or None
     return bool((m.chat and m.chat.type == "private") and m.matches
                 and not m.edit_date)
Ejemplo n.º 3
0
async def del_sudo_cmd(message: Message):
    cmd = message.filtered_input_str
    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
    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}),
            CHANNEL.log(f"cmd : `{cmd}` removed from **SUDO**!"),
            message.edit(f"cmd : `{cmd}` removed from **SUDO**!", del_in=5))
Ejemplo n.º 4
0
async def raw_say(message: Message, name, collection):
    user = message.new_chat_members[0] if name == "Welcome" \
        else message.left_chat_member
    user_dict = await userge.get_user_dict(user.id)
    user_dict.update(
        {'chat': message.chat.title if message.chat.title else "this group"})
    found = await collection.find_one({'_id': message.chat.id}, {
        'media': 0,
        'name': 0
    })
    caption = found['data']
    file_type = found['type'] if 'type' in found else ''
    file_id = found['fid'] if 'fid' in found else ''
    file_ref = found['fref'] if 'fref' in found else ''
    if caption:
        caption = caption.format_map(SafeDict(**user_dict))
    if file_id:
        try:
            await send_proper_type(message, caption, file_type, file_id,
                                   file_ref)
        except (FileIdInvalid, FileReferenceEmpty, BadRequest):
            found = await collection.find_one({'_id': message.chat.id}, {
                'media': 1,
                'name': 1
            })
            file_name = found['name']
            media = found['media']
            tmp_media_path = os.path.join(Config.DOWN_PATH, file_name)
            async with aiofiles.open(tmp_media_path, "wb") as media_file:
                await media_file.write(base64.b64decode(media))
            file_id, file_ref = await send_proper_type(message, caption,
                                                       file_type,
                                                       tmp_media_path)
            await collection.update_one(
                {'_id': message.chat.id},
                {"$set": {
                    'fid': file_id,
                    'fref': file_ref
                }},
                upsert=True)
            os.remove(tmp_media_path)
    else:
        await message.reply(caption, del_in=Config.WELCOME_DELETE_TIMEOUT)
    message.stop_propagation()
Ejemplo n.º 5
0
async def term_(message: Message):
    """ run commands in shell (terminal with live update) """
    cmd = await init_func(message)
    if cmd is None:
        return

    await message.edit("`Executing terminal ...`")
    try:
        parsed_cmd = parse_py_template(cmd, message)
    except Exception as e:  # pylint: disable=broad-except
        await message.err(str(e))
        await CHANNEL.log(f"**Exception**: {type(e).__name__}\n**Message**: " +
                          str(e))
        return
    try:
        t_obj = await Term.execute(parsed_cmd)  # type: Term
    except Exception as t_e:  # pylint: disable=broad-except
        await message.err(str(t_e))
        return

    cur_user = getuser()
    try:
        uid = geteuid()
    except ImportError:
        uid = 1
    prefix = f"<b>{cur_user}:~#</b>" if uid == 0 else f"<b>{cur_user}:~$</b>"
    output = f"{prefix} <pre>{cmd}</pre>\n"

    async def _worker():
        await t_obj.wait()
        while not t_obj.finished:
            await message.edit(f"{output}<pre>{await t_obj.read_line()}</pre>",
                               parse_mode='html')
            try:
                await asyncio.wait_for(t_obj.finish_listener,
                                       Config.EDIT_SLEEP_TIMEOUT)
            except asyncio.TimeoutError:
                pass

    def _on_cancel():
        t_obj.cancel()
        task.cancel()

    task = asyncio.create_task(_worker())
    with message.cancel_callback(_on_cancel):
        try:
            await task
        except asyncio.CancelledError:
            await message.canceled(reply=True)
            return

    out_data = f"{output}<pre>{await t_obj.get_output()}</pre>\n{prefix}"
    await message.edit_or_send_as_file(out_data,
                                       parse_mode='html',
                                       filename="term.txt",
                                       caption=cmd)
Ejemplo n.º 6
0
async def split_(message: Message) -> None:
    """ split files """
    split_size = int(message.matches[0].group(1))
    file_path = str(message.matches[0].group(2))
    if not file_path:
        await message.err("missing file path!")
        return
    if not isfile(file_path):
        await message.err("file path not exists!")
        return
    await message.edit("`processing...`")
    start_t = datetime.now()
    s_obj = SCLib(file_path)
    s_obj.split(split_size)
    tmp = \
        "__Splitting file path...__\n" + \
        "```{}({}%)```\n" + \
        "**File Path** : `{}`\n" + \
        "**Dest** : `{}`\n" + \
        "**Completed** : `{}`\n" + \
        "**Total** : `{}`\n" + \
        "**Speed** : `{}/s`\n" + \
        "**ETA** : `{}`\n" + \
        "**Completed Files** : `{}/{}`"

    async def _worker():
        while not s_obj.finished:
            await message.edit(
                tmp.format(s_obj.progress, s_obj.percentage, file_path,
                           s_obj.final_file_path, humanbytes(s_obj.completed),
                           humanbytes(s_obj.total), humanbytes(s_obj.speed),
                           s_obj.eta, s_obj.completed_files,
                           s_obj.total_files))
            await sleep(Config.EDIT_SLEEP_TIMEOUT)

    def _on_cancel():
        s_obj.cancel()
        task.cancel()

    task = asyncio.create_task(_worker())
    with message.cancel_callback(_on_cancel):
        try:
            await task
        except asyncio.CancelledError:
            await message.canceled()
            return

    if s_obj.output:
        await message.err(s_obj.output, show_help=False)
    else:
        end_t = datetime.now()
        m_s = (end_t - start_t).seconds
        await message.edit(
            f"**split** `{file_path}` into `{s_obj.final_file_path}` "
            f"in `{m_s}` seconds.",
            log=__name__)
Ejemplo n.º 7
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.º 8
0
async def del_sudo(message: Message):
    """delete sudo user"""
    if "-all" in message.flags:
        Config.SUDO_USERS.clear()
        Config.TRUSTED_SUDO_USERS.clear()
        await asyncio.gather(
            SUDO_USERS_COLLECTION.drop(),
            TRUSTED_SUDO_USERS.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.TRUSTED_SUDO_USERS and user_id not in Config.SUDO_USERS:
        await message.edit(f"user : `{user_id}` already not in any **SUDO**!",
                           del_in=5)
    elif user_id in Config.TRUSTED_SUDO_USERS:
        Config.TRUSTED_SUDO_USERS.remove(user_id)
        await asyncio.gather(
            TRUSTED_SUDO_USERS.delete_one({"_id": user_id}),
            message.edit(
                f"user : `{user_id}` removed from **TRUSTED SUDO**!",
                del_in=5,
                log=__name__,
            ),
        )
    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.º 9
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:
            if chat.type == "private":
                c_name = " ".join([chat.first_name, chat.last_name or ""])
            else:
                c_name = chat.title
            Config.DISABLED_CHATS.add(chat.id)
            await asyncio.gather(
                DISABLED_CHATS.insert_one({
                    "_id": chat.id,
                    "title": chat.title
                }),
                message.edit(
                    f"CHAT : `{c_name}` added to **DISABLED_CHATS**!\n`Bot might restart, wait for some time...`",
                    del_in=5,
                    log=__name__,
                ),
            )
Ejemplo n.º 10
0
async def video_compress(message: Message):
    """ compress video """
    replied = message.reply_to_message
    if message.filtered_input_str and ' ' not in message.filtered_input_str:
        return await message.err("path not specified!")

    percentage, input_str = message.filtered_input_str.split(' ', 1)
    data = await get_media_path_and_name(message, input_str=input_str)
    if not data:
        return

    dl_loc, file_name = data
    FF_MPEG_DOWN_LOAD_MEDIA_PATH.mkdir(parents=True, exist_ok=True)
    await message.edit("`Compressing media...`")
    # https://github.com/kkroening/ffmpeg-python/issues/545
    info = await probe(dl_loc)
    total_time = floor(float(info['streams'][0]['duration']))
    target_percentage = int(percentage)
    filesize = Path(dl_loc).stat().st_size
    # https://github.com/AbirHasan2005/VideoCompress/blob/main/bot/helper_funcs/ffmpeg.py#L60
    calculated_percentage = 100 - target_percentage
    target_size = (calculated_percentage / 100) * filesize
    target_bitrate = int(floor(target_size * 8 / total_time))
    if target_bitrate // 1000000 >= 1:
        bitrate = str(target_bitrate // 1000000) + "M"
    else:
        bitrate = str(target_bitrate // 1000) + "k"
    video_file = f"{FF_MPEG_DOWN_LOAD_MEDIA_PATH}/compressed_{file_name}"
    start = datetime.now()
    try:
        await run(
            ffmpeg.input(dl_loc).output(video_file,
                                        video_bitrate=bitrate,
                                        bufsize=bitrate,
                                        vcodec="h264",
                                        preset="ultrafast"))
    except ffmpeg.Error as e:
        await message.err(f"{e.stderr}")
    else:
        message_id = replied.id if replied else None
        caption = (
            f"[{humanbytes(Path(video_file).stat().st_size)}]\n"
            f"{replied.caption if hasattr(replied, 'media') else file_name}")
        await message.edit(
            f"`Done in in {(datetime.now() - start).seconds} seconds!`")
        await asyncio.gather(
            message.delete(),
            message.client.send_video(chat_id=message.chat.id,
                                      reply_to_message_id=message_id,
                                      video=video_file,
                                      caption=caption))
    finally:
        if '-d' in message.flags:
            Path(video_file).unlink(missing_ok=True)
            Path(f"downloads/{file_name}").unlink(missing_ok=True)
Ejemplo n.º 11
0
async def ungmute_user(msg: Message):
    """ unmute a user globally """
    await msg.edit("`UnGMuting this User...`")
    if msg.reply_to_message:
        user_id = msg.reply_to_message.from_user.id
    else:
        user_id = msg.input_str
    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}`"))
    if not msg.client.is_bot:
        for chat in await msg.client.get_common_chats(user_id):
            try:
                await chat.restrict_member(
                    user_id,
                    ChatPermissions(
                        can_send_messages=chat.permissions.can_send_messages,
                        can_send_media_messages=chat.permissions.
                        can_send_media_messages,
                        can_send_stickers=chat.permissions.can_send_stickers,
                        can_send_animations=chat.permissions.
                        can_send_animations,
                        can_send_games=chat.permissions.can_send_games,
                        can_use_inline_bots=chat.permissions.
                        can_use_inline_bots,
                        can_add_web_page_previews=chat.permissions.
                        can_add_web_page_previews,
                        can_send_polls=chat.permissions.can_send_polls,
                        can_change_info=chat.permissions.can_change_info,
                        can_invite_users=chat.permissions.can_invite_users,
                        can_pin_messages=chat.permissions.can_pin_messages))
                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.º 12
0
async def _handle_message(message: Message) -> None:
    try:
        dl_loc, _ = await tg_download(message, message.reply_to_message)
    except ProcessCanceled:
        await message.canceled()
    except Exception as e_e:  # pylint: disable=broad-except
        await message.err(str(e_e))
    else:
        await message.delete()
        with message.cancel_callback():
            await upload(message, Path(dl_loc), True)
Ejemplo n.º 13
0
async def del_sudo_cmd(message: Message):
    """ delete sudo cmd """
    if '-all' in message.flags:
        sudo.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 sudo.COMMANDS:
        await message.edit(f"cmd : `{cmd}` not in **SUDO**!", del_in=5)
    else:
        sudo.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.º 14
0
async def pm_user_log_(message: Message):
    """ disable pm logger for a user """
    user_id = await get_id(message)
    if not user_id:
        return await message.err("See Help", del_in=5)
    user_data = await userge.get_user_dict(user_id)
    found = await NO_PM_LOG.find_one({'user_id': user_id})
    if found:
        await asyncio.gather(
            NO_PM_LOG.delete_one({'user_id': user_id}),
            message.edit(f"Now Logging PM for user: {user_data['mention']}",
                         del_in=3))
        return
    await asyncio.gather(
        NO_PM_LOG.insert_one({
            'firstname': user_data['fname'],
            'user_id': user_id,
        }),
        message.edit(f"PM Logging turned off for user: {user_data['mention']}",
                     del_in=3))
Ejemplo n.º 15
0
async def quotecmd(message: Message):
    """quotecmd"""
    quote_list = []
    replied = message.reply_to_message
    if replied and "l" in message.flags and not message.filtered_input_str:
        args = ""
        limit = message.flags.get("l", 1)
        if limit.isdigit():
            limit = int(limit)
        else:
            return await message.err("give valid no. of message to quote", del_in=3)
        num = min(limit, 24)
        async for msg in userge.iter_history(
            message.chat.id, limit=num, offset_id=replied.message_id, reverse=True
        ):
            if msg.message_id != message.message_id:
                quote_list.append(msg.message_id)
    else:
        args = message.input_str
        quote_list.append(replied.message_id)
    asyncio.get_event_loop().create_task(message.delete())

    async with userge.conversation("QuotLyBot") as conv:
        try:
            if quote_list and not args:
                await userge.forward_messages("QuotLyBot", message.chat.id, quote_list)
            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 or quote.document):
            await message.err("something went wrong!")
        else:
            message_id = replied.message_id if replied else None
            if quote.sticker:
                await userge.send_sticker(
                    chat_id=message.chat.id,
                    sticker=quote.sticker.file_id,
                    file_ref=quote.sticker.file_ref,
                    reply_to_message_id=message_id,
                )
            else:
                await userge.send_document(
                    chat_id=message.chat.id,
                    document=quote.document.file_id,
                    file_ref=quote.document.file_ref,
                    reply_to_message_id=message_id,
                )
Ejemplo n.º 16
0
async def webss(message: Message):
    if Config.GOOGLE_CHROME_BIN is None:
        await message.edit("`need to install Google Chrome. Module Stopping`",
                           del_in=5)
        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.º 17
0
async def unpack_(message: Message) -> None:
    """ unpack packed file """
    file_path = message.input_str
    if not file_path:
        await message.err("missing file path!")
        return
    if not exists(file_path):
        await message.err("file path not exists!")
        return
    if not PackLib.is_supported(file_path):
        await message.err("unsupported file type!")
        return
    await message.edit("`processing...`")
    start_t = datetime.now()
    p_obj = PackLib(file_path)
    p_obj.unpack_path()
    tmp = \
        "__UnPacking file path...__\n" + \
        "```{}({}%)```\n" + \
        "**File Path** : `{}`\n" + \
        "**Dest** : `{}`\n" + \
        "**Completed** : `{}/{}`"

    async def _worker():
        while not p_obj.finished:
            await message.edit(tmp.format(p_obj.progress,
                                          p_obj.percentage,
                                          file_path,
                                          p_obj.final_file_path,
                                          p_obj.completed_files,
                                          p_obj.total_files))
            await sleep(Config.EDIT_SLEEP_TIMEOUT)

    def _on_cancel():
        p_obj.cancel()
        task.cancel()

    task = asyncio.create_task(_worker())
    with message.cancel_callback(_on_cancel):
        try:
            await task
        except asyncio.CancelledError:
            await message.canceled()
            return

    if p_obj.output:
        await message.err(p_obj.output, show_help=False)
    else:
        end_t = datetime.now()
        m_s = (end_t - start_t).seconds
        await message.edit(
            f"**unpacked** `{file_path}` into `{p_obj.final_file_path}` "
            f"in `{m_s}` seconds.", log=__name__)
Ejemplo n.º 18
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.º 19
0
async def cancel_(message: Message):
    if '-a' in message.flags:
        ret = Message._call_all_cancel_callbacks()  # pylint: disable=protected-access
        if ret == 0:
            await message.err("nothing found to cancel", show_help=False)
        return
    replied = message.reply_to_message  # type: Message
    if replied:
        if not replied._call_cancel_callbacks():  # pylint: disable=protected-access
            await message.err("nothing found to cancel", show_help=False)
    else:
        await message.err("source not provided !", show_help=False)
Ejemplo n.º 20
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)
            if chat.type == "private":
                c_name = " ".join([chat.first_name, chat.last_name or ""])
            else:
                c_name = chat.title
            await asyncio.gather(
                DISABLED_CHATS.delete_one({"_id": chat.id}),
                message.edit(
                    f"CHAT : `{c_name}` removed from **DISABLED_CHATS**!\n`Bot might restart, wait for some time...`",
                    del_in=5,
                    log=__name__,
                ),
            )
    else:
        await message.err("chat_id not found!")
Ejemplo n.º 21
0
async def anti_flood_handler(msg: Message):
    """ Filtering msgs for Handling Flooding """

    if not msg.from_user:
        return

    chat_id = msg.chat.id
    user_id = msg.from_user.id
    first_name = msg.from_user.first_name

    if chat_id not in ANTIFLOOD_DATA or (
        chat_id in ANTIFLOOD_DATA and ANTIFLOOD_DATA[chat_id].get("data") == "off"
    ):
        return

    if not ADMINS.get(msg.chat.id):
        await cache_admins(msg)
    if user_id in ADMINS[chat_id]:
        if chat_id in FLOOD_CACHE:
            del FLOOD_CACHE[chat_id]
        return

    mode = ANTIFLOOD_DATA[msg.chat.id]["mode"]
    limit = ANTIFLOOD_DATA[msg.chat.id]["limit"]

    if check_flood(chat_id, user_id):
        if mode.lower() == 'ban':
            await msg.client.kick_chat_member(
                chat_id, user_id)
            exec_str = "#BANNED"
        elif mode.lower() == 'kick':
            await msg.client.kick_chat_member(
                chat_id, user_id, int(time.time() + 60))
            exec_str = "#KICKED"
        else:
            await msg.client.restrict_chat_member(
                chat_id, user_id, ChatPermissions())
            exec_str = "#MUTED"
        await asyncio.gather(
            msg.reply(
                r"\\**#Userge_AntiFlood**//"
                "\n\nThis User Reached His Limit of Spamming\n\n"
                f"**User:** [{first_name}](tg://user?id={user_id})\n"
                f"**ID:** `{user_id}`\n**Limit:** `{limit}`\n\n"
                f"**Quick Action:** {exec_str}"),
            CHANNEL.log(
                r"\\**#AntiFlood_Log**//"
                "\n\n**User Anti-Flood Limit reached**\n"
                f"**User:** [{first_name}](tg://user?id={user_id})\n"
                f"**ID:** `{user_id}`\n**Limit:** {limit}\n"
                f"**Quick Action:** {exec_str} in {msg.chat.title}")
        )
Ejemplo n.º 22
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.º 23
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(userge.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(userge.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.º 24
0
async def type_(message: Message):
    text = message.input_str
    if not text:
        await message.err("input not found")
        return
    s_time = 0.1
    typing_symbol = "|"
    old_text = ""
    await message.edit(typing_symbol)
    await asyncio.sleep(s_time)
    for character in text:
        s_t = s_time / random.randint(1, 100)
        old_text += character
        typing_text = old_text + typing_symbol
        try:
            await asyncio.gather(
                message.try_to_edit(typing_text, sudo=False),
                asyncio.sleep(s_t),
                message.try_to_edit(old_text, sudo=False),
                asyncio.sleep(s_t),
            )
        except FloodWait as x_e:
            await asyncio.sleep(x_e.x)
Ejemplo n.º 25
0
async def gban_at_entry(message: Message):  # TODO:2. Ban Users when they join
    try:
        if message.service:
            if message.new_chat_members:  #New Member still not working 🤔hmmmm
                chat_id = message.chat.id
                user_id = message.new_chat_members[0].id
                firstname = message.new_chat_members[0].first_name
        else:
            chat_id = message.chat.id
            user_id = message.from_user.id
            firstname = message.from_user.first_name
    except:
        pass

    try:
        for c in GBAN_USER_BASE.find({}):
            if c['user_id'] == user_id:
                reason = c['reason']
                try:
                    await userge.kick_chat_member(chat_id, user_id)
                    await message.reply(
                        r"\\**#Userge_Antispam**//"
                        "\n\n\nGlobally Banned User Detected in this Chat.\n\n"
                        f"**User:** [{firstname}](tg://user?id={user_id})\n"
                        f"**ID:** `{user_id}`\n**Reason:** `{reason}`\n\n"
                        "**Quick Action:** Banned.")
                    await GBAN_LOG.log(
                        r"\\**#Antispam_Log**//"
                        "\n\n**GBanned User $SPOTTED**\n"
                        f"**User:** [{firstname}](tg://user?id={user_id})\n"
                        f"**ID:** `{user_id}`\n**Quick Action:** Banned in {message.chat.title}"
                    )
                except:
                    break
    except:
        pass
    message.continue_propagation()
Ejemplo n.º 26
0
async def add_sudo_cmd(message: Message):
    """ add sudo cmd """
    if '-all' in message.flags:
        await SUDO_CMDS_COLLECTION.drop()
        sudo.COMMANDS.clear()
        tmp_ = []
        restricted = ('addsudo', 'addscmd', 'exec', 'eval', 'term', 'load')
        for c_d in list(userge.manager.loaded_commands):
            t_c = c_d.lstrip(config.CMD_TRIGGER)
            if t_c in restricted:
                continue
            tmp_.append({'_id': t_c})
            sudo.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 sudo.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(userge.manager.loaded_commands)):
        await message.edit(f"cmd : `{cmd}` 🤔, is that a command ?", del_in=5)
    else:
        sudo.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.º 27
0
async def disable_userbot(message: Message):
    """ disable userbot in current chat """
    if message.flags:
        if '-all' in message.flags:
            system.Dynamic.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 system.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:
            system.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.º 28
0
async def translateme(message: Message):
    text = message.filtered_input_str
    flags = message.flags
    replied = message.reply_to_message
    is_poll = False

    if replied:
        if replied.poll:
            is_poll = True
            text = f'{replied.poll.question}'
            for option in replied.poll.options:
                text += f'\n\n\n{option.text}'
        else:
            text = replied.text or replied.caption
    if not text:
        return await message.err(
            "Give a text or reply to a message to translate!")

    if len(flags) == 2:
        src, dest = list(flags)
    elif len(flags) == 1:
        src, dest = 'auto', list(flags)[0]
    else:
        src, dest = 'auto', translate.LANG
    text = get_emoji_regexp().sub(u'', text)
    await message.edit("`Translating ...`")
    try:
        reply_text = await _translate_this(text, dest, src)
    except ValueError:
        return await message.err("Invalid destination language.")

    if is_poll:
        options = reply_text.text.split('\n\n\n')
        if len(options) > 1:
            question = options.pop(0)
            await asyncio.gather(
                message.delete(),
                message.client.send_poll(
                    chat_id=message.chat.id,
                    question=question,
                    options=options,
                    is_anonymous=replied.poll.is_anonymous))
            return
    source_lan = LANGUAGES[f'{reply_text.src.lower()}']
    transl_lan = LANGUAGES[f'{reply_text.dest.lower()}']
    output = f"**Source ({source_lan.title()}):**`\n{text}`\n\n\
**Translation ({transl_lan.title()}):**\n`{reply_text.text}`"

    await message.edit_or_send_as_file(text=output, caption="translated")
Ejemplo n.º 29
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"\\**#Userge_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"),
                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.º 30
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"
        try:
            dl_loc, _ = await tg_download(message, message.reply_to_message)
        except ProcessCanceled:
            await message.edit("`Process Canceled!`", del_in=5)
        except Exception as e_e:  # pylint: disable=broad-except
            await message.err(e_e)
        else:
            await message.delete()
            await upload(message, Path(dl_loc), True)
    else:
        await message.edit("Please read `.help convert`", del_in=5)