Пример #1
0
async def initial_works(c: Mizuhara, 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
                new_chat = m.chat.id

            try:
                await migrate_chat(old_chat, new_chat)
            except Exception as ef:
                LOGGER.error(ef)
                return
        else:
            userdb.update_user(m.from_user.id, m.from_user.username, m.chat.id,
                               m.chat.title)
            if m.reply_to_message:
                userdb.update_user(
                    m.reply_to_message.from_user.id,
                    m.reply_to_message.from_user.username,
                    m.chat.id,
                    m.chat.title,
                )
            if m.forward_from:
                userdb.update_user(m.forward_from.id, m.forward_from.username)
    except AttributeError:
        pass  # Skip attribute errors!
    return
Пример #2
0
    async def start(self):
        await super().start()

        me = await self.get_me()  # Get bot info from pyrogram client
        LOGGER.info("Starting bot...")
        """Redis Content Setup!"""
        await self.get_admins()  # Load admins in cache
        set_key("SUPPORT_STAFF", SUPPORT_STAFF)  # Load SUPPORT_STAFF in cache
        set_key("BOT_ID", int(me.id))  # Save Bot ID in Redis!
        """Redis Content Setup!"""

        # Show in Log that bot has started
        LOGGER.info(
            f"Pyrogram v{__version__}\n(Layer - {layer}) started on @{me.username}"
        )
        LOGGER.info(load_cmds(ALL_PLUGINS))
        LOGGER.info(f"Redis Keys Loaded: {allkeys()}")

        # Send a message to MESSAGE_DUMP telling that the bot has started and has loaded all plugins!
        await self.send_message(
            MESSAGE_DUMP,
            (f"<b><i>Bot started on Pyrogram v{__version__} (Layer - {layer})</i></b>\n\n"
             "<b>Loaded Plugins:</b>\n"
             f"<i>{list(HELP_COMMANDS.keys())}</i>\n"
             "<b>Redis Keys Loaded:</b>\n"
             f"<i>{allkeys()}</i>"),
        )

        LOGGER.info("Bot Started Successfully!")
Пример #3
0
async def prevent_approved(c: Mizuhara, m: Message):
    x = app_db.all_approved(m.chat.id)
    LOGGER.info(x)
    ul = []
    for j in x:
        ul.append(j.user_id)
    for i in ul:
        await c.restrict_chat_member(
            chat_id=m.chat.id,
            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 asyncio.sleep(0.2)

    return
Пример #4
0
async def pin_message(c: Mizuhara, m: Message):

    _ = GetLang(m).strs

    res = await admin_check(c, m)
    if not res:
        return

    pin_loud = m.text.split(" ", 1)
    if m.reply_to_message:
        try:
            disable_notification = True

            if len(pin_loud) >= 2 and pin_loud[1] in [
                    "alert", "notify", "loud"
            ]:
                disable_notification = False

            pinned_event = await c.pin_chat_message(
                m.chat.id,
                m.reply_to_m.message_id,
                disable_notification=disable_notification,
            )
            await m.reply_text(_("admin.pinnedmsg"))

        except errors.ChatAdminRequired:
            await m.reply_text(_("admin.notadmin"))
        except Exception as ef:
            await m.reply_text(_("admin.useadmincache"))
            LOGGER.error(ef)
    else:
        await m.reply_text(_("admin.nopinmsg"))
    return
Пример #5
0
async def adminlist(c: Mizuhara, m: Message):
    _ = GetLang(m).strs
    try:
        me_id = int(get_key("BOT_ID"))  # Get Bot ID from Redis!
        adminlist = get_key("ADMINDICT")[str(
            m.chat.id)]  # Load ADMINDICT from string
        adminstr = _("admin.adminlist").format(chat_title=m.chat.title)
        for i in adminlist:
            usr = await c.get_users(i)
            if i == me_id:
                adminstr += f"- {mention_html(usr.first_name, i)} (Me)\n"
            else:
                usr = await c.get_users(i)
                adminstr += f"- {mention_html(usr.first_name, i)} (`{i}`)\n"
        await m.reply_text(adminstr)
    except Exception as ef:

        if str(ef) == str(m.chat.id):
            await m.reply_text(_("admin.useadmincache"))
        else:
            await m.reply_text(
                _("admin.somerror").format(SUPPORT_GROUP=SUPPORT_GROUP, ef=ef))
            LOGGER.error(ef)

    return
Пример #6
0
async def del_blacklist(c: Mizuhara, m: Message):
    try:
        user_list = []
        approved_users = app_db.all_approved(m.chat.id)
        for auser in approved_users:
            user_list.append(int(auser.user_id))
        async for i in m.chat.iter_members(filter="administrators"):
            user_list.append(i.user.id)
        if m.from_user.id in user_list:
            del user_list  # Reset Admin list, just in case new admins are added!
            return
        if m.text:
            chat_filters = db.get_chat_blacklist(m.chat.id)
            if not chat_filters:
                return
            for trigger in chat_filters:
                pattern = r"( |^|[^\w])" + trigger + r"( |$|[^\w])"
                match = regex_searcher(pattern, m.text.lower())
                if not match:
                    continue
                if match:
                    try:
                        await m.delete()
                    except Exception as ef:
                        LOGGER.info(ef)
                    break
    except AttributeError:
        pass  # Skip attribute errors!
Пример #7
0
async def demote_usr(c: Mizuhara, m: Message):

    _ = GetLang(m).strs

    res = await admin_check(c, m)
    if not res:
        return

    from_user = await m.chat.get_member(m.from_user.id)

    # If user does not have permission to invite other users, return
    if from_user.can_invite_users or from_user.status == "creator":

        try:
            link = await c.export_chat_invite_link(m.chat.id)
            await m.reply_text(_("admin.invitelink").format(link=link))
        except errors.ChatAdminRequired:
            await m.reply_text(_("admin.notadmin"))
        except errors.ChatAdminInviteRequired:
            await m.reply_text(_("admin.noinviteperm"))
        except Exception as ef:
            await m.reply_text(_("admin.useadmincache"))
            LOGGER.error(ef)

        return

    await m.reply_text(_("admin.nouserinviteperm"))
    return
Пример #8
0
async def gban_watcher(c: Mizuhara, m: Message):
    try:
        if db.is_user_gbanned(m.from_user.id):
            try:
                await c.kick_chat_member(m.chat.id, m.from_user.id)
                await m.reply_text((
                    f"This user ({mention_html(m.from_user.first_name, m.from_user.id)}) "
                    "has been banned globally!\n\n"
                    f"To get unbanned appeal at {SUPPORT_GROUP}"), )
                LOGGER.info(f"Banned user {m.from_user.id} in {m.chat.id}")
                return
            except (errors.ChatAdminRequired or errors.UserAdminInvalid):
                # Bot not admin in group and hence cannot ban users!
                # TO-DO - Improve Error Detection
                LOGGER.info(
                    f"User ({m.from_user.id}) is admin in group {m.chat.name} ({m.chat.id})"
                )
                pass
            except Exception as excp:
                await c.send_message(
                    MESSAGE_DUMP,
                    f"<b>Gban Watcher Error!</b>\n<b>Chat:</b> {m.chat.id}\n<b>Error:</b> `{excp}`",
                )
    except AttributeError:
        pass  # Skip attribute errors!
    return
Пример #9
0
async def migrate_chat(old_chat, new_chat):
    LOGGER.info(f"Migrating from {str(old_chat)} to {str(new_chat)}")
    userdb.migrate_chat(old_chat, new_chat)
    langdb.migrate_chat(old_chat, new_chat)
    ruledb.migrate_chat(old_chat, new_chat)
    bldb.migrate_chat(old_chat, new_chat)
    notedb.migrate_chat(old_chat, new_chat)
    LOGGER.info("Successfully migrated!")
Пример #10
0
async def get_note(c: Mizuhara, m: Message):
    if len(m.text.split()) >= 2:
        note = m.text.split()[1]
    else:
        await m.reply_text("Give me a note tag!")

    getnotes = db.get_note(m.chat.id, note)
    if not getnotes:
        await m.reply_text("This note does not exist!")
        return

    if getnotes["type"] == Types.TEXT:
        teks, button = parse_button(getnotes.get("value"))
        button = build_keyboard(button)
        button = InlineKeyboardMarkup(button) if button else None
        if button:
            try:
                await m.reply_text(teks, reply_markup=button)
                return
            except Exception as ef:
                await m.reply_text("An error has accured! Cannot parse note.")
                LOGGER.error(ef)
                return
        else:
            await m.reply_text(teks)
            return
    elif getnotes["type"] in (
            Types.STICKER,
            Types.VOICE,
            Types.VIDEO_NOTE,
            Types.CONTACT,
            Types.ANIMATED_STICKER,
    ):
        await GET_FORMAT[getnotes["type"]](m.chat.id, getnotes["file"])
    else:
        if getnotes.get("value"):
            teks, button = parse_button(getnotes.get("value"))
            button = build_keyboard(button)
            button = InlineKeyboardMarkup(button) if button else None
        else:
            teks = None
            button = None
        if button:
            try:
                await m.reply_text(teks, reply_markup=button)
                return
            except Exception as ef:
                await m.reply_text("An error has accured! Cannot parse note.")
                LOGGER.error(ef)
                return
        else:
            await GET_FORMAT[getnotes["type"]](m.chat.id,
                                               getnotes["file"],
                                               caption=teks)
    return
Пример #11
0
async def demote_usr(c: Mizuhara, m: Message):

    _ = GetLang(m).strs

    res = await admin_check(c, m)
    if not res:
        return

    from_user = await m.chat.get_member(m.from_user.id)

    # If user does not have permission to demote other users, return
    if from_user.can_promote_members or from_user.status == "creator":

        user_id, user_first_name = await extract_user(c, m)
        try:
            await m.chat.promote_member(
                user_id=user_id,
                can_change_info=False,
                can_delete_messages=False,
                can_restrict_members=False,
                can_invite_users=False,
                can_pin_messages=False,
            )
            await m.reply_text(
                _("admin.demoted").format(
                    demoter=mention_html(m.from_user.first_name,
                                         m.from_user.id),
                    demoted=mention_html(user_first_name, user_id),
                    chat_title=m.chat.title,
                ))

            # ----- Add admin to redis cache! -----
            ADMINDICT = get_key("ADMINDICT")  # Load ADMINDICT from string
            adminlist = []
            async for i in m.chat.iter_members(filter="administrators"):
                adminlist.append(i.user.id)
            ADMINDICT[str(m.chat.id)] = adminlist
            set_key("ADMINDICT", ADMINDICT)

        except errors.ChatAdminRequired:
            await m.reply_text(_("admin.notadmin"))
        except Exception as ef:
            await m.reply_text(_("admin.useadmincache"))
            LOGGER.error(ef)

        return

    await m.reply_text(_("admin.nodemoteperm"))
    return
Пример #12
0
async def unpin_message(c: Mizuhara, m: Message):

    _ = GetLang(m).strs

    res = await admin_check(c, m)
    if not res:
        return

    try:
        await m.chat.unpin_chat_message(m.chat.id)
    except errors.ChatAdminRequired:
        await m.reply_text(_("admin.notadmin"))
    except Exception as ef:
        await m.reply_text(
            _("admin.somerror").format(SUPPORT_GROUP=SUPPORT_GROUP, ef=ef))
        LOGGER.error(ef)
    return
Пример #13
0
async def ban_usr(c: Mizuhara, m: Message):

    _ = GetLang(m).strs

    res = await admin_check(c, m)
    if not res:
        return

    from_user = await m.chat.get_member(m.from_user.id)

    if from_user.can_restrict_members or from_user.status == "creator":
        user_id, user_first_name = await extract_user(c, m)
        try:
            await c.kick_chat_member(m.chat.id, user_id)
            await m.reply_text(
                f"Banned {mention_html(user_first_name, user_id)}")
        except errors.ChatAdminRequired:
            await m.reply_text(_("admin.notadmin"))
        except Exception as ef:
            await m.reply_text(f"Error: {ef}\n\nReport it in Support Group!")
            LOGGER.error(ef)

    return
Пример #14
0
async def reload_admins(c: Mizuhara, m: Message):

    _ = GetLang(m).strs

    res = await admin_check(c, m)
    if not res:
        return

    ADMINDICT = get_key("ADMINDICT")  # Load ADMINDICT from string

    try:
        adminlist = []
        async for i in m.chat.iter_members(filter="administrators"):
            adminlist.append(i.user.id)
        ADMINDICT[str(m.chat.id)] = adminlist
        set_key("ADMINDICT", ADMINDICT)
        await m.reply_text(_("admin.reloadedadmins"))
        LOGGER.info(f"Reloaded admins for {m.chat.title}({m.chat.id})")
    except Exception as ef:
        await m.reply_text(_("admin.useadmincache"))
        LOGGER.error(ef)

    return
Пример #15
0
 async def stop(self, *args):
     # Send a message to MESSAGE_DUMP telling that the bot has stopped!
     await self.send_message(
         MESSAGE_DUMP,
         "<i><b>Bot Stopped!</b></i>",
     )
     await super().stop()
     # Flush Redis data
     try:
         flushredis()
         LOGGER.info("Flushed Redis!")
     except Exception as ef:
         LOGGER.error(ef)
     LOGGER.info("Bot Stopped.\nkthxbye!")
Пример #16
0
    async def get_admins(self):
        LOGGER.info("Begin caching admins...")
        begin = time.time()
        c = self

        # Flush Redis data
        try:
            flushredis()
        except Exception as ef:
            LOGGER.error(ef)

        # Get bot info
        me = await self.get_me()

        all_chats = userdb.get_all_chats() or []  # Get list of all chats
        LOGGER.info(f"{len(all_chats)} chats loaded.")
        ADMINDICT = {}
        for chat in all_chats:
            adminlist = []
            try:
                async for i in c.iter_chat_members(chat_id=chat.chat_id,
                                                   filter="administrators"):
                    adminlist.append(i.user.id)

                ADMINDICT[str(
                    chat.chat_id)] = adminlist  # Remove the last space

                LOGGER.info(
                    f"Set {len(adminlist)} admins for {chat.chat_id}\n{adminlist}"
                )
                del adminlist  # Delete list var
            except errors.PeerIdInvalid:
                pass
            except Exception as ef:
                LOGGER.error(ef)

        try:
            set_key("ADMINDICT", ADMINDICT)
            del ADMINDICT
            end = time.time()
            LOGGER.info(
                f"Set admin list cache!\nTime Taken: {round(end-begin, 2)}s")
        except Exception as ef:
            LOGGER.error(f"Could not set ADMINDICT!\n{ef}")
Пример #17
0
async def report(c: Mizuhara, m: Message):
    me = await c.get_me()

    if m.chat and m.reply_to_message and db.chat_should_report(m.chat.id):
        reported_user = m.reply_to_message.from_user
        chat_name = m.chat.title or m.chat.username
        admin_list = await c.get_chat_members(m.chat.id,
                                              filter="administrators")

        if m.from_user.id == reported_user.id:
            await m.reply_text(
                "Uh yeah, Sure sure...you don't need to report yourself!")
            return

        if reported_user.id == me.id:
            await m.reply_text("Nice try.")
            return

        if reported_user.id in SUPPORT_STAFF:
            await m.reply_text("Uh? You reporting whitelisted users?")
            return

        if m.chat.username and m.chat.type == "supergroup":

            reported = f"{mention_html(m.from_user.first_name, m.from_user.id)} reported {mention_html(reported_user.first_name, reported_user.id)} to the admins!"

            msg = (
                f"<b>⚠️ Report: </b>{html.escape(m.chat.title)}\n"
                f"<b> • Report by:</b> {mention_html(m.from_user.first_name, m.from_user.id)}(<code>{m.from_user.id}</code>)\n"
                f"<b> • Reported user:</b> {mention_html(reported_user.first_name, reported_user.id)} (<code>{reported_user.id}</code>)\n"
            )
            link = f'<b> • Reported message:</b> <a href="https://t.me/{m.chat.username}/{m.reply_to_message.message_id}">click here</a>'
            should_forward = False
            keyboard = [
                [
                    InlineKeyboardButton(
                        "➡ Message",
                        url=
                        f"https://t.me/{m.chat.username}/{m.reply_to_message.message_id}",
                    )
                ],
                [
                    InlineKeyboardButton(
                        "⚠ Kick",
                        callback_data=
                        f"report_{m.chat.id}=kick={reported_user.id}={reported_user.first_name}",
                    ),
                    InlineKeyboardButton(
                        "⛔️ Ban",
                        callback_data=
                        f"report_{m.chat.id}=banned={reported_user.id}={reported_user.first_name}",
                    ),
                ],
                [
                    InlineKeyboardButton(
                        "❎ Delete Message",
                        callback_data=
                        f"report_{m.chat.id}=delete={reported_user.id}={m.reply_to_message.message_id}",
                    )
                ],
            ]
            reply_markup = InlineKeyboardMarkup(keyboard)
        else:
            reported = f"{mention_html(m.from_user.first_name, m.from_user.id)} reported {mention_html(reported_user.first_name, reported_user.id)} to the admins!"

            msg = f'{mention_html(m.from_user.first_name, m.from_user.id)} is calling for admins in "{html.escape(chat_name)}"!'
            link = ""
            should_forward = True

        for admin in admin_list:
            if admin.user.is_bot:  # can't message bots
                continue

            if db.user_should_report(admin.user.id):
                try:
                    if not m.chat.type == "supergroup":
                        await c.send_message(admin.user.id, msg + link)

                        if should_forward:
                            await m.reply_to_message.forward(admin.user.id)

                            if (
                                    len(m.text.split()) > 1
                            ):  # If user is giving a reason, send his message too
                                await m.reply_to_message.forward(admin.user.id)
                    if not m.chat.username:
                        await c.send_message(admin.user.id, msg + link)

                        if should_forward:
                            await m.reply_to_message.forward(admin.user.id)

                            if (
                                    len(m.text.split()) > 1
                            ):  # If user is giving a reason, send his message too
                                await m.forward(admin.user.id)

                    if m.chat.username and m.chat.type == "supergroup":
                        await c.send_message(admin.user.id,
                                             msg + link,
                                             reply_markup=reply_markup)

                        if should_forward:
                            await m.reply_to_message.forward(admin.user.id)

                            if (
                                    len(m.text.split()) > 1
                            ):  # If user is giving a reason, send his message too
                                await m.forward(admin.user.id)

                except Unauthorized:
                    pass
                except BadRequest:
                    LOGGER.exception("Exception while reporting user")

        await m.reply_to_message.reply_text(
            f"{mention_html(m.from_user.first_name, m.from_user.id)} reported the message to the admins."
        )
        return
    return