djs_model/audit_log.rs
1//! [Audit logs](https://docs.discord.com/developers/resources/audit-log): the administrative
2//! actions taken in a guild, with what they changed.
3//!
4//! An [`AuditLog`] (returned by `GET /guilds/{guild.id}/audit-logs`) holds
5//! [`AuditLogEntry`]s plus the users, webhooks, threads, commands and other objects they
6//! refer to. Each entry's [`changes`](AuditLogEntry::changes) keep their "mixed" values as
7//! [`JsonValue`]s, which convert to the field's type on demand (D-070, D-072).
8
9use compact_str::CompactString;
10use serde::{Deserialize, Serialize};
11
12use crate::{
13 application_command::ApplicationCommand,
14 auto_moderation::{Rule, TriggerType},
15 channel::{Channel, OverwriteType},
16 guild::{IntegrationType, PartialIntegration},
17 guild_scheduled_event::GuildScheduledEvent,
18 id::{ApplicationId, AuditLogEntryId, ChannelId, GenericId, GuildId, MessageId, UserId},
19 macros::int_enum,
20 user::User,
21 util::{JsonValue, JsonValueError},
22 webhook::Webhook,
23};
24
25/// A guild's [audit log](https://docs.discord.com/developers/resources/audit-log#audit-log-object):
26/// entries, most recent first, and the objects they refer to.
27///
28/// Requires the `VIEW_AUDIT_LOG` permission.
29///
30/// discord.js counterpart: `GuildAuditLogs`.
31#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
32#[non_exhaustive]
33pub struct AuditLog {
34 /// The application commands referred to by the entries.
35 #[serde(default)]
36 pub application_commands: Vec<ApplicationCommand>,
37 /// The entries, from most to least recent.
38 #[serde(default)]
39 pub audit_log_entries: Vec<AuditLogEntry>,
40 /// The auto moderation rules referred to by the entries.
41 #[serde(default)]
42 pub auto_moderation_rules: Vec<Rule>,
43 /// The scheduled events referred to by the entries.
44 #[serde(default)]
45 pub guild_scheduled_events: Vec<GuildScheduledEvent>,
46 /// The integrations referred to by the entries (partial objects).
47 #[serde(default)]
48 pub integrations: Vec<PartialIntegration>,
49 /// The threads referred to by the entries (archived threads may not be cached elsewhere).
50 #[serde(default)]
51 pub threads: Vec<Channel>,
52 /// The users referred to by the entries.
53 #[serde(default)]
54 pub users: Vec<User>,
55 /// The webhooks referred to by the entries.
56 #[serde(default)]
57 pub webhooks: Vec<Webhook>,
58}
59
60/// An [audit log entry](https://docs.discord.com/developers/resources/audit-log#audit-log-entry-object):
61/// one administrative action.
62///
63/// Some actions done in quick succession by the same user are merged into one entry
64/// (message deletes, member moves and disconnects, channel and role reordering); only the
65/// first reason is kept.
66///
67/// Contains floats (through [`JsonValue`]), so it is `PartialEq` but not `Eq` (D-064).
68///
69/// discord.js counterpart: `GuildAuditLogsEntry`.
70#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
71#[non_exhaustive]
72pub struct AuditLogEntry {
73 /// The entry's ID.
74 pub id: AuditLogEntryId,
75 /// What happened.
76 pub action_type: AuditLogEvent,
77 /// The affected entity (webhook, user, role, …); for
78 /// [`ApplicationCommandPermissionUpdate`](AuditLogEvent::ApplicationCommandPermissionUpdate)
79 /// the command or the application.
80 pub target_id: Option<GenericId>,
81 /// The user or app that made the change.
82 pub user_id: Option<UserId>,
83 /// What was changed on the target.
84 #[serde(default, skip_serializing_if = "Vec::is_empty")]
85 pub changes: Vec<AuditLogChange>,
86 /// Extra information for some event types.
87 #[serde(default, skip_serializing_if = "Option::is_none")]
88 pub options: Option<Box<AuditLogEntryOptions>>,
89 /// The reason given with the `X-Audit-Log-Reason` header (1-512 characters).
90 #[serde(default, skip_serializing_if = "Option::is_none")]
91 pub reason: Option<CompactString>,
92 /// The guild (only in the `GUILD_AUDIT_LOG_ENTRY_CREATE` gateway event).
93 #[serde(default, skip_serializing_if = "Option::is_none")]
94 pub guild_id: Option<GuildId>,
95}
96
97int_enum! {
98 /// The [action of an audit log entry](https://docs.discord.com/developers/resources/audit-log#audit-log-entry-object-audit-log-events).
99 ///
100 /// discord.js counterpart: `AuditLogEvent`.
101 pub enum AuditLogEvent: u8 {
102 /// Server settings were updated (changes: guild fields).
103 GuildUpdate = 1,
104 /// A channel was created (changes: channel fields).
105 ChannelCreate = 10,
106 /// A channel's settings were updated (changes: channel fields).
107 ChannelUpdate = 11,
108 /// A channel was deleted (changes: channel fields).
109 ChannelDelete = 12,
110 /// A permission overwrite was added to a channel (changes: overwrite fields; options:
111 /// `id`, `type`, `role_name`).
112 ChannelOverwriteCreate = 13,
113 /// A permission overwrite was updated (changes: overwrite fields; options: `id`, `type`,
114 /// `role_name`).
115 ChannelOverwriteUpdate = 14,
116 /// A permission overwrite was deleted (changes: overwrite fields; options: `id`, `type`,
117 /// `role_name`).
118 ChannelOverwriteDelete = 15,
119 /// Channels were reordered (options: `count`).
120 ChannelPositionUpdate = 16,
121 /// A member was kicked (options: `integration_type`).
122 MemberKick = 20,
123 /// Members were pruned (options: `delete_member_days`, `members_removed`).
124 MemberPrune = 21,
125 /// A member was banned.
126 MemberBanAdd = 22,
127 /// A ban was lifted.
128 MemberBanRemove = 23,
129 /// A member was updated (changes: member fields).
130 MemberUpdate = 24,
131 /// A member was added to or removed from roles (changes: `$add` / `$remove` with partial
132 /// roles; options: `integration_type`).
133 MemberRoleUpdate = 25,
134 /// A member was moved to another voice channel (options: `channel_id`, `count`).
135 MemberMove = 26,
136 /// A member was disconnected from a voice channel (options: `count`).
137 MemberDisconnect = 27,
138 /// A bot was added.
139 BotAdd = 28,
140 /// A role was created (changes: role fields).
141 RoleCreate = 30,
142 /// A role was edited (changes: role fields).
143 RoleUpdate = 31,
144 /// A role was deleted (changes: role fields).
145 RoleDelete = 32,
146 /// Roles were reordered (options: `count`).
147 RolePositionUpdate = 33,
148 /// An invite was created (changes: invite fields, `channel_id` instead of `channel`).
149 InviteCreate = 40,
150 /// An invite was updated (changes: invite fields).
151 InviteUpdate = 41,
152 /// An invite was deleted (changes: invite fields).
153 InviteDelete = 42,
154 /// A webhook was created (changes: webhook fields, `avatar_hash` instead of `avatar`).
155 WebhookCreate = 50,
156 /// A webhook was updated (changes: webhook fields).
157 WebhookUpdate = 51,
158 /// A webhook was deleted (changes: webhook fields).
159 WebhookDelete = 52,
160 /// An emoji was created (changes: emoji fields).
161 EmojiCreate = 60,
162 /// An emoji was renamed (changes: emoji fields).
163 EmojiUpdate = 61,
164 /// An emoji was deleted (changes: emoji fields).
165 EmojiDelete = 62,
166 /// A message was deleted (options: `channel_id`, `count`).
167 MessageDelete = 72,
168 /// Messages were bulk-deleted (options: `count`).
169 MessageBulkDelete = 73,
170 /// A message was pinned (options: `channel_id`, `message_id`).
171 MessagePin = 74,
172 /// A message was unpinned (options: `channel_id`, `message_id`).
173 MessageUnpin = 75,
174 /// An app was added (changes: integration fields).
175 IntegrationCreate = 80,
176 /// An app was updated, e.g. its scopes (changes: integration fields).
177 IntegrationUpdate = 81,
178 /// An app was removed (changes: integration fields).
179 IntegrationDelete = 82,
180 /// A stage went live (changes: stage instance fields; options: `channel_id`).
181 StageInstanceCreate = 83,
182 /// A stage instance was updated (changes: stage instance fields; options: `channel_id`).
183 StageInstanceUpdate = 84,
184 /// A stage ended (changes: stage instance fields; options: `channel_id`).
185 StageInstanceDelete = 85,
186 /// A sticker was created (changes: sticker fields).
187 StickerCreate = 90,
188 /// A sticker was updated (changes: sticker fields).
189 StickerUpdate = 91,
190 /// A sticker was deleted (changes: sticker fields).
191 StickerDelete = 92,
192 /// A scheduled event was created (changes: scheduled event fields).
193 GuildScheduledEventCreate = 100,
194 /// A scheduled event was updated (changes: scheduled event fields).
195 GuildScheduledEventUpdate = 101,
196 /// A scheduled event was cancelled (changes: scheduled event fields).
197 GuildScheduledEventDelete = 102,
198 /// A thread was created (changes: thread fields).
199 ThreadCreate = 110,
200 /// A thread was updated (changes: thread fields).
201 ThreadUpdate = 111,
202 /// A thread was deleted (changes: thread fields).
203 ThreadDelete = 112,
204 /// A command's permissions were updated (changes keyed by the role, channel or user ID
205 /// with command permission objects; options: `application_id`).
206 ApplicationCommandPermissionUpdate = 121,
207 /// A soundboard sound was created (changes: soundboard sound fields).
208 SoundboardSoundCreate = 130,
209 /// A soundboard sound was updated (changes: soundboard sound fields).
210 SoundboardSoundUpdate = 131,
211 /// A soundboard sound was deleted (changes: soundboard sound fields).
212 SoundboardSoundDelete = 132,
213 /// An auto moderation rule was created (changes: rule fields).
214 AutoModerationRuleCreate = 140,
215 /// An auto moderation rule was updated (changes: rule fields).
216 AutoModerationRuleUpdate = 141,
217 /// An auto moderation rule was deleted (changes: rule fields).
218 AutoModerationRuleDelete = 142,
219 /// Auto moderation blocked a message (options: rule name and trigger type,
220 /// `channel_id`).
221 AutoModerationBlockMessage = 143,
222 /// Auto moderation flagged a message to a channel (options: rule name and trigger type,
223 /// `channel_id`).
224 AutoModerationFlagToChannel = 144,
225 /// Auto moderation timed a member out (options: rule name and trigger type,
226 /// `channel_id`).
227 AutoModerationUserCommunicationDisabled = 145,
228 /// Auto moderation quarantined a member (options: rule name and trigger type,
229 /// `channel_id`).
230 AutoModerationQuarantineUser = 146,
231 /// A creator monetization request was created.
232 CreatorMonetizationRequestCreated = 150,
233 /// The creator monetization terms were accepted.
234 CreatorMonetizationTermsAccepted = 151,
235 /// An onboarding question was created (changes: onboarding prompt fields).
236 OnboardingPromptCreate = 163,
237 /// An onboarding question was updated (changes: onboarding prompt fields).
238 OnboardingPromptUpdate = 164,
239 /// An onboarding question was deleted (changes: onboarding prompt fields).
240 OnboardingPromptDelete = 165,
241 /// Onboarding was created (changes: onboarding fields).
242 OnboardingCreate = 166,
243 /// Onboarding was updated (changes: onboarding fields).
244 OnboardingUpdate = 167,
245 /// The server guide was created.
246 HomeSettingsCreate = 190,
247 /// The server guide was updated.
248 HomeSettingsUpdate = 191,
249 /// A user set a voice channel status (options: `channel_id`, `status`).
250 VoiceChannelStatusCreate = 192,
251 /// A user deleted a voice channel status (options: `channel_id`).
252 VoiceChannelStatusDelete = 193,
253 }
254}
255
256/// The [optional entry info](https://docs.discord.com/developers/resources/audit-log#audit-log-entry-object-optional-audit-entry-info)
257/// of some event types (D-071): see each [`AuditLogEvent`] for the fields it has.
258///
259/// Discord sends the counts and types as strings; they are decoded as numbers and enums and
260/// written back as strings.
261///
262/// discord.js counterpart: `GuildAuditLogsEntry#extra`.
263#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
264#[non_exhaustive]
265#[doc(alias = "OptionalAuditEntryInfo")]
266pub struct AuditLogEntryOptions {
267 /// The application whose command permissions were updated.
268 #[serde(default, skip_serializing_if = "Option::is_none")]
269 pub application_id: Option<ApplicationId>,
270 /// The name of the auto moderation rule that triggered.
271 #[serde(default, skip_serializing_if = "Option::is_none")]
272 pub auto_moderation_rule_name: Option<CompactString>,
273 /// The trigger type of the auto moderation rule that triggered.
274 #[serde(
275 default,
276 skip_serializing_if = "Option::is_none",
277 with = "option_string_number"
278 )]
279 pub auto_moderation_rule_trigger_type: Option<TriggerType>,
280 /// The channel the entities were in.
281 #[serde(default, skip_serializing_if = "Option::is_none")]
282 pub channel_id: Option<ChannelId>,
283 /// The number of entities targeted, or of position updates.
284 #[serde(
285 default,
286 skip_serializing_if = "Option::is_none",
287 with = "option_string_number"
288 )]
289 pub count: Option<u32>,
290 /// The inactivity in days after which members were pruned.
291 #[serde(
292 default,
293 skip_serializing_if = "Option::is_none",
294 with = "option_string_number"
295 )]
296 pub delete_member_days: Option<u32>,
297 /// The overwritten role or member.
298 #[serde(default, skip_serializing_if = "Option::is_none")]
299 pub id: Option<GenericId>,
300 /// The number of members removed by a prune.
301 #[serde(
302 default,
303 skip_serializing_if = "Option::is_none",
304 with = "option_string_number"
305 )]
306 pub members_removed: Option<u32>,
307 /// The pinned or unpinned message.
308 #[serde(default, skip_serializing_if = "Option::is_none")]
309 pub message_id: Option<MessageId>,
310 /// The overwritten role's name (role overwrites only).
311 #[serde(default, skip_serializing_if = "Option::is_none")]
312 pub role_name: Option<CompactString>,
313 /// Whether the overwritten entity is a role or a member.
314 #[serde(
315 default,
316 rename = "type",
317 skip_serializing_if = "Option::is_none",
318 with = "option_string_number"
319 )]
320 pub kind: Option<OverwriteType>,
321 /// The type of integration that performed the action.
322 #[serde(default, skip_serializing_if = "Option::is_none")]
323 pub integration_type: Option<IntegrationType>,
324 /// The new voice channel status.
325 #[serde(default, skip_serializing_if = "Option::is_none")]
326 pub status: Option<CompactString>,
327}
328
329/// A number Discord sends as a decimal string.
330trait StringNumber: Sized + Copy {
331 fn from_u64(value: u64) -> Option<Self>;
332 fn to_u64(self) -> u64;
333}
334
335impl StringNumber for u32 {
336 fn from_u64(value: u64) -> Option<Self> {
337 Self::try_from(value).ok()
338 }
339
340 fn to_u64(self) -> u64 {
341 self.into()
342 }
343}
344
345impl StringNumber for OverwriteType {
346 fn from_u64(value: u64) -> Option<Self> {
347 u8::try_from(value).ok().map(Self::from)
348 }
349
350 fn to_u64(self) -> u64 {
351 u8::from(self).into()
352 }
353}
354
355impl StringNumber for TriggerType {
356 fn from_u64(value: u64) -> Option<Self> {
357 u8::try_from(value).ok().map(Self::from)
358 }
359
360 fn to_u64(self) -> u64 {
361 u8::from(self).into()
362 }
363}
364
365/// (De)serializes an optional number written as a decimal string (numbers are accepted too).
366mod option_string_number {
367 use core::marker::PhantomData;
368
369 use serde::{
370 Deserializer, Serializer,
371 de::{Error, Unexpected, Visitor},
372 };
373
374 use super::StringNumber;
375
376 #[expect(clippy::ref_option, reason = "signature required by serde(with)")]
377 pub(super) fn serialize<T: StringNumber, S: Serializer>(
378 value: &Option<T>,
379 serializer: S,
380 ) -> Result<S::Ok, S::Error> {
381 match value {
382 Some(value) => serializer.collect_str(&value.to_u64()),
383 None => serializer.serialize_none(),
384 }
385 }
386
387 pub(super) fn deserialize<'de, T: StringNumber, D: Deserializer<'de>>(
388 deserializer: D,
389 ) -> Result<Option<T>, D::Error> {
390 struct NumberVisitor<T>(PhantomData<T>);
391
392 impl<'de, T: StringNumber> Visitor<'de> for NumberVisitor<T> {
393 type Value = Option<T>;
394
395 fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
396 f.write_str("a number as a decimal string")
397 }
398
399 fn visit_none<E: Error>(self) -> Result<Self::Value, E> {
400 Ok(None)
401 }
402
403 fn visit_unit<E: Error>(self) -> Result<Self::Value, E> {
404 Ok(None)
405 }
406
407 fn visit_some<D: Deserializer<'de>>(
408 self,
409 deserializer: D,
410 ) -> Result<Self::Value, D::Error> {
411 deserializer.deserialize_any(self)
412 }
413
414 fn visit_u64<E: Error>(self, value: u64) -> Result<Self::Value, E> {
415 T::from_u64(value)
416 .map(Some)
417 .ok_or_else(|| E::invalid_value(Unexpected::Unsigned(value), &self))
418 }
419
420 fn visit_str<E: Error>(self, value: &str) -> Result<Self::Value, E> {
421 value
422 .parse()
423 .ok()
424 .and_then(T::from_u64)
425 .map(Some)
426 .ok_or_else(|| E::invalid_value(Unexpected::Str(value), &self))
427 }
428 }
429
430 deserializer.deserialize_option(NumberVisitor(PhantomData))
431 }
432}
433
434/// A [change](https://docs.discord.com/developers/resources/audit-log#audit-log-change-object)
435/// in an audit log entry: one field of the target, with its old and new value (D-070).
436///
437/// The key is usually a field of the changed object, with these exceptions:
438/// - member role updates use `$add` / `$remove`, with arrays of partial roles
439/// (`{"id", "name"}`) as the new value;
440/// - command permission updates use the role, channel or user ID, with command permission
441/// objects as values;
442/// - invites use `channel_id` instead of `channel`, webhooks `avatar_hash` instead of `avatar`.
443///
444/// An absent [`new_value`](Self::new_value) means the field was reset or set to `null`; an
445/// absent [`old_value`](Self::old_value) means it was `null` before.
446///
447/// discord.js counterpart: `AuditLogChange`.
448///
449/// # Examples
450///
451/// ```
452/// use djs_model::{audit_log::AuditLogChange, permissions::Permissions};
453///
454/// let change: AuditLogChange =
455/// serde_json::from_str(r#"{"key":"permissions","old_value":"0","new_value":"8"}"#).unwrap();
456/// assert_eq!(change.key, "permissions");
457/// let new: Option<Permissions> = change.new_value_as().unwrap();
458/// assert_eq!(new, Some(Permissions::ADMINISTRATOR));
459/// ```
460#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
461#[non_exhaustive]
462pub struct AuditLogChange {
463 /// The changed field (see the exceptions above).
464 pub key: CompactString,
465 /// The value before the change.
466 #[serde(default, skip_serializing_if = "Option::is_none")]
467 pub old_value: Option<JsonValue>,
468 /// The value after the change.
469 #[serde(default, skip_serializing_if = "Option::is_none")]
470 pub new_value: Option<JsonValue>,
471}
472
473impl AuditLogChange {
474 /// Converts the [`old_value`](Self::old_value) to the field's type (`Ok(None)` if absent).
475 ///
476 /// discord.js counterpart: the `old` of `AuditLogChange`.
477 ///
478 /// # Errors
479 ///
480 /// Returns an error if the value does not have the shape of `T`.
481 pub fn old_value_as<'a, T: Deserialize<'a>>(&'a self) -> Result<Option<T>, JsonValueError> {
482 self.old_value.as_ref().map(JsonValue::to_type).transpose()
483 }
484
485 /// Converts the [`new_value`](Self::new_value) to the field's type (`Ok(None)` if absent).
486 ///
487 /// discord.js counterpart: the `new` of `AuditLogChange`.
488 ///
489 /// # Errors
490 ///
491 /// Returns an error if the value does not have the shape of `T`.
492 pub fn new_value_as<'a, T: Deserialize<'a>>(&'a self) -> Result<Option<T>, JsonValueError> {
493 self.new_value.as_ref().map(JsonValue::to_type).transpose()
494 }
495}
496
497#[cfg(test)]
498mod tests {
499 use core::mem::size_of;
500
501 use super::*;
502
503 #[test]
504 fn sizes() {
505 assert!(
506 size_of::<AuditLogEntry>() <= 128,
507 "{}",
508 size_of::<AuditLogEntry>()
509 );
510 }
511}