feat: automod

#8886 djs
This commit is contained in:
March 7th
2022-12-20 22:46:50 +07:00
parent ef2deb64f7
commit 294005bac7
22 changed files with 1191 additions and 4 deletions

View File

@@ -0,0 +1,89 @@
'use strict';
const { AutoModerationRuleTriggerTypes } = require('../util/Constants');
/**
* Represents the structure of an executed action when an {@link AutoModerationRule} is triggered.
*/
class AutoModerationActionExecution {
constructor(data, guild) {
/**
* The guild where this action was executed from.
* @type {Guild}
*/
this.guild = guild;
/**
* The action that was executed.
* @type {AutoModerationAction}
*/
this.action = data.action;
/**
* The id of the auto moderation rule this action belongs to.
* @type {Snowflake}
*/
this.ruleId = data.rule_id;
/**
* The trigger type of the auto moderation rule which was triggered.
* @type {AutoModerationRuleTriggerType}
*/
this.ruleTriggerType = AutoModerationRuleTriggerTypes[data.rule_trigger_type];
/**
* The id of the user that triggered this action.
* @type {Snowflake}
*/
this.userId = data.user_id;
/**
* The id of the channel where this action was triggered from.
* @type {?Snowflake}
*/
this.channelId = data.channel_id ?? null;
/**
* The id of the message that triggered this action.
* @type {?Snowflake}
* <info>This will not be present if the message was blocked or the content was not part of any message.</info>
*/
this.messageId = data.message_id ?? null;
/**
* The id of any system auto moderation messages posted as a result of this action.
* @type {?Snowflake}
*/
this.alertSystemMessageId = data.alert_system_message_id ?? null;
/**
* The content that triggered this action.
* <info>This property requires the {@link GatewayIntentBits.MessageContent} privileged gateway intent.</info>
* @type {string}
*/
this.content = data.content;
/**
* The word or phrase configured in the rule that triggered this action.
* @type {?string}
*/
this.matchedKeyword = data.matched_keyword ?? null;
/**
* The substring in content that triggered this action.
* @type {?string}
*/
this.matchedContent = data.matched_content ?? null;
}
/**
* The auto moderation rule this action belongs to.
* @type {?AutoModerationRule}
* @readonly
*/
get autoModerationRule() {
return this.guild.autoModerationRules.cache.get(this.ruleId) ?? null;
}
}
module.exports = AutoModerationActionExecution;

View File

