Exemplo n.º 1
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}!")
Exemplo n.º 2
0
async def remove_last_warn_btn(c: Alita, q: CallbackQuery):

    try:
        admins_group = {i[0] for i in ADMIN_CACHE[q.message.chat.id]}
    except KeyError:
        admins_group = {i[0] for i in (await admin_cache_reload(q, "warn_btn"))}

    if q.from_user.id not in admins_group:
        await q.answer("You are not allowed to use this!", show_alert=True)
        return

    args = q.data.split(".")
    action = args[1]
    user_id = int(args[2])
    chat_id = int(q.message.chat.id)
    user = Users.get_user_info(int(user_id))
    user_first_name = user["name"]

    if action == "remove":
        warn_db = Warns(q.message.chat.id)
        _, num_warns = warn_db.remove_warn(user_id)
        await q.message.edit_text(
            (
                f"Admin {(await mention_html(q.from_user.first_name, q.from_user.id))} "
                "removed last warn for "
                f"{(await mention_html(user_first_name, user_id))}\n"
                f"<b>Current Warnings:</b> {num_warns}"
            ),
        )
    if action == "kick":
        try:
            await c.kick_chat_member(chat_id, user_id, until_date=int(time() + 45))
            await q.message.edit_text(
                (
                    f"Admin {(await mention_html(q.from_user.first_name, q.from_user.id))} "
                    "kicked user "
                    f"{(await mention_html(user_first_name, user_id))} for last warning!"
                ),
            )
        except RPCError as err:
            await q.message.edit_text(
                f"🛑 Failed to Kick\n<b>Error:</b>\n</code>{err}</code>",
            )

    await q.answer()
    return
Exemplo n.º 3
0
async def gdpr_remove(_, m: Message):
    if m.from_user.id in SUPPORT_STAFF:
        await m.reply_text(
            "You're in my support staff, I cannot do that unless you are no longer a part of it!",
        )
        return

    Users(m.from_user.id).delete_user()
    await m.reply_text(
        "Your personal data has been deleted.\n"
        "Note that this will not unban you from any chats, as that is telegram data, not Alita data."
        " Flooding, warns, and gbans are also preserved, as of "
        "[this](https://ico.org.uk/for-organisations/guide-to-the-general-data-protection-regulation-gdpr/individual-rights/right-to-erasure/),"
        " which clearly states that the right to erasure does not apply 'for the performance of a task carried out in the public interest', "
        "as is the case for the aforementioned pieces of data.",
        disable_web_page_preview=True,
    )
    await m.stop_propagation()
Exemplo n.º 4
0
from alita.database.approve_db import Approve
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"
Exemplo n.º 5
0
async def initial_works(_, m: Message):
    chatdb = Chats(m.chat.id)
    try:
        if m.migrate_to_chat_id or m.migrate_from_chat_id:
            new_chat = m.migrate_to_chat_id or m.chat.id
            try:
                await migrate_chat(m, new_chat)
            except RPCError as ef:
                LOGGER.error(ef)
                return
        elif m.reply_to_message and not m.forward_from:
            chatdb.update_chat(
                m.chat.title,
                m.reply_to_message.from_user.id,
            )
            Users(m.reply_to_message.from_user.id).update_user(
                (
                    f"{m.reply_to_message.from_user.first_name} {m.reply_to_message.from_user.last_name}"
                    if m.reply_to_message.from_user.last_name
                    else m.reply_to_message.from_user.first_name
                ),
                m.reply_to_message.from_user.username,
            )
        elif m.forward_from and not m.reply_to_message:
            chatdb.update_chat(
                m.chat.title,
                m.forward_from.id,
            )
            Users(m.forward_from.id).update_user(
                (
                    f"{m.forward_from.first_name} {m.forward_from.last_name}"
                    if m.forward_from.last_name
                    else m.forward_from.first_name
                ),
                m.forward_from.username,
            )
        elif m.reply_to_message:
            chatdb.update_chat(
                m.chat.title,
                m.reply_to_message.forward_from.id,
            )
            Users(m.forward_from.id).update_user(
                (
                    f"{m.reply_to_message.forward_from.first_name} {m.reply_to_message.forward_from.last_name}"
                    if m.reply_to_message.forward_from.last_name
                    else m.reply_to_message.forward_from.first_name
                ),
                m.forward_from.username,
            )
        else:
            chatdb.update_chat(m.chat.title, m.from_user.id)
            Users(m.from_user.id).update_user(
                (
                    f"{m.from_user.first_name} {m.from_user.last_name}"
                    if m.from_user.last_name
                    else m.from_user.first_name
                ),
                m.from_user.username,
            )
    except AttributeError:
        pass  # Skip attribute errors!
    return
