Beispiel #1
0
async def check_approval(c: Alita, m: Message):
    db = Approve(m.chat.id)

    try:
        user_id, user_first_name, _ = await extract_user(c, m)
    except Exception:
        return
    check_approve = db.check_approve(user_id)
    LOGGER.info(
        f"{m.from_user.id} checking approval of {user_id} in {m.chat.id}")

    if not user_id:
        await m.reply_text(
            "I don't know who you're talking about, you're going to need to specify a user!",
        )
        return
    if check_approve:
        await m.reply_text(
            f"{(await mention_html(user_first_name, user_id))} is an approved user. Locks, antiflood, and blacklists won't apply to them.",
        )
    else:
        await m.reply_text(
            f"{(await mention_html(user_first_name, user_id))} is not an approved user. They are affected by normal commands.",
        )
    return
Beispiel #2
0
async def migrate_chat(m: Message, new_chat: int) -> None:
    LOGGER.info(f"Migrating from {m.chat.id} to {new_chat}...")
    langdb = Langs(m.chat.id)
    notedb = Notes()
    gdb = Greetings(m.chat.id)
    ruledb = Rules(m.chat.id)
    userdb = Users(m.chat.id)
    chatdb = Chats(m.chat.id)
    bldb = Blacklist(m.chat.id)
    approvedb = Approve(m.chat.id)
    reportdb = Reporting(m.chat.id)
    notes_settings = NotesSettings()
    pins_db = Pins(m.chat.id)
    fldb = Filters()
    disabl = Disabling(m.chat.id)
    disabl.migrate_chat(new_chat)
    gdb.migrate_chat(new_chat)
    chatdb.migrate_chat(new_chat)
    userdb.migrate_chat(new_chat)
    langdb.migrate_chat(new_chat)
    ruledb.migrate_chat(new_chat)
    bldb.migrate_chat(new_chat)
    notedb.migrate_chat(m.chat.id, new_chat)
    approvedb.migrate_chat(new_chat)
    reportdb.migrate_chat(new_chat)
    notes_settings.migrate_chat(m.chat.id, new_chat)
    pins_db.migrate_chat(new_chat)
    fldb.migrate_chat(m.chat.id, new_chat)
    LOGGER.info(f"Successfully migrated from {m.chat.id} to {new_chat}!")
Beispiel #3
0
async def unapproveall_callback(_, q: CallbackQuery):
    user_id = q.from_user.id
    db = Approve(q.message.chat.id)
    approved_people = db.list_approved()
    user_status = (await q.message.chat.get_member(user_id)).status
    if user_status not in {"creator", "administrator"}:
        await q.answer(
            "You're not even an admin, don't try this explosive shit!",
            show_alert=True,
        )
        return
    if user_status != "creator":
        await q.answer(
            "You're just an admin, not owner\nStay in your limits!",
            show_alert=True,
        )
        return
    db.unapprove_all()
    for i in approved_people:
        await q.message.chat.restrict_member(
            user_id=i[0],
            permissions=q.message.chat.permissions,
        )
    await q.message.delete()
    LOGGER.info(f"{user_id} disapproved all users in {q.message.chat.id}")
    await q.answer("Disapproved all users!", show_alert=True)
    return
Beispiel #4
0
async def approve_user(c: Alita, m: Message):
    db = Approve(m.chat.id)

    chat_title = m.chat.title

    try:
        user_id, user_first_name, _ = await extract_user(c, m)
    except Exception:
        return

    if not user_id:
        await m.reply_text(
            "I don't know who you're talking about, you're going to need to specify a user!",
        )
        return
    try:
        member = await m.chat.get_member(user_id)
    except UserNotParticipant:
        await m.reply_text("This user is not in this chat!")
        return

    except RPCError as ef:
        await m.reply_text(
            f"<b>Error</b>: <code>{ef}</code>\nReport it to @{SUPPORT_GROUP}",
        )
        return
    if member.status in ("administrator", "creator"):
        await m.reply_text(
            "User is already admin - blacklists and locks already don't apply to them.",
        )
        return
    already_approved = db.check_approve(user_id)
    if already_approved:
        await m.reply_text(
            f"{(await mention_html(user_first_name, user_id))} is already approved in {chat_title}",
        )
        return
    db.add_approve(user_id, user_first_name)
    LOGGER.info(f"{user_id} approved by {m.from_user.id} in {m.chat.id}")

    # Allow all permissions
    try:
        await m.chat.unban_member(user_id=user_id)
    except RPCError as g:
        await m.reply_text(f"Error: {g}")
        return
    await m.reply_text(
        (
            f"{(await mention_html(user_first_name, user_id))} has been approved in {chat_title}!\n"
            "They will now be ignored by blacklists, locks and antiflood!"
        ),
    )
    return
