AntiSpamHandler

Note, this is the main entrance to this entire package. As such this should be the only thing you interact with.

This handler propagation method also returns the following dictionary for you to use:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
{
    "should_be_punished_this_message": boolean,
    "was_warned": boolean,
    "was_kicked": boolean,
    "was_banned": boolean,
    "status": string,
    "warn_count": integer,
    "kick_count": integer,
    "duplicate_counter": integer,
    "pre_invoke_extensions": list,
    "after_invoke_extensions": list,
}
class antispam.anti_spam_handler.AntiSpamHandler(bot: Union[discord.ext.commands.bot.Bot, discord.ext.commands.bot.AutoShardedBot, discord.client.Client, discord.shard.AutoShardedClient], **kwargs)

The overall handler for the DPY Anti-spam package

DEFAULTS:
warn_threshold: 3
This is the amount of duplicates that result in a warning within the message_interval
kick_threshold: 2
This is the amount of warns required before a kick is the next punishment
ban_threshold: 2
This is the amount of kicks required before a ban is the next punishment
message_interval: 30000ms (30 Seconds)
Amount of time a message is kept before being discarded. Essentially the amount of time (In milliseconds) a message can count towards spam
guild_warn_message: “Hey $MENTIONUSER, please stop spamming/sending duplicate messages.”
The message to be sent in the guild upon warn_threshold being reached
guild_kick_message: “$USERNAME was kicked for spamming/sending duplicate messages.”
The message to be sent in the guild upon kick_threshold being reached
guild_ban_message: “$USERNAME was banned for spamming/sending duplicate messages.”
The message to be sent in the guild upon ban_threshold being reached
user_kick_message : “Hey $MENTIONUSER, you are being kicked from $GUILDNAME for spamming/sending duplicate messages.”
The message to be sent to the user who is being warned
user_ban_message : “Hey $MENTIONUSER, you are being banned from $GUILDNAME for spamming/sending duplicate messages.”
The message to be sent to the user who is being banned
user_failed_kick_message : “I failed to punish you because I lack permissions, but still you shouldn’t spam”
The message to be sent to the user if the bot fails to kick them
user_failed_ban_message : “I failed to punish you because I lack permissions, but still you shouldn’t spam”
The message to be sent to the user if the bot fails to ban them
message_duplicate_count: 5
The amount of duplicate messages needed within message_interval to trigger a punishment
message_duplicate_accuracy: 90
How ‘close’ messages need to be to be registered as duplicates (Out of 100)
delete_spam: True

Whether or not to delete messages marked as spam

Won’t delete messages if no_punish is True

ignore_perms: [8]

The perms (ID Form), that bypass anti-spam

Not Implemented

ignore_users: []
The users (ID Form), that bypass anti-spam
ignore_channels: []
Channels (ID Form), that bypass anti-spam
ignore_roles: []
The roles (ID Form), that bypass anti-spam
ignore_guilds: []
Guilds (ID Form), that bypass anti-spam
ignore_bots: True
Should bots bypass anti-spam?
warn_only: False
Whether or not to only warn users, this means it will not kick or ban them
no_punish: False

Don’t punish anyone, simply return whether or not they should be punished within propagate. This essentially lets the end user handle punishments themselves.

To check if someone should be punished, use the returned value from the propagate method. If should_be_punished_this_message is True then this package believes they should be punished. Otherwise just ignore that message since it shouldn’t be punished.

per_channel_spam: False
Track spam as per channel, rather then per guild.
guild_warn_message_delete_after: None
The time to delete the guild_warn_message message
user_kick_message_delete_after: None
The time to delete the user_kick_message message
guild_kick_message_delete_after: None
The time to delete the guild_kick_message message
user_ban_message_delete_after: None
The time to delete the user_ban_message message
guild_ban_message_delete_after: None
The time to delete the guild_ban_message message
delete_zero_width_chars: True
Should zero width characters be removed from messages
__init__(bot: Union[discord.ext.commands.bot.Bot, discord.ext.commands.bot.AutoShardedBot, discord.client.Client, discord.shard.AutoShardedClient], **kwargs)