Exemplo n.º 6
0
# GNU Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from traceback import format_exc
from typing import Tuple

from pyrogram.types.messages_and_media.message import Message

from alita import LOGGER
from alita.bot_class import Alita
from alita.database.users_db import Users

# Initialize
db = Users()


async def extract_user(c: Alita, m: Message) -> Tuple[int, str, str]:
    """Extract the user from the provided message."""
    user_id = None
    user_first_name = None
    user_name = None

    if m.reply_to_message and m.reply_to_message.from_user:
        user_id = m.reply_to_message.from_user.id
        user_first_name = m.reply_to_message.from_user.first_name
        user_name = m.reply_to_message.from_user.username

    elif len(m.text.split()) > 1:
        if len(m.entities) > 1:
Exemplo n.º 7
0
    PREFIX_HANDLER,
    SUPPORT_GROUP,
    SUPPORT_STAFF,
)
from alita.bot_class import Alita
from alita.database.antispam_db import GBan
from alita.database.users_db import Users
from alita.tr_engine import tlang
from alita.utils.clean_file import remove_markdown_and_html
from alita.utils.custom_filters import command, sudo_filter
from alita.utils.extract_user import extract_user
from alita.utils.parser import mention_html

# Initialize
db = GBan()
user_db = Users()


@Alita.on_message(command(["gban", "globalban"]) & sudo_filter)
async def gban(c: Alita, m: Message):

    if len(m.text.split()) == 1:
        await m.reply_text(tlang(m, "antispam.gban.how_to"))
        return

    if len(m.text.split()) == 2 and not m.reply_to_message:
        await m.reply_text(tlang(m, "antispam.gban.enter_reason"))
        return

    user_id, user_first_name, _ = await extract_user(c, m)
Exemplo n.º 8
0
async def my_info(c: Alita, m: Message):
    try:
        user_id, name, user_name = await extract_user(c, m)
    except PeerIdInvalid:
        await m.reply_text(tlang(m, "utils.user_info.peer_id_error"))
        return
    except ValueError as ef:
        if "Peer id invalid" in str(ef):
            await m.reply_text(tlang(m, "utils.user_info.id_not_found"))
        return
    try:
        user = Users.get_user_info(int(user_id))
        name = user["name"]
        user_name = user["username"]
        user_id = user["_id"]
    except KeyError:
        LOGGER.warning(f"Calling api to fetch info about user {user_id}")
        user = await c.get_users(user_id)
        name = (escape(user["first_name"] + " " + user["last_name"])
                if user["last_name"] else user["first_name"])
        user_name = user["username"]
        user_id = user["id"]
    except PeerIdInvalid:
        await m.reply_text(tlang(m, "utils.no_user_db"))
        return
    except (RPCError, Exception) as ef:
        await m.reply_text((tlang(m, "general.some_error")).format(
            SUPPORT_GROUP=SUPPORT_GROUP,
            ef=ef,
        ), )
        return

    gbanned, reason_gban = gban_db.get_gban(user_id)
    LOGGER.info(f"{m.from_user.id} used info cmd for {user_id} in {m.chat.id}")

    text = (tlang(m, "utils.user_info.info_text.main")).format(
        user_id=user_id,
        user_name=name,
    )

    if user_name:
        text += (tlang(m, "utils.user_info.info_text.username")).format(
            username=user_name, )

    text += (tlang(m, "utils.user_info.info_text.perma_link")).format(
        perma_link=(await mention_html("Click Here", user_id)), )

    if gbanned:
        text += f"\nThis user is Globally banned beacuse: {reason_gban}\n"

    if user_id == OWNER_ID:
        text += tlang(m, "utils.user_info.support_user.owner")
    elif user_id in DEV_USERS:
        text += tlang(m, "utils.user_info.support_user.dev")
    elif user_id in SUDO_USERS:
        text += tlang(m, "utils.user_info.support_user.sudo")
    elif user_id in WHITELIST_USERS:
        text += tlang(m, "utils.user_info.support_user.whitelist")

    await m.reply_text(text, parse_mode="html", disable_web_page_preview=True)
    return
