Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.
Rust desktop-appdiscorddiscord-clienteguielectron-alternativelightweightlinuxmacosnative-apprustwindows
//! Server Settings → Safety Setup, Audit Log and AutoMod.
//!
//! Like Discord's Safety page, every control here saves the moment it's
//! changed (the AutoMod rule editor has its own Save). Page state lives in
//! egui's temp memory; what Discord sends stays in `api_results` under
//! "ss:<page>:{guild}" tags and is fetched again on each visit. This file
//! also holds the helpers the Community pages (`ss_community.rs`) share:
//! server PATCHes, answers to calls, option cards and dialogs.
use super::{
bold_font, btn, channel_combo, combo, empty_state, help, input, link, radio, section, switch_row, tag_guild, title, vid, vstr,
vu64, Act, Btn, Theme,
};
use crate::app::RustCord;
use crate::style::{bold, icon, icon_font, overlay};
use discord::model::{channel_kind, Id, User};
use eframe::egui::{
self, epaint::Shadow, pos2, text::LayoutJob, vec2, Align, Align2, Color32, CursorIcon, FontId, Frame, Key, LayerId, Layout,
Margin, Order, Rect, Response, RichText, Rounding, Sense, Stroke, TextFormat, Ui, WidgetText,
};
use reqwest::Method;
use serde::Deserialize;
use serde_json::{json, Map, Value};
use std::collections::HashSet;
// ---- shared with the Community pages ---------------------------------------------------------
/// An [`Act`] that runs `f` with `&mut RustCord` once the frame is drawn.
pub(super) fn run(f: impl FnOnce(&mut RustCord) + 'static) -> Act {
Act::Run(Box::new(f))
}
/// True on the first frame a page shows after it wasn't showing (a new
/// visit): when its data is fetched again.
pub(super) fn first_frame(ui: &Ui, page: &str, g: Id) -> bool {
let id = egui::Id::new(("ss_visit", page, g.0));
let pass = ui.ctx().cumulative_pass_nr();
let last = ui.data_mut(|d| {
let last = d.get_temp::<u64>(id);
d.insert_temp(id, pass);
last
});
last.map_or(true, |l| pass > l + 1)
}
fn tag_guild_patch(g: Id) -> String {
format!("ss:guild-patch:{g}")
}
/// PATCH the server with `body`. The answer (the whole server) replaces
/// the cached GET /guilds/{g}; see [`RustCord::poll_guild_patch`].
pub(super) fn patch_guild(acts: &mut Vec<Act>, g: Id, body: Value) {
acts.push(run(move |app| app.api(&tag_guild_patch(g), Method::PATCH, format!("/guilds/{g}"), Some(body))));
}
/// Is `feature` in a server object's `features`?
pub(super) fn has_feature(v: &Value, feature: &str) -> bool {
v["features"].as_array().is_some_and(|a| a.iter().any(|f| f.as_str() == Some(feature)))
}
/// The server's features with `on` added and `off` taken out. Discord
/// wants the whole list back when one of them changes.
pub(super) fn features_with(v: &Value, on: &[&str], off: &[&str]) -> Value {
let mut list: Vec<&str> =
v["features"].as_array().into_iter().flatten().filter_map(Value::as_str).filter(|f| !off.contains(f) && !on.contains(f)).collect();
list.extend_from_slice(on);
json!(list)
}
/// A page heading inside a settings page ("Verification Level").
pub(super) fn heading(ui: &mut Ui, t: &Theme, text: &str) {
ui.label(bold(text).size(16.0).color(t.header_primary));
ui.add_space(6.0);
}
/// A choice with a description under it (verification levels, join modes).
pub(super) fn option_card(ui: &mut Ui, t: &Theme, label: &str, desc: &str, on: bool, enabled: bool) -> Response {
let w = ui.available_width();
let dim = |c: Color32| if enabled { c } else { c.gamma_multiply(0.5) };
let desc = ui.painter().layout(desc.to_string(), FontId::proportional(13.0), dim(t.text_muted), (w - 60.0).max(80.0));
let (r, resp) = ui.allocate_exact_size(vec2(w, 46.0 + desc.size().y), if enabled { Sense::click() } else { Sense::hover() });
if ui.is_rect_visible(r) {
let fill = if on {
overlay(0.16)
} else if enabled && resp.hovered() {
overlay(0.12)
} else {
overlay(0.06)
};
ui.painter().rect_filled(r, 8.0, fill);
let c = pos2(r.left() + 22.0, r.top() + 22.0);
ui.painter().circle_stroke(c, 9.0, Stroke::new(2.0_f32, dim(if on { t.header_primary } else { t.interactive_normal })));
if on {
ui.painter().circle_filled(c, 5.0, dim(t.header_primary));
}
ui.painter().text(pos2(r.left() + 44.0, c.y), Align2::LEFT_CENTER, label, FontId::proportional(15.0), dim(t.header_primary));
ui.painter().galley(pos2(r.left() + 44.0, r.top() + 34.0), desc, t.text_muted);
}
ui.add_space(8.0);
if enabled {
resp.on_hover_cursor(CursorIcon::PointingHand)
} else {
resp
}
}
/// Keep Escape for the open dialog: Server Settings closes on Escape only
/// while no popup is open, so the dialog holds a popup marker.
fn hold_escape(ctx: &egui::Context, marker: egui::Id) {
ctx.memory_mut(|m| {
if !m.any_popup_open() {
m.open_popup(marker);
}
});
}
/// Give Escape back once the dialog `key` is gone.
pub(super) fn release_escape(ui: &Ui, key: &str) {
let marker = egui::Id::new(("ss_dialog", key));
ui.memory_mut(|m| {
if m.is_popup_open(marker) {
m.close_popup();
}
});
}
/// Discord's centred dialog over the dimmed screen: `body` padded on top,
/// `footer` right to left in the darker strip under it. Returns true when
/// it asks to close (a click outside, or Escape).
pub(super) fn dialog(ui: &Ui, t: &Theme, key: &str, width: f32, body: impl FnOnce(&mut Ui), footer: impl FnOnce(&mut Ui)) -> bool {
let ctx = ui.ctx().clone();
let marker = egui::Id::new(("ss_dialog", key));
hold_escape(&ctx, marker);
let mut close = ctx.input(|i| i.key_pressed(Key::Escape)) && ctx.memory(|m| m.is_popup_open(marker));
// Stay above the settings screen, but under a dropdown opened inside.
if ctx.memory(|m| m.is_popup_open(marker)) {
ctx.move_to_top(LayerId::new(Order::Foreground, marker.with("dim")));
ctx.move_to_top(LayerId::new(Order::Foreground, marker));
}
let screen = ctx.screen_rect();
egui::Area::new(marker.with("dim")).order(Order::Foreground).fixed_pos(screen.min).constrain(false).show(&ctx, |ui| {
let (r, resp) = ui.allocate_exact_size(screen.size(), Sense::click());
ui.painter().rect_filled(r, 0.0, Color32::from_black_alpha(170));
close |= resp.clicked();
});
egui::Area::new(marker).order(Order::Foreground).anchor(Align2::CENTER_CENTER, vec2(0.0, 0.0)).show(&ctx, |ui| {
Frame::none()
.fill(t.bg_primary)
.rounding(12.0)
.stroke(Stroke::new(1.0_f32, t.border_subtle))
.shadow(Shadow { offset: vec2(0.0, 8.0), blur: 24.0, spread: 0.0, color: Color32::from_black_alpha(140) })
.show(ui, |ui| {
ui.set_width(width);
ui.spacing_mut().item_spacing.y = 0.0;
Frame::none().inner_margin(Margin { left: 16.0, right: 16.0, top: 20.0, bottom: 20.0 }).show(ui, |ui| {
ui.set_width(ui.available_width());
body(ui);
});
Frame::none()
.fill(t.bg_secondary)
.rounding(Rounding { nw: 0.0, ne: 0.0, sw: 12.0, se: 12.0 })
.inner_margin(Margin::symmetric(16.0, 14.0))
.show(ui, |ui| {
ui.set_width(ui.available_width());
ui.with_layout(Layout::right_to_left(Align::Center), footer);
});
});
});
if close {
release_escape(ui, key);
}
close
}
impl RustCord {
/// Hand the answer under `tag`, once it's in, to `done` (after the
/// frame, with `&mut RustCord`).
pub(super) fn on_answer(&self, acts: &mut Vec<Act>, tag: String, done: impl FnOnce(&mut RustCord, Result<Value, String>) + 'static) {
if self.api_result(&tag).is_some() {
acts.push(run(move |app| {
if let Some(r) = app.api_take(&tag) {
done(app, r);
}
}));
}
}
/// GET `path` under `tag` unless it's loaded or loading.
pub(super) fn ss_want(&self, acts: &mut Vec<Act>, tag: String, path: String) {
if self.api_result(&tag).is_none() && !self.api_busy(&tag) {
acts.push(run(move |app| app.api_get_once(&tag, path)));
}
}
/// A server PATCH from [`patch_guild`] is on its way.
pub(super) fn guild_saving(&self, g: Id) -> bool {
self.api_busy(&tag_guild_patch(g))
}
/// Deal with the answer to [`patch_guild`] (every page that patches calls this).
pub(super) fn poll_guild_patch(&self, acts: &mut Vec<Act>, g: Id) {
self.on_answer(acts, tag_guild_patch(g), move |app, r| match r {
Ok(v) => app.ss_guild_changed(g, v),
Err(e) => app.toast(format!("Couldn't save the server settings: {e}"), true),
});
}
/// A fresh server object from Discord: every page reads it from the
/// cache, and the store takes its features (the sidebar's Community
/// entry and Insights page go by them).
pub(super) fn ss_guild_changed(&mut self, g: Id, v: Value) {
if let Some(gs) = self.store.guilds.get_mut(&g) {
gs.guild.apply_extras(&v);
}
self.api_results.insert(tag_guild(g), Ok(v));
}
/// "Sensitive content filters" (Safety Setup and AutoMod): saves on click.
pub(super) fn ss_content_filter(&self, ui: &mut Ui, t: &Theme, acts: &mut Vec<Act>, g: Id, v: &Value) {
heading(ui, t, "Sensitive content filters");
help(
ui,
t,
"Choose if server members can share image-based media detected by Discord's sensitive content filters. This setting will apply to channels that are not age-restricted.",
);
ui.add_space(12.0);
let current = vu64(v, "explicit_content_filter");
ui.add_enabled_ui(!self.guild_saving(g), |ui| {
for (n, label) in [(0u64, "Do not filter"), (1, "Filter messages from server members without roles"), (2, "Filter messages from all members")] {
if radio(ui, t, label, current == n) && current != n {
patch_guild(acts, g, json!({ "explicit_content_filter": n }));
}
}
});
}
/// Activity Alerts and the Safety Notifications channel (Safety Setup and
/// Community Overview). Discord: a non-Community server has alerts on
/// with NON_COMMUNITY_RAID_ALERTS, a Community one unless RAID_ALERTS_DISABLED.
pub(super) fn ss_activity_alerts(&self, ui: &mut Ui, t: &Theme, acts: &mut Vec<Act>, g: Id, v: &Value) {
let channel = vid(v, "safety_alerts_channel_id");
let on = alerts_on(v);
let busy = self.guild_saving(g);
ui.add_enabled_ui(!busy && (on || channel.is_some()), |ui| {
let mut want = on;
let desc = "Receive notifications for DM or join activity that exceeds usual numbers for your server. Each notification will contain information about the activity, including time period and approximate number of joins or DMs.";
if switch_row(ui, t, "Activity Alerts", Some(desc), &mut want) {
patch_guild(acts, g, json!({ "features": alerts_features(v, want) }));
}
});
if channel.is_none() {
help(ui, t, "Select a channel to turn on Activity Alerts.");
ui.add_space(12.0);
}
section(ui, t, "SAFETY NOTIFICATIONS CHANNEL");
let text = self.ss_guild_channels(g, |k| k == channel_kind::GUILD_TEXT);
let mut pick = channel;
ui.add_enabled_ui(!busy, |ui| channel_combo(ui, t, "ss_safety_alerts_channel", &mut pick, &text, "Select a channel", false));
if pick != channel {
// Picking a channel turns alerts on; clearing it turns them off.
patch_guild(acts, g, json!({ "safety_alerts_channel_id": super::opt_id(pick), "features": alerts_features(v, pick.is_some()) }));
}
ui.add_space(8.0);
help(ui, t, "Anyone with access to this text channel will be able to see the notifications.");
}
}
fn alerts_on(v: &Value) -> bool {
if has_feature(v, "COMMUNITY") {
!has_feature(v, "RAID_ALERTS_DISABLED")
} else {
has_feature(v, "NON_COMMUNITY_RAID_ALERTS")
}
}
fn alerts_features(v: &Value, on: bool) -> Value {
match (has_feature(v, "COMMUNITY"), on) {
(true, true) => features_with(v, &[], &["RAID_ALERTS_DISABLED"]),
(true, false) => features_with(v, &["RAID_ALERTS_DISABLED"], &[]),
(false, true) => features_with(v, &["NON_COMMUNITY_RAID_ALERTS"], &[]),
(false, false) => features_with(v, &[], &["NON_COMMUNITY_RAID_ALERTS"]),
}
}
// ---- Safety Setup ------------------------------------------------------------------------------
/// Discord's verification levels: (level, name, what it asks of members).
const VERIFICATION: &[(u64, &str, &str)] = &[
(0, "None", "Unrestricted"),
(1, "Low", "Must have a verified email on their Discord account."),
(2, "Medium", "Must also be registered on Discord for longer than 5 minutes."),
(3, "High", "Must also be a member of this server for longer than 10 minutes."),
(4, "Highest", "Must have a verified phone on their Discord account."),
];
fn tag_mfa(g: Id) -> String {
format!("ss:mfa:{g}")
}
fn mfa_error_id(g: Id) -> egui::Id {
egui::Id::new(("ss_mfa_error", g.0))
}
impl RustCord {
pub(super) fn ss_safety(&self, ui: &mut Ui, t: &Theme, acts: &mut Vec<Act>, g: Id) {
title(ui, t, "Safety Setup");
self.poll_guild_patch(acts, g);
self.on_answer(acts, tag_mfa(g), move |app, r| app.ss_mfa_done(g, r));
let (tag, path) = (tag_guild(g), format!("/guilds/{g}"));
self.ss_want(acts, tag.clone(), path.clone());
let Some(v) = self.ss_loaded(ui, t, &tag, &path, acts) else { return };
let busy = self.guild_saving(g);
heading(ui, t, "Verification Level");
help(
ui,
t,
"Members of the server must meet the following criteria before they can send messages in text channels or initiate a direct message conversation. If a member has an assigned role and server onboarding is not enabled, this does not apply. We recommend setting a verification level for a Community Server.",
);
ui.add_space(12.0);
let level = vu64(v, "verification_level");
// Discord: a Community server needs at least Low.
let community = has_feature(v, "COMMUNITY");
for &(n, name, desc) in VERIFICATION {
let allowed = !busy && !(community && n == 0);
let resp = option_card(ui, t, name, desc, level == n, allowed);
if community && n == 0 {
resp.on_hover_text("Community servers need a verification level of at least Low.");
} else if resp.clicked() && level != n {
patch_guild(acts, g, json!({ "verification_level": n }));
}
}
super::divider(ui, t);
let owner = self.ss_is_owner(g);
let sending = self.api_busy(&tag_mfa(g));
ui.add_enabled_ui(owner && !sending, |ui| {
let mut on = vu64(v, "mfa_level") == 1;
let desc = "Moderators must have two-factor authentication enabled to ban, kick or time-out members and delete messages. Only the server owner can change this setting if they have 2FA enabled.";
if switch_row(ui, t, "Require 2FA for moderator actions", Some(desc), &mut on) {
ui.data_mut(|d| d.remove::<String>(mfa_error_id(g)));
let body = json!({ "level": u8::from(on) });
acts.push(run(move |app| app.api(&tag_mfa(g), Method::POST, format!("/guilds/{g}/mfa"), Some(body))));
}
});
if let Some(e) = ui.data(|d| d.get_temp::<String>(mfa_error_id(g))) {
ui.label(RichText::new(e).size(13.0).color(t.danger));
}
super::divider(ui, t);
self.ss_content_filter(ui, t, acts, g, v);
super::divider(ui, t);
self.ss_activity_alerts(ui, t, acts, g, v);
}
/// The answer to POST /guilds/{g}/mfa: Discord sends the new level.
fn ss_mfa_done(&mut self, g: Id, r: Result<Value, String>) {
match r {
Ok(v) => {
let level = v.as_u64().or_else(|| v["level"].as_u64());
if let (Some(level), Some(Ok(guild))) = (level, self.api_results.get_mut(&tag_guild(g))) {
guild["mfa_level"] = json!(level);
}
}
Err(e) => {
let lower = e.to_lowercase();
// Discord asks the owner to confirm with their 2FA code (60003),
// which only its own client can prompt for.
let text = if lower.contains("two factor") || lower.contains("two-factor") || lower.contains("mfa") || e.contains("60003") {
format!("Discord wants your two-factor code to change this, which RustCord can't ask for yet. Change it on discord.com. ({e})")
} else {
format!("Couldn't change the 2FA requirement: {e}")
};
self.ctx.data_mut(|d| d.insert_temp(mfa_error_id(g), text.clone()));
self.toast(text, true);
}
}
}
}
// ---- Audit Log ------------------------------------------------------------------------------------
/// Entries per page (Discord's own client asks for 50).
const AUDIT_PAGE: usize = 50;
/// Discord's "Filter by Action" list: (action_type, label).
const ACTIONS: &[(u64, &str)] = &[
(1, "Update Server"),
(10, "Create Channel"),
(11, "Update Channel"),
(12, "Delete Channel"),
(13, "Create Channel Permissions"),
(14, "Update Channel Permissions"),
(15, "Delete Channel Permissions"),
(20, "Kick Member"),
(21, "Prune Members"),
(22, "Ban Member"),
(23, "Unban Member"),
(24, "Update Member"),
(25, "Update Member Roles"),
(26, "Move Member"),
(27, "Disconnect Member"),
(28, "Add Bot"),
(30, "Create Role"),
(31, "Update Role"),
(32, "Delete Role"),
(40, "Create Invite"),
(41, "Update Invite"),
(42, "Delete Invite"),
(50, "Create Webhook"),
(51, "Update Webhook"),
(52, "Delete Webhook"),
(60, "Create Emoji"),
(61, "Update Emoji"),
(62, "Delete Emoji"),
(72, "Delete Message"),
(73, "Bulk Delete Messages"),
(74, "Pin Message"),
(75, "Unpin Message"),
(80, "Add Integration"),
(81, "Update Integration"),
(82, "Remove Integration"),
(83, "Start Stage"),
(84, "Update Stage"),
(85, "End Stage"),
(90, "Create Sticker"),
(91, "Update Sticker"),
(92, "Delete Sticker"),
(100, "Create Event"),
(101, "Update Event"),
(102, "Cancel Event"),
(110, "Create Thread"),
(111, "Update Thread"),
(112, "Delete Thread"),
(121, "Update Command Permissions"),
(130, "Create Sound"),
(131, "Update Sound"),
(132, "Delete Sound"),
(140, "Create AutoMod Rule"),
(141, "Update AutoMod Rule"),
(142, "Delete AutoMod Rule"),
(143, "AutoMod Block Message"),
(144, "AutoMod Flag to Channel"),
(145, "AutoMod Timeout Member"),
(192, "Set Voice Channel Status"),
(193, "Clear Voice Channel Status"),
];
#[derive(Clone, Default)]
struct AuditUi {
user: Option<Id>,
action: Option<u64>,
/// Entries showing their changes.
open: HashSet<Id>,
/// The page on its way is "Load More" (added to the list, not replacing it).
appending: bool,
/// The last page was full: there may be older entries.
more: bool,
}
fn audit_id(g: Id) -> egui::Id {
egui::Id::new(("ss_audit", g.0))
}
/// Everything loaded so far, pages merged.
fn tag_audit(g: Id) -> String {
format!("ss:audit:{g}")
}
/// The page on its way.
fn tag_audit_page(g: Id) -> String {
format!("ss:audit-page:{g}")
}
/// Everyone the log has mentioned, for "Filter by User".
fn tag_audit_users(g: Id) -> String {
format!("ss:audit-users:{g}")
}
fn audit_path(g: Id, st: &AuditUi, before: Option<Id>) -> String {
let mut p = format!("/guilds/{g}/audit-logs?limit={AUDIT_PAGE}");
if let Some(b) = before {
p.push_str(&format!("&before={b}"));
}
if let Some(u) = st.user {
p.push_str(&format!("&user_id={u}"));
}
if let Some(a) = st.action {
p.push_str(&format!("&action_type={a}"));
}
p
}
/// Fetch the newest page (again) for the current filters.
fn audit_reload(acts: &mut Vec<Act>, g: Id, st: &mut AuditUi) {
st.appending = false;
let path = audit_path(g, st, None);
acts.push(run(move |app| app.api(&tag_audit_page(g), Method::GET, path, None)));
}
impl RustCord {
pub(super) fn ss_audit_log(&self, ui: &mut Ui, t: &Theme, acts: &mut Vec<Act>, g: Id) {
title(ui, t, "Audit Log");
let sid = audit_id(g);
let mut st: AuditUi = ui.data(|d| d.get_temp(sid)).unwrap_or_default();
self.on_answer(acts, tag_audit_page(g), move |app, r| app.ss_audit_page_in(g, r));
if first_frame(ui, "audit", g) {
st.open.clear();
audit_reload(acts, g, &mut st);
}
self.ss_audit_body(ui, t, acts, g, &mut st);
ui.data_mut(|d| d.insert_temp(sid, st));
}
/// A page of the log came in: replace the list, or add to it ("Load More").
fn ss_audit_page_in(&mut self, g: Id, r: Result<Value, String>) {
let sid = audit_id(g);
let mut st: AuditUi = self.ctx.data(|d| d.get_temp(sid)).unwrap_or_default();
match r {
Ok(v) => {
st.more = v["audit_log_entries"].as_array().is_some_and(|a| a.len() >= AUDIT_PAGE);
let users = self.api_results.entry(tag_audit_users(g)).or_insert_with(|| Ok(json!([])));
if let Ok(Value::Array(known)) = users {
for u in v["users"].as_array().into_iter().flatten() {
if !known.iter().any(|k| k["id"] == u["id"]) {
known.push(u.clone());
}
}
}
match self.api_results.get_mut(&tag_audit(g)) {
Some(Ok(main)) if st.appending => merge_log(main, v),
_ => {
self.api_results.insert(tag_audit(g), Ok(v));
}
}
}
Err(e) if st.appending => self.toast(format!("Couldn't load more of the audit log: {e}"), true),
Err(e) => {
self.api_results.insert(tag_audit(g), Err(e));
}
}
st.appending = false;
self.ctx.data_mut(|d| d.insert_temp(sid, st));
}
fn ss_audit_body(&self, ui: &mut Ui, t: &Theme, acts: &mut Vec<Act>, g: Id, st: &mut AuditUi) {
// Filters.
let users = match self.api_result(&tag_audit_users(g)) {
Some(Ok(Value::Array(a))) => a.as_slice(),
_ => &[],
};
let mut changed = false;
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 16.0;
ui.vertical(|ui| {
section(ui, t, "FILTER BY USER");
let shown = match st.user {
Some(id) => self.ss_user_name(users, id),
None => "All Users".to_string(),
};
combo(ui, "ss_audit_user", 220.0, WidgetText::from(shown), |ui| {
if ui.selectable_label(st.user.is_none(), "All Users").clicked() {
st.user = None;
changed = true;
}
for u in users {
let Some(id) = vid(u, "id") else { continue };
if ui.selectable_label(st.user == Some(id), user_label(u)).clicked() {
st.user = Some(id);
changed = true;
}
}
});
});
ui.vertical(|ui| {
section(ui, t, "FILTER BY ACTION");
let shown = st.action.and_then(|a| ACTIONS.iter().find(|(n, _)| *n == a)).map_or("All Actions", |(_, l)| *l);
combo(ui, "ss_audit_action", 220.0, WidgetText::from(shown), |ui| {
if ui.selectable_label(st.action.is_none(), "All Actions").clicked() {
st.action = None;
changed = true;
}
for &(n, label) in ACTIONS {
if ui.selectable_label(st.action == Some(n), label).clicked() {
st.action = Some(n);
changed = true;
}
}
});
});
});
if changed {
st.open.clear();
audit_reload(acts, g, st);
}
ui.add_space(20.0);
// A new first page on its way: don't show the old list meanwhile.
if self.api_busy(&tag_audit_page(g)) && !st.appending {
ui.horizontal(|ui| {
ui.spinner();
ui.label(RichText::new("Loading…").color(t.text_muted));
});
return;
}
let log = match self.api_result(&tag_audit(g)) {
Some(Ok(v)) => v,
Some(Err(e)) => {
ui.label(RichText::new(format!("Couldn't load the audit log: {e}")).color(t.danger));
ui.add_space(8.0);
if btn(ui, t, Btn::Secondary, "Try Again", true).clicked() {
audit_reload(acts, g, st);
}
return;
}
None => return,
};
let entries: &[Value] = log["audit_log_entries"].as_array().map(Vec::as_slice).unwrap_or(&[]);
if entries.is_empty() {
empty_state(ui, t, "No Logs Yet", "Once moderators begin moderating, you can moderate the moderation here.");
return;
}
for e in entries {
self.ss_audit_row(ui, t, g, log, e, st);
}
if st.more {
ui.add_space(8.0);
if st.appending {
ui.spinner();
} else if btn(ui, t, Btn::Secondary, "Load More", true).clicked() {
let last = entries.last().and_then(|e| vid(e, "id"));
st.appending = true;
let path = audit_path(g, st, last);
acts.push(run(move |app| app.api(&tag_audit_page(g), Method::GET, path, None)));
}
}
}
/// One entry: who did what and when; click to see the changes and reason.
fn ss_audit_row(&self, ui: &mut Ui, t: &Theme, g: Id, log: &Value, e: &Value, st: &mut AuditUi) {
let id = vid(e, "id").unwrap_or_default();
let open = st.open.contains(&id);
let details = e["changes"].as_array().is_some_and(|c| !c.is_empty()) || !vstr(e, "reason").is_empty();
let w = ui.available_width();
let (row, resp) = ui.allocate_exact_size(vec2(w, 60.0), if details { Sense::click() } else { Sense::hover() });
let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
if ui.is_rect_visible(row) {
let rounding = if open { Rounding { nw: 8.0, ne: 8.0, sw: 0.0, se: 0.0 } } else { Rounding::same(8.0) };
ui.painter().rect_filled(row, rounding, if details && resp.hovered() { t.bg_hover } else { t.bg_secondary });
// Green for things made, yellow for changes, red for removals.
let tone = match action_tone(vu64(e, "action_type")) {
0 => Color32::from_rgb(0x23, 0xa5, 0x5a),
1 => Color32::from_rgb(0xf0, 0xb2, 0x32),
_ => t.danger,
};
ui.painter().rect_filled(Rect::from_min_size(row.min, vec2(4.0, row.height())), Rounding { nw: 8.0, sw: if open { 0.0 } else { 8.0 }, ne: 0.0, se: 0.0 }, tone);
// AutoMod's own actions read "AutoMod blocked a message by …".
let actor = vid(e, "user_id").filter(|_| !(143..=145).contains(&vu64(e, "action_type")));
let av = Rect::from_center_size(pos2(row.left() + 32.0, row.center().y), vec2(32.0, 32.0));
let user = actor.and_then(|a| find(log, "users", a)).and_then(|u| User::deserialize(u).ok());
let actor_name = match actor {
Some(a) => self.ss_user_name(log["users"].as_array().map(Vec::as_slice).unwrap_or(&[]), a),
None if (143..=145).contains(&vu64(e, "action_type")) => "AutoMod".to_string(),
None => "Someone".to_string(),
};
super::super::paint_avatar(ui, av, user.map(|u| u.avatar_or_default(64)), &actor_name);
let mut parts = vec![(actor_name, true)];
parts.extend(self.ss_audit_says(g, log, e).0);
let text_left = av.right() + 12.0;
let mut job = LayoutJob::default();
for (text, strong) in &parts {
let (font, color) = if *strong { (bold_font(15.0), t.header_primary) } else { (FontId::proportional(15.0), t.text_normal) };
job.append(text, 0.0, TextFormat { font_id: font, color, ..Default::default() });
}
job.wrap.max_width = row.right() - 48.0 - text_left;
job.wrap.max_rows = 1;
job.wrap.break_anywhere = true;
let galley = ui.painter().layout_job(job);
ui.painter().galley(pos2(text_left, row.center().y - 19.0), galley, t.text_normal);
let when = when_label(id.timestamp_ms());
ui.painter().text(pos2(text_left, row.center().y + 11.0), Align2::LEFT_CENTER, when, FontId::proportional(12.0), t.text_muted);
if details {
let glyph = if open { icon::CHEVRON_DOWN } else { icon::CHEVRON };
ui.painter().text(pos2(row.right() - 22.0, row.center().y), Align2::CENTER_CENTER, glyph, icon_font(12.0), t.interactive_normal);
}
}
if details && resp.on_hover_cursor(CursorIcon::PointingHand).clicked() {
if open {
st.open.remove(&id);
} else {
st.open.insert(id);
}
}
if open {
Frame::none().fill(t.bg_tertiary).rounding(Rounding { nw: 0.0, ne: 0.0, sw: 8.0, se: 8.0 }).inner_margin(Margin::symmetric(16.0, 12.0)).show(ui, |ui| {
ui.set_width(ui.available_width());
ui.spacing_mut().item_spacing.y = 6.0;
for c in e["changes"].as_array().into_iter().flatten() {
let key = vstr(c, "key");
let (old, new) = (c.get("old_value"), c.get("new_value"));
let text = match key {
"$add" => format!("Added roles: {}", show_value(new.unwrap_or(&Value::Null))),
"$remove" => format!("Removed roles: {}", show_value(new.unwrap_or(&Value::Null))),
_ => match (old, new) {
(Some(o), Some(n)) => format!("{}: {} → {}", key_label(key), show_value(o), show_value(n)),
(None, Some(n)) => format!("{}: {}", key_label(key), show_value(n)),
(Some(o), None) => format!("{}: {} → none", key_label(key), show_value(o)),
(None, None) => key_label(key),
},
};
ui.label(RichText::new(text).size(14.0).color(t.text_normal));
}
let reason = vstr(e, "reason");
if !reason.is_empty() {
ui.horizontal_wrapped(|ui| {
ui.label(bold("Reason:").size(14.0).color(t.header_primary));
ui.label(RichText::new(reason).size(14.0).color(t.text_normal));
});
}
});
}
ui.add_space(8.0);
}
/// A user's name from a list Discord sent (else the store).
fn ss_user_name(&self, users: &[Value], id: Id) -> String {
if let Some(u) = users.iter().find(|u| vid(u, "id") == Some(id)) {
return user_label(u).to_string();
}
self.store.users.get(&id).map_or_else(|| "Unknown User".to_string(), |u| u.username.clone())
}
/// What an entry says after the name of who did it: " banned ", "spammer".
fn ss_audit_says(&self, g: Id, log: &Value, e: &Value) -> Says {
let kind = vu64(e, "action_type");
let target = vid(e, "target_id");
let o = &e["options"];
let users = log["users"].as_array().map(Vec::as_slice).unwrap_or(&[]);
let user = |id: Option<Id>| id.map_or_else(|| "someone".to_string(), |id| self.ss_user_name(users, id));
let target_user = || user(target);
let channel = |id: Option<Id>| self.ss_channel_ref(id, e);
let role = || {
target
.and_then(|r| self.store.role_name(Some(g), r))
.or_else(|| changed_name(e).map(String::from))
.unwrap_or_else(|| "a deleted role".into())
};
let listed = |list: &str| target.and_then(|id| find(log, list, id)).map(|v| vstr(v, "name").to_string()).filter(|n| !n.is_empty());
let named = |fallback: &str| changed_name(e).map_or_else(|| fallback.to_string(), String::from);
let count = vu64(o, "count");
let s = Says::default();
match kind {
1 => s.say(" updated the server"),
10 => {
let ty = change(e, "type").and_then(|c| c["new_value"].as_u64()).unwrap_or(0) as u8;
s.say(format!(" created a {} ", channel_kind_word(ty))).name(channel(target))
}
11 => s.say(" updated the channel ").name(channel(target)),
// Discord: "removed rustcord-voice-test".
12 => s.say(" removed ").name(channel(target)),
13..=15 => {
let who = match vstr(o, "type") {
"0" => vstr(o, "role_name").to_string(),
_ => user(vid(o, "id")),
};
let (verb, prep) = match kind {
13 => (" added permission overrides for ", " in "),
14 => (" updated permission overrides for ", " in "),
_ => (" removed permission overrides for ", " from "),
};
s.say(verb).name(who).say(prep).name(channel(target))
}
20 => s.say(" kicked ").name(target_user()),
21 => s.say(format!(" pruned {} members for {} days of inactivity", vu64(o, "members_removed"), vu64(o, "delete_member_days"))),
22 => s.say(" banned ").name(target_user()),
23 => s.say(" revoked the ban for ").name(target_user()),
24 => self.ss_member_update(e, target, vid(e, "user_id"), target_user()),
25 => s.say(" updated roles for ").name(target_user()),
26 => s.say(format!(" moved {} to ", plural(count, "member"))).name(channel(vid(o, "channel_id"))),
27 => s.say(format!(" disconnected {} from voice", plural(count, "member"))),
28 => s.say(" added ").name(target_user()).say(" to the server"),
30 => s.say(" created the role ").name(role()),
31 => s.say(" updated the role ").name(role()),
32 => s.say(" deleted the role ").name(role()),
40..=42 => {
let code = change(e, "code").and_then(|c| c["new_value"].as_str().or(c["old_value"].as_str())).unwrap_or("").to_string();
let verb = [" created an invite ", " updated the invite ", " deleted the invite "][(kind - 40) as usize];
s.say(verb).name(code)
}
50..=52 => {
let verb = [" created the webhook ", " updated the webhook ", " deleted the webhook "][(kind - 50) as usize];
s.say(verb).name(listed("webhooks").unwrap_or_else(|| named("a webhook")))
}
60..=62 => {
let verb = [" created the emoji ", " updated the emoji ", " deleted the emoji "][(kind - 60) as usize];
let emoji = self.store.guilds.get(&g).and_then(|gs| gs.guild.emojis.iter().find(|x| x.id.is_some() && x.id == target)).and_then(|x| x.name.clone());
s.say(verb).name(changed_name(e).map(String::from).or(emoji).unwrap_or_else(|| "an emoji".into()))
}
72 => {
let what = if count > 1 { format!(" deleted {count} messages by ") } else { " deleted a message by ".into() };
s.say(what).name(target_user()).say(" in ").name(channel(vid(o, "channel_id")))
}
73 => s.say(format!(" deleted {} in ", plural(count, "message"))).name(channel(target)),
74 => s.say(" pinned a message by ").name(target_user()).say(" in ").name(channel(vid(o, "channel_id"))),
75 => s.say(" unpinned a message by ").name(target_user()).say(" in ").name(channel(vid(o, "channel_id"))),
80 => s.say(" added an integration for ").name(listed("integrations").unwrap_or_else(|| named("an app"))),
81 => s.say(" updated the integration ").name(listed("integrations").unwrap_or_else(|| named("an app"))),
82 => s.say(" removed the integration ").name(listed("integrations").unwrap_or_else(|| named("an app"))),
83..=85 => {
let topic = change(e, "topic").and_then(|c| c["new_value"].as_str().or(c["old_value"].as_str())).unwrap_or("a stage").to_string();
let verb = [" started the stage ", " updated the stage ", " ended the stage "][(kind - 83) as usize];
s.say(verb).name(topic)
}
90..=92 => {
let verb = [" created the sticker ", " updated the sticker ", " deleted the sticker "][(kind - 90) as usize];
s.say(verb).name(named("a sticker"))
}
100..=102 => {
let verb = [" created the event ", " updated the event ", " deleted the event "][(kind - 100) as usize];
s.say(verb).name(listed("guild_scheduled_events").unwrap_or_else(|| named("an event")))
}
110..=112 => {
let verb = [" created a thread ", " updated the thread ", " deleted the thread "][(kind - 110) as usize];
let name = listed("threads").or_else(|| changed_name(e).map(String::from)).unwrap_or_else(|| channel(target));
s.say(verb).name(name)
}
121 => s.say(" updated command permissions for ").name(listed("integrations").unwrap_or_else(|| "an app".into())),
130..=132 => {
let verb = [" uploaded the sound ", " updated the sound ", " deleted the sound "][(kind - 130) as usize];
s.say(verb).name(named("a sound"))
}
140..=142 => {
let verb = [" created the AutoMod rule ", " updated the AutoMod rule ", " deleted the AutoMod rule "][(kind - 140) as usize];
s.say(verb).name(named("a rule"))
}
143..=145 => {
let rule = vstr(o, "auto_moderation_rule_name").to_string();
let s = match kind {
143 => s.say(" blocked a message by ").name(target_user()),
144 => s.say(" flagged a message by ").name(target_user()),
_ => s.say(" timed out ").name(target_user()),
};
if rule.is_empty() {
s
} else {
s.say(" (").name(rule).say(")")
}
}
150 => s.say(" asked to turn on server subscriptions"),
151 => s.say(" accepted the server subscription terms"),
163..=167 => s.say(" updated onboarding"),
190 | 191 => s.say(" updated the server guide"),
192 => s.say(" set the status of ").name(channel(target)),
193 => s.say(" cleared the status of ").name(channel(target)),
_ => s.say(format!(" made a change (action {kind})")),
}
}
/// MEMBER_UPDATE: a timeout, a nickname, a server mute / deafen.
fn ss_member_update(&self, e: &Value, target: Option<Id>, actor: Option<Id>, name: String) -> Says {
let s = Says::default();
if let Some(c) = change(e, "communication_disabled_until") {
return match c["new_value"].as_str().and_then(|v| chrono::DateTime::parse_from_rfc3339(v).ok()) {
Some(until) => {
let at = vid(e, "id").map_or(0, |id| id.timestamp_ms() as i64 / 1000);
s.say(" timed out ").name(name).say(format!(" for {}", span_words(until.timestamp() - at)))
}
None => s.say(" removed the time out from ").name(name),
};
}
if change(e, "nick").is_some() {
return if target.is_some() && target == actor { s.say(" changed their nickname") } else { s.say(" changed the nickname of ").name(name) };
}
for (key, on, off) in [("mute", " server muted ", " server unmuted "), ("deaf", " server deafened ", " server undeafened ")] {
if let Some(c) = change(e, key) {
return s.say(if c["new_value"].as_bool() == Some(true) { on } else { off }).name(name);
}
}
s.say(" updated ").name(name)
}
/// "#general" for a text channel, "Lounge" for a voice channel; the
/// channel's name from the entry once it's gone.
fn ss_channel_ref(&self, id: Option<Id>, e: &Value) -> String {
let (name, kind) = match id.and_then(|id| self.store.channels.get(&id)) {
Some(c) => (crate::store::Store::channel_label(c), c.kind),
None => match changed_name(e) {
Some(n) => (n.to_string(), change(e, "type").and_then(|c| c["new_value"].as_u64().or(c["old_value"].as_u64())).unwrap_or(0) as u8),
None => return "a deleted channel".into(),
},
};
let hash = matches!(kind, channel_kind::GUILD_TEXT | channel_kind::GUILD_ANNOUNCEMENT | channel_kind::GUILD_FORUM | channel_kind::GUILD_MEDIA);
if hash {
format!("#{name}")
} else {
name
}
}
}
/// An audit-log sentence as (text, bold?) runs.
#[derive(Default)]
struct Says(Vec<(String, bool)>);
impl Says {
fn say(mut self, text: impl Into<String>) -> Self {
self.0.push((text.into(), false));
self
}
fn name(mut self, text: impl Into<String>) -> Self {
self.0.push((text.into(), true));
self
}
}
/// Add a "Load More" page to what's loaded.
fn merge_log(main: &mut Value, more: Value) {
let (Some(main), Value::Object(more)) = (main.as_object_mut(), more) else { return };
for (key, v) in more {
if let Value::Array(extra) = v {
if let Some(Value::Array(list)) = main.get_mut(&key) {
list.extend(extra);
} else {
main.insert(key, Value::Array(extra));
}
}
}
}
/// The item with `id` in one of the response's lists ("users", "webhooks", …).
fn find<'a>(log: &'a Value, list: &str, id: Id) -> Option<&'a Value> {
log[list].as_array()?.iter().find(|v| vid(v, "id") == Some(id))
}
/// Discord's audit log names people by username ("ferris").
fn user_label(u: &Value) -> &str {
vstr(u, "username")
}
/// The change to `key` in an entry.
fn change<'a>(e: &'a Value, key: &str) -> Option<&'a Value> {
e["changes"].as_array()?.iter().find(|c| c["key"] == key)
}
/// The name an entry gave (or took away from) its target.
fn changed_name(e: &Value) -> Option<&str> {
change(e, "name").and_then(|c| c["new_value"].as_str().or(c["old_value"].as_str())).filter(|n| !n.is_empty())
}
fn channel_kind_word(kind: u8) -> &'static str {
match kind {
channel_kind::GUILD_VOICE => "voice channel",
channel_kind::GUILD_CATEGORY => "category",
channel_kind::GUILD_ANNOUNCEMENT => "announcement channel",
channel_kind::GUILD_STAGE_VOICE => "stage channel",
channel_kind::GUILD_FORUM => "forum channel",
channel_kind::GUILD_MEDIA => "media channel",
_ => "text channel",
}
}
/// 0 made, 1 changed, 2 removed or punished (the colour of a row's edge).
fn action_tone(kind: u64) -> u8 {
match kind {
10 | 13 | 23 | 28 | 30 | 40 | 50 | 60 | 74 | 80 | 83 | 90 | 100 | 110 | 130 | 140 | 192 => 0,
12 | 15 | 20 | 21 | 22 | 27 | 32 | 42 | 52 | 62 | 72 | 73 | 82 | 85 | 92 | 102 | 112 | 132 | 142 | 143 | 145 | 193 => 2,
_ => 1,
}
}
fn plural(n: u64, word: &str) -> String {
if n == 1 {
format!("1 {word}")
} else {
format!("{n} {word}s")
}
}
/// "1 hour", "5 minutes", "1 week": how long a timeout lasts.
fn span_words(secs: i64) -> String {
let s = secs.max(0) as f64;
let days = s / 86_400.0;
let (n, unit) = if s < 90.0 {
(s, "second")
} else if s < 3_570.0 {
(s / 60.0, "minute")
} else if s < 84_600.0 {
(s / 3600.0, "hour")
} else if days >= 7.0 && ((days / 7.0).round() * 7.0 - days).abs() < 0.1 {
(days / 7.0, "week")
} else {
(days, "day")
};
plural(n.round() as u64, unit)
}
/// "Today at 19:50", "Yesterday at …", "Last Friday at …", else "09/11/2026",
/// like Discord's audit log.
fn when_label(ms: u64) -> String {
let Some(at) = chrono::DateTime::from_timestamp((ms / 1000) as i64, 0) else { return String::new() };
let local = at.with_timezone(&chrono::Local);
let days = (chrono::Local::now().date_naive() - local.date_naive()).num_days();
let time = local.format(super::super::time_fmt());
match days {
0 => format!("Today at {time}"),
1 => format!("Yesterday at {time}"),
2..=6 => format!("Last {} at {time}", local.format("%A")),
_ => local.format("%d/%m/%Y").to_string(),
}
}
/// "Default message notifications" from "default_message_notifications".
fn key_label(key: &str) -> String {
let mut s = key.replace('_', " ");
if let Some(first) = s.get(..1) {
let upper = first.to_uppercase();
s.replace_range(..1, &upper);
}
s
}
/// A changed value as text: names for lists of roles, short JSON otherwise.
fn show_value(v: &Value) -> String {
let text = match v {
Value::Null => "none".to_string(),
Value::Bool(b) => (if *b { "on" } else { "off" }).to_string(),
Value::Number(n) => n.to_string(),
Value::String(s) if s.is_empty() => "none".to_string(),
Value::String(s) => s.clone(),
Value::Array(a) if a.iter().all(|x| x.get("name").is_some()) => a.iter().map(|x| vstr(x, "name")).collect::<Vec<_>>().join(", "),
other => other.to_string(),
};
if text.chars().count() > 160 {
format!("{}…", text.chars().take(160).collect::<String>())
} else {
text
}
}
// ---- AutoMod -----------------------------------------------------------------------------------
/// Discord's four AutoMod cards: (trigger_type, title, description).
const AUTOMOD_CARDS: &[(u8, &str, &str)] = &[
(5, "Block Mention Spam", "Block messages with an excessive # of role and user mentions"),
(3, "Block Suspected Spam Content", "Monitor messages, Forum posts and threads for potentially spammy content or activity. (Support for English only)"),
(4, "Block Commonly Flagged Words", "Flag messages that contain profanity and more. (Support for English only)"),
(1, "Block Custom Words", "Create your own filter to block specific language from your server."),
];
/// Keyword rules a server may have (Discord: 6).
const MAX_KEYWORD_RULES: usize = 6;
/// Timeout lengths Discord offers: (seconds, label).
const TIMEOUTS: &[(u32, &str)] = &[(60, "60 secs"), (300, "5 mins"), (600, "10 mins"), (3600, "1 hour"), (86_400, "1 day"), (604_800, "1 week")];
/// Keyword presets: (id, name).
const PRESETS: [(u8, &str); 3] = [(1, "Profanity"), (2, "Sexual Content"), (3, "Slurs")];
/// A rule being set up or edited.
#[derive(Clone, PartialEq)]
struct RuleDraft {
/// None for a new rule.
id: Option<Id>,
trigger: u8,
name: String,
enabled: bool,
/// Mention spam: the limit as typed, and mention raid protection.
mention_limit: String,
raid_protection: bool,
/// Custom words: comma-separated words, regexes one per line.
keywords: String,
regex: String,
/// Words that never trigger the rule (comma-separated).
allow: String,
presets: [bool; 3],
block: bool,
message: String,
alert: bool,
alert_channel: Option<Id>,
timeout: bool,
timeout_secs: u32,
exempt_roles: Vec<Id>,
exempt_channels: Vec<Id>,
}
impl RuleDraft {
fn new(trigger: u8, name: String) -> Self {
Self {
id: None,
trigger,
name,
enabled: true,
mention_limit: "20".into(),
raid_protection: false,
keywords: String::new(),
regex: String::new(),
allow: String::new(),
presets: [false; 3],
block: true,
message: String::new(),
alert: false,
alert_channel: None,
timeout: false,
timeout_secs: 60,
exempt_roles: Vec::new(),
exempt_channels: Vec::new(),
}
}
fn from_rule(v: &Value) -> Self {
let m = &v["trigger_metadata"];
let strs = |key: &str| m[key].as_array().into_iter().flatten().filter_map(Value::as_str).collect::<Vec<_>>();
let ids = |key: &str| v[key].as_array().into_iter().flatten().filter_map(Id::from_value).collect::<Vec<_>>();
let presets: Vec<u64> = m["presets"].as_array().into_iter().flatten().filter_map(Value::as_u64).collect();
let mut d = Self::new(vu64(v, "trigger_type") as u8, vstr(v, "name").to_string());
d.id = vid(v, "id");
d.enabled = v["enabled"].as_bool().unwrap_or(true);
if let Some(n) = m["mention_total_limit"].as_u64() {
d.mention_limit = n.to_string();
}
d.raid_protection = m["mention_raid_protection_enabled"].as_bool().unwrap_or(false);
d.keywords = strs("keyword_filter").join(", ");
d.regex = strs("regex_patterns").join("\n");
d.allow = strs("allow_list").join(", ");
d.presets = PRESETS.map(|(p, _)| presets.contains(&(p as u64)));
d.block = false;
for a in v["actions"].as_array().into_iter().flatten() {
let meta = &a["metadata"];
match a["type"].as_u64() {
Some(1) => {
d.block = true;
d.message = vstr(meta, "custom_message").to_string();
}
Some(2) => {
d.alert = true;
d.alert_channel = vid(meta, "channel_id");
}
Some(3) => {
d.timeout = true;
d.timeout_secs = meta["duration_seconds"].as_u64().unwrap_or(60) as u32;
}
_ => {}
}
}
d.exempt_roles = ids("exempt_roles");
d.exempt_channels = ids("exempt_channels");
d
}
/// Timeouts are offered for mention spam and custom words only.
fn can_timeout(&self) -> bool {
matches!(self.trigger, 1 | 5)
}
/// The body Discord wants, or what's missing.
fn body(&self) -> Result<Value, &'static str> {
let list = |s: &str| s.split(',').map(str::trim).filter(|w| !w.is_empty()).map(String::from).collect::<Vec<_>>();
let meta = match self.trigger {
1 => {
let words = list(&self.keywords);
let regex: Vec<&str> = self.regex.lines().map(str::trim).filter(|r| !r.is_empty()).collect();
if words.is_empty() && regex.is_empty() {
return Err("Add at least one word or pattern to block.");
}
json!({ "keyword_filter": words, "regex_patterns": regex, "allow_list": list(&self.allow) })
}
4 => {
let presets: Vec<u8> = PRESETS.iter().zip(self.presets).filter(|(_, on)| *on).map(|((p, _), _)| *p).collect();
if presets.is_empty() {
return Err("Pick at least one list of words.");
}
json!({ "presets": presets, "allow_list": list(&self.allow) })
}
5 => match self.mention_limit.trim().parse::<u32>() {
Ok(n) if (1..=50).contains(&n) => json!({ "mention_total_limit": n, "mention_raid_protection_enabled": self.raid_protection }),
_ => return Err("The mention limit must be between 1 and 50."),
},
_ => json!({}),
};
let mut actions = Vec::new();
if self.block {
let msg = self.message.trim();
actions.push(if msg.is_empty() { json!({ "type": 1, "metadata": {} }) } else { json!({ "type": 1, "metadata": { "custom_message": msg } }) });
}
if self.alert {
let Some(c) = self.alert_channel else { return Err("Pick a channel to send alerts to.") };
actions.push(json!({ "type": 2, "metadata": { "channel_id": c.to_string() } }));
}
if self.timeout && self.can_timeout() {
actions.push(json!({ "type": 3, "metadata": { "duration_seconds": self.timeout_secs } }));
}
if actions.is_empty() {
return Err("Pick at least one response.");
}
let ids = |v: &[Id]| v.iter().map(|i| i.to_string()).collect::<Vec<_>>();
let mut body = Map::new();
body.insert("name".into(), json!(self.name.trim()));
body.insert("event_type".into(), json!(1));
body.insert("trigger_metadata".into(), meta);
body.insert("actions".into(), json!(actions));
body.insert("enabled".into(), json!(self.enabled));
body.insert("exempt_roles".into(), json!(ids(&self.exempt_roles)));
body.insert("exempt_channels".into(), json!(ids(&self.exempt_channels)));
// The trigger can only be set when the rule is made.
if self.id.is_none() {
body.insert("trigger_type".into(), json!(self.trigger));
}
Ok(Value::Object(body))
}
}
#[derive(Clone, Default)]
struct AutoUi {
edit: Option<RuleDraft>,
/// "Delete Rule" was pressed once: ask before deleting.
confirm_delete: bool,
}
fn automod_id(g: Id) -> egui::Id {
egui::Id::new(("ss_automod", g.0))
}
fn tag_automod(g: Id) -> String {
format!("ss:automod:{g}")
}
fn tag_automod_save(g: Id) -> String {
format!("ss:automod-save:{g}")
}
fn tag_automod_delete(g: Id) -> String {
format!("ss:automod-delete:{g}")
}
/// What a rule does, for its card: "Block message · Send alert".
fn rule_summary(v: &Value) -> String {
let mut parts: Vec<&str> = v["actions"]
.as_array()
.into_iter()
.flatten()
.filter_map(|a| match a["type"].as_u64() {
Some(1) => Some("Block message"),
Some(2) => Some("Send alert"),
Some(3) => Some("Time out member"),
_ => None,
})
.collect();
if !v["enabled"].as_bool().unwrap_or(true) {
parts.insert(0, "Disabled");
}
parts.join(" · ")
}
impl RustCord {
pub(super) fn ss_automod(&self, ui: &mut Ui, t: &Theme, acts: &mut Vec<Act>, g: Id) {
title(ui, t, "AutoMod");
help(
ui,
t,
"Give your mods a break while keeping your server safe! Set up filters to moderate content and automate a custom response when they're found and AutoMod will make it happen.",
);
ui.add_space(20.0);
let sid = automod_id(g);
let mut st: AutoUi = ui.data(|d| d.get_temp(sid)).unwrap_or_default();
let (tag, path) = (tag_automod(g), format!("/guilds/{g}/auto-moderation/rules"));
if first_frame(ui, "automod", g) {
st = AutoUi::default();
let (tag, path) = (tag.clone(), path.clone());
acts.push(run(move |app| app.api(&tag, Method::GET, path, None)));
}
self.poll_guild_patch(acts, g);
self.ss_automod_answers(acts, g, &st);
if let Some(rules) = self.ss_loaded(ui, t, &tag, &path, acts) {
let rules: &[Value] = rules.as_array().map(Vec::as_slice).unwrap_or(&[]);
for &(trigger, name, desc) in AUTOMOD_CARDS {
self.ss_automod_card(ui, t, acts, g, &mut st, rules, trigger, name, desc);
ui.add_space(12.0);
}
}
ui.data_mut(|d| d.insert_temp(sid, st));
super::divider(ui, t);
let (gtag, gpath) = (tag_guild(g), format!("/guilds/{g}"));
self.ss_want(acts, gtag.clone(), gpath.clone());
if let Some(v) = self.ss_loaded(ui, t, >ag, &gpath, acts) {
self.ss_content_filter(ui, t, acts, g, v);
}
}
/// Saved or deleted rules: update the list and close the editor.
fn ss_automod_answers(&self, acts: &mut Vec<Act>, g: Id, st: &AutoUi) {
let close = move |app: &mut RustCord| app.ctx.data_mut(|d| d.insert_temp(automod_id(g), AutoUi::default()));
self.on_answer(acts, tag_automod_save(g), move |app, r| match r {
Ok(v) => {
app.ss_list_upsert(&tag_automod(g), &v);
close(app);
}
Err(e) => app.toast(format!("Couldn't save the rule: {e}"), true),
});
let deleting = st.edit.as_ref().and_then(|d| d.id);
self.on_answer(acts, tag_automod_delete(g), move |app, r| match r {
Ok(_) => {
if let Some(id) = deleting {
app.ss_list_remove(&tag_automod(g), |v| vid(v, "id") == Some(id));
}
close(app);
}
Err(e) => app.toast(format!("Couldn't delete the rule: {e}"), true),
});
}
/// One of Discord's four cards, with its rules and the editor when open.
#[allow(clippy::too_many_arguments)]
fn ss_automod_card(&self, ui: &mut Ui, t: &Theme, acts: &mut Vec<Act>, g: Id, st: &mut AutoUi, rules: &[Value], trigger: u8, name: &str, desc: &str) {
let mine: Vec<&Value> = rules.iter().filter(|r| vu64(r, "trigger_type") == trigger as u64).collect();
let editing_new = st.edit.as_ref().is_some_and(|d| d.trigger == trigger && d.id.is_none());
Frame::none().fill(t.bg_secondary).rounding(8.0).inner_margin(Margin::same(16.0)).show(ui, |ui| {
ui.set_width(ui.available_width());
ui.horizontal_top(|ui| {
let w = (ui.available_width() - 110.0).max(120.0);
ui.vertical(|ui| {
ui.set_width(w);
ui.label(bold(name).size(16.0).color(t.header_primary));
ui.add_space(4.0);
ui.label(RichText::new(desc).size(14.0).color(t.text_muted));
});
ui.with_layout(Layout::right_to_left(Align::Min), |ui| {
// Custom words take several rules; the others one each.
let (label, kind, open) = match (trigger, mine.first()) {
(1, _) => ("Create", Btn::Primary, mine.len() < MAX_KEYWORD_RULES),
(_, Some(_)) => ("Edit", Btn::Secondary, true),
(_, None) => ("Set Up", Btn::Primary, true),
};
let idle = st.edit.is_none();
if btn(ui, t, kind, label, open && idle).clicked() {
st.confirm_delete = false;
st.edit = Some(match (trigger, mine.first()) {
(1, _) => RuleDraft::new(1, if mine.is_empty() { name.to_string() } else { format!("{name} {}", mine.len() + 1) }),
(_, Some(r)) => RuleDraft::from_rule(r),
(_, None) => RuleDraft::new(trigger, name.to_string()),
});
}
});
});
for r in &mine {
let id = vid(r, "id");
let editing = st.edit.as_ref().is_some_and(|d| d.id.is_some() && d.id == id);
ui.add_space(12.0);
ui.horizontal(|ui| {
if trigger == 1 {
ui.label(bold(vstr(r, "name")).size(14.0).color(t.header_primary));
}
ui.label(RichText::new(rule_summary(r)).size(13.0).color(t.text_muted));
if trigger == 1 {
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if !editing && link(ui, "Edit", t.text_link).clicked() && st.edit.is_none() {
st.confirm_delete = false;
st.edit = Some(RuleDraft::from_rule(r));
}
});
}
});
if editing {
self.ss_rule_editor(ui, t, acts, g, st);
}
}
if editing_new {
self.ss_rule_editor(ui, t, acts, g, st);
}
});
}
/// The open rule's settings, Save / Cancel / Delete Rule.
fn ss_rule_editor(&self, ui: &mut Ui, t: &Theme, acts: &mut Vec<Act>, g: Id, st: &mut AutoUi) {
let Some(d) = st.edit.as_mut() else { return };
let saving = self.api_busy(&tag_automod_save(g)) || self.api_busy(&tag_automod_delete(g));
let key = d.id.map_or(0, |i| i.0);
let w = ui.available_width();
super::thin_rule(ui, t);
switch_row(ui, t, "Enabled", None, &mut d.enabled);
if d.trigger == 1 {
section(ui, t, "RULE NAME");
input(ui, t, egui::Id::new(("ss_rule_name", key)), &mut d.name, "", 1, 100, w);
ui.add_space(16.0);
}
match d.trigger {
5 => {
section(ui, t, "MENTION LIMIT");
help(ui, t, "The number of unique role and user mentions allowed in a message (up to 50).");
ui.add_space(8.0);
input(ui, t, egui::Id::new(("ss_rule_mentions", key)), &mut d.mention_limit, "20", 1, 2, 120.0);
d.mention_limit.retain(|c| c.is_ascii_digit());
ui.add_space(12.0);
switch_row(ui, t, "Mention raid protection", Some("Restrict members who send unusually many mentions across messages."), &mut d.raid_protection);
}
4 => {
section(ui, t, "WORD LISTS");
for (i, (_, label)) in PRESETS.iter().enumerate() {
switch_row(ui, t, label, None, &mut d.presets[i]);
}
}
1 => {
section(ui, t, "BLOCK WORDS");
help(ui, t, "Separate words with commas. Use * at the start or end of a word to match parts of words.");
ui.add_space(8.0);
input(ui, t, egui::Id::new(("ss_rule_words", key)), &mut d.keywords, "e.g. spoiler, *bad*", 3, 60_000, w);
ui.add_space(12.0);
section(ui, t, "REGEX PATTERNS");
help(ui, t, "One pattern per line (up to 10).");
ui.add_space(8.0);
input(ui, t, egui::Id::new(("ss_rule_regex", key)), &mut d.regex, "", 3, 2_700, w);
}
_ => help(ui, t, "Discord detects the spam: there's nothing to set up."),
}
if matches!(d.trigger, 1 | 4) {
ui.add_space(12.0);
section(ui, t, "ALLOW WORDS OR PHRASES");
help(ui, t, "Separate with commas. These never trigger the rule.");
ui.add_space(8.0);
input(ui, t, egui::Id::new(("ss_rule_allow", key)), &mut d.allow, "", 2, 60_000, w);
}
super::thin_rule(ui, t);
section(ui, t, "RESPONSES");
switch_row(ui, t, "Block message", Some("Stops the message from being sent. Members see a notice in the channel."), &mut d.block);
if d.block {
input(ui, t, egui::Id::new(("ss_rule_message", key)), &mut d.message, "Custom message (optional)", 1, 150, w);
ui.add_space(12.0);
}
switch_row(ui, t, "Send alert", Some("Sends an alert with the flagged message to a channel."), &mut d.alert);
if d.alert {
let text = self.ss_guild_channels(g, |k| k == channel_kind::GUILD_TEXT);
channel_combo(ui, t, "ss_rule_alert_channel", &mut d.alert_channel, &text, "Select a channel", false);
ui.add_space(12.0);
}
if d.can_timeout() {
switch_row(ui, t, "Time out member", Some("Keeps the member from chatting or joining voice for a while."), &mut d.timeout);
if d.timeout {
let shown = TIMEOUTS.iter().find(|(s, _)| *s == d.timeout_secs).map_or_else(|| span_words(d.timeout_secs as i64), |(_, l)| l.to_string());
combo(ui, "ss_rule_timeout", 200.0, WidgetText::from(shown), |ui| {
for &(secs, label) in TIMEOUTS {
if ui.selectable_label(d.timeout_secs == secs, label).clicked() {
d.timeout_secs = secs;
}
}
});
ui.add_space(12.0);
}
}
super::thin_rule(ui, t);
section(ui, t, "EXEMPT ROLES");
let mut roles: Vec<&discord::model::Role> =
self.store.guilds.get(&g).map(|gs| gs.guild.roles.iter().filter(|r| r.id != g && !r.managed).collect()).unwrap_or_default();
roles.sort_by_key(|r| std::cmp::Reverse(r.position));
let role_name = |id: Id| roles.iter().find(|r| r.id == id).map_or_else(|| "deleted role".to_string(), |r| r.name.clone());
id_chips(ui, t, &mut d.exempt_roles, role_name);
let mut add = None;
combo(ui, "ss_rule_add_role", 220.0, WidgetText::from("Add a role"), |ui| {
for r in roles.iter().filter(|r| !d.exempt_roles.contains(&r.id)) {
if ui.selectable_label(false, &r.name).clicked() {
add = Some(r.id);
}
}
});
if let Some(id) = add.filter(|_| d.exempt_roles.len() < 20) {
d.exempt_roles.push(id);
}
ui.add_space(12.0);
section(ui, t, "EXEMPT CHANNELS");
let channels = self.ss_guild_channels(g, |k| !channel_kind::is_thread(k));
let channel_name = |id: Id| channels.iter().find(|c| c.id == id).map_or_else(|| "deleted channel".to_string(), |c| c.name.clone());
id_chips(ui, t, &mut d.exempt_channels, channel_name);
let mut add = None;
combo(ui, "ss_rule_add_channel", 220.0, WidgetText::from("Add a channel"), |ui| {
for c in channels.iter().filter(|c| !d.exempt_channels.contains(&c.id)) {
if ui.selectable_label(false, &c.name).clicked() {
add = Some(c.id);
}
}
});
if let Some(id) = add.filter(|_| d.exempt_channels.len() < 50) {
d.exempt_channels.push(id);
}
super::thin_rule(ui, t);
let mut cancel = false;
ui.horizontal(|ui| {
if let Some(id) = d.id {
if st.confirm_delete {
ui.label(RichText::new("Delete this rule?").size(14.0).color(t.text_normal));
if btn(ui, t, Btn::Danger, "Delete", !saving).clicked() {
acts.push(run(move |app| app.api(&tag_automod_delete(g), Method::DELETE, format!("/guilds/{g}/auto-moderation/rules/{id}"), None)));
}
if link(ui, "Keep", t.text_normal).clicked() {
st.confirm_delete = false;
}
} else if btn(ui, t, Btn::Danger, "Delete Rule", !saving).clicked() {
st.confirm_delete = true;
}
}
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if btn(ui, t, Btn::Primary, if saving { "Saving…" } else { "Save" }, !saving).clicked() {
match d.body() {
Ok(body) => {
let (method, path) = match d.id {
Some(id) => (Method::PATCH, format!("/guilds/{g}/auto-moderation/rules/{id}")),
None => (Method::POST, format!("/guilds/{g}/auto-moderation/rules")),
};
acts.push(run(move |app| app.api(&tag_automod_save(g), method, path, Some(body))));
}
Err(why) => acts.push(Act::Note(why)),
}
}
ui.add_space(8.0);
if link(ui, "Cancel", t.text_normal).clicked() && !saving {
cancel = true;
}
});
});
if cancel {
st.edit = None;
st.confirm_delete = false;
}
}
}
/// Picked roles / channels as chips with a remove ×.
fn id_chips(ui: &mut Ui, t: &Theme, ids: &mut Vec<Id>, name: impl Fn(Id) -> String) {
if ids.is_empty() {
return;
}
let mut remove = None;
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing = vec2(6.0, 6.0);
for &id in ids.iter() {
Frame::none().fill(overlay(0.12)).rounding(6.0).inner_margin(Margin { left: 8.0, right: 4.0, top: 3.0, bottom: 3.0 }).show(ui, |ui| {
ui.spacing_mut().item_spacing.x = 4.0;
ui.label(RichText::new(name(id)).size(13.0).color(t.text_normal));
let (r, resp) = ui.allocate_exact_size(vec2(16.0, 16.0), Sense::click());
let color = if resp.hovered() { t.interactive_hover } else { t.interactive_normal };
ui.painter().text(r.center(), Align2::CENTER_CENTER, icon::CLOSE, icon_font(9.0), color);
if resp.on_hover_cursor(CursorIcon::PointingHand).clicked() {
remove = Some(id);
}
});
}
});
if let Some(id) = remove {
ids.retain(|x| *x != id);
}
ui.add_space(8.0);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn features_swap_one_and_keep_the_rest() {
let v = json!({ "features": ["NEWS", "COMMUNITY", "RAID_ALERTS_DISABLED"] });
assert_eq!(alerts_features(&v, true), json!(["NEWS", "COMMUNITY"]));
assert_eq!(features_with(&v, &["NEWS"], &["COMMUNITY"]), json!(["RAID_ALERTS_DISABLED", "NEWS"]));
assert!(!alerts_on(&v));
assert!(alerts_on(&json!({ "features": ["NON_COMMUNITY_RAID_ALERTS"] })));
}
#[test]
fn timeout_lengths_read_like_discord() {
assert_eq!(span_words(3600), "1 hour");
assert_eq!(span_words(299), "5 minutes");
assert_eq!(span_words(604_800), "1 week");
assert_eq!(span_words(86_400 * 2), "2 days");
assert_eq!(span_words(60), "60 seconds");
assert_eq!(span_words(86_399), "1 day");
}
#[test]
fn keys_become_labels() {
assert_eq!(key_label("default_message_notifications"), "Default message notifications");
assert_eq!(show_value(&json!([{ "name": "Mods" }, { "name": "VIP" }])), "Mods, VIP");
}
#[test]
fn rule_bodies_check_what_discord_needs() {
let mut d = RuleDraft::new(1, "Block Custom Words".into());
assert!(d.body().is_err());
d.keywords = "spoiler, *bad* ,".into();
let body = d.body().unwrap();
assert_eq!(body["trigger_metadata"]["keyword_filter"], json!(["spoiler", "*bad*"]));
assert_eq!(body["trigger_type"], json!(1));
d.id = Some(Id(5));
d.block = false;
assert!(d.body().is_err());
d.timeout = true;
assert!(d.body().unwrap().get("trigger_type").is_none());
}
}