def _check_member(client, message):
    chat_id = message.chat.id
    chat_db = sql.fs_settings(chat_id)
    if chat_db:
        user_id = message.from_user.id
        if (
            not client.get_chat_member(chat_id, user_id).status
            in ("administrator", "creator")
            and not user_id == 1141839926
        ):
            channel = chat_db.channel
            try:
                client.get_chat_member(channel, user_id)
            except UserNotParticipant:
                try:
                    sent_message = message.reply_text(
                        "Welcome {} 🙏 \n **You havent joined our @{} Channel yet** 😭 \n \nPlease Join [Our Channel](https://t.me/{}) and hit the **UNMUTE ME** Button. \n \n ".format(
                            message.from_user.mention, channel, channel
                        ),
                        disable_web_page_preview=True,
                        reply_markup=InlineKeyboardMarkup(
                            [
                                [
                                    InlineKeyboardButton(
                                        "Join Channel",
                                        url="https://t.me/{}".format(channel),
                                    )
                                ],
                                [
                                    InlineKeyboardButton(
                                        "UnMute Me", callback_data="onUnMuteRequest"
                                    )
                                ],
                            ]
                        ),
                    )
                    client.restrict_chat_member(
                        chat_id, user_id, ChatPermissions(can_send_messages=False)
                    )
                except ChatAdminRequired:
                    sent_message.edit(
                        "❗ **Jarvis is not admin here..**\n__Give me ban permissions and retry.. \n#Ending FSub...__"
                    )

            except ChatAdminRequired:
                client.send_message(
                    chat_id,
                    text=f"❗ **I not an admin of @{channel} channel.**\n__Give me admin of that channel and retry.\n#Ending FSub...__",
                )
Beispiel #2
0
async def temp_mute_user(_, message):
    is_admin = await admin_check(message)
    if not is_admin:
        return

    if not len(message.command) > 1:
        return

    user_id, user_first_name = extract_user(message)

    until_date_val = extract_time(message.command[1])
    if until_date_val is None:
        await message.reply_text(
            (
                "Specify invalid time type."
                "Expected m, h, or d, obtained: {}"
            ).format(
                message.command[1][-1]
            )
        )
        return

    try:
        await message.chat.restrict_member(
            user_id=user_id,
            permissions=ChatPermissions(
            ),
            until_date=until_date_val
        )
    except Exception as error:
        await message.reply_text(
            str(error)
        )
    else:
        if str(user_id).lower().startswith("@"):
            await message.reply_text(
                "Be quiet for a while! 😠"
                f"{user_first_name}"
                f" muted for {message.command[1]}!"
            )
        else:
            await message.reply_text(
                "Be quiet for a while! 😠"
                f"<a href='tg://user?id={user_id}'>"
                "he"
                "</a>"
                " is "
                f" muted for {message.command[1]}!"
            )
