Exemplo n.º 1
0
def mention_answer(client: Client, message: Message, aid: int, uid: int,
                   action_type: str) -> str:
    # Mention abuse
    try:
        # Basic data
        gid = message.chat.id
        mid = message.message_id

        # Abuse
        if action_type == "abuse":
            message.reply_to_message = message
            message.reply_to_message.from_user.id = uid
            message.reply_to_message.from_user.is_self = lang("abuse_mention")
            text, markup = warn_user(client, message, uid, aid)
            text += f"{lang('reason')}{lang('colon')}{code(lang('reason_abuse'))}\n"

            # Edit the report message
            thread(edit_message_text, (client, gid, mid, text, markup))
            delay(180, delete_message, [client, gid, mid])

        # Delete
        elif action_type == "delete":
            glovar.message_ids[gid] = (0, 0)
            save("message_ids")
            delete_message(client, gid, mid)
    except Exception as e:
        logger.warning(f"Mention answer error: {e}", exc_info=True)

    return ""
Exemplo n.º 2
0
def save_admins(gid: int, admin_members: List[ChatMember]) -> bool:
    # Save the group's admin list
    result = False

    try:
        # Admin list
        glovar.admin_ids[gid] = {admin.user.id for admin in admin_members
                                 if (((not admin.user.is_bot and not admin.user.is_deleted)
                                      and admin.can_delete_messages
                                      and admin.can_restrict_members)
                                     or admin.status == "creator"
                                     or admin.user.id in glovar.bot_ids)}
        save("admin_ids")

        # Trust list
        glovar.trust_ids[gid] = {admin.user.id for admin in admin_members
                                 if ((not admin.user.is_bot and not admin.user.is_deleted)
                                     or admin.user.id in glovar.bot_ids)}
        save("trust_ids")

        result = True
    except Exception as e:
        logger.warning(f"Save admins error: {e}", exc_info=True)

    return result
Exemplo n.º 3
0
def receive_rollback(client: Client, message: Message, data: dict) -> bool:
    # Receive rollback data
    try:
        # Basic data
        aid = data["admin_id"]
        the_type = data["type"]
        the_data = receive_file_data(client, message)

        if not the_data:
            return True

        exec(f"glovar.{the_type} = the_data")
        save(the_type)

        # Send debug message
        text = (
            f"{lang('project')}{lang('colon')}{general_link(glovar.project_name, glovar.project_link)}\n"
            f"{lang('admin_project')}{lang('colon')}{mention_id(aid)}\n"
            f"{lang('action')}{lang('colon')}{code(lang('rollback'))}\n"
            f"{lang('more')}{lang('colon')}{code(the_type)}\n")
        thread(send_message, (client, glovar.debug_channel_id, text))
    except Exception as e:
        logger.warning(f"Receive rollback error: {e}", exc_info=True)

    return False
Exemplo n.º 4
0
def undo_user(client: Client, message: Message, aid: int, uid: int,
              action_type: str) -> str:
    try:
        # Basic
        gid = message.chat.id
        mid = message.message_id

        # Init user data
        if not init_user_id(uid):
            return ""

        # Check the user's lock
        if gid in glovar.user_ids[uid]["lock"]:
            return lang("answer_proceeded")

        # Proceed
        glovar.user_ids[uid]["lock"].add(gid)
        try:
            if action_type == "ban":
                text = unban_user(client, message, uid, aid)
            else:
                text = unwarn_user(client, message, uid, aid)

            thread(edit_message_text, (client, gid, mid, text))
        finally:
            glovar.user_ids[uid]["lock"].discard(gid)

        # Save data
        save("user_ids")
    except Exception as e:
        logger.warning(f"Undo user error: {e}", exc_info=True)

    return ""
Exemplo n.º 5
0
def receive_watch_user(data: dict) -> bool:
    # Receive watch users that other bots shared
    try:
        # Basic data
        the_type = data["type"]
        uid = data["id"]
        until = data["until"]

        # Decrypt the data
        until = crypt_str("decrypt", until, glovar.key)
        until = get_int(until)

        # Add to list
        if the_type == "ban":
            glovar.watch_ids["ban"][uid] = until
        elif the_type == "delete":
            glovar.watch_ids["delete"][uid] = until
        else:
            return False

        save("watch_ids")

        return True
    except Exception as e:
        logger.warning(f"Receive watch user error: {e}", exc_info=True)

    return False
Exemplo n.º 6
0
def reset_data(client: Client) -> bool:
    # Reset data every month
    try:
        glovar.bad_ids = {"users": set()}
        save("bad_ids")

        glovar.left_group_ids = set()
        save("left_group_ids")

        glovar.user_ids = {}
        save("user_ids")

        glovar.watch_ids = {"ban": {}, "delete": {}}
        save("watch_ids")

        glovar.reports = {}
        save("reports")

        # Send debug message
        text = (
            f"{lang('project')}{lang('colon')}{general_link(glovar.project_name, glovar.project_link)}\n"
            f"{lang('action')}{lang('colon')}{code(lang('reset'))}\n")
        thread(send_message, (client, glovar.debug_channel_id, text))

        return True
    except Exception as e:
        logger.warning(f"Reset data error: {e}", exc_info=True)

    return False