This is the first initialization of the entire spam handler, this is also where the initial options are set

Parameters:
  • bot (commands.Bot or commands.AutoShardedBot or discord.Client or discord.AutoShardedClient) – The commands.Bot or commands.AutoSharedBot or discord.Client or discord.AutoShardedClient instance
  • warn_threshold (int, optional) – This is the amount of messages in a row that result in a warning within the message_interval
  • kick_threshold (int, optional) – The amount of ‘warns’ before a kick occurs
  • ban_threshold (int, optional) – The amount of ‘kicks’ that occur before a ban occurs
  • message_interval (int, optional) – Amount of time a message is kept before being discarded. Essentially the amount of time (In milliseconds) a message can count towards spam
  • guild_warn_message (Union[str, dict], optional) – The message to be sent in the guild upon warn_threshold being reached
  • guild_kick_message (Union[str, dict], optional) – The message to be sent in the guild upon kick_threshold being reached
  • guild_ban_message (Union[str, dict], optional) – The message to be sent in the guild upon ban_threshold being reached
  • user_kick_message (Union[str, dict], optional) – The message to be sent to the user who is being warned
  • user_ban_message (Union[str, dict], optional) – The message to be sent to the user who is being banned
  • user_failed_kick_message (Union[str, dict], optional) – The message to be sent to the user if the bot fails to kick them
  • user_failed_ban_message (Union[str, dict], optional) – The message to be sent to the user if the bot fails to ban them
  • message_duplicate_count (int, optional) – Amount of duplicate messages needed to trip a punishment
  • message_duplicate_accuracy (float, optional) – How ‘close’ messages need to be to be registered as duplicates (Out of 100)
  • delete_spam (bool, optional) – Whether or not to delete any messages marked as spam
  • ignore_perms (list, optional) – The perms (ID Form), that bypass anti-spam
  • ignore_channels (list, optional) – The channels (ID Form) that are ignored
  • ignore_roles (list, optional) – The roles (ID, Name) that are ignored
  • ignore_guilds (list, optional) – The guilds (ID) that are ignored
  • ignore_users (list, optional) – The users (ID Form), that bypass anti-spam
  • ignore_bots (bool, optional) – Should bots bypass anti-spam?
  • warn_only (bool, optional) – Only warn users?
  • no_punish (bool, optional) – Dont punish users? Return if they should be punished or not without actually punishing them
  • per_channel_spam (bool, optional) – Track spam as per channel, rather then per guild
  • guild_warn_message_delete_after (int, optional) – The time to delete the guild_warn_message message
  • user_kick_message_delete_after (int, optional) – The time to delete the user_kick_message message
  • guild_kick_message_delete_after (int, optional) – The time to delete the guild_kick_message message
  • user_ban_message_delete_after (int, optional) – The time to delete the user_ban_message message
  • guild_ban_message_delete_after (int, optional) – The time to delete the guild_ban_message message
  • delete_zero_width_chars (bool) – Should zero width characters be removed from messages
add_custom_guild_options(guild_id: int, **kwargs)

Set a guild’s options to a custom set, rather then the base level set used and defined in ASH initialization

Other Parameters:
 
  • guild_id (int) – The id of the guild to create
  • warn_threshold (int, optional) – This is the amount of messages in a row that result in a warning within the message_interval
  • kick_threshold (int, optional) – The amount of ‘warns’ before a kick occurs
  • ban_threshold (int, optional) – The amount of ‘kicks’ that occur before a ban occurs
  • message_interval (int, optional) – Amount of time a message is kept before being discarded. Essentially the amount of time (In milliseconds) a message can count towards spam
  • guild_warn_message (Union[str, dict], optional) – The message to be sent in the guild upon warn_threshold being reached
  • guild_kick_message (Union[str, dict], optional) – The message to be sent in the guild upon kick_threshold being reached
  • guild_ban_message (Union[str, dict], optional) – The message to be sent in the guild upon ban_threshold being reached
  • user_kick_message (Union[str, dict], optional) – The message to be sent to the user who is being warned
  • user_ban_message (Union[str, dict], optional) – The message to be sent to the user who is being banned
  • user_failed_kick_message (Union[str, dict], optional) – The message to be sent to the user if the bot fails to kick them
  • user_failed_ban_message (Union[str, dict], optional) – The message to be sent to the user if the bot fails to ban them
  • message_duplicate_count (int, optional) – Amount of duplicate messages needed to trip a punishment
  • message_duplicate_accuracy (float, optional) – How ‘close’ messages need to be to be registered as duplicates (Out of 100)
  • delete_spam (bool, optional) – Whether or not to delete any messages marked as spam
  • ignore_perms (list, optional) – The perms (ID Form), that bypass anti-spam
  • ignore_channels (list, optional) – The channels (ID Form) that are ignored
  • ignore_roles (list, optional) – The roles (ID, Name) that are ignored
  • ignore_guilds (list, optional) – The guilds (ID) that are ignored
  • ignore_users (list, optional) – The users (ID Form), that bypass anti-spam
  • ignore_bots (bool, optional) – Should bots bypass anti-spam?
  • warn_only (bool, optional) – Only warn users?
  • no_punish (bool, optional) – Dont punish users? Return if they should be punished or not without actually punishing them
  • per_channel_spam (bool, optional) – Track spam as per channel, rather then per guild
  • guild_warn_message_delete_after (int, optional) – The time to delete the guild_warn_message message
  • user_kick_message_delete_after (int, optional) – The time to delete the user_kick_message message
  • guild_kick_message_delete_after (int, optional) – The time to delete the guild_kick_message message
  • user_ban_message_delete_after (int, optional) – The time to delete the user_ban_message message
  • guild_ban_message_delete_after (int, optional) – The time to delete the guild_ban_message message
  • delete_zero_width_chars (bool) – Should zero width characters be removed from messages

Warning

If using AntiSpamTracker, please call this method on that class instance. Not this one.

Notes

This will override any current settings, if you wish to continue using existing settings and merely change some I suggest using the get_options method first and then giving those values back to this method with the changed arguments

This is also a somewhat expensive operation at O(n) where n is the total number of users cached for the guild

add_ignored_item(item: int, ignore_type: str) → None

TODO Document this better with ignore_type notations Add an item to the relevant ignore list

Parameters:
  • item (int) – The id of the thing to ignore
  • ignore_type (str) – A string representation of the ignored items overall container
Raises:
  • BaseASHException – Invalid ignore ignore_type
  • ValueError – item is not of ignore_type int or int convertible

Notes

This will silently ignore any attempts to add an item already added.

get_guild_options(guild_id: int) → tuple

Get the options dictionary for a given guild, if the guild doesnt exist raise an exception

Parameters:guild_id (int) – The guild to get custom options for
Returns:The options for this guild as tuple[0] and tuple[1] is a bool which is used to say if the guild has custom options or not

Be wary of the return value. It is in the format, (dict, boolean), where dict is the options and boolean is whether or not these options are custom

Return type:tuple
Raises:BaseASHException – This guild does not exist

Notes

The value for tuple[1] is not checked/ensured at runtime. Be wary of this if you access guild and manually change options rather then using this libraries methods.

Another thing to note is this returns a deepcopy of the options dictionary. This is to encourage usage of this libraries methods for changing options, rather then playing around with them yourself and potentially doing damage.

static load_from_dict(bot, data: dict, *, raise_on_exception: bool = True)

Can be used as an entry point when starting your bot to reload a previous state so you don’t lose all of the previous punishment records, etc, etc