Beispiel #5
0
async def unapproveall_users(_, m: Message):
    db = Approve(m.chat.id)

    all_approved = db.list_approved()
    if not all_approved:
        await m.reply_text("No one is approved in this chat.")
        return

    await m.reply_text(
        "Are you sure you want to remove everyone who is approved in this chat?",
        reply_markup=ikb([[("⚠️ Confirm", "unapprove_all"),
                           ("❌ Cancel", "close_admin")]], ),
    )
    return
Beispiel #6
0
async def prevent_approved(m: Message):
    approved_users = Approve(m.chat.id).list_approved()
    ul = [user[0] for user in approved_users]
    for i in ul:
        try:
            await m.chat.unban_member(user_id=i)
        except (ChatAdminRequired, ChatNotModified, RPCError):
            continue
        LOGGER.info(f"Approved {i} in {m.chat.id}")
        await sleep(0.1)
    return
Beispiel #7
0
async def disapprove_user(c: Alita, m: Message):
    db = Approve(m.chat.id)

    chat_title = m.chat.title
    try:
        user_id, user_first_name, _ = await extract_user(c, m)
    except Exception:
        return
    already_approved = db.check_approve(user_id)
    if not user_id:
        await m.reply_text(
            "I don't know who you're talking about, you're going to need to specify a user!",
        )
        return
    try:
        member = await m.chat.get_member(user_id)
    except UserNotParticipant:
        if already_approved:  # If user is approved and not in chat, unapprove them.
            db.remove_approve(user_id)
            LOGGER.info(
                f"{user_id} disapproved in {m.chat.id} as UserNotParticipant")
        await m.reply_text("This user is not in this chat, unapproved them.")
        return
    except RPCError as ef:
        await m.reply_text(
            f"<b>Error</b>: <code>{ef}</code>\nReport it to @{SUPPORT_GROUP}",
        )
        return

    if member.status in ("administrator", "creator"):
        await m.reply_text("This user is an admin, they can't be disapproved.")
        return

    if not already_approved:
        await m.reply_text(
            f"{(await mention_html(user_first_name, user_id))} isn't approved yet!",
        )
        return

    db.remove_approve(user_id)
    LOGGER.info(f"{user_id} disapproved by {m.from_user.id} in {m.chat.id}")

    # Set permission same as of current user by fetching them from chat!
    await m.chat.restrict_member(
        user_id=user_id,
        permissions=m.chat.permissions,
    )

    await m.reply_text(
        f"{(await mention_html(user_first_name, user_id))} is no longer approved in {chat_title}.",
    )
    return
Beispiel #8
0
async def check_approved(_, m: Message):
    db = Approve(m.chat.id)

    chat = m.chat
    chat_title = chat.title
    msg = "The following users are approved:\n"
    approved_people = db.list_approved()

    if not approved_people:
        await m.reply_text(f"No users are approved in {chat_title}.")
        return

    for user_id, user_name in approved_people.items():
        try:
            await chat.get_member(user_id)  # Check if user is in chat or not
        except UserNotParticipant:
            db.remove_approve(user_id)
            continue
        except PeerIdInvalid:
            pass
        msg += f"- `{user_id}`: {user_name}\n"
    await m.reply_text(msg)
    LOGGER.info(f"{m.from_user.id} checking approved users in {m.chat.id}")
    return
Beispiel #9
0
async def check_approval(c: Alita, m: Message):
    db = Approve(m.chat.id)

    try:
        user_id, user_first_name, _ = await extract_user(c, m)
    except Exception:
        return
    check_approve = db.check_approve(user_id)
    LOGGER.info(f"{m.from_user.id} checking approval of {user_id} in {m.chat.id}")

    if not user_id:
        await m.reply_text(
            "I don't know who you're talking about, you're going to need to specify a user!",
        )
        return
    if check_approve:
        await m.reply_text(
            f"{(await mention_html(user_first_name, user_id))} является одобренным пользователем.  Блокировки, антифлуд и черные списки на них не распространяются..",
        )
    else:
        await m.reply_text(
            f"{(await mention_html(user_first_name, user_id))} не является одобренным пользователям. На него действуют обычные наказания.",
        )
    return