Exemplo n.º 7
0
def init_user_id(uid: int) -> bool:
    # Init user data
    try:
        if glovar.user_ids.get(uid) is None:
            glovar.user_ids[uid] = deepcopy(glovar.default_user_status)
            save("user_ids")

        return True
    except Exception as e:
        logger.warning(f"Init user id {uid} error: {e}", exc_info=True)

    return False
Exemplo n.º 8
0
def receive_config_commit(data: dict) -> bool:
    # Receive config commit
    try:
        # Basic data
        gid = data["group_id"]
        config = data["config"]

        glovar.configs[gid] = config
        save("configs")

        return True
    except Exception as e:
        logger.warning(f"Receive config commit error: {e}", exc_info=True)

    return False
Exemplo n.º 9
0
def receive_help_report(client: Client, data: dict) -> bool:
    # Receive help report requests
    try:
        # Basic data
        gid = data["group_id"]
        uid = data["user_id"]
        mid = data["message_id"]

        # Check declared status
        if is_declared_message_id(gid, mid):
            return True

        # Check group
        if gid not in glovar.admin_ids:
            return True

        if not init_group_id(gid):
            return True

        if not glovar.configs[gid]["report"]["auto"]:
            return True

        if not (init_user_id(0) and init_user_id(uid)
                and gid not in glovar.user_ids[uid]["lock"]
                and gid not in glovar.user_ids[uid]["waiting"]
                and gid not in glovar.user_ids[uid]["ban"]):
            return True

        the_message = get_message(client, gid, mid)

        if not the_message:
            return True

        text, markup, key = report_user(gid, the_message.from_user, 0, mid)
        result = send_message(client, gid, text, mid, markup)

        if result:
            glovar.reports[key]["report_id"] = result.message_id
        else:
            glovar.reports[key].pop(key, {})

        save("reports")

        return True
    except Exception as e:
        logger.warning(f"Receive help report error: {e}", exc_info=True)

    return False
Exemplo n.º 10
0
def receive_remove_watch(data: int) -> bool:
    # Receive removed watching users
    try:
        # Basic data
        uid = data

        # Reset watch status
        glovar.watch_ids["ban"].pop(uid, 0)
        glovar.watch_ids["delete"].pop(uid, 0)
        save("watch_ids")

        return True
    except Exception as e:
        logger.warning(f"Receive remove watch error: {e}", exc_info=True)

    return False
Exemplo n.º 11
0
def receive_add_bad(data: dict) -> bool:
    # Receive bad users or channels that other bots shared
    try:
        # Basic data
        the_id = data["id"]
        the_type = data["type"]

        # Receive bad user
        if the_type == "user":
            glovar.bad_ids["users"].add(the_id)

        save("bad_ids")

        return True
    except Exception as e:
        logger.warning(f"Receive add bad error: {e}", exc_info=True)

    return False
Exemplo n.º 12
0
def forgive(client: Client, message: Message) -> bool:
    # Forgive users

    if not message or not message.chat:
        return True

    # Basic data
    gid = message.chat.id
    mid = message.message_id

    try:
        # Check permission
        if not is_class_c(None, None, message):
            return True

        # Get user id
        uid, _ = get_class_d_id(message)

        # Check user status
        if not uid or uid in glovar.admin_ids[gid]:
            return True

        # Forgive the user
        reason = get_command_type(message)
        text, success = forgive_user(client, message, uid, reason)
        glovar.user_ids[uid]["lock"].discard(gid)
        save("user_ids")

        if success:
            secs = 180
        else:
            secs = 15

        # Send the report message
        thread(send_report_message, (secs, client, gid, text, None))

        return True
    except Exception as e:
        logger.warning(f"Forgive error: {e}", exc_info=True)
    finally:
        delete_message(client, gid, mid)

    return False
Exemplo n.º 13
0
def receive_remove_score(data: int) -> bool:
    # Receive remove user's score
    glovar.locks["message"].acquire()
    try:
        # Basic data
        uid = data

        if not glovar.user_ids.get(uid):
            return True

        glovar.user_ids[uid] = deepcopy(glovar.default_user_status)
        save("user_ids")

        return True
    except Exception as e:
        logger.warning(f"Receive remove score error: {e}", exc_info=True)
    finally:
        glovar.locks["message"].release()

    return False
