Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for Auto Moderation feature #2035

Merged
merged 18 commits into from Jul 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
133 changes: 133 additions & 0 deletions src/builder/edit_automod_rule.rs
@@ -0,0 +1,133 @@
use std::collections::HashMap;

use crate::json::{json, Value};
use crate::model::guild::automod::{Action, EventType, Trigger};
use crate::model::id::{ChannelId, RoleId};

#[derive(Clone, Debug)]
pub struct EditAutoModRule(pub HashMap<&'static str, Value>);

impl EditAutoModRule {
/// The display name of the rule.
pub fn name<D: ToString>(&mut self, name: D) -> &mut Self {
self.0.insert("name", Value::from(name.to_string()));

self
}

/// Set the event context the rule should be checked.
pub fn event_type(&mut self, event_type: EventType) -> &mut Self {
self.0.insert("event_type", u8::from(event_type).into());

self
}

/// Set the type of content which can trigger the rule.
///
/// **None**: The trigger type can't be edited after creation. Only its values.
pub fn trigger(&mut self, trigger: Trigger) -> &mut Self {
self.0.insert("trigger_type", u8::from(trigger.kind()).into());

match trigger {
Trigger::Keyword(keyword_filter) => {
let value = json!({
"keyword_filter": keyword_filter,
});
self.0.insert("trigger_metadata", value);
},
Trigger::KeywordPreset(presets) => {
let value = json!({
"presets": presets,
});
self.0.insert("trigger_metadata", value);
},
_ => {},
}

self
}

/// Set the actions which will execute when the rule is triggered.
pub fn actions<I>(&mut self, actions: I) -> &mut Self
where
I: IntoIterator<Item = Action>,
{
let actions = actions
.into_iter()
.map(|action| {
let kind = action.kind();
match action {
Action::Alert(channel_id) => {
json!({
"type": kind,
"metadata": {
"channel_id": channel_id.0.to_string(),
},
})
},
Action::Timeout(duration) => {
json!({
"type": kind,
"metadata": {
"duration_seconds": duration,
},
})
},
Action::BlockMessage | Action::Unknown(_) => {
json!({
"type": kind,
})
},
}
})
.collect();

self.0.insert("actions", actions);

self
}

/// Set whether the rule is enabled.
pub fn enabled(&mut self, enabled: bool) -> &mut Self {
self.0.insert("enabled", Value::from(enabled));

self
}

/// Set roles that should not be affected by the rule.
///
/// Maximum of 20.
pub fn exempt_roles<I>(&mut self, roles: I) -> &mut Self
where
I: IntoIterator<Item = RoleId>,
{
let ids = roles.into_iter().map(|id| id.0.to_string()).collect();

self.0.insert("exempt_roles", ids);

self
}

/// Set channels that should not be affected by the rule.
///
/// Maximum of 50.
pub fn exempt_channels<I>(&mut self, channels: I) -> &mut Self
where
I: IntoIterator<Item = ChannelId>,
{
let ids = channels.into_iter().map(|id| id.0.to_string()).collect();

self.0.insert("exempt_channels", ids);

self
}
}

impl Default for EditAutoModRule {
fn default() -> Self {
let mut builder = Self(HashMap::new());
builder.event_type(EventType::MessageSend);

builder
}
}
2 changes: 2 additions & 0 deletions src/builder/mod.rs
Expand Up @@ -23,6 +23,7 @@ mod create_scheduled_event;
mod create_stage_instance;
mod create_sticker;
mod create_thread;
mod edit_automod_rule;
mod edit_channel;
mod edit_guild;
mod edit_guild_welcome_screen;
Expand Down Expand Up @@ -78,6 +79,7 @@ pub use self::create_scheduled_event::CreateScheduledEvent;
pub use self::create_stage_instance::CreateStageInstance;
pub use self::create_sticker::CreateSticker;
pub use self::create_thread::CreateThread;
pub use self::edit_automod_rule::EditAutoModRule;
pub use self::edit_channel::EditChannel;
pub use self::edit_guild::EditGuild;
pub use self::edit_guild_welcome_screen::EditGuildWelcomeScreen;
Expand Down
20 changes: 20 additions & 0 deletions src/client/dispatch.rs
Expand Up @@ -373,6 +373,26 @@ async fn handle_event(
},
);
},
Event::AutoModerationRuleCreate(event) => {
spawn_named("dispatch::event_handler::auto_moderation_rule_create", async move {
event_handler.auto_moderation_rule_create(context, event.rule).await;
});
},
Event::AutoModerationRuleUpdate(event) => {
spawn_named("dispatch::event_handler::auto_moderation_rule_update", async move {
event_handler.auto_moderation_rule_update(context, event.rule).await;
});
},
Event::AutoModerationRuleDelete(event) => {
spawn_named("dispatch::event_handler::auto_moderation_rule_delete", async move {
event_handler.auto_moderation_rule_delete(context, event.rule).await;
});
},
Event::AutoModerationActionExecution(event) => {
spawn_named("dispatch::event_handler::auto_moderation_action_execution", async move {
event_handler.auto_moderation_action_execution(context, event.execution).await;
});
},
Event::ChannelCreate(mut event) => {
update(&cache_and_http, &mut event);
match event.channel {
Expand Down
21 changes: 21 additions & 0 deletions src/client/event_handler.rs
Expand Up @@ -7,6 +7,7 @@ use crate::client::bridge::gateway::event::*;
use crate::json::Value;
use crate::model::application::command::CommandPermission;
use crate::model::application::interaction::Interaction;
use crate::model::guild::automod::{ActionExecution, Rule};
use crate::model::prelude::*;

/// The core trait for handling events by serenity.
Expand All @@ -22,6 +23,26 @@ pub trait EventHandler: Send + Sync {
) {
}

/// Dispatched when an auto moderation rule was created.
///
/// Provides said rule's data.
async fn auto_moderation_rule_create(&self, _ctx: Context, _rule: Rule) {}

/// Dispatched when an auto moderation rule was updated.
///
/// Provides said rule's data.
async fn auto_moderation_rule_update(&self, _ctx: Context, _rule: Rule) {}

/// Dispatched when an auto moderation rule was deleted.
///
/// Provides said rule's data.
async fn auto_moderation_rule_delete(&self, _ctx: Context, _rule: Rule) {}

/// Dispatched when an auto moderation rule was triggered and an action was executed.
///
/// Provides said action execution's data.
async fn auto_moderation_action_execution(&self, _ctx: Context, _execution: ActionExecution) {}

/// Dispatched when the cache has received and inserted all data from
/// guilds.
///
Expand Down
88 changes: 88 additions & 0 deletions src/http/client.rs
Expand Up @@ -22,6 +22,7 @@ use super::{AttachmentType, GuildPagination, HttpError, UserPagination};
use crate::internal::prelude::*;
use crate::json::prelude::*;
use crate::model::application::command::{Command, CommandPermission};
use crate::model::guild::automod::Rule;
use crate::model::prelude::*;
use crate::{constants, utils};

Expand Down Expand Up @@ -2409,6 +2410,93 @@ impl Http {
.await
}

/// Retrieves all auto moderation rules in a guild.
///
/// This method requires `MANAGE_GUILD` permissions.
pub async fn get_automod_rules(&self, guild_id: u64) -> Result<Vec<Rule>> {
self.fire(Request {
body: None,
multipart: None,
headers: None,
route: RouteInfo::GetAutoModRules {
guild_id,
},
})
.await
}

/// Retrieves an auto moderation rule in a guild.
///
/// This method requires `MANAGE_GUILD` permissions.
pub async fn get_automod_rule(&self, guild_id: u64, rule_id: u64) -> Result<Rule> {
self.fire(Request {
body: None,
multipart: None,
headers: None,
route: RouteInfo::GetAutoModRule {
guild_id,
rule_id,
},
})
.await
}

/// Creates an auto moderation rule in a guild.
///
/// This method requires `MANAGE_GUILD` permissions.
pub async fn create_automod_rule(&self, guild_id: u64, map: &JsonMap) -> Result<Rule> {
let body = to_vec(&map)?;

self.fire(Request {
body: Some(&body),
multipart: None,
headers: None,
route: RouteInfo::CreateAutoModRule {
guild_id,
},
})
.await
}

/// Retrieves an auto moderation rule in a guild.
///
/// This method requires `MANAGE_GUILD` permissions.
pub async fn edit_automod_rule(
&self,
guild_id: u64,
rule_id: u64,
map: &JsonMap,
) -> Result<Rule> {
let body = to_vec(&map)?;

self.fire(Request {
body: Some(&body),
multipart: None,
headers: None,
route: RouteInfo::EditAutoModRule {
guild_id,
rule_id,
},
})
.await
}

/// Deletes an auto moderation rule in a guild.
///
/// This method requires `MANAGE_GUILD` permissions.
pub async fn delete_automod_rule(&self, guild_id: u64, rule_id: u64) -> Result<()> {
self.wind(204, Request {
body: None,
multipart: None,
headers: None,
route: RouteInfo::DeleteAutoModRule {
guild_id,
rule_id,
},
})
.await
}

/// Gets current bot gateway.
pub async fn get_bot_gateway(&self) -> Result<BotGateway> {
self.fire(Request {
Expand Down