@@ -0,0 +1,279 @@
'use strict';
const { Collection } = require('@discordjs/collection');
const Base = require('./Base');
const {
AutoModerationRuleKeywordPresetTypes,
AutoModerationRuleTriggerTypes,
AutoModerationRuleEventTypes,
AutoModerationActionTypes,
} = require('../util/Constants');
/**
* Represents an auto moderation rule.
* @extends {Base}
*/
class AutoModerationRule extends Base {
constructor(client, data, guild) {
super(client);
/**
* The id of this auto moderation rule.
* @type {Snowflake}
*/
this.id = data.id;
/**
* The guild this auto moderation rule is for.
* @type {Guild}
*/
this.guild = guild;
/**
* The user that created this auto moderation rule.
* @type {Snowflake}
*/
this.creatorId = data.creator_id;
/**
* The trigger type of this auto moderation rule.
* @type {AutoModerationRuleTriggerType}
*/
this.triggerType = AutoModerationRuleTriggerTypes[data.trigger_type];
this._patch(data);
}
_patch(data) {
if ('name' in data) {
/**
* The name of this auto moderation rule.
* @type {string}
*/
this.name = data.name;
}
if ('event_type' in data) {
/**
* The event type of this auto moderation rule.
* @type {AutoModerationRuleEventType}
*/
this.eventType = AutoModerationRuleEventTypes[data.event_type];
}
if ('trigger_metadata' in data) {
/**
* Additional data used to determine whether an auto moderation rule should be triggered.
* @typedef {Object} AutoModerationTriggerMetadata
* @property {string[]} keywordFilter The substrings that will be searched for in the content
* @property {string[]} regexPatterns The regular expression patterns which will be matched against the content
* <info>Only Rust-flavored regular expressions are supported.</info>
* @property {AutoModerationRuleKeywordPresetType[]} presets
* The internally pre-defined wordsets which will be searched for in the content
* @property {string[]} allowList The substrings that will be exempt from triggering
* {@link AutoModerationRuleTriggerTypes.Keyword} and {@link AutoModerationRuleTriggerTypes.KeywordPreset}
* @property {?number} mentionTotalLimit The total number of role & user mentions allowed per message
*/
/**
* The trigger metadata of the rule.
* @type {AutoModerationTriggerMetadata}
*/
this.triggerMetadata = {
keywordFilter: data.trigger_metadata.keyword_filter ?? [],
regexPatterns: data.trigger_metadata.regex_patterns ?? [],
presets: data.trigger_metadata.presets?.map(preset => AutoModerationRuleKeywordPresetTypes[preset]) ?? [],
allowList: data.trigger_metadata.allow_list ?? [],
mentionTotalLimit: data.trigger_metadata.mention_total_limit ?? null,
};
}
if ('actions' in data) {
/**
* An object containing information about an auto moderation rule action.
* @typedef {Object} AutoModerationAction
* @property {AutoModerationActionType} type The type of this auto moderation rule action
* @property {AutoModerationActionMetadata} metadata Additional metadata needed during execution
*/
/**
* Additional data used when an auto moderation rule is executed.
* @typedef {Object} AutoModerationActionMetadata
* @property {?Snowflake} channelId The id of the channel to which content will be logged
* @property {?number} durationSeconds The timeout duration in seconds
*/
/**
* The actions of this auto moderation rule.
* @type {AutoModerationAction[]}
*/
this.actions = data.actions.map(action => ({
type: AutoModerationActionTypes[action.type],
metadata: {
durationSeconds: action.metadata.duration_seconds ?? null,
channelId: action.metadata.channel_id ?? null,
},
}));
}
if ('enabled' in data) {
/**
* Whether this auto moderation rule is enabled.
* @type {boolean}
*/
this.enabled = data.enabled;
}
if ('exempt_roles' in data) {
/**
* The roles exempt by this auto moderation rule.
* @type {Collection<Snowflake, Role>}
*/
this.exemptRoles = new Collection(
data.exempt_roles.map(exemptRole => [exemptRole, this.guild.roles.cache.get(exemptRole)]),
);
}
if ('exempt_channels' in data) {
/**
* The channels exempt by this auto moderation rule.
* @type {Collection<Snowflake, GuildChannel|ThreadChannel>}
*/
this.exemptChannels = new Collection(
data.exempt_channels.map(exemptChannel => [exemptChannel, this.guild.channels.cache.get(exemptChannel)]),
);
}
}
/**
* Edits this auto moderation rule.
* @param {AutoModerationRuleEditOptions} options Options for editing this auto moderation rule
* @returns {Promise<AutoModerationRule>}
*/
edit(options) {
return this.guild.autoModerationRules.edit(this.id, options);
}
/**
* Deletes this auto moderation rule.
* @param {string} [reason] The reason for deleting this auto moderation rule
* @returns {Promise<void>}
*/
delete(reason) {
return this.guild.autoModerationRules.delete(this.id, reason);
}
/**
* Sets the name for this auto moderation rule.
* @param {string} name The name of this auto moderation rule
* @param {string} [reason] The reason for changing the name of this auto moderation rule
* @returns {Promise<AutoModerationRule>}
*/
setName(name, reason) {
return this.edit({ name, reason });
}
/**
* Sets the event type for this auto moderation rule.
* @param {AutoModerationRuleEventType} eventType The event type of this auto moderation rule
* @param {string} [reason] The reason for changing the event type of this auto moderation rule
* @returns {Promise<AutoModerationRule>}
*/
setEventType(eventType, reason) {
return this.edit({ eventType, reason });
}
/**
* Sets the keyword filter for this auto moderation rule.
* @param {string[]} keywordFilter The keyword filter of this auto moderation rule
* @param {string} [reason] The reason for changing the keyword filter of this auto moderation rule
* @returns {Promise<AutoModerationRule>}
*/
setKeywordFilter(keywordFilter, reason) {
return this.edit({ triggerMetadata: { ...this.triggerMetadata, keywordFilter }, reason });
}
/**
* Sets the regular expression patterns for this auto moderation rule.
* @param {string[]} regexPatterns The regular expression patterns of this auto moderation rule
* <info>Only Rust-flavored regular expressions are supported.</info>
* @param {string} [reason] The reason for changing the regular expression patterns of this auto moderation rule
* @returns {Promise<AutoModerationRule>}
*/
setRegexPatterns(regexPatterns, reason) {
return this.edit({ triggerMetadata: { ...this.triggerMetadata, regexPatterns }, reason });
}
/**
* Sets the presets for this auto moderation rule.
* @param {AutoModerationRuleKeywordPresetType[]} presets The presets of this auto moderation rule
* @param {string} [reason] The reason for changing the presets of this auto moderation rule
* @returns {Promise<AutoModerationRule>}
*/
setPresets(presets, reason) {
return this.edit({ triggerMetadata: { ...this.triggerMetadata, presets }, reason });
}
/**
* Sets the allow list for this auto moderation rule.
* @param {string[]} allowList The allow list of this auto moderation rule
* @param {string} [reason] The reason for changing the allow list of this auto moderation rule
* @returns {Promise<AutoModerationRule>}
*/
setAllowList(allowList, reason) {
return this.edit({ triggerMetadata: { ...this.triggerMetadata, allowList }, reason });
}
/**
* Sets the mention total limit for this auto moderation rule.
* @param {number} mentionTotalLimit The mention total limit of this auto moderation rule
* @param {string} [reason] The reason for changing the mention total limit of this auto moderation rule
* @returns {Promise<AutoModerationRule>}
*/
setMentionTotalLimit(mentionTotalLimit, reason) {
return this.edit({ triggerMetadata: { ...this.triggerMetadata, mentionTotalLimit }, reason });
}
/**
* Sets the actions for this auto moderation rule.
* @param {AutoModerationActionOptions} actions The actions of this auto moderation rule
* @param {string} [reason] The reason for changing the actions of this auto moderation rule
* @returns {Promise<AutoModerationRule>}
*/
setActions(actions, reason) {
return this.edit({ actions, reason });
}
/**
* Sets whether this auto moderation rule should be enabled.
* @param {boolean} [enabled=true] Whether to enable this auto moderation rule
* @param {string} [reason] The reason for enabling or disabling this auto moderation rule
* @returns {Promise<AutoModerationRule>}
*/
setEnabled(enabled = true, reason) {
return this.edit({ enabled, reason });
}
/**
* Sets the exempt roles for this auto moderation rule.
* @param {Collection<Snowflake, Role>|RoleResolvable[]} [exemptRoles] The exempt roles of this auto moderation rule
* @param {string} [reason] The reason for changing the exempt roles of this auto moderation rule
* @returns {Promise<AutoModerationRule>}
*/
setExemptRoles(exemptRoles, reason) {
return this.edit({ exemptRoles, reason });
}
/**
* Sets the exempt channels for this auto moderation rule.
* @param {Collection<Snowflake, GuildChannel|ThreadChannel>|GuildChannelResolvable[]} [exemptChannels]
* The exempt channels of this auto moderation rule
* @param {string} [reason] The reason for changing the exempt channels of this auto moderation rule
* @returns {Promise<AutoModerationRule>}
*/
setExemptChannels(exemptChannels, reason) {
return this.edit({ exemptChannels, reason });
}
}
module.exports = AutoModerationRule;