Exemplo n.º 14
0
def init_group_id(gid: int) -> bool:
    # Init group data
    try:
        if gid == glovar.test_group_id:
            return False

        if gid in glovar.left_group_ids:
            return False

        if glovar.admin_ids.get(gid) is None:
            glovar.admin_ids[gid] = set()
            save("admin_ids")

        if glovar.message_ids.get(gid) is None:
            glovar.message_ids[gid] = (0, 0)
            save("message_ids")

        if glovar.configs.get(gid) is None:
            glovar.configs[gid] = deepcopy(glovar.default_config)
            save("configs")

        if glovar.counts.get(gid) is None:
            glovar.counts[gid] = {}

        if glovar.declared_message_ids.get(gid) is None:
            glovar.declared_message_ids[gid] = set()

        return True
    except Exception as e:
        logger.warning(f"Init group id {gid} error: {e}", exc_info=True)

    return False
Exemplo n.º 15
0
def receive_user_score(project: str, data: dict) -> bool:
    # Receive and update user's score
    glovar.locks["message"].acquire()
    try:
        # Basic data
        project = project.lower()
        uid = data["id"]

        if not init_user_id(uid):
            return True

        score = data["score"]
        glovar.user_ids[uid]["score"][project] = score
        save("user_ids")

        return True
    except Exception as e:
        logger.warning(f"Receive user score error: {e}", exc_info=True)
    finally:
        glovar.locks["message"].release()

    return False
Exemplo n.º 16
0
def update_score(client: Client, uid: int) -> bool:
    # Update a user's score, share it
    try:
        ban_count = len(glovar.user_ids[uid]["ban"])
        kick_count = len(glovar.user_ids[uid]["kick"])
        warn_count = len(glovar.user_ids[uid]["warn"])
        score = ban_count * 1 + kick_count * 0.3 + warn_count * 0.4
        glovar.user_ids[uid]["score"][glovar.sender.lower()] = score
        save("user_ids")
        share_data(client=client,
                   receivers=glovar.receivers["score"],
                   action="update",
                   action_type="score",
                   data={
                       "id": uid,
                       "score": round(score, 1)
                   })

        return True
    except Exception as e:
        logger.warning(f"Update score error: {e}", exc_info=True)

    return False
Exemplo n.º 17
0
def leave_group(client: Client, gid: int) -> bool:
    # Leave a group, clear it's data
    try:
        glovar.left_group_ids.add(gid)
        save("left_group_ids")
        thread(leave_chat, (client, gid))

        glovar.admin_ids.pop(gid, None)
        save("admin_ids")

        glovar.message_ids.pop(gid, (0, 0))
        save("message_ids")

        glovar.configs.pop(gid, None)
        save("configs")

        return True
    except Exception as e:
        logger.warning(f"Leave group error: {e}", exc_info=True)

    return False
Exemplo n.º 18
0
def receive_clear_data(client: Client, data_type: str, data: dict) -> bool:
    # Receive clear data command
    glovar.locks["message"].acquire()
    try:
        # Basic data
        aid = data["admin_id"]
        the_type = data["type"]

        # Clear bad data
        if data_type == "bad":
            if the_type == "channels":
                glovar.bad_ids["channels"] = set()
            elif the_type == "users":
                glovar.bad_ids["users"] = set()

            save("bad_ids")

        # Clear user data
        if data_type == "user":
            if the_type == "all":
                glovar.user_ids = {}

            save("user_ids")

        # Clear watch data
        if data_type == "watch":
            if the_type == "all":
                glovar.watch_ids = {"ban": {}, "delete": {}}
            elif the_type == "ban":
                glovar.watch_ids["ban"] = {}
            elif the_type == "delete":
                glovar.watch_ids["delete"] = {}

            save("watch_ids")

        # Send debug message
        text = (
            f"{lang('project')}{lang('colon')}{general_link(glovar.project_name, glovar.project_link)}\n"
            f"{lang('admin_project')}{lang('colon')}{mention_id(aid)}\n"
            f"{lang('action')}{lang('colon')}{code(lang('clear'))}\n"
            f"{lang('more')}{lang('colon')}{code(f'{data_type} {the_type}')}\n"
        )
        thread(send_message, (client, glovar.debug_channel_id, text))
    except Exception as e:
        logger.warning(f"Receive clear data: {e}", exc_info=True)
    finally:
        glovar.locks["message"].release()

    return False
Exemplo n.º 19
0
def receive_remove_bad(data: dict) -> bool:
    # Receive removed bad objects
    try:
        # Basic data
        the_id = data["id"]
        the_type = data["type"]

        # Remove bad user
        if the_type == "user":
            glovar.bad_ids["users"].discard(the_id)
            glovar.watch_ids["ban"].pop(the_id, {})
            glovar.watch_ids["delete"].pop(the_id, {})
            save("watch_ids")
            glovar.user_ids[the_id] = deepcopy(glovar.default_user_status)
            save("user_ids")

        save("bad_ids")

        return True
    except Exception as e:
        logger.warning(f"Receive remove bad error: {e}", exc_info=True)

    return False
Exemplo n.º 20
0
def config_directly(client: Client, message: Message) -> bool:
    # Config the bot directly

    if not message or not message.chat:
        return True

    # Basic data
    gid = message.chat.id
    mid = message.message_id

    try:
        # Check permission
        if not is_class_c(None, None, message):
            return True

        aid = message.from_user.id
        success = True
        reason = lang("config_updated")
        new_config = deepcopy(glovar.configs[gid])
        text = f"{lang('admin_group')}{lang('colon')}{code(aid)}\n"

        # Check command format
        command_type, command_context = get_command_context(message)
        if command_type:
            if command_type == "show":
                text += f"{lang('action')}{lang('colon')}{code(lang('config_show'))}\n"
                text += get_config_text(new_config)
                thread(send_report_message, (30, client, gid, text))
                return True

            now = get_now()
            if now - new_config["lock"] > 310:
                if command_type == "default":
                    new_config = deepcopy(glovar.default_config)
                else:
                    if command_context:
                        if command_type in {"delete", "mention"}:
                            if command_context == "off":
                                new_config[command_type] = False
                            elif command_context == "on":
                                new_config[command_type] = True
                            else:
                                success = False
                                reason = lang("command_para")
                        elif command_type == "limit":
                            limit = get_int(command_context)
                            if 2 <= limit <= 5:
                                new_config["limit"] = limit
                            else:
                                success = False
                                reason = lang("command_para")
                        elif command_type == "report":
                            if not new_config.get("report"):
                                new_config["report"] = {}

                            if command_context == "off":
                                new_config["report"]["auto"] = False
                                new_config["report"]["manual"] = False
                            elif command_context == "auto":
                                new_config["report"]["auto"] = True
                                new_config["report"]["manual"] = False
                            elif command_context == "manual":
                                new_config["report"]["auto"] = False
                                new_config["report"]["manual"] = True
                            elif command_context == "both":
                                new_config["report"]["auto"] = True
                                new_config["report"]["manual"] = True
                            else:
                                success = False
                                reason = lang("command_para")
                        else:
                            success = False
                            reason = lang("command_type")
                    else:
                        success = False
                        reason = lang("command_lack")

                    if success:
                        new_config["default"] = False
            else:
                success = False
                reason = lang("config_locked")
        else:
            success = False
            reason = lang("command_usage")

        if success and new_config != glovar.configs[gid]:
            # Save new config
            glovar.configs[gid] = new_config
            save("configs")

            # Send debug message
            debug_text = get_debug_text(client, message.chat)
            debug_text += (
                f"{lang('admin_group')}{lang('colon')}{code(message.from_user.id)}\n"
                f"{lang('action')}{lang('colon')}{code(lang('config_change'))}\n"
                f"{lang('more')}{lang('colon')}{code(f'{command_type} {command_context}')}\n"
            )
            thread(send_message, (client, glovar.debug_channel_id, debug_text))

        text += (
            f"{lang('action')}{lang('colon')}{code(lang('config_change'))}\n"
            f"{lang('status')}{lang('colon')}{code(reason)}\n")
        thread(send_report_message,
               ((lambda x: 10 if x else 5)(success), client, gid, text))

        return True
    except Exception as e:
        logger.warning(f"Config directly error: {e}", exc_info=True)
    finally:
        delete_message(client, gid, mid)

    return False
Exemplo n.º 21
0
def interval_hour_01(client: Client) -> bool:
    # Execute every hour
    result = False

    glovar.locks["message"].acquire()

    try:
        # Clear old calling messages
        now = get_now()

        for gid in list(glovar.message_ids):
            mid, time = glovar.message_ids[gid]

            if not time:
                continue

            if now - time < 86400:
                continue

            glovar.message_ids[gid] = (0, 0)
            delete_message(client, gid, mid)

        save("message_ids")

        # Clear old reports
        now = get_now()

        for key in list(glovar.reports):
            report_record = glovar.reports[key]
            time = report_record["time"]

            if not time:
                glovar.reports.pop(key, {})
                continue

            if now - time < 86400:
                continue

            gid = report_record["group_id"]
            mid = report_record["report_id"]
            thread(delete_message, (client, gid, mid))
            glovar.reports.pop(key, {})

        save("reports")

        # Clear user's waiting status
        reported_users = {
            glovar.reports[key]["user_id"]
            for key in glovar.reports
        }

        for uid in set(glovar.user_ids) - reported_users:
            glovar.user_ids[uid]["waiting"] = set()

        save("user_ids")

        result = True
    except Exception as e:
        logger.warning(f"Interval hour 01 error: {e}", exc_info=True)
    finally:
        glovar.locks["message"].release()

    return result
Exemplo n.º 22
0
def forgive_user(client: Client,
                 message: Message,
                 uid: int,
                 reason: str = None) -> (str, bool):
    # Forgive user
    text = ""
    success = False
    try:
        # Basic data
        gid = message.chat.id
        aid = message.from_user.id

        # Init user data
        if not init_user_id(uid):
            return "", False

        # Check users' locks
        if gid in glovar.user_ids[uid]["lock"]:
            return "", False

        # Proceed
        glovar.user_ids[uid]["lock"].add(gid)
        try:
            # Text prefix
            text += f"{lang('user_id')}{lang('colon')}{mention_id(uid)}\n"

            if gid in glovar.user_ids[uid]["ban"]:
                glovar.user_ids[uid]["ban"].discard(gid)
                thread(unban_chat_member, (client, gid, uid))
                text += (
                    f"{lang('action')}{lang('colon')}{code(lang('action_unban'))}\n"
                    f"{lang('status')}{lang('colon')}{code(lang('status_succeeded'))}\n"
                )
                success = True
            elif glovar.user_ids[uid]["warn"].get(gid, 0):
                glovar.user_ids[uid]["warn"].pop(gid, 0)
                text += (
                    f"{lang('action')}{lang('colon')}{code(lang('action_unwarns'))}\n"
                    f"{lang('status')}{lang('colon')}{code(lang('status_succeeded'))}\n"
                )
                success = True
            elif gid in glovar.user_ids[uid]["waiting"]:
                glovar.user_ids[uid]["waiting"].discard(gid)
                text += (
                    f"{lang('action')}{lang('colon')}{code(lang('action_unwait'))}\n"
                    f"{lang('status')}{lang('colon')}{code(lang('status_succeeded'))}\n"
                )
                success = True
            else:
                text += (
                    f"{lang('action')}{lang('colon')}{code(lang('action_forgive'))}\n"
                    f"{lang('status')}{lang('colon')}{code(lang('status_failed'))}\n"
                    f"{lang('reason')}{lang('colon')}{code(lang('reason_none'))}\n"
                )
                success = False

            text += f"{lang('description')}{lang('colon')}{code(lang('description_by_admin'))}\n"

            if not success:
                return text, success

            save("user_ids")

            if reason:
                text += f"{lang('reason')}{lang('colon')}{code(reason)}\n"

            update_score(client, uid)
            send_debug(client=client,
                       message=message,
                       action=lang("action_forgive"),
                       uid=uid,
                       aid=aid,
                       reason=reason)
        finally:
            glovar.user_ids[uid]["lock"].discard(gid)
    except Exception as e:
        logger.warning(f"Forgive user error: {e}")

    return text, success
Exemplo n.º 23
0
def report_answer(client: Client,
                  message: Message,
                  gid: int,
                  aid: int,
                  mid: int,
                  action_type: str,
                  key: str,
                  reason: str = None) -> str:
    # Answer the user's report
    try:
        report_record = glovar.reports.get(key)

        if not report_record:
            message_text = get_text(message)
            uid = get_int(message_text.split("\n")[0].split(lang("colon"))[1])
            text = (
                f"{lang('description')}{lang('colon')}{code(lang('description_by_admin'))}\n"
                f"{lang('status')}{lang('colon')}{code(lang('status_failed'))}\n"
                f"{lang('reason')}{lang('colon')}{code(lang('expired'))}\n")
            thread(edit_message_text, (client, gid, mid, text))
            delay(15, delete_message, [client, gid, mid])
            glovar.user_ids[uid]["waiting"].discard(gid)
            save("user_ids")
            return ""

        if not report_record["time"]:
            return ""

        rid = report_record["reporter_id"]
        uid = report_record["user_id"]
        r_mid = report_record["message_id"]
        record_reason = report_record["reason"]

        if not reason:
            reason = record_reason

        if not (init_user_id(rid) and init_user_id(uid)):
            return ""

        # Check users' locks
        if gid in glovar.user_ids[uid]["lock"] or gid in glovar.user_ids[rid][
                "lock"]:
            return lang("answer_proceeded")

        # Lock the report status
        glovar.reports[key]["time"] = 0
        try:
            if action_type == "ban":
                text, markup = ban_user(client, message, uid, aid, 0, reason)
                thread(delete_message, (client, gid, r_mid))
            elif action_type == "warn":
                text, markup = warn_user(client, message, uid, aid, reason)
                thread(delete_message, (client, gid, r_mid))
            elif action_type == "abuse":
                if not rid:
                    return ""

                message.reply_to_message.from_user.id = rid
                message.reply_to_message.from_user.is_self = lang(
                    "abuse_report")
                text, markup = warn_user(client, message, rid, aid)
                text += f"{lang('reason')}{lang('colon')}{code(lang('reason_abuse'))}\n"
            else:
                reported_link = general_link(
                    r_mid, f'{get_channel_link(message)}/{r_mid}')

                if rid:
                    reporter_text = code(rid)
                else:
                    reporter_text = code(lang("auto_triggered"))

                text = (
                    f"{lang('reported_user')}{lang('colon')}{mention_id(uid)}\n"
                    f"{lang('reported_message')}{lang('colon')}{reported_link}\n"
                    f"{lang('reporter')}{lang('colon')}{reporter_text}\n"
                    f"{lang('action')}{lang('colon')}{code(lang('action_cancel'))}\n"
                    f"{lang('status')}{lang('colon')}{code(lang('status_succeeded'))}\n"
                    f"{lang('description')}{lang('colon')}{code(lang('description_by_admin'))}\n"
                )
                markup = None

            if markup:
                secs = 180
            else:
                secs = 15

            thread(edit_message_text, (client, gid, mid, text, markup))
            delay(secs, delete_message, [client, gid, mid])
        finally:
            glovar.user_ids[uid]["lock"].discard(gid)
            glovar.user_ids[rid]["lock"].discard(gid)
            glovar.user_ids[uid]["waiting"].discard(gid)
            glovar.user_ids[rid]["waiting"].discard(gid)
            save("user_ids")
    except Exception as e:
        logger.warning(f"Report answer error: {e}", exc_info=True)

    return ""
Exemplo n.º 24
0
def report_user(gid: int,
                user: User,
                rid: int,
                mid: int,
                name: str = None,
                reason: str = None) -> (str, InlineKeyboardMarkup, str):
    # Report a user
    text = ""
    markup = None
    key = ""

    try:
        if user:
            uid = user.id
        else:
            return "", None

        glovar.user_ids[uid]["waiting"].add(gid)
        glovar.user_ids[rid]["waiting"].add(gid)
        save("user_ids")

        key = random_str(8)

        while glovar.reports.get(key):
            key = random_str(8)

        glovar.reports[key] = {
            "time": get_now(),
            "group_id": gid,
            "reporter_id": rid,
            "user_id": uid,
            "message_id": mid,
            "report_id": 0,
            "reason": reason
        }

        if rid:
            reporter_text = code("██████")
        else:
            reporter_text = code(lang("auto_triggered"))

        text = f"{lang('reported_user')}{lang('colon')}{mention_id(uid)}\n"

        if name:
            text += f"{lang('reported_name')}{lang('colon')}{code(name)}\n"

        text += (
            f"{lang('reported_message')}{lang('colon')}{general_link(mid, f'{get_channel_link(gid)}/{mid}')}\n"
            f"{lang('reporter')}{lang('colon')}{reporter_text}\n"
            f"{lang('mention_admins')}{lang('colon')}{get_admin_text(gid)}\n"
            f"{lang('description')}{lang('colon')}{code(lang('description_wait_admin'))}\n"
        )

        if reason:
            text += f"{lang('reason')}{lang('colon')}{code(reason)}\n"

        warn_data = button_data("report", "warn", key)
        ban_data = button_data("report", "ban", key)
        cancel_data = button_data("report", "cancel", key)
        markup_list = [[
            InlineKeyboardButton(text=lang("warn"), callback_data=warn_data),
            InlineKeyboardButton(text=lang("ban"), callback_data=ban_data)
        ],
                       [
                           InlineKeyboardButton(text=lang("cancel"),
                                                callback_data=cancel_data)
                       ]]

        if rid:
            abuse_data = button_data("report", "abuse", key)
            markup_list[1].append(
                InlineKeyboardButton(text=lang("abuse"),
                                     callback_data=abuse_data))

        markup = InlineKeyboardMarkup(markup_list)
    except Exception as e:
        logger.warning(f"Report user error: {e}", exc_info=True)

    return text, markup, key
Exemplo n.º 25
0
def config(client: Client, message: Message) -> bool:
    # Request CONFIG session

    if not message or not message.chat:
        return True

    # Basic data
    gid = message.chat.id
    mid = message.message_id

    try:
        # Check permission
        if not is_class_c(None, None, message):
            return True

        # Check command format
        command_type = get_command_type(message)
        if not command_type or not re.search(f"^{glovar.sender}$",
                                             command_type, re.I):
            return True

        now = get_now()

        # Check the config lock
        if now - glovar.configs[gid]["lock"] < 310:
            return True

        # Set lock
        glovar.configs[gid]["lock"] = now
        save("configs")

        # Ask CONFIG generate a config session
        group_name, group_link = get_group_info(client, message.chat)
        share_data(client=client,
                   receivers=["CONFIG"],
                   action="config",
                   action_type="ask",
                   data={
                       "project_name": glovar.project_name,
                       "project_link": glovar.project_link,
                       "group_id": gid,
                       "group_name": group_name,
                       "group_link": group_link,
                       "user_id": message.from_user.id,
                       "config": glovar.configs[gid],
                       "default": glovar.default_config
                   })

        # Send debug message
        text = get_debug_text(client, message.chat)
        text += (
            f"{lang('admin_group')}{lang('colon')}{code(message.from_user.id)}\n"
            f"{lang('action')}{lang('colon')}{code(lang('config_create'))}\n")
        thread(send_message, (client, glovar.debug_channel_id, text))

        return True
    except Exception as e:
        logger.warning(f"Config error: {e}", exc_info=True)
    finally:
        if is_class_c(None, None, message):
            delay(3, delete_message, [client, gid, mid])
        else:
            delete_message(client, gid, mid)

    return False
Exemplo n.º 26
0
def update_admins(client: Client) -> bool:
    # Update admin list every day
    result = False

    glovar.locks["admin"].acquire()

    try:
        # Basic data
        group_list = list(glovar.admin_ids)

        # Check groups
        for gid in group_list:
            group_name, group_link = get_group_info(client, gid)
            admin_members = get_admins(client, gid)

            # Bot is not in the chat, leave automatically without approve
            if admin_members is False or any(
                    admin.user.is_self for admin in admin_members) is False:
                leave_group(client, gid)
                share_data(client=client,
                           receivers=["MANAGE"],
                           action="leave",
                           action_type="info",
                           data={
                               "group_id": gid,
                               "group_name": group_name,
                               "group_link": group_link
                           })
                project_text = general_link(glovar.project_name,
                                            glovar.project_link)
                debug_text = (
                    f"{lang('project')}{lang('colon')}{project_text}\n"
                    f"{lang('group_name')}{lang('colon')}{general_link(group_name, group_link)}\n"
                    f"{lang('group_id')}{lang('colon')}{code(gid)}\n"
                    f"{lang('status')}{lang('colon')}{code(lang('leave_auto'))}\n"
                    f"{lang('reason')}{lang('colon')}{code(lang('reason_leave'))}\n"
                )
                thread(send_message,
                       (client, glovar.debug_channel_id, debug_text))
                continue

            # Check the admin list
            if not (admin_members
                    and any([admin.user.is_self for admin in admin_members])):
                continue

            # Save the admin list
            save_admins(gid, admin_members)

            # Ignore the group
            if gid in glovar.lack_group_ids:
                continue

            # Check the permissions
            if glovar.user_id not in glovar.admin_ids[gid]:
                reason = "user"
            elif any(admin.user.is_self and admin.can_delete_messages
                     and admin.can_restrict_members
                     for admin in admin_members):
                glovar.lack_group_ids.discard(gid)
                save("lack_group_ids")
                continue
            else:
                reason = "permissions"
                glovar.lack_group_ids.add(gid)
                save("lack_group_ids")

            # Send the leave request
            share_data(client=client,
                       receivers=["MANAGE"],
                       action="leave",
                       action_type="request",
                       data={
                           "group_id": gid,
                           "group_name": group_name,
                           "group_link": group_link,
                           "reason": reason
                       })
            reason = lang(f"reason_{reason}")
            project_link = general_link(glovar.project_name,
                                        glovar.project_link)
            debug_text = (
                f"{lang('project')}{lang('colon')}{project_link}\n"
                f"{lang('group_name')}{lang('colon')}{general_link(group_name, group_link)}\n"
                f"{lang('group_id')}{lang('colon')}{code(gid)}\n"
                f"{lang('status')}{lang('colon')}{code(reason)}\n")
            thread(send_message, (client, glovar.debug_channel_id, debug_text))

        result = True
    except Exception as e:
        logger.warning(f"Update admin error: {e}", exc_info=True)
    finally:
        glovar.locks["admin"].release()

    return result
