Ejemplo n.º 1
0
async def addmany_reactionroles(message: discord.Message, args: List[str],
                                client: discord.Client, **kwargs: Any) -> Any:
    if not message.guild:
        return 1

    try:
        rr_message, nargs = await parse_channel_message(message, args, client)
    except lib_parsers.errors.message_parse_failure:
        return 1

    args = args[nargs:]

    with db_hlapi(message.guild.id) as db:
        reactionroles = json.loads(
            db.grab_config("reaction-role-data") or "{}")

    for i in range(len(args) // 2):
        try:
            emoji = await valid_emoji(message, args[i * 2], client)
            role = await get_exact_role(message, args[i * 2 + 1])
            await rindex_check(message, role)
        except (InvalidEmoji, NoRoleError, RindexFailure):
            return 1

        if str(rr_message.id) in reactionroles:
            reactionroles[str(rr_message.id)][emoji] = role.id
        else:
            reactionroles[str(rr_message.id)] = {}
            reactionroles[str(rr_message.id)][emoji] = role.id

    with db_hlapi(message.guild.id) as db:
        db.add_config("reaction-role-data", json.dumps(reactionroles))

    if kwargs["verbose"]:
        await message.channel.send("Added Multiple reactionroles")
Ejemplo n.º 2
0
async def rr_purge(message: discord.Message, args: List[str],
                   client: discord.Client, **kwargs: Any) -> Any:
    if not message.guild:
        return 1

    try:
        message_id = int(args[0].replace("-", "/").split("/")[-1])
    except IndexError:
        await message.channel.send("ERROR: No message id supplied")
        return 1
    except ValueError:
        await message.channel.send("ERROR: Message id is not a valid int")
        return 1

    with db_hlapi(message.guild.id) as db:
        reactionroles: Any = db.grab_config("reaction-role-data")

    if not reactionroles:
        await message.channel.send("ERROR: This guild has no reactionroles")
        return 1

    reactionroles = json.loads(reactionroles)

    if str(message_id) in reactionroles:
        del reactionroles[str(message_id)]
    else:
        await message.channel.send("ERROR: This message has no reactionroles")
        return 1

    with db_hlapi(message.guild.id) as db:
        db.add_config("reaction-role-data", json.dumps(reactionroles))

    if kwargs["verbose"]:
        await message.channel.send(
            f"Purged reactionroles from message with id {message_id}")
Ejemplo n.º 3
0
async def update_csv_blacklist(message: discord.Message,
                               args: List[str],
                               name: str,
                               verbose: bool = True,
                               allowed: Optional[str] = None) -> None:
    if not message.guild:
        raise blacklist_input_error("No Guild Attached")

    if len(args) >= 2 and args[1] in ["rm", "remove"]:
        with db_hlapi(message.guild.id) as db:
            db.delete_config(name)

        await message.channel.send(f"Removed {name} config from database")
        return

    if not args or len(args) != 1:
        await message.channel.send(f"Malformed {name}")
        raise blacklist_input_error(f"Malformed {name}")

    if (allowed is not None) and not all(i in allowed for i in args[0]):
        await message.channel.send(
            f"The {name} does not support characters used, only supports {allowed}"
        )
        raise blacklist_input_error("Unsupported chars")

    with db_hlapi(message.guild.id) as db:
        db.add_config(name, args[0])

    if verbose: await message.channel.send(f"Updated {name} successfully")
Ejemplo n.º 4
0
async def parse_role(message: discord.Message,
                     args: list[str],
                     db_entry: str,
                     verbose: bool = True) -> int:
    """
    Parse a role from a command and put it into the db under the db_entry name

    :returns: int -- The success state of adding the role to the db, 0 being no error
    """

    if not message.guild:
        await message.channel.send("ERROR: Could not resolve guild")
        return 1

    if args:
        role_str: str = args[0].strip("<@&>")
    else:
        with db_hlapi(message.guild.id) as db:
            try:
                r_int = int(db.grab_config(db_entry) or 0)
            except ValueError:
                await message.channel.send(
                    f"ERROR: {db_entry} is corrupt, please reset this role config"
                )
                return 1
        await message.channel.send(
            f"{db_entry} is {message.guild.get_role(r_int)}")
        return 0

    if role_str in ["remove", "rm", "delete"]:
        with db_hlapi(message.guild.id) as db:
            db.delete_config(db_entry)
        await message.channel.send(f"Deleted {db_entry} role config")
        return 0

    try:
        role = message.guild.get_role(int(role_str))
    except ValueError:
        await message.channel.send(constants.sonnet.error_role.invalid)
        return 1

    if not role:
        await message.channel.send(constants.sonnet.error_role.invalid)
        return 1

    with db_hlapi(message.guild.id) as db:
        db.add_config(db_entry, str(role.id))

    if verbose: await message.channel.send(f"Updated {db_entry} to {role}")

    return 0
Ejemplo n.º 5
0
async def set_usertrust_use(message: discord.Message, args: List[str],
                            client: discord.Client, **kwargs: Any) -> Any:

    if args:
        gate = bool(parse_boolean(args[0]))
        with db_hlapi(message.guild.id) as db:
            db.add_config("usertrust-enabled", str(int(gate)))
            if kwargs["verbose"]:
                await message.channel.send(
                    f"Set usertrust enabled to {bool(gate)}")
    else:
        with db_hlapi(message.guild.id) as db:
            gate = bool(int(db.grab_config("usertrust-enabled") or "0"))
        await message.channel.send(f"Usertrust enabled is {bool(gate)}")
Ejemplo n.º 6
0
    async def timestampedit(self, args: List[str],
                            client: discord.Client) -> int:
        # notifier-log-timestamp
        cnf_name: Final[str] = "notifier-log-timestamp"

        if args:  # I hate this code holy shit its so unreadable
            if args[0] == "add" and len(args) >= 2:  # Add timestamp

                try:  # Parse time
                    jointime = MustParseDuration(args[1])
                except lib_goparsers.errors.ParseFailureError:
                    await self.m.channel.send("ERROR: Invalid time format")
                    return 1

                if jointime < 0 or jointime > 60 * 60 * 24 * 30:  # Only allow JT up to a month, ive learned to never trust input the hard way
                    await self.m.channel.send(
                        "ERROR: Time range entered is larger than one month (~30 days)"
                    )
                    return 1

                with db_hlapi(self.guild.id) as db:  # Add to db
                    db.add_config(cnf_name, str(jointime))

                await self.m.channel.send(
                    f"Updated new user notify time to <{format_duration(jointime)} since creation"
                )
                return 0

            elif args[0] == "remove":  # Remove timestamp

                with db_hlapi(self.guild.id) as db:
                    db.delete_config(cnf_name)
                await self.m.channel.send("Deleted new user notify time")
                return 0

            else:  # Error
                await self.m.channel.send("Invalid args passed")
                return 1

        else:  # Show current timestamp

            with db_hlapi(self.guild.id) as db:
                jointime_str = db.grab_config(cnf_name)

            fmt = format_duration(
                int(jointime_str)) if jointime_str else "None"

            await self.m.channel.send(f"new user notify is set to {fmt}")
            return 0
Ejemplo n.º 7
0
async def set_embed_typec(message: discord.Message, args: List[str],
                          typec: str, verbose: bool,
                          ramfs: lexdpyk.ram_filesystem) -> int:
    if not message.guild:
        return 1

    if args:

        if args[0] == "reset":

            with db_hlapi(message.guild.id) as db:
                db.delete_config(f"embed-color-{typec}")

            if verbose:
                await message.channel.send(
                    f"Reset {typec}-color to its default value")

            return 0

        try:
            colint: int = int(args[0], 16)
        except ValueError:
            await message.channel.send("ERROR: Not a valid color")
            return 1
    else:
        with db_hlapi(message.guild.id) as db:
            colhex = db.grab_config(f"embed-color-{typec}")
        if colhex:
            await message.channel.send(
                f"{typec}-color is set to {zpadhex(int(colhex, 16))}")
        else:
            await message.channel.send(
                f"{typec}-color is not set (default: {zpadhex(load_embed_color(message.guild, typec, ramfs))})"
            )

        return 0

    if colint >= (2**24):
        await message.channel.send("ERROR: Color out of 24bit range")
        return 1

    with db_hlapi(message.guild.id) as db:
        db.add_config(f"embed-color-{typec}", hex(colint))

    if verbose:
        await message.channel.send(
            f"Updated {typec}-color to {zpadhex(colint)}")

    return 0
Ejemplo n.º 8
0
async def remove_reactionroles(message: discord.Message, args: List[str],
                               client: discord.Client, **kwargs: Any) -> Any:
    if not message.guild:
        return 1

    try:
        rr_message, nargs = await parse_channel_message(message, args, client)
    except lib_parsers.errors.message_parse_failure:
        return 1

    args = args[nargs:]

    if not args:
        await message.channel.send("ERROR: Not enough args supplied")
        return 1

    try:
        emoji = await valid_emoji(message, args[0], client)
    except InvalidEmoji:
        return 1

    with db_hlapi(message.guild.id) as db:
        reactionroles: Any = db.grab_config("reaction-role-data")

    if not reactionroles:
        await message.channel.send("ERROR: This guild has no reactionroles")
        return 1

    reactionroles = json.loads(reactionroles)

    if str(rr_message.id) in reactionroles:
        if emoji in reactionroles[str(rr_message.id)]:
            del reactionroles[str(rr_message.id)][emoji]
        else:
            await message.channel.send(
                f"ERROR: This message does not have {emoji} reactionrole on it"
            )
            return 1
    else:
        await message.channel.send(
            "ERROR: This message has no reactionroles on it")
        return 1

    with db_hlapi(message.guild.id) as db:
        db.add_config("reaction-role-data", json.dumps(reactionroles))

    if kwargs["verbose"]:
        await message.channel.send(
            f"Removed reactionrole {emoji} from message id {rr_message.id}")
Ejemplo n.º 9
0
async def antispam_time_set(message: discord.Message, args: List[str],
                            client: discord.Client, **kwargs: Any) -> Any:
    if not message.guild:
        return 1

    if args:
        try:
            mutetime = MustParseDuration(args[0])
        except lib_goparsers.errors.ParseFailureError:
            await message.channel.send("ERROR: Invalid time format")
            return 1
    else:
        mutetime = int(kwargs["conf_cache"]["antispam-time"])
        await message.channel.send(f"Antispam mute time is {mutetime} seconds")
        return 0

    if mutetime < 0:
        await message.channel.send("ERROR: Mutetime cannot be negative")
        return 1

    elif mutetime >= 60 * 60 * 256:
        await message.channel.send(
            "ERROR: Mutetime cannot be greater than 256 hours")
        return 1

    with db_hlapi(message.guild.id) as db:
        db.add_config("antispam-time", str(mutetime))

    if kwargs["verbose"]:
        await message.channel.send(
            f"Set antispam mute time to {format_duration(mutetime)}")
Ejemplo n.º 10
0
async def faq_get(message: discord.Message, args: List[str],
                  client: discord.Client, **kwargs: Any) -> Any:
    if not message.guild:
        return 1

    if not args:
        await message.channel.send("No args passed")
        return 1

    with db_hlapi(message.guild.id) as db:
        db.inject_enum(faq_name, faq_enum)

        maybedata = db.grab_enum(faq_name, args[0])

        if maybedata is None:
            await message.channel.send("ERROR: FAQ requested does not exist")
            return 1

        _, _, content, perm = maybedata  # pylint: disable=E0633

        if await parse_permissions(message,
                                   kwargs["conf_cache"],
                                   str(perm),
                                   verbose=False):
            await message.channel.send(content)
            return 0
        else:
            await message.channel.send(
                "You dont have permission to request this FAQ")
            return 1
Ejemplo n.º 11
0
async def __help_override__(
        message: discord.Message, args: List[str], client: discord.Client,
        **kwargs: Any) -> Optional[Tuple[str, List[Tuple[str, str]]]]:
    if not message.guild:
        return None

    PREFIX = kwargs["conf_cache"]["prefix"]

    clist: List[Tuple[str, str]] = [(f"{PREFIX}{v['pretty_name']}",
                                     str(v["description"]))
                                    for _, v in commands.items()]

    clist.sort(key=lambda s: s[0])

    with db_hlapi(message.guild.id) as db:
        db.inject_enum(faq_name, faq_enum)

        for i in sorted(db.list_enum(faq_name)):
            # We can cast here because list_enum confirmed its existance
            # pylint: disable=E0633
            _, meta, _, _ = cast(Tuple[str, str, str, str],
                                 db.grab_enum(faq_name, i))

            clist.append((f"{PREFIX}faq {i}", str(meta if meta else i)), )

        faq_description = db.grab_config(
            "faq_description") or category_info["description"]

    # TODO(ultrabear) Custom description per guild
    return faq_description, clist
Ejemplo n.º 12
0
async def faq_set_description(message: discord.Message, args: List[str],
                              client: discord.Client, **kwargs: Any) -> Any:
    if not message.guild:
        return 1

    if not args:
        await message.channel.send("ERROR: Missing FAQ name")
        return 1

    if len(args) < 2:
        await message.channel.send("ERROR: Missing FAQ desc")
        return 1

    name = args[0]
    desc = stripargs(message.content, 2)

    if len(desc) > 256:
        await message.channel.send("ERROR: FAQ description too large")
        return 1

    with db_hlapi(message.guild.id) as db:
        db.inject_enum(faq_name, faq_enum)

        maybefaq = db.grab_enum(faq_name, name)

        if maybefaq is None:
            await message.channel.send("ERROR: FAQ entry does not exist")
            return 1

        _, _, body, perm = maybefaq  # pylint: disable=E0633

        db.set_enum(faq_name, [name, desc, body, perm])

    if kwargs["verbose"]:
        await message.channel.send(f"Updated description for FAQ entry {name}")
Ejemplo n.º 13
0
async def set_starboard_count(message: discord.Message, args: List[str],
                              client: discord.Client, **kwargs: Any) -> Any:
    if not message.guild:
        return 1

    if args:

        try:
            count = int(args[0])

            if count > 100:
                await message.channel.send(
                    "ERROR: Cannot set a starboard count higher than 100")
                return 1

            with db_hlapi(message.guild.id) as database:
                database.add_config("starboard-count", str(int(count)))

            if kwargs["verbose"]:
                await message.channel.send(
                    f"Updated starboard count to {count}")

        except ValueError:
            await message.channel.send("ERROR: Invalid input, enter a number")
            return 1

    else:
        mconf = load_message_config(message.guild.id,
                                    kwargs["ramfs"],
                                    datatypes=starboard_cache)
        count = int(mconf["starboard-count"])
        await message.channel.send(f"Starboard count is {count}")
Ejemplo n.º 14
0
async def get_users_trust(message: discord.Message, args: List[str],
                          client: discord.Client, **kwargs: Any) -> Any:

    try:
        user, _ = await parse_user_member(message,
                                          args,
                                          client,
                                          default_self=True)
    except lib_parsers.errors.user_parse_error:
        return 1

    t_count: int

    with db_hlapi(message.guild.id) as db:
        db.inject_enum("usertrust", [("userID", str), ("count", int)])

        trust = db.grab_enum("usertrust", str(user.id))

        if trust and isinstance(trust[1], int):
            t_count = trust[1]
        else:
            t_count = 0

    trusted = get_trust_pool(message.guild, kwargs["kernel_ramfs"])

    fmt = f"```\nUser: {user}\nMcount: {t_count}\nHas Trusted Role: {user.id in trusted}\n```"

    await message.channel.send(fmt)
Ejemplo n.º 15
0
async def faq_set(message: discord.Message, args: List[str],
                  client: discord.Client, **kwargs: Any) -> Any:
    if not message.guild:
        return 1

    if not args:
        await message.channel.send("ERROR: Missing FAQ name")
        return 1

    if len(args) < 2:
        await message.channel.send("ERROR: Missing FAQ body")
        return 1

    name = args[0]
    body = stripargs(message.content, 2)

    if len(body) > constants.message.content:
        await message.channel.send("ERROR: FAQ body too large")
        return 1
    elif len(name) >= 32:
        await message.channel.send("ERROR: FAQ name too large")
        return 1

    with db_hlapi(message.guild.id) as db:
        db.inject_enum(faq_name, faq_enum)

        db.set_enum(faq_name, [name, "", body, "everyone"])

    if kwargs["verbose"]:
        await message.channel.send(f"Created new FAQ entry under name {name}")
Ejemplo n.º 16
0
async def set_blacklist_infraction_level(message: discord.Message,
                                         args: List[str],
                                         client: discord.Client,
                                         **kwargs: Any) -> Any:
    if not message.guild:
        return 1

    if args:
        action = args[0].lower()
    else:
        await message.channel.send(
            f"blacklist action is `{kwargs['conf_cache']['blacklist-action']}`"
        )
        return

    if not action in ["warn", "kick", "mute", "ban"]:
        await message.channel.send(
            "ERROR: Blacklist action is not valid\nValid Actions: `warn` `mute` `kick` `ban`"
        )
        return 1

    with db_hlapi(message.guild.id) as database:
        database.add_config("blacklist-action", action)

    if kwargs["verbose"]:
        await message.channel.send(f"Updated blacklist action to `{action}`")
Ejemplo n.º 17
0
async def on_usertrust_message(message: discord.Message, **kargs: Any) -> None:

    if parse_skip_message(kargs["client"], message):
        return

    trusted = get_trust_pool(message.guild, kargs["kernel_ramfs"])

    # Give up if user is already trusted
    if message.author.id in trusted:
        return

    utrust_cache = load_message_config(message.guild.id,
                                       kargs["ramfs"],
                                       datatypes=trust_types)

    if not bool(int(utrust_cache["usertrust-enabled"])):
        return

    with db_hlapi(message.guild.id) as db:

        db.inject_enum("usertrust", [("userID", str), ("count", int)])

        # Inc counter
        if ucol := db.grab_enum("usertrust", str(message.author.id)):
            count = int(ucol[1]) + 1
        else:
Ejemplo n.º 18
0
    async def defaultpfpedit(self, args: List[str],
                             client: discord.Client) -> int:
        # notifier-log-defaultpfp
        cnf_name: Final[str] = "notifier-log-defaultpfp"

        if args:
            with db_hlapi(self.guild.id) as db:
                db.add_config(cnf_name,
                              str(true := int(parse_boolean(args[0]))))
            await self.m.channel.send(
                f"Updated defaultpfp checking to {bool(true)}")
        else:
            with db_hlapi(self.guild.id) as db:
                await self.m.channel.send(
                    f"Defaultpfp checking is set to {bool(int(db.grab_config(cnf_name) or 0))}"
                )

        return 0
Ejemplo n.º 19
0
async def on_ready(**kargs: Any) -> None:

    inc_statistics_better(0, "on-ready", kargs["kernel_ramfs"])

    Client: discord.Client = kargs["client"]
    print(f'{Client.user} has connected to Discord!')

    # Warn if user is not bot
    if not Client.user.bot:
        print(
            "WARNING: The connected account is not a bot, as it is against ToS we do not condone user botting"
        )

    # bot start time check to not reparse timers on network disconnect
    if kargs["bot_start"] > (time.time() - 10):

        with db_hlapi(None) as db:
            mutes: List[Tuple[str, str, str, int]] = db.fetch_all_mutes()
            lost_mutes = sorted(mutes, key=lambda a: a[3])

        ts = datetime_now().timestamp()

        lost_mute_timers = [i for i in lost_mutes if 0 != i[3]]

        if lost_mute_timers:

            print(f"Lost mutes: {len(lost_mute_timers)}")
            for i in lost_mute_timers:
                if i[3] < ts:
                    await attempt_unmute(Client, i)

            lost_mute_timers = [i for i in lost_mute_timers if i[3] >= ts]
            if lost_mute_timers:
                print(
                    f"Mute timers to recover: {len(lost_mute_timers)}\nThis process will end in {round(lost_mutes[-1][3]-time.time())} seconds"
                )

                for i in lost_mute_timers:
                    await asyncio.sleep(i[3] - datetime_now().timestamp())
                    with db_hlapi(int(i[0])) as db:
                        if db.is_muted(infractionid=i[1]):
                            await attempt_unmute(Client, i)

            print("Mutes recovered")
Ejemplo n.º 20
0
async def clear_faq_description(message: discord.Message, args: List[str],
                                client: discord.Client, **kwargs: Any) -> Any:
    if not message.guild:
        return 1

    with db_hlapi(message.guild.id) as db:
        db.delete_config("faq_description")

    if kwargs["verbose"]:
        await message.channel.send("Deleted FAQ help description")
Ejemplo n.º 21
0
async def attempt_unmute(Client: discord.Client,
                         mute_entry: Tuple[str, str, str, int]) -> None:

    with db_hlapi(int(mute_entry[0])) as db:
        db.unmute_user(infractionid=mute_entry[1])
        mute_role_id = db.grab_config("mute-role")

    if (guild := Client.get_guild(int(mute_entry[0]))) and mute_role_id:
        if (user := guild.get_member(int(
                mute_entry[2]))) and (mute_role := guild.get_role(
                    int(mute_role_id))):
Ejemplo n.º 22
0
async def add_reactionroles(message: discord.Message, args: List[str],
                            client: discord.Client, **kwargs: Any) -> Any:
    if not message.guild:
        return 1

    try:
        rr_message, nargs = await parse_channel_message(message, args, client)
    except lib_parsers.errors.message_parse_failure:
        return 1

    args = args[nargs:]

    if len(args) < 2:
        await message.channel.send("ERROR: Not enough args supplied")
        return 1

    try:
        emoji = await valid_emoji(message, args[0], client)
        role = await get_exact_role(message, args[1])
        await rindex_check(message, role)
    except (InvalidEmoji, NoRoleError, RindexFailure):
        return 1

    with db_hlapi(message.guild.id) as db:
        reactionroles = json.loads(
            db.grab_config("reaction-role-data") or "{}")

    if str(rr_message.id) in reactionroles:
        reactionroles[str(rr_message.id)][emoji] = role.id
    else:
        reactionroles[str(rr_message.id)] = {}
        reactionroles[str(rr_message.id)][emoji] = role.id

    with db_hlapi(message.guild.id) as db:
        db.add_config("reaction-role-data", json.dumps(reactionroles))

    if kwargs["verbose"]:
        await message.channel.send(
            f"Added reactionrole to message id {rr_message.id}: {emoji}:{role.mention}",
            allowed_mentions=discord.AllowedMentions.none())
Ejemplo n.º 23
0
def parse_blacklist(
        indata: _parse_blacklist_inputs) -> tuple[bool, bool, list[str]]:
    """
    Deprecated, this should be in dlib_messages.py
    Parse the blacklist over a message object

    :returns: Tuple[bool, bool, List[str]] -- broke blacklist, broke notifer list, list of strings of infraction messages
    """
    message, blacklist, ramfs = indata

    if not message.guild:
        return False, False, []

    # Preset values
    broke_blacklist = False
    notifier = False
    infraction_type = []

    # Compilecheck regex
    try:
        ramfs.ls(f"{message.guild.id}/regex")
    except FileNotFoundError:

        with db_hlapi(message.guild.id) as db:
            reglist = {}
            for regex_type in ["regex-blacklist", "regex-notifier"]:
                if dat := db.grab_config(regex_type):
                    reglist[regex_type] = [
                        " ".join(i.split(" ")[1:])[1:-2]
                        for i in json.loads(dat)["blacklist"]
                    ]
                else:
                    reglist[regex_type] = []

        for regex_type in ["regex-blacklist", "regex-notifier"]:
            ramfs.mkdir(f"{message.guild.id}/regex/{regex_type}")
            for i in reglist[regex_type]:
                regexname = hex(
                    int.from_bytes(
                        hashlib.sha256(i.encode("utf8")).digest(),
                        "big"))[-32:]
                ramfs.create_f(
                    f"{message.guild.id}/regex/{regex_type}/{regexname}",
                    f_type=re.compile,
                    f_args=[i])

        if blacklist["url-blacklist"]:
            ramfs.create_f(f"{message.guild.id}/regex/url",
                           f_type=re.compile,
                           f_args=[_compileurl(blacklist["url-blacklist"])])
        else:
            ramfs.create_f(f"{message.guild.id}/regex/url", f_type=returnsNone)
Ejemplo n.º 24
0
async def grab_mute_role(message: discord.Message,
                         ramfs: lexdpyk.ram_filesystem) -> discord.Role:
    if not message.guild:
        raise NoMuteRole("No guild table to find mute role")

    with db_hlapi(message.guild.id) as db:
        mute_role = db.grab_config("mute-role")

        if mute_role and (mute_role_obj := message.guild.get_role(
                int(mute_role))):
            return mute_role_obj

        else:
Ejemplo n.º 25
0
async def set_prefix(message: discord.Message, args: List[str],
                     client: discord.Client, **kwargs: Any) -> Any:
    if not message.guild:
        return 1

    if args:
        prefix = args[0]
        with db_hlapi(message.guild.id) as database:
            database.add_config("prefix", prefix)
    else:
        prefix = kwargs["conf_cache"]["prefix"]

    if kwargs["verbose"]:
        await message.channel.send(f"Prefix set to `{prefix}`")
Ejemplo n.º 26
0
async def on_message_delete(message: discord.Message, **kargs: Any) -> None:

    client: discord.Client = kargs["client"]
    kernel_ramfs: lexdpyk.ram_filesystem = kargs["kernel_ramfs"]
    ramfs: lexdpyk.ram_filesystem = kargs["ramfs"]

    # Ignore bots
    if parse_skip_message(client, message):
        return
    elif not message.guild:
        return

    files: Optional[List[discord.File]] = grab_files(message.guild.id, message.id, kernel_ramfs, delete=True)

    inc_statistics_better(message.guild.id, "on-message-delete", kernel_ramfs)

    # Add to log
    with db_hlapi(message.guild.id) as db:
        message_log = db.grab_config("message-log")

    try:
        if not (message_log and (log_channel := client.get_channel(int(message_log)))):
            return
    except ValueError:
        try:
            await message.channel.send("ERROR: message-log config is corrupt in database, please reset")
        except discord.errors.Forbidden:
            pass
        return

    if not isinstance(log_channel, discord.TextChannel):
        return

    message_embed = discord.Embed(
        title=f"Message deleted in #{message.channel}", description=message.content[:constants.embed.description], color=load_embed_color(message.guild, embed_colors.deletion, ramfs)
        )

    # Parse for message lengths >2048 (discord now does 4000 hhhhhh)
    if len(message.content) > constants.embed.description:
        limend = constants.embed.description + constants.embed.field.value
        message_embed.add_field(name="(Continued)", value=message.content[constants.embed.description:limend])

        if len(message.content) > limend:
            flimend = limend + constants.embed.field.value
            message_embed.add_field(name="(Continued further)", value=message.content[limend:flimend])

    message_embed.set_author(name=f"{message.author} ({message.author.id})", icon_url=user_avatar_url(message.author))

    if (r := message.reference) and (rr := r.resolved) and isinstance(rr, discord.Message):
        message_embed.add_field(name="Replying to:", value=f"{rr.author.mention} [(Link)]({rr.jump_url})")
Ejemplo n.º 27
0
async def char_antispam_set(message: discord.Message, args: List[str],
                            client: discord.Client, **kwargs: Any) -> Any:
    if not message.guild:
        return 1

    if not args:
        antispam = kwargs["conf_cache"]["char-antispam"]
        await message.channel.send(
            f"CharAntispam timings are M:{antispam[0]},S:{antispam[1]},C:{antispam[2]}"
        )
        return

    if len(args) == 1:
        try:
            messages, seconds, chars = [float(i) for i in args[0].split(",")]
        except ValueError:
            await message.channel.send("ERROR: Incorrect args supplied")
            return 1

    elif len(args) > 1:
        try:
            messages = float(args[0])
            seconds = float(args[1])
            chars = float(args[2])
        except ValueError:
            await message.channel.send("ERROR: Incorrect args supplied")
            return 1

    # Prevent bullshit
    outside_range = "ERROR: Cannot go outside range"
    if not (2 <= messages <= 64):
        await message.channel.send(f"{outside_range} 2-64 messages")
        return 1
    elif not (0 <= seconds <= 10):
        await message.channel.send(f"{outside_range} 0-10 seconds")
        return 1
    elif not (128 <= chars <= 2**16):
        await message.channel.send(f"{outside_range} 128-{2**16} chars")
        return 1

    with db_hlapi(message.guild.id) as database:
        database.add_config("char-antispam",
                            f"{int(messages)},{seconds},{int(chars)}")

    if kwargs["verbose"]:
        await message.channel.send(
            f"Updated char antispam timings to M:{int(messages)},S:{seconds},C:{int(chars)}"
        )
Ejemplo n.º 28
0
async def sleep_and_unmute(guild: discord.Guild, member: discord.Member,
                           infractionID: str, mute_role: discord.Role,
                           mutetime: int,
                           ramfs: lexdpyk.ram_filesystem) -> None:

    await asyncio.sleep(mutetime)

    # unmute in db
    with db_hlapi(guild.id) as db:
        if db.is_muted(infractionid=infractionID):
            db.unmute_user(infractionid=infractionID)

            try:
                await member.remove_roles(mute_role)
            except discord.errors.HTTPException:
                pass
Ejemplo n.º 29
0
async def usertrust_count(message: discord.Message, args: List[str],
                          client: discord.Client, **kwargs: Any) -> Any:

    try:
        count = int(args[0])
    except (ValueError, IndexError):
        await message.channel.send("ERROR: No int supplied or int is invalid")
        return 1

    if 2**32 < count or count < 10:
        await message.channel.send(
            f"ERROR: Count cannot exceed range 10-{2**32}")

    with db_hlapi(message.guild.id) as db:
        db.add_config("usertrust-message-count", str(count))

    await message.channel.send(f"Updated usertrust message count to {count}")
Ejemplo n.º 30
0
async def set_view_infractions(message: discord.Message, args: List[str],
                               client: discord.Client, **kwargs: Any) -> Any:
    if not message.guild:
        return 1

    gate: bool

    if args:

        gate = pb if isinstance(
            (pb := parse_boolean(args[0])), bool) else False

        with db_hlapi(message.guild.id) as db:
            db.add_config("member-view-infractions", str(int(gate)))

        if kwargs["verbose"]:
            await message.channel.send(
                f"Set member view own infractions to {gate}")