Exemplo n.º 9
0
from alita import LOGGER, SUPPORT_STAFF
from alita.bot_class import Alita
from alita.database.rules_db import Rules
from alita.database.users_db import Users
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.custom_filters import admin_filter, command, restrict_filter
from alita.utils.extract_user import extract_user
from alita.utils.parser import mention_html

warn_db = Warns()
rules_db = Rules()
warn_settings_db = WarnSettings()
users_db = Users()


@Alita.on_message(
    command(["warn", "swarn", "dwarn"]) & restrict_filter,
)
async def warn(c: Alita, m: Message):
    from alita import BOT_ID, BOT_USERNAME

    if m.reply_to_message:
        r_id = m.reply_to_message.message_id
        if len(m.text.split()) >= 2:
            reason = m.text.split(None, 1)[1]
    elif not m.reply_to_message:
        r_id = m.message_id
        if len(m.text.split()) >= 3:
Exemplo n.º 10
0
async def extract_user(c: Alita, m: Message) -> Tuple[int, str, str]:
    """Extract the user from the provided message."""
    user_id = None
    user_first_name = None
    user_name = None

    if m.reply_to_message and m.reply_to_message.from_user:
        user_id = m.reply_to_message.from_user.id
        user_first_name = m.reply_to_message.from_user.first_name
        user_name = m.reply_to_message.from_user.username

    elif len(m.text.split()) > 1:
        if len(m.entities) > 1:
            required_entity = m.entities[1]
            if required_entity.type == "text_mention":
                user_id = required_entity.user.id
                user_first_name = required_entity.user.first_name
                user_name = required_entity.user.username
            elif required_entity.type in ("mention", "phone_number"):
                # new long user ids are identified as phone_number
                user_found = m.text[required_entity.offset:(
                    required_entity.offset + required_entity.length)]

                try:
                    user_found = int(user_found)
                except (ValueError, Exception) as ef:
                    if "invalid literal for int() with base 10:" in str(ef):
                        user_found = str(user_found)
                    else:
                        LOGGER.error(ef)
                        LOGGER.error(format_exc())

                try:
                    user = Users.get_user_info(user_found)
                    user_id = user["_id"]
                    user_first_name = user["name"]
                    user_name = user["username"]
                except KeyError:
                    # If user not in database
                    try:
                        user = await c.get_users(user_found)
                    except Exception as ef:
                        return await m.reply_text(
                            f"User not found ! Error: {ef}")
                    user_id = user.id
                    user_first_name = user.first_name
                    user_name = user.username
                except Exception as ef:
                    user_id = user_found
                    user_first_name = user_found
                    user_name = ""
                    LOGGER.error(ef)
                    LOGGER.error(format_exc())

        else:
            try:
                user_id = int(m.text.split()[1])
            except (ValueError, Exception) as ef:
                if "invalid literal for int() with base 10:" in str(ef):
                    user_id = (str(m.text.split()[1]) if
                               (m.text.split()[1]).startswith("@") else None)
                else:
                    user_id = m.text.split()[1]
                    LOGGER.error(ef)
                    LOGGER.error(format_exc())

            if user_id is not None:
                try:
                    user = Users.get_user_info(user_id)
                    user_first_name = user["name"]
                    user_name = user["username"]
                except Exception as ef:
                    try:
                        user = await c.get_users(user_id)
                    except Exception as ef:
                        return await m.reply_text(
                            f"User not found ! Error: {ef}")
                    user_first_name = user.first_name
                    user_name = user.username
                    LOGGER.error(ef)
                    LOGGER.error(format_exc())

    else:
        user_id = m.from_user.id
        user_first_name = m.from_user.first_name
        user_name = m.from_user.username

    return user_id, user_first_name, user_name