Beispiel #10
0
async def prevent_approved(m: Message):
    approved_users = Approve(m.chat.id).list_approved()
    ul = [user[0] for user in approved_users]
    for i in ul:
        await m.chat.restrict_member(
            user_id=i,
            permissions=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,
                can_change_info=True,
                can_invite_users=True,
                can_pin_messages=True,
            ),
        )
        LOGGER.info(f"Approved {i} in {m.chat.id}")
        await sleep(0.1)

    return
Beispiel #11
0
from alita.database.blacklist_db import Blacklist
from alita.database.chats_db import Chats
from alita.database.filters_db import Filters
from alita.database.notes_db import Notes, NotesSettings
from alita.database.rules_db import Rules
from alita.database.users_db import Users
from alita.database.warns_db import Warns, WarnSettings
from alita.utils.custom_filters import command, dev_filter

# initialise
bldb = Blacklist()
gbandb = GBan()
notesdb = Notes()
rulesdb = Rules()
userdb = Users()
appdb = Approve()
chatdb = Chats()
fldb = Filters()
pinsdb = Pins()
notesettings_db = NotesSettings()
warns_db = Warns()
warns_settings_db = WarnSettings()


@Alita.on_message(command("stats", DEV_PREFIX_HANDLER) & dev_filter)
async def get_stats(_, m: Message):
    replymsg = await m.reply_text("<b><i>Fetching Stats...</i></b>", quote=True)
    rply = (
        f"<b>Users:</b> <code>{(userdb.count_users())}</code> in <code>{(chatdb.count_chats())}</code> chats\n"
        f"<b>Anti Channel Pin:</b> <code>{(pinsdb.count_chats('antichannelpin'))}</code> enabled chats\n"
        f"<b>Clean Linked:</b> <code>{(pinsdb.count_chats('cleanlinked'))}</code> enabled chats\n"
Beispiel #12
0
async def bl_watcher(_, m: Message):
    if m and not m.from_user:
        return

    bl_db = Blacklist(m.chat.id)

    async def perform_action_blacklist(m: Message, action: str, trigger: str):
        if action == "kick":
            await m.chat.kick_member(m.from_user.id, int(time() + 45))
            await m.reply_text(
                tlang(m, "blacklist.bl_watcher.action_kick").format(
                    user=m.from_user.username
                    or f"<b>{m.from_user.first_name}</b>", ), )

        elif action == "ban":
            (await m.chat.kick_member(m.from_user.id, ))
            await m.reply_text(
                tlang(m, "blacklist.bl_watcher.action_ban").format(
                    user=m.from_user.username
                    or f"<b>{m.from_user.first_name}</b>", ), )

        elif action == "mute":
            await m.chat.restrict_member(
                m.from_user.id,
                ChatPermissions(
                    can_send_messages=False,
                    can_send_media_messages=False,
                    can_send_stickers=False,
                    can_send_animations=False,
                    can_send_games=False,
                    can_use_inline_bots=False,
                    can_add_web_page_previews=False,
                    can_send_polls=False,
                    can_change_info=False,
                    can_invite_users=True,
                    can_pin_messages=False,
                ),
            )

            await m.reply_text(
                tlang(m, "blacklist.bl_watcher.action_mute").format(
                    user=m.from_user.username
                    or f"<b>{m.from_user.first_name}</b>", ), )

        elif action == "warn":
            warns_settings_db = WarnSettings(m.chat.id)
            warns_db = Warns(m.chat.id)
            warn_settings = warns_settings_db.get_warnings_settings()
            warn_reason = bl_db.get_reason()
            _, num = warns_db.warn_user(m.from_user.id, warn_reason)
            if num >= warn_settings["warn_limit"]:
                if warn_settings["warn_mode"] == "kick":
                    await m.chat.kick_member(
                        m.from_user.id,
                        until_date=int(time() + 45),
                    )
                    action = "kicked"
                elif warn_settings["warn_mode"] == "ban":
                    await m.chat.kick_member(m.from_user.id)
                    action = "banned"
                elif warn_settings["warn_mode"] == "mute":
                    await m.chat.restrict_member(m.from_user.id,
                                                 ChatPermissions())
                    action = "muted"
                await m.reply_text((
                    f"Warnings {num}/{warn_settings['warn_limit']}\n"
                    f"{(await mention_html(m.from_user.first_name, m.from_user.id))} has been <b>{action}!</b>"
                ), )
                return
            await m.reply_text(
                (
                    f"{(await mention_html(m.from_user.first_name, m.from_user.id))} warned {num}/{warn_settings['warn_limit']}\n"
                    # f"Last warn was for:\n<i>{warn_reason}</i>"
                    f"Last warn was for:\n<i>{warn_reason.format(trigger)}</i>"
                ), )
        return

    if m.from_user.id in SUPPORT_STAFF:
        # Don't work on Support Staff!
        return

    # If no blacklists, then return
    chat_blacklists = bl_db.get_blacklists()
    if not chat_blacklists:
        return

    # Get admins from admin_cache, reduces api calls
    try:
        admin_ids = {i[0] for i in ADMIN_CACHE[m.chat.id]}
    except KeyError:
        admin_ids = await admin_cache_reload(m, "blacklist_watcher")

    if m.from_user.id in admin_ids:
        return

    # Get approved user from cache/database
    app_users = Approve(m.chat.id).list_approved()
    if m.from_user.id in {i[0] for i in app_users}:
        return

    # Get action for blacklist
    action = bl_db.get_action()
    for trigger in chat_blacklists:
        pattern = r"( |^|[^\w])" + re_escape(trigger) + r"( |$|[^\w])"
        match = await regex_searcher(pattern, m.text.lower())
        if not match:
            continue
        if match:
            try:
                await perform_action_blacklist(m, action, trigger)
                LOGGER.info(
                    f"{m.from_user.id} {action}ed for using blacklisted word {trigger} in {m.chat.id}",
                )
                await m.delete()
            except RPCError as ef:
                LOGGER.error(ef)
                LOGGER.error(format_exc())
            break
    return
Beispiel #13
0
from alita import LOGGER, MESSAGE_DUMP, SUPPORT_STAFF
from alita.bot_class import Alita
from alita.database.antichannelpin_db import Pins
from alita.database.antispam_db import ANTISPAM_BANNED, GBan
from alita.database.approve_db import Approve
from alita.database.blacklist_db import Blacklist
from alita.database.group_blacklist import BLACKLIST_CHATS
from alita.database.warns_db import Warns, WarnSettings
from alita.tr_engine import tlang
from alita.utils.caching import ADMIN_CACHE, admin_cache_reload
from alita.utils.parser import mention_html
from alita.utils.regex_utils import regex_searcher

# Initialise
bl_db = Blacklist()
app_db = Approve()
gban_db = GBan()
pins_db = Pins()
warns_db = Warns()
warns_settings_db = WarnSettings()


@Alita.on_message(filters.linked_channel)
async def antichanpin_cleanlinked(c: Alita, m: Message):
    try:
        msg_id = m.message_id
        curr = pins_db.get_current_stngs(m.chat.id)
        if curr["antichannelpin"]:
            await c.unpin_chat_message(chat_id=m.chat.id, message_id=msg_id)
            LOGGER.info(f"AntiChannelPin: msgid-{m.message_id} unpinned in {m.chat.id}")
        if curr["cleanlinked"]:
Beispiel #14
0
async def promote_usr(c: Alita, m: Message):
    from alita import BOT_ID

    global ADMIN_CACHE

    if len(m.text.split()) == 1 and not m.reply_to_message:
        await m.reply_text(tlang(m, "admin.promote.no_target"))
        return

    try:
        user_id, user_first_name, user_name = await extract_user(c, m)
    except Exception:
        return

    bot = await c.get_chat_member(m.chat.id, BOT_ID)

    if user_id == BOT_ID:
        await m.reply_text("Huh, how can I even promote myself?")
        return

    if not bot.can_promote_members:
        return await m.reply_text("I don't have enough permissions",
                                  )  # This should be here
    # If user is alreay admin
    try:
        admin_list = {i[0] for i in ADMIN_CACHE[m.chat.id]}
    except KeyError:
        admin_list = {
            i[0]
            for i in (await admin_cache_reload(m, "promote_cache_update"))
        }

    if user_id in admin_list:
        await m.reply_text(
            "This user is already an admin, how am I supposed to re-promote them?",
        )
        return

    try:
        await m.chat.promote_member(
            user_id=user_id,
            can_change_info=bot.can_change_info,
            can_invite_users=bot.can_invite_users,
            can_delete_messages=bot.can_delete_messages,
            can_restrict_members=bot.can_restrict_members,
            can_pin_messages=bot.can_pin_messages,
            # can_promote_members=bot.can_promote_members,
            can_manage_chat=bot.can_manage_chat,
            can_manage_voice_chats=bot.can_manage_voice_chats,
        )

        title = ""  # Deafult title
        if len(m.text.split()) == 3 and not m.reply_to_message:
            title = m.text.split()[2]
        elif len(m.text.split()) == 2 and m.reply_to_message:
            title = m.text.split()[1]
        if len(title) > 16:
            title = title[0:16]  # trim title to 16 characters

        try:
            await c.set_administrator_title(m.chat.id, user_id, title)
        except Exception as e:
            LOGGER.error(e)

        LOGGER.info(
            f"{m.from_user.id} promoted {user_id} in {m.chat.id} with title '{title}'",
        )

        await m.reply_text((tlang(m, "admin.promote.promoted_user")).format(
            promoter=(await mention_html(
                m.from_user.first_name,
                m.from_user.id,
            )),
            promoted=(await mention_html(user_first_name, user_id)),
            chat_title=m.chat.title + f"\nTitle set to {title}"
            if title != "Admin" else "Default Admin!",
        ), )

        # If user is approved, disapprove them as they willbe promoted and get even more rights
        if Approve(m.chat.id).check_approve(user_id):
            Approve(m.chat.id).remove_approve(user_id)

        # ----- Add admin to temp cache -----
        try:
            inp1 = user_name or user_first_name
            admins_group = ADMIN_CACHE[m.chat.id]
            admins_group.append((user_id, inp1))
            ADMIN_CACHE[m.chat.id] = admins_group
        except KeyError:
            await admin_cache_reload(m, "promote_key_error")

    except ChatAdminRequired:
        await m.reply_text(tlang(m, "admin.not_admin"))
    except RightForbidden:
        await m.reply_text(tlang(m, "admin.promote.bot_no_right"))
    except UserAdminInvalid:
        await m.reply_text(tlang(m, "admin.user_admin_invalid"))
    except RPCError as ef:
        await m.reply_text((tlang(m, "general.some_error")).format(
            SUPPORT_GROUP=SUPPORT_GROUP,
            ef=ef,
        ), )
    except Exception as e:
        await m.reply_text((tlang(m, "general.some_error")).format(
            SUPPORT_GROUP=SUPPORT_GROUP,
            ef=e,
        ), )
        LOGGER.error(e)
        LOGGER.error(format_exc())

    return
Beispiel #15
0
from alita.database.filters_db import Filters
from alita.database.lang_db import Langs
from alita.database.notes_db import Notes, NotesSettings
from alita.database.reporting_db import Reporting
from alita.database.rules_db import Rules
from alita.database.users_db import Users

# Initialise
langdb = Langs()
notedb = Notes()
ruledb = Rules()
userdb = Users()
chatdb = Chats()
bldb = Blacklist()
flooddb = AntiFlood()
approvedb = Approve()
reportdb = Reporting()
notes_settings = NotesSettings()
pins_db = Pins()
fldb = Filters()


@Alita.on_message(filters.group, group=4)
async def initial_works(_, m: Message):
    try:
        if m.migrate_to_chat_id or m.migrate_from_chat_id:
            if m.migrate_to_chat_id:
                old_chat = m.chat.id
                new_chat = m.migrate_to_chat_id
            elif m.migrate_from_chat_id:
                old_chat = m.migrate_from_chat_id
Beispiel #16
0
    CallbackQuery,
    ChatPermissions,
    InlineKeyboardButton,
    InlineKeyboardMarkup,
    Message,
)

from alita import LOGGER, SUPPORT_GROUP
from alita.bot_class import Alita
from alita.database.approve_db import Approve
from alita.utils.custom_filters import admin_filter, command, owner_filter
from alita.utils.extract_user import extract_user
from alita.utils.parser import mention_html

# Initialise
db = Approve()


@Alita.on_message(
    command("approve") & admin_filter, )
async def approve_user(c: Alita, m: Message):

    chat_title = m.chat.title
    chat_id = m.chat.id
    user_id, user_first_name, _ = await extract_user(c, m)
    if not user_id:
        await m.reply_text(
            "I don't know who you're talking about, you're going to need to specify a user!",
        )
        return
    try: