Main Interface

This file deals with the AntiSpamHandler as it is the primary Interface for you to interact with.

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

Punishment messages won’t be sent unless a guild sets a log channel.

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

antispam.CorePayload

class antispam.AntiSpamHandler(bot, *, is_using_hikari: bool = False, options: antispam.dataclasses.options.Options = None, cache: antispam.abc.Cache = None)

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
member_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
member_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
member_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
member_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: False

Whether or not to delete messages marked as spam

Won’t delete messages if no_punish is True

Note, this method is expensive. It will all messages marked as spam, and this means an api call per message.

mention_on_embed: True
If the message your trying to send is an embed, also send some content to mention the person being punished.
ignored_members: []
The users (ID Form), that bypass anti-spam
ignored_channels: []
Channels (ID Form), that bypass anti-spam
ignored_roles: []
The roles (ID Form), that bypass anti-spam
ignored_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 member_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 member_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
is_using_hikari: False
Set this to True if you are using the package with hikari rather then discord.py
__init__(bot, *, is_using_hikari: bool = False, options: antispam.dataclasses.options.Options = None, cache: antispam.abc.Cache = None)

AntiSpamHandler entry point.

Parameters:
  • bot – A reference to your discord bot object.
  • is_using_hikari (bool, Optional) – Set this to True if you are using this package within hikari rather then discord.py
  • options (Options, Optional) – An instance of your custom Options the handler should use
  • cache (Cache, Optional) – Your choice of backend caching
add_guild_log_channel(log_channel: int, guild_id: int) → None

Registers a log channel on a guild internally

Parameters:
  • log_channel (int) – The channel id you wish to use for logging
  • guild_id (int) – The id of the guild to store this on

Notes

Not setting a log channel means it will not send any punishment messages

add_guild_options(guild_id: int, options: antispam.dataclasses.options.Options) → None

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

Warning

If using/modifying AntiSpamHandler.options to give to this method you will also be modifying the overall options.

To get an options item you can modify freely call AntiSpamHandler.get_options(), this method will give you an instance of the current options you are free to modify however you like.

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

add_ignored_item(item: int, ignore_type: antispam.enums.ignored_types.IgnoreType) → None

Add an item to the relevant ignore list

Parameters:
  • item (int) – The id of the thing to ignore
  • ignore_type (IgnoreType) – An enum representing the item to ignore
Raises:

ValueError – item is not of type int or int convertible

Notes

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

clean_cache(strict=False) → None

Cleans the internal cache, pruning any old/un-needed entries.

TODO Test these modes Non Strict mode:

  • Member deletion criteria:
    • warn_count == default
    • kick_count == default
    • duplicate_counter == default
    • duplicate_channel_counter_dict == default
    • addons dict == default
    • Also must have no active messages after cleaning.
  • Guild deletion criteria:
    • options are not custom
    • log_channel_id is not set
    • addons dict == default
    • Also must have no members stored
Strict mode:
  • Member deletion criteria
    • Has no active messages
  • Guild deletion criteria
    • Does not have custom options
    • log_channel_id is not set
    • Has no active members
Parameters:strict (bool) – Toggles the above

Notes

This is expensive, and likely only required to be run every so often depending on how high traffic your bot is.

get_guild_options(guild_id: int) → antispam.dataclasses.options.Options

Get the options dataclass 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
Return type:Options
Raises:GuildNotFound – This guild does not exist

Notes

This returns a copy of the options, if you wish to change the options on the guild you should use the package methods.

init() → None

This method provides a means to initialize any async calls cleanly and without asyncio madness.

Notes

This method is guaranteed to be called before the first time propagate runs. However, it will not be run when the class is initialized.

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 – 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)

propagate(message) → Union[antispam.dataclasses.core.CorePayload, dict, None]

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 (Union[discord.Message, hikari.messages.Message]) – The message that needs to be propagated out
Returns:A dictionary of useful information about the Member in question
Return type:dict
register_plugin(plugin, force_overwrite=False) → None

Registers a plugin for usage for within the package

Parameters:
  • plugin – The plugin 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:

PluginError – A plugin with this name is already loaded

Notes

This must be a class instance, and must subclass BasePlugin

remove_guild_log_channel(guild_id: int) → None

Removes a registered guild log channel

Parameters:guild_id (int) – The guild to remove it from

Notes

Silently ignores guilds which don’t exist

remove_guild_options(guild_id: int) → None

Reset a guilds options to the ASH options

Parameters:guild_id (int) – The guild to reset

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

remove_ignored_item(item: int, ignore_type: antispam.enums.ignored_types.IgnoreType) → None

Remove an item from the relevant ignore list

Parameters:
  • item (int) – The id of the thing to un-ignore
  • ignore_type (IgnoreType) – An enum representing the item to ignore
Raises:

ValueError – item is not of type int or int convertible

Notes

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

reset_member_count(member_id: int, guild_id: int, reset_type: antispam.enums.reset_type.ResetType) → None

Reset an internal counter attached to a User object

Parameters:
  • member_id (int) – The user to reset
  • guild_id (int) – The guild they are attached to
  • reset_type (ResetType) – An enum representing the counter 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_plugin(plugin_name: str) → None

Used to unregister or remove a plugin that is currently loaded into AntiSpamHandler

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