Parameters:
  • bot (commands.Bot) – The bot instance
  • data (dict) – The data to load AntiSpamHandler from
  • raise_on_exception (bool) –

    Whether or not to raise if an issue is encountered while trying to rebuild AntiSpamHandler from a saved state

    If you set this to False, and an exception occurs during the build process. This will return an AntiSpamHandler instance without any of the saved state and is equivalent to simply doing AntiSpamHandler(bot)

Returns:

A new AntiSpamHandler instance where the state is equal to the provided dict

Return type:

AntiSpamHandler

Warning

Don’t provide data that was not given to you outside of the save_to_dict method unless you are maintaining the correct format.

Notes

This method does not check for data conformity. Any invalid input will error unless you set raise_on_exception to False in which case the following occurs

If you set raise_on_exception to False, and an exception occurs during the build process. This method will return an AntiSpamhandler instance without any of the saved state and is equivalent to simply doing AntiSpamHandler(bot)

This is fairly computationally expensive. It deepcopy’s nearly everything lol.

propagate(message: discord.message.Message) → Optional[dict]

This method is the base level intake for messages, then propagating it out to the relevant guild or creating one if that is required

For what this returns please see the top of this page.

Parameters:message (discord.Message) – The message that needs to be propagated out
Returns:A dictionary of useful information about the user in question
Return type:dict
register_extension(extension, force_overwrite=False) → None

Registers an extension for usage for within the package

Parameters:
  • extension – The extension to register
  • force_overwrite (bool) –

    Whether to overwrite any duplicates currently stored.

    Think of this as calling unregister_extension and then proceeding to call this method.

Raises:

ExtensionError – An extension with this name is already loaded

Notes

This must be a class instance, and must subclass BaseExtension

remove_custom_guild_options(guild_id: int) → None

Reset a guilds options to the ASH options

Parameters:guild_id (int) – The guild to reset

Warning

If using AntiSpamTracker, please call this method on that class instance. Not this one.

Notes

This method will silently ignore guilds that do not exist, as it is considered to have ‘removed’ custom options due to how Guild’s are created

This is also a somewhat expensive operation at O(n) where n is the total number of users cached for the guild

remove_ignored_item(item: int, ignore_type: str) → None

Remove an item from the relevant ignore list

Parameters:
  • item (int) – The id of the thing to un-ignore
  • ignore_type (str) – A string representation of the ignored items overall container
Raises:
  • BaseASHException – Invalid ignore ignore_type
  • ValueError – item is not of ignore_type int or int convertible

Notes

This will silently ignore any attempts to remove an item not ignored.

reset_user_count(user_id: int, guild_id: int, counter: str) → None

Reset an internal counter attached to a User object

Parameters:
  • user_id (int) – The user to reset
  • guild_id (int) – The guild they are attached to
  • counter (str) –

    A str denoting which count to reset, Options are:

    warn_counter -> Reset the warn count

    kick_counter -> Reset the kick count

Raises:

LogicError – Invalid count to reset

Notes

Silently ignores if the User or Guild does not exist. This is because in the packages mind, the counts are ‘reset’ since the default value is the reset value.

save_to_dict() → dict

Creates a ‘save point’ of the current state for this handler which can then be used to restore state at a later date

Returns:The saved state in a dictionary form. You can give this to load_from_dict to reload the saved state
Return type:dict

Notes

For most expected use-case’s the returned Messages will be outdated, however, they are included as it is technically part of the current state.

Note that is method is expensive in both time and memory. It has to iterate over every single stored class instance within the library and store it in a dictionary.

For bigger bots, it is likely better you create this process yourself using generators in order to reduce overhead.

Warning

Due to the already expensive nature of this method, all returned option dictionaries are not deepcopied. Modifying them during runtime will cause this library to begin using that modified copy.

unregister_extension(extension_name: str) → None

Used to unregister or remove an extension that is currently loaded into AntiSpamHandler

Parameters:extension_name (str) – The name of the class you want to unregister
Raises:ExtensionError – This extension isn’t loaded