View File

@@ -10,6 +10,7 @@ const Integration = require('./Integration');
const Webhook = require('./Webhook');
const WelcomeScreen = require('./WelcomeScreen');
const { Error } = require('../errors');
const AutoModerationRuleManager = require('../managers/AutoModerationRuleManager');
const GuildBanManager = require('../managers/GuildBanManager');
const GuildChannelManager = require('../managers/GuildChannelManager');
const GuildEmojiManager = require('../managers/GuildEmojiManager');
@@ -111,6 +112,12 @@ class Guild extends AnonymousGuild {
*/
this.scheduledEvents = new GuildScheduledEventManager(this);
/**
* A manager of the auto moderation rules of this guild.
* @type {AutoModerationRuleManager}
*/
this.autoModerationRules = new AutoModerationRuleManager(this);
if (!data) return;
if (data.unavailable) {

View File

@@ -1,13 +1,14 @@
'use strict';
const { Collection } = require('@discordjs/collection');
const AutoModerationRule = require('./AutoModerationRule');
const { GuildScheduledEvent } = require('./GuildScheduledEvent');
const Integration = require('./Integration');
const Invite = require('./Invite');
const { StageInstance } = require('./StageInstance');
const { Sticker } = require('./Sticker');
const Webhook = require('./Webhook');
const { OverwriteTypes, PartialTypes } = require('../util/Constants');
const { OverwriteTypes, PartialTypes, AutoModerationRuleTriggerTypes } = require('../util/Constants');
const SnowflakeUtil = require('../util/SnowflakeUtil');
const Util = require('../util/Util');
@@ -26,6 +27,7 @@ const Util = require('../util/Util');
* * STICKER
* * THREAD
* * GUILD_SCHEDULED_EVENT
* * AUTO_MODERATION
* @typedef {string} AuditLogTargetType
*/
@@ -49,6 +51,7 @@ const Targets = {
STAGE_INSTANCE: 'STAGE_INSTANCE',
STICKER: 'STICKER',
THREAD: 'THREAD',
AUTO_MODERATION: 'AUTO_MODERATION',
UNKNOWN: 'UNKNOWN',
};
@@ -102,6 +105,12 @@ const Targets = {
* * THREAD_CREATE: 110
* * THREAD_UPDATE: 111
* * THREAD_DELETE: 112
* * AUTO_MODERATION_RULE_CREATE: 140
* * AUTO_MODERATION_RULE_UPDATE: 141
* * AUTO_MODERATION_RULE_DELETE: 142
* * AUTO_MODERATION_BLOCK_MESSAGE: 143
* * AUTO_MODERATION_FLAG_TO_CHANNEL: 144
* * AUTO_MODERATION_USER_COMMUNICATION_DISABLED: 145
* @typedef {?(number|string)} AuditLogAction
* @see {@link https://discord.com/developers/docs/resources/audit-log#audit-log-entry-object-audit-log-events}
*/
@@ -160,6 +169,12 @@ const Actions = {
THREAD_CREATE: 110,
THREAD_UPDATE: 111,
THREAD_DELETE: 112,
AUTO_MODERATION_RULE_CREATE: 140,
AUTO_MODERATION_RULE_UPDATE: 141,
AUTO_MODERATION_RULE_DELETE: 142,
AUTO_MODERATION_BLOCK_MESSAGE: 143,
AUTO_MODERATION_FLAG_TO_CHANNEL: 144,
AUTO_MODERATION_USER_COMMUNICATION_DISABLED: 145,
};
/**
@@ -193,6 +208,17 @@ class GuildAuditLogs {
}
}
/**
* Cached auto moderation rules.
* @type {Collection<Snowflake, AutoModerationRule>}
* @private
*/
this.autoModerationRules = data.auto_moderation_rules.reduce(
(autoModerationRules, autoModerationRule) =>
autoModerationRules.set(autoModerationRule.id, guild.autoModerationRules._add(autoModerationRule)),
new Collection(),
);
/**
* The entries for this guild's audit logs
* @type {Collection<Snowflake, GuildAuditLogsEntry>}
@@ -229,10 +255,11 @@ class GuildAuditLogs {
* * A sticker
* * A guild scheduled event
* * A thread
* * An auto moderation rule
* * An object with an id key if target was deleted
* * An object where the keys represent either the new value or the old value
* @typedef {?(Object|Guild|Channel|User|Role|Invite|Webhook|GuildEmoji|Message|Integration|StageInstance|Sticker|
* GuildScheduledEvent)} AuditLogEntryTarget
* GuildScheduledEvent|AutoModerationRule)} AuditLogEntryTarget
*/
/**
@@ -254,6 +281,7 @@ class GuildAuditLogs {
if (target < 100) return Targets.STICKER;
if (target < 110) return Targets.GUILD_SCHEDULED_EVENT;
if (target < 120) return Targets.THREAD;
if (target >= 140 && target < 150) return Targets.AUTO_MODERATION;
return Targets.UNKNOWN;
}
@@ -288,6 +316,8 @@ class GuildAuditLogs {
Actions.STICKER_CREATE,
Actions.GUILD_SCHEDULED_EVENT_CREATE,
Actions.THREAD_CREATE,
Actions.AUTO_MODERATION_RULE_CREATE,
Actions.AUTO_MODERATION_BLOCK_MESSAGE,
].includes(action)
) {
return 'CREATE';
@@ -313,6 +343,7 @@ class GuildAuditLogs {
Actions.STICKER_DELETE,
Actions.GUILD_SCHEDULED_EVENT_DELETE,
Actions.THREAD_DELETE,
Actions.AUTO_MODERATION_RULE_DELETE,
].includes(action)
) {
return 'DELETE';
@@ -335,6 +366,7 @@ class GuildAuditLogs {
Actions.STICKER_UPDATE,
Actions.GUILD_SCHEDULED_EVENT_UPDATE,
Actions.THREAD_UPDATE,
Actions.AUTO_MODERATION_RULE_UPDATE,
].includes(action)
) {
return 'UPDATE';
@@ -476,6 +508,15 @@ class GuildAuditLogsEntry {
};
break;
case Actions.AUTO_MODERATION_BLOCK_MESSAGE:
case Actions.AUTO_MODERATION_FLAG_TO_CHANNEL:
case Actions.AUTO_MODERATION_USER_COMMUNICATION_DISABLED:
this.extra = {
autoModerationRuleName: data.options.auto_moderation_rule_name,
autoModerationRuleTriggerType: AutoModerationRuleTriggerTypes[data.options.auto_moderation_rule_trigger_type],
};
break;
default:
break;
}
@@ -603,6 +644,20 @@ class GuildAuditLogsEntry {
{ id: data.target_id, guild_id: guild.id },
),
);
} else if (targetType === Targets.AUTO_MODERATION) {
this.target =
guild.autoModerationRules.cache.get(data.target_id) ??
new AutoModerationRule(
guild.client,
this.changes.reduce(
(o, c) => {
o[c.key] = c.new ?? c.old;
return o;
},
{ id: data.target_id, guild_id: guild.id },
),
guild,
);
} else if (data.target_id) {
this.target = guild[`${targetType.toLowerCase()}s`]?.cache.get(data.target_id) ?? { id: data.target_id };
}