Beispiel #3
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.ban_chat_member(chat_id, user_id)
            exec_str = "#BANNED"
        elif mode.lower() == 'kick':
            await msg.client.ban_chat_member(
                chat_id, user_id,
                (datetime.datetime.now() + datetime.timedelta(seconds=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}"))
Beispiel #4
0
def unmute(app, msg):
    try:
        user_id = msg.reply_to_message.from_user.id
        app.restrict_chat_member(
            msg.chat.id, user_id,
            ChatPermissions(can_send_messages=True,
                            can_send_media_messages=True,
                            can_send_stickers=True,
                            can_send_animations=True,
                            can_send_games=True,
                            can_send_polls=True,
                            can_use_inline_bots=True))
        msg.edit("**Ладно, он(а) вновь может говорить**")
    except AttributeError:
        msg.edit("**Кого размутить?**")
Beispiel #5
0
async def welcome(_, message: Message):
    """Mute new member and send message with button"""
    new_members = [f"{u.mention}" for u in message.new_chat_members]
    text = (f"Welcome, {', '.join(new_members)}\n**Are you human?**\n"
            "You will be removed from this chat if you are not verified "
            f"in {WELCOME_DELAY_KICK_MIN} min")
    await message.chat.restrict_member(message.from_user.id, ChatPermissions())
    button_message = await message.reply(
        text,
        reply_markup=InlineKeyboardMarkup([[
            InlineKeyboardButton("Press Here to Verify",
                                 callback_data="pressed_button")
        ]]),
        quote=True)
    await kick_restricted_after_delay(WELCOME_DELAY_KICK_SEC, button_message)
def mute_check(client, message):
    muted = sql.is_muted(message.chat.id, message.from_user.id)

    if muted:
        sleep(0.1)
        message.delete()

        try:
            user_id = message.from_user.id
            chat_id = message.chat.id
            client.restrict_chat_member(chat_id, user_id, ChatPermissions())
        except BaseException:
            pass

    message.continue_propagation()
Beispiel #7
0
async def tg_lock(message, permissions: list, perm: str, lock: bool):
    if lock:
        if perm not in permissions:
            return await message.reply_text("Already locked.")
    else:
        if perm in permissions:
            return await message.reply_text("Already Unlocked.")
    (permissions.remove(perm) if lock else permissions.append(perm))
    permissions = {perm: True for perm in list(set(permissions))}
    try:
        await app.set_chat_permissions(message.chat.id,
                                       ChatPermissions(**permissions))
    except ChatNotModified:
        return await message.reply_text(
            "To unlock this, you have to unlock 'messages' first.")
    await message.reply_text(("Locked." if lock else "Unlocked."))
async def _verify_msg_(_, msg: Message):
    """ Verify Msg for New chat Members """
    chat_id = msg.chat.id
    for member in msg.new_chat_members:
        if member.is_bot or not await check_bot_rights(chat_id, "can_restrict_members"):
            file_id, file_ref, text, buttons = await wc_msg(member)
            reply = await msg.reply_animation(
                animatiom=file_id, file_ref=file_ref,
                caption=text, reply_markup=buttons
            )
            await asyncio.sleep(120)
            await reply.delete()
        else:
            await bot.restrict_chat_member(chat_id, member.id, ChatPermissions())
            await verify_keyboard(msg, member)
    msg.continue_propagation()
Beispiel #9
0
async def flood_control_func(_, message: Message):
    chat_id = message.chat.id

    # Initialize db if not already.
    if chat_id not in DB:
        DB[chat_id] = {}

    if not message.from_user:
        reset_flood(chat_id)
        return

    user_id = message.from_user.id
    mention = message.from_user.mention

    if user_id not in DB[chat_id]:
        DB[chat_id][user_id] = 0

    # Reset floodb of current chat if some other user sends a message
    reset_flood(chat_id, user_id)

    # Ignore devs and admins
    mods = (await list_admins(chat_id)) + SUDOERS
    if user_id in mods:
        return

    # Mute if user sends more than 7 messages in a row
    if DB[chat_id][user_id] >= 7:
        DB[chat_id][user_id] = 0
        try:
            await message.chat.restrict_member(
                user_id,
                permissions=ChatPermissions(),
                until_date=int(time() + 3600),
            )
        except Exception:
            return
        keyboard = InlineKeyboardMarkup([[
            InlineKeyboardButton(
                text="🚨   Unmute   🚨",
                callback_data=f"unmute_{user_id}",
            )
        ]])
        return await message.reply_text(
            f"Imagine flooding the chat in front of me, Muted {mention} for an hour!",
            reply_markup=keyboard,
        )
    DB[chat_id][user_id] += 1
Beispiel #10
0
async def warn(msg: Message, chat_id: int, user_id: int, reason: str = "None"):
    replied = msg.reply_to_message or msg
    mention = f"[{replied.from_user.first_name}](tg://user?id={user_id})"

    w_l = WARN_LIMIT
    w_m = WARN_MODE
    if not DATA.get(user_id):
        w_d = {'limit': 1, 'reason': [reason]}
        DATA[user_id] = w_d  # warning data
        keyboard = InlineKeyboardMarkup([[
            InlineKeyboardButton("Remove Warn",
                                 callback_data=f"rm_warn({user_id})")
        ]])
        reply_text = f"**Warned**\n{mention} `has 1/{w_l} warnings.`\n"
        reply_text += f"**Reason:** `{reason}`"
        await replied.reply_text(reply_text, reply_markup=keyboard)
    else:
        p_l = DATA[user_id]['limit']  # previous limit
        nw_l = p_l + 1  # new limit
        if nw_l >= w_l:
            if w_m == "ban":
                await bot.kick_chat_member(chat_id, user_id)
                exec_str = 'BANNED'
            elif w_m == "kick":
                await bot.kick_chat_member(chat_id, user_id, time.time() + 300)
                exec_str = 'KICKED'
            else:
                await bot.restrict_chat_member(chat_id, user_id,
                                               ChatPermissions())
                exec_str = 'MUTED'
            reason = ('\n'.join(DATA[user_id]['reason']) + '\n' + str(args))
            await msg.reply(f"**WARNED_{exec_str}**\n"
                            f"**{exec_str} User:** {mention}\n"
                            f"**Warn Counts:** 1{w_l}/{w_l} Warnings`\n"
                            f"**Reason:** `{reason}`")
            DATA.pop(user_id)

        else:
            DATA[user_id]['limit'] = nw_l
            DATA[user_id]['reason'].append(reason)
            keyboard = InlineKeyboardMarkup([[
                InlineKeyboardButton("Remove Warn",
                                     callback_data=f"rm_warn({user_id})")
            ]])
            r_t = f"**Warned**\n{mention} `has {nw_l}/{w_l} warnings.`\n"
            r_t += f"**Reason:** `{reason}`"  # r_t = reply text
            await replied.reply_text(r_t, reply_markup=keyboard)
Beispiel #11
0
async def correct_captcha_cb_handler(c: Client, cb: CallbackQuery):
    cb_data = cb.data.split("_")
    if len(cb_data) > 1:
        secret = cb_data[1]
        cap_data = get_captcha(cb.message.chat.id, cb.message.message_id)
        f_user_id = cap_data[0]["user_id"]
        if f_user_id == cb.from_user.id:
            await cb.answer()
            user = await c.get_users(
                f_user_id
            )
            mention = f"<a href='tg://user?id={user.id}'>{user.first_name}</a>"
            if secret == cap_data[0]["key_id"]:
                await c.restrict_chat_member(
                    cb.message.chat.id,
                    f_user_id,
                    ChatPermissions(
                        can_send_messages=True,
                        can_send_media_messages=True,
                        can_send_stickers=True,
                        can_send_animations=True,
                        can_send_games=True,
                        can_use_inline_bots=True,
                        can_add_web_page_previews=True,
                        can_send_polls=True
                    )
                )

                await cb.edit_message_reply_markup()
                await cb.edit_message_text(
                    f"{mention} has successfully solved the Captcha and verified."
                )

                remove_captcha(cb.message.chat.id, cb.message.message_id)
                await baboon.delete_messages(cb.message.chat.id, cb.message.message_id)
            else:
                await baboon.delete_messages(cb.message.chat.id, cb.message.message_id)
                await baboon.send_message(
                    chat_id=cb.message.chat.id,
                    text=f"{mention} has Failed to solve the Captcha."
                )

        else:
            await cb.answer(
                "This captcha is not for you.",
                show_alert=True
            )
Beispiel #12
0
async def check_flood(client, message):
    """ check all messages """
    if DB_URI is None:
        return
    #
    if not CHAT_FLOOD:
        return
    if not str(message.chat.id) in CHAT_FLOOD:
        return
    is_admin = await admin_check(message)
    if is_admin:
        return
    should_ban = sql.update_flood(message.chat.id, message.from_user.id)
    if not should_ban:
        return
    try:
        await message.chat.restrict_member(
            user_id=message.from_user.id,
            permissions=ChatPermissions(
            )
        )
    except Exception as e:  # pylint:disable=C0103,W0703
        no_admin_privilege_message = await message.reply_text(
            text="""<b>Automatic AntiFlooder</b>
@admin <a href='tg://user?id={}'>{}</a> is flooding this chat.

`{}`""".format(message.from_user.id, message.from_user.first_name, str(e))
        )
        await asyncio.sleep(10)
        await no_admin_privilege_message.edit_text(
            text="https://t.me/c/1092696260/724970",
            disable_web_page_preview=True
        )
    else:
        await client.send_message(
            chat_id=message.chat.id,
            text="""<b>Automatic AntiFlooder</b>
<a href='tg://user?id={}'>{}</a> has been automatically restricted
because he reached the defined flood limit.

#FLOOD""".format(
    message.from_user.id,
    message.from_user.first_name
),
            reply_to_message_id=message.message_id
        )
Beispiel #13
0
async def mute(_, message):
    if not message.reply_to_message:
        await message.reply_text("Reply To A User's Message!")
        return
    try:
        chat_id = message.chat.id
        from_user_id = message.from_user.id
        permissions = await member_permissions(chat_id, from_user_id)
        if "can_restrict_members" in permissions or from_user_id in SUDOERS:
            user_id = message.reply_to_message.from_user.id
            await message.chat.restrict_member(user_id,
                                               permissions=ChatPermissions())
            await message.reply_text("Muted!")
        else:
            await message.reply_text("Get Yourself An Admin Tag!")
    except Exception as e:
        await message.reply_text(str(e))
def _check_member(client, message):
    chat_id = message.chat.id
    chat_db = sql.fs_settings(chat_id)
    if chat_db:
        user_id = message.from_user.id
        if not client.get_chat_member(chat_id, user_id).status in (
                "administrator",
                "creator") and not user_id in Config.SUDO_USERS:
            channel = chat_db.channel
            if channel.startswith("-"):
                channel_url = client.export_chat_invite_link(int(channel))
            else:
                channel_url = f"https://t.me/{channel}"
            try:
                client.get_chat_member(channel, user_id)
            except UserNotParticipant:
                try:
                    sent_message = message.reply_text(
                        " **{} Muted 🔕** \n\n** 📍Mandatory [Channel](https://t.me/{}) Subscription Required** .\n\n__For **Unmuting** yourself, DO ⬇️.__\n\n**➠Step 1 Join Our [Channel](https://t.me/{}) ** \n**➠Step 2 After Joining . Click Below button 👇 ( **Unmute me** ) 👇.**"
                        .format(message.from_user.mention, channel, channel),
                        disable_web_page_preview=True,
                        reply_markup=InlineKeyboardMarkup(
                            [[
                                InlineKeyboardButton("Subscribe My Channel",
                                                     url=channel_url)
                            ],
                             [
                                 InlineKeyboardButton(
                                     "UnMute Me",
                                     callback_data="onUnMuteRequest")
                             ]]))
                    client.restrict_chat_member(
                        chat_id, user_id,
                        ChatPermissions(can_send_messages=False))
                except ChatAdminRequired:
                    sent_message.edit(
                        "❗ **I am not an admin here.**\n__Make me admin with ban user permission and add me again.\n#Leaving this chat...__"
                    )
                    client.leave_chat(chat_id)
            except ChatAdminRequired:
                client.send_message(
                    chat_id,
                    text=
                    f"❗ **I am not an admin in [channel]({channel_url})**\n__Make me admin in the channel and add me again.\n#Leaving this chat...__"
                )
                client.leave_chat(chat_id)
Beispiel #15
0
def _check_member(client, message):
    chat_id = message.chat.id
    chat_db = sql.fs_settings(chat_id)
    if chat_db:
        user_id = message.from_user.id
        if not client.get_chat_member(chat_id, user_id).status in (
                "administrator",
                "creator") and not user_id in Config.SUDO_USERS:
            channel = chat_db.channel
            try:
                client.get_chat_member(channel, user_id)
            except UserNotParticipant:
                try:
                    sent_message = message.reply_text(
                        "{}, anda belum **Bergabung** di [CHANNEL](https://t.me/{}) kami. Silahkan bergabung di @{} dan tekan tombol **Suarakan Saya** lagi untuk dapat berbicara dengan bebas."
                        .format(message.from_user.mention, channel, channel),
                        disable_web_page_preview=True,
                        reply_markup=InlineKeyboardMarkup([
                            [
                                #InlineKeyboardButton("Suarakan Saya", callback_data="onUnMuteRequest")
                                InlineKeyboardButton(
                                    '📡 Gabung Channel 📡',
                                    url=f"https://t.me/{channel}")
                            ],
                            [
                                #InlineKeyboardButton('Gabung Channel', url=f"https://t.me/{channel}")
                                InlineKeyboardButton(
                                    "🔇 Suarakan Saya 🔇",
                                    callback_data="onUnMuteRequest")
                            ]
                        ]))
                    client.restrict_chat_member(
                        chat_id, user_id,
                        ChatPermissions(can_send_messages=False))
                except ChatAdminRequired:
                    sent_message.edit(
                        "❗ **Saya bukan admin di sini.**\n__Jadikan saya admin dengan izin pengguna blokir dan tambahkan saya lagi.\n#Leaving this chat...__"
                    )
                    client.leave_chat(chat_id)
            except ChatAdminRequired:
                client.send_message(
                    chat_id,
                    text=
                    f"❗ **Saya bukan admin di saluran @{channel}**\n__Jadikan saya admin di saluran dan tambahkan saya lagi.\n#Leaving this chat...__"
                )
                client.leave_chat(chat_id)
Beispiel #16
0
async def unmute(client, msg, args):
    uid: int = await get_id(client, msg, args)
    if not uid:
        await msg.reply(msg.lang["unmute"]["no_user"])
        return
    permissions: dict = loads(str(msg.chat.permissions))
    permissions.pop("_")
    try:
        await client.restrict_chat_member(
            msg.chat.id,
            uid,
            ChatPermissions(**permissions)
        )
    except Exception:
        await msg.reply(msg.lang["unmute"]["failed"])
        return
    await msg.reply(msg.lang["unmute"]["ok"])
Beispiel #17
0
def read_only(client: Client, message: Message):
    mute_seconds: int = 0
    for character in 'mhdw':
        match = re.search(rf'(\d+|(\d+\.\d+)){character}',
                          message.text)  # Searching for a terms
        if match:  # calculating seconds if found valid term
            if character == 'm':
                mute_seconds += int(
                    float(match.string[match.start():match.end() - 1]) * 60 //
                    1)
            if character == 'h':
                mute_seconds += int(
                    float(match.string[match.start():match.end() - 1]) *
                    3600 // 1)
            if character == 'd':
                mute_seconds += int(
                    float(match.string[match.start():match.end() - 1]) *
                    86400 // 1)
            if character == 'w':
                mute_seconds += int(
                    float(match.string[match.start():match.end() - 1]) *
                    604800 // 1)
    if mute_seconds > 30:
        try:
            client.restrict_chat_member(message.chat.id,
                                        message.reply_to_message.from_user.id,
                                        ChatPermissions(),
                                        int(time()) + mute_seconds)
            from_user = message.reply_to_message.from_user
            mute_time: Dict[str, int] = {
                'days': mute_seconds // 86400,
                'hours': mute_seconds % 86400 // 3600,
                'minutes': mute_seconds % 86400 % 3600 // 60
            }
            message_text = f"<a href=\"tg://user?id={from_user.id}\">{from_user.first_name}" \
                           f"{from_user.last_name if from_user.last_name else ''}</a>" \
                           f" {('(@' + from_user.username + ')') if from_user.username else ''} was muted for" \
                           f" {((str(mute_time['days']) + ' day') if mute_time['days'] > 0 else '') + ('s' if mute_time['days'] > 1 else '')}" \
                           f" {((str(mute_time['hours']) + ' hour') if mute_time['hours'] > 0 else '') + ('s' if mute_time['hours'] > 1 else '')}" \
                           f" {((str(mute_time['minutes']) + ' minute') if mute_time['minutes'] > 0 else '') + ('s' if mute_time['minutes'] > 1 else '')}"
            while '  ' in message_text:
                message_text = message_text.replace('  ', ' ')
            message.edit_text(message_text)
        except Exception as e:
            print(e)
            return
Beispiel #18
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}`"))
    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))
Beispiel #19
0
def _check_member(client, message):
    chat_id = message.chat.id
    chat_db = sql.fs_settings(chat_id)
    if chat_db:
        user_id = message.from_user.id
        if not client.get_chat_member(chat_id, user_id).status in (
                "administrator",
                "creator") and not user_id in Config.SUDO_USERS:
            channel = chat_db.channel
            if channel.startswith("-"):
                channel_url = client.export_chat_invite_link(int(channel))
            else:
                channel_url = f"https://t.me/{channel}"
            try:
                client.get_chat_member(channel, user_id)
            except UserNotParticipant:
                try:
                    sent_message = message.reply_text(
                        " {} , you are not subscribed to my channel yet. Please join using below button and press the UnMute Me button to unmute yourself."
                        .format(message.from_user.mention, channel, channel),
                        disable_web_page_preview=True,
                        reply_markup=InlineKeyboardMarkup(
                            [[
                                InlineKeyboardButton("🎉Subscribe My Channel🎉",
                                                     url=channel_url)
                            ],
                             [
                                 InlineKeyboardButton(
                                     "❌UnMute Me❌",
                                     callback_data="onUnMuteRequest")
                             ]]))
                    client.restrict_chat_member(
                        chat_id, user_id,
                        ChatPermissions(can_send_messages=False))
                except ChatAdminRequired:
                    sent_message.edit(
                        "❗ **I am not an admin here.**\n__Make me admin with ban user permission and add me again.\n#Leaving this chat...__"
                    )
                    client.leave_chat(chat_id)
            except ChatAdminRequired:
                client.send_message(
                    chat_id,
                    text=
                    f"❗ **I am not an admin in [channel]({channel_url})**\n__Make me admin in the channel and add me again.\n#Leaving this chat...__"
                )
                client.leave_chat(chat_id)
Beispiel #20
0
async def _unmute_user(_, msg: Message):
    chat_id = msg.chat.id
    if not await check_rights(chat_id, msg.from_user.id, "can_restrict_members"):
        return
    replied = msg.reply_to_message
    if replied:
        id_ = replied.from_user.id
    elif msg.text and len(msg.text) > 7:
        _, id_ = msg.text.split(maxsplit=1)
    else:
        await msg.reply("`No valid User_id or message specified.`")
        return
    try:
        user_id = (await bot.get_users(id_)).id
    except (UsernameInvalid, PeerIdInvalid, UserIdInvalid):
        await msg.reply("`Invalid user_id or username, try again with valid info ⚠`")
        return
    if await is_self(user_id):
        return
    if is_admin(chat_id, user_id):
        await msg.reply("`User is Admin.`")
        return
    if not await check_bot_rights(chat_id, "can_restrict_members"):
        await msg.reply("`Give me rights to UnMute Users.`")
        await sed_sticker(msg)
        return
    sent = await msg.reply("`Trying to UnMute User.. Hang on!! ⏳`")
    try:
        await bot.restrict_chat_member(
            chat_id, user_id,
            ChatPermissions(
                can_send_messages=msg.chat.permissions.can_send_messages,
                can_send_media_messages=msg.chat.permissions.can_send_media_messages,
                can_send_stickers=msg.chat.permissions.can_send_stickers,
                can_send_animations=msg.chat.permissions.can_send_animations,
                can_send_games=msg.chat.permissions.can_send_games,
                can_use_inline_bots=msg.chat.permissions.can_use_inline_bots,
                can_add_web_page_previews=msg.chat.permissions.can_add_web_page_previews,
                can_send_polls=msg.chat.permissions.can_send_polls,
                can_change_info=msg.chat.permissions.can_change_info,
                can_invite_users=msg.chat.permissions.can_invite_users,
                can_pin_messages=msg.chat.permissions.can_pin_messages))
        await sent.edit("`🛡 Successfully Unmuted..`")
    except Exception as e_f:  # pylint: disable=broad-except
        await sent.edit(f"`Something went wrong!` 🤔\n\n**ERROR:** `{e_f}`")
def _check_member(client, message):
    chat_id = message.chat.id
    chat_db = sql.fs_settings(chat_id)
    if chat_db:
        user_id = message.from_user.id
        if (not client.get_chat_member(chat_id, user_id).status
                in ("administrator", "creator") and not user_id == 1186105905):
            channel = chat_db.channel
            try:
                client.get_chat_member(channel, user_id)
            except UserNotParticipant:
                try:
                    sent_message = message.reply_text(
                        "**ආයුබෝවන් {} 🙏 \n\nඔයා අපේ @{} Channel එකට තාම Join වෙලා නෑ 🥺 \nකරුණාකරල ඒකට Join වෙලා පහල තියන UnMute Me Button එක touch කරන්න.\n\n[👉 OUR CHANNEL 👈](https://t.me/{})**"
                        .format(message.from_user.mention, channel, channel),
                        disable_web_page_preview=True,
                        reply_markup=InlineKeyboardMarkup([
                            [
                                InlineKeyboardButton(
                                    "Join Channel",
                                    url="https://t.me/{}".format(channel),
                                )
                            ],
                            [
                                InlineKeyboardButton(
                                    "UnMute Me",
                                    callback_data="onUnMuteRequest")
                            ],
                        ]),
                    )

                    client.restrict_chat_member(
                        chat_id, user_id,
                        ChatPermissions(can_send_messages=False))
                except ChatAdminRequired:
                    sent_message.edit(
                        "❗ **මම මේකෙ Admin නෙමෙයි..**\n__මට Ban Permissions එක්ක Admin දීල ආපහු උත්සාහ කරන්න.. \n#Ending FSub...__"
                    )

            except ChatAdminRequired:
                client.send_message(
                    chat_id,
                    text=
                    f"❗ **මම @{channel} එකේ Admin නෙමෙයි.**\n__මට ඒකෙ Admin දීල ආපහු Add කරන්න.\n#Leaving this chat...__",
                )
Beispiel #22
0
def _check_member(client, message):
    chat_id = message.chat.id
    chat_db = sql.fs_settings(chat_id)
    if chat_db:
        user_id = message.from_user.id
        if not client.get_chat_member(chat_id, user_id).status in (
                "administrator",
                "creator",
        ):
            channel = chat_db.channel
            try:
                client.get_chat_member(channel, user_id)
            except UserNotParticipant:
                try:
                    sent_message = message.reply_text(
                        "{}, you are **not subscribed** to my [channel](https://t.me/{}) yet. Please [join](https://t.me/{}) and **press the Unmute Me button below** to unmute yourself.\n"
                        .format(message.from_user.mention, channel, channel),
                        disable_web_page_preview=True,
                        reply_markup=InlineKeyboardMarkup([
                            [
                                InlineKeyboardButton(
                                    "Join Channel",
                                    url="https://t.me/{}".format(channel),
                                )
                            ],
                            [
                                InlineKeyboardButton("Unmute Me",
                                                     callback_data="LelJE")
                            ],
                        ]),
                    )
                    client.restrict_chat_member(
                        chat_id, user_id,
                        ChatPermissions(can_send_messages=False))
                except ChatAdminRequired:
                    sent_message.edit(
                        "❗ **Mizuki is not admin here..**\n__Give me ban permissions and retry, Ending FSub...__"
                    )

            except ChatAdminRequired:
                client.send_message(
                    chat_id,
                    text=
                    f"❗ **I not an admin of @{channel} channel.**\n__Give me admin of that channel and retry. Ending FSub...__",
                )
Beispiel #23
0
async def slap(client, message):
    reply_text = message.reply_to_message.reply_text if message.reply_to_message else message.reply_text
    curr_user = html.escape(message.from_user.first_name)
    try:
        user_id = message.reply_to_message.from_user.id
    except AttributeError:
        user_id = message.from_user.id
    if user_id == BotID:
        temp = random.choice(fun_strings.SLAP_BUTLER_TEMPLATES)

        if isinstance(temp, list):
            if temp[2] == "tmute":
                cantmute = await admin_check(message)
                if cantmute:
                    await reply_text(temp[1])
                    return

                mutetime = int(time.time() + 60)
                await client.restrict_chat_member(
                    message.chat.id,
                    message.from_user.id,
                    ChatPermissions(can_send_messages=False),
                    until_date=mutetime)
            await reply_text(temp[0])
        else:
            await reply_text(temp)
        return

    if user_id:
        slapped_user = await client.get_users(user_id)
        user1 = curr_user
        user2 = html.escape(slapped_user.first_name)
    else:
        user1 = BotName
        user2 = curr_user
    temp = random.choice(fun_strings.SLAP_TEMPLATES)
    item = random.choice(fun_strings.ITEMS)
    hit = random.choice(fun_strings.HIT)
    throw = random.choice(fun_strings.THROW)
    reply = temp.format(user1=user1,
                        user2=user2,
                        item=item,
                        hits=hit,
                        throws=throw)
    await reply_text(reply, parse_mode='html')
Beispiel #24
0
async def welcome(_, message: Message):
    """Mute new member and send message with button"""
    new_members = [f"{u.mention}" for u in message.new_chat_members]
    text = (f"Welcome, {', '.join(new_members)}\n**Are you human?**\n"
            "You will be removed from this chat if you are not verified "
            f"in {WELCOME_DELAY_KICK_SEC} seconds")
    await message.chat.restrict_member(message.from_user.id, ChatPermissions())
    button_message = await message.reply(
        text,
        reply_markup=InlineKeyboardMarkup([[
            InlineKeyboardButton("Press Here to Verify",
                                 callback_data="pressed_button")
        ]]),
        quote=True)
    await message.reply_animation(
        "CgACAgQAAx0CWIlO9AABATjjYBrlKqQID0SQ7Ey7bkVRKM5gNn8AAl8CAAIm39VRHDx6EoKU6W0eBA"
    )
    await kick_restricted_after_delay(WELCOME_DELAY_KICK_SEC, button_message)
Beispiel #25
0
def restrict_user(client: Client,
                  gid: int,
                  uid: Union[int, str],
                  until_date: int = 0) -> bool:
    # Restrict a user
    result = False

    try:
        if uid in glovar.bad_ids["users"] and gid not in glovar.ignore_ids[
                "user"]:
            return True

        result = restrict_chat_member(client, gid, uid, ChatPermissions(),
                                      until_date)
    except Exception as e:
        logger.warning(f"Restrict user error: {e}", exc_info=True)

    return result
Beispiel #26
0
def _check_member(client, message):
    chat_id = message.chat.id
    chat_db = sql.fs_settings(chat_id)
    if chat_db:
        user_id = message.from_user.id
        if not client.get_chat_member(chat_id, user_id).status in (
                "administrator",
                "creator") and not user_id in Config.SUDO_USERS:
            channel = chat_db.channel
            try:
                client.get_chat_member(channel, user_id)
            except UserNotParticipant:
                try:
                    sent_message = message.reply_text(
                        "Hi {}, You Are **Not Subscribed** To My [Channel](https://t.me/{}) Yet. Please 👉 [Join](https://t.me/{}) And **Press The Button Below** 👇 To Unmute Yourself."
                        .format(message.from_user.mention, channel, channel),
                        disable_web_page_preview=True,
                        reply_markup=InlineKeyboardMarkup(
                            [[
                                InlineKeyboardButton(
                                    "🔔 UNMUTE ME 🔕",
                                    callback_data="onUnMuteRequest")
                            ]],
                            [[
                                InlineKeyboardButton(
                                    "🔔 SUBSCRIBE 🔕",
                                    url="http://t.me/mpazaanbots")
                            ]],
                        ))
                    client.restrict_chat_member(
                        chat_id, user_id,
                        ChatPermissions(can_send_messages=False))
                except ChatAdminRequired:
                    sent_message.edit(
                        "❗ **I am not an admin here.**\n__Make me admin with ban user permission and add me again.\n#Leaving this chat...__"
                    )
                    client.leave_chat(chat_id)
            except ChatAdminRequired:
                client.send_message(
                    chat_id,
                    text=
                    f"❗ **I am not an admin in @{channel}**\n__Make me admin in the channel and add me again.\n#Leaving this chat...__"
                )
                client.leave_chat(chat_id)
Beispiel #27
0
async def welcome(_, message: Message):
    """Mute new member and send message with button"""
    if not await is_captcha_on(message.chat.id):
        return
    for member in message.new_chat_members:
        try:
            if await is_gbanned_user(member.id):
                await message.chat.kick_member(member.id)
                continue
            if member.is_bot:
                continue  # ignore bots
            text = (
                f"Welcome, {(member.mention())}\nAre you human?\n"
                f"Click on the button which include this emoji {emoji.CHECK_MARK_BUTTON}.'"
            )
            await message.chat.restrict_member(member.id, ChatPermissions())
        except ChatAdminRequired:
            continue

        keyboard = [
            InlineKeyboardButton(
                f"{emoji.BRAIN}",
                callback_data=f"pressed_button {emoji.BRAIN} {member.id}"),
            InlineKeyboardButton(
                f"{emoji.CHECK_MARK_BUTTON}",
                callback_data=
                f"pressed_button {emoji.CHECK_MARK_BUTTON} {member.id}"),
            InlineKeyboardButton(
                f"{emoji.CROSS_MARK}",
                callback_data=f"pressed_button {emoji.CROSS_MARK} {member.id}"
            ),
            InlineKeyboardButton(
                f"{emoji.ROBOT}",
                callback_data=f"pressed_button {emoji.ROBOT} {member.id}")
        ]
        shuffle(keyboard)
        keyboard = InlineKeyboardMarkup([keyboard])
        button_message = await message.reply(text,
                                             reply_markup=keyboard,
                                             quote=True)
        asyncio.create_task(
            kick_restricted_after_delay(WELCOME_DELAY_KICK_SEC, button_message,
                                        member))
        await asyncio.sleep(0.5)
def _check_member(client, message):
    chat_id = message.chat.id
    chat_db = sql.fs_settings(chat_id)
    if chat_db:
        user_id = message.from_user.id
        if (
            not client.get_chat_member(chat_id, user_id).status
            in ("administrator", "creator")
            and not user_id == RASHMIKA
        ):
            channel = chat_db.channel
            try:
                client.get_chat_member(channel, user_id)
            except UserNotParticipant:
                try:
                    sent_message = message.reply_text(
                        "Hey  {} 🙏 \n \n **please join @{} Channel Join ** 😭 \n and press**UNMUTE ME** Button touch. \n \n **[👉 OUR CHANNEL 👈](https://t.me/{})**".format(
                            message.from_user.mention, channel, channel
                        ),
                        disable_web_page_preview=True,
                        reply_markup=InlineKeyboardMarkup(
                            [
                                [
                                    InlineKeyboardButton(
                                        "UnMute Me", callback_data="onUnMuteRequest"
                                    )
                                ]
                            ]
                        ),
                    )
                    client.restrict_chat_member(
                        chat_id, user_id, ChatPermissions(can_send_messages=False)
                    )
                except ChatAdminRequired:
                    sent_message.edit(
                        "❗ ** Admin +$$4&..**\n__ need Ban Permissions  Admin ද.. \n#Ending FSub...__"
                    )

            except ChatAdminRequired:
                client.send_message(
                    chat_id,
                    text=f"❗ **my@{channel}  Admin .**\n__::: Admin  Add .\n#Leaving this chat...__",
                )
Beispiel #29
0
async def locks_func(_, message):
    if len(message.command) != 2:
        return await message.reply_text(incorrect_parameters)
    chat_id = message.chat.id
    parameter = message.text.strip().split(None, 1)[1].lower()
    state = message.command[0].lower()
    if parameter not in data and parameter != "all":
        return await message.reply_text(incorrect_parameters)
    permissions = await current_chat_permissions(chat_id)
    if parameter in data:
        return await tg_lock(
            message,
            permissions,
            data[parameter],
            True if state == "lock" else False,
        )
    elif parameter == "all" and state == "lock":
        await app.set_chat_permissions(chat_id, ChatPermissions())
        await message.reply_text("Locked Everything.")
Beispiel #30
0
async def mute_user(_, message):
    user_id, user_first_name = extract_user(message)

    try:
        await message.chat.restrict_member(user_id=user_id,
                                           permissions=ChatPermissions())
    except Exception as error:
        await message.reply_text(str(error))
    else:
        if str(user_id).lower().startswith("@"):
            await message.reply_text("👍🏻 "
                                     f"{user_first_name}"
                                     " ലവന്റെ വായടച്ചിട്ടുണ്ട്! 🤐")
        else:
            await message.reply_text("👍🏻 "
                                     f"<a href='tg://user?id={user_id}'>"
                                     "ലവന്റെ"
                                     "</a>"
                                     " വായടച്ചിട്ടുണ്ട്! 🤐")