Exemplo n.º 27
0
def report(client: Client, message: Message) -> bool:
    # Report spam messages

    if not message or not message.chat:
        return True

    # Basic data
    gid = message.chat.id
    mid = message.message_id

    try:
        # Normal user
        if not is_class_c(None, None, message):
            # Check config
            if not glovar.configs[gid]["report"]["manual"]:
                return True

            rid = message.from_user.id
            now = message.date or get_now()

            # Init user data
            if not init_user_id(rid):
                return True

            # Get user id
            uid, r_mid = get_class_d_id(message)

            # Init user data
            if not uid or not init_user_id(uid):
                return True

            # Check user status
            bad_user = (gid in glovar.user_ids[rid]["lock"]
                        or gid in glovar.user_ids[uid]["lock"]
                        or gid in glovar.user_ids[rid]["waiting"]
                        or gid in glovar.user_ids[uid]["waiting"]
                        or gid in glovar.user_ids[uid]["ban"]
                        or is_watch_user(message.from_user, "ban", now)
                        or is_watch_user(message.from_user, "delete", now)
                        or is_high_score_user(message.from_user))
            good_user = (is_class_e_user(message.from_user)
                         and uid not in glovar.admin_ids[gid])

            # Users can not self-report
            if uid == rid or (bad_user and not good_user):
                return True

            # Reporter cannot report someone by replying WARN's report
            r_message = message.reply_to_message

            if r_message.from_user.is_self:
                return True

            # Proceed
            if r_message.service:
                name = get_full_name(r_message.from_user)
            else:
                name = None

            reason = get_command_type(message)

            text, markup, key = report_user(gid, r_message.from_user, rid,
                                            r_mid, name, reason)
            result = send_message(client, gid, text, r_mid, markup)

            if result:
                glovar.reports[key]["report_id"] = result.message_id
            else:
                glovar.reports.pop(key, {})

            save("reports")

        # Admin
        else:
            aid = message.from_user.id
            action_type, reason = get_command_context(message)

            # Text prefix
            text = (
                f"{lang('admin')}{lang('colon')}{code(aid)}\n"
                f"{lang('action')}{lang('colon')}{code(lang('action_answer'))}\n"
            )

            # Check command format
            if action_type not in {"warn", "ban", "cancel", "abuse"
                                   } or not message.reply_to_message:
                text += (
                    f"{lang('status')}{lang('colon')}{code(lang('status_failed'))}\n"
                    f"{lang('reason')}{lang('colon')}{code(lang('command_usage'))}\n"
                )
                thread(send_report_message, (15, client, gid, text))
                return True

            # Check the evidence message
            r_message = get_message(client, gid,
                                    message.reply_to_message.message_id)
            if not r_message or not r_message.reply_to_message:
                text += (
                    f"{lang('status')}{lang('colon')}{code(lang('status_failed'))}\n"
                    f"{lang('reason')}{lang('colon')}{code(lang('reason_deleted'))}\n"
                )
                thread(send_report_message, (15, client, gid, text))
                return True

            # Check the report message
            callback_data_list = get_callback_data(r_message)
            if not callback_data_list or callback_data_list[0]["a"] != "report":
                text += (
                    f"{lang('status')}{lang('colon')}{code(lang('status_failed'))}\n"
                    f"{lang('reason')}{lang('colon')}{code(lang('command_reply'))}\n"
                )
                thread(send_report_message, (15, client, gid, text))
                return True

            # Proceed
            key = callback_data_list[0]["d"]
            report_answer(client=client,
                          message=r_message,
                          gid=gid,
                          aid=aid,
                          mid=r_message.message_id,
                          action_type=action_type,
                          key=key,
                          reason=reason)

        return True
    except Exception as e:
        logger.warning(f"Report error: {e}", exc_info=True)
    finally:
        delete_message(client, gid, mid)

    return False
Exemplo n.º 28
0
def admin(client: Client, message: Message) -> bool:
    # Mention admins

    if not message or not message.chat:
        return True

    # Basic data
    gid = message.chat.id
    mid = message.message_id

    try:
        # Check permission
        if is_class_c(None, None, message):
            return True

        # Check config
        if not glovar.configs[gid].get("mention"):
            return True

        uid = message.from_user.id

        # Init user data
        if not init_user_id(uid):
            return True

        # Warned user and the user having report status can't mention admins
        if (gid in glovar.user_ids[uid]["waiting"]
                or gid in glovar.user_ids[uid]["ban"]
                or glovar.user_ids[uid]["warn"].get(gid)):
            return True

        # Generate report text
        text = (
            f"{lang('from_user')}{lang('colon')}{mention_id(uid)}\n"
            f"{lang('mention_admins')}{lang('colon')}{get_admin_text(gid)}\n")
        reason = get_command_type(message)

        if reason:
            text += f"{lang('reason')}{lang('colon')}{code(reason)}\n"

        # Generate report markup
        button_abuse = button_data("mention", "abuse", uid)
        button_delete = button_data("mention", "delete", uid)
        markup = InlineKeyboardMarkup([[
            InlineKeyboardButton(text=lang("abuse"),
                                 callback_data=button_abuse),
            InlineKeyboardButton(text=lang("del"), callback_data=button_delete)
        ]])

        # Send the report message
        if message.reply_to_message:
            rid = message.reply_to_message.message_id
        else:
            rid = None

        result = send_message(client, gid, text, rid, markup)

        if not result:
            return True

        old_mid, _ = glovar.message_ids.get(gid, (0, 0))
        old_mid and thread(delete_message, (client, gid, old_mid))
        sent_mid = result.message_id
        glovar.message_ids[gid] = (sent_mid, get_now())
        save("message_ids")

        return True
    except Exception as e:
        logger.warning(f"Admin error: {e}", exc_info=True)
    finally:
        delete_message(client, gid, mid)

    return False