feat(Guild): AuditLogs (#96)

* fetch audit logs

* vefificationLevel

* types
This commit is contained in:
MARCROCK22 2022-08-07 22:18:39 -04:00 committed by GitHub
parent e25c527f0e
commit 4d90686ee6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 473 additions and 350 deletions

View File

@ -1,4 +1,4 @@
import type { Snowflake } from '../common'; import type { AuditLogEvents, Snowflake } from '../common';
export * from './cdn'; export * from './cdn';
export function USER(userId?: Snowflake): string { export function USER(userId?: Snowflake): string {
@ -132,6 +132,30 @@ export function GUILD_EMOJIS(guildId: Snowflake): string {
return `/guilds/${guildId}/emojis`; return `/guilds/${guildId}/emojis`;
} }
export interface GetAuditLogs {
userId?: Snowflake;
actionType?: AuditLogEvents
before?: Snowflake;
limit?: number;
}
export function GUILD_AUDIT_LOGS(guildId: Snowflake, options?: GetAuditLogs) {
let url = `/guilds/${guildId}/audit-logs?`;
if (options) {
const obj = {
user_id: options.userId,
action_type: options.actionType,
before: options.before,
limit: options.limit
};
for (const [key, value] of Object.entries(obj)) {
if (!value) continue;
url += `&${key}=${value}`
}
}
return url;
}
export function GUILD_EMOJI(guildId: Snowflake, emojiId: Snowflake): string { export function GUILD_EMOJI(guildId: Snowflake, emojiId: Snowflake): string {
return `/guilds/${guildId}/emojis/${emojiId}`; return `/guilds/${guildId}/emojis/${emojiId}`;
} }

View File

@ -1439,7 +1439,12 @@ export interface DiscordAuditLog {
/** List of audit log entries, sorted from most to least recent */ /** List of audit log entries, sorted from most to least recent */
audit_log_entries: DiscordAuditLogEntry[]; audit_log_entries: DiscordAuditLogEntry[];
/** List of partial integration objects */ /** List of partial integration objects */
integrations: Partial<DiscordIntegration>[]; integrations: ({
type: 'youtube' | 'twitch' | 'discord';
id: string;
name: string;
account: DiscordIntegrationAccount;
} & Partial<DiscordIntegration>)[];
/** /**
* List of threads found in the audit log. * List of threads found in the audit log.
* Threads referenced in `THREAD_CREATE` and `THREAD_UPDATE` events are included in the threads map since archived threads might not be kept in memory by clients. * Threads referenced in `THREAD_CREATE` and `THREAD_UPDATE` events are included in the threads map since archived threads might not be kept in memory by clients.

View File

@ -26,6 +26,11 @@ import {
GetBans, GetBans,
GetInvite, GetInvite,
ListGuildMembers, ListGuildMembers,
GetAuditLogs,
GUILD_AUDIT_LOGS,
DiscordAuditLog,
AuditLogEvents,
DiscordAuditLogChange,
} from '@biscuitland/api-types'; } from '@biscuitland/api-types';
import type { ImageFormat, ImageSize } from '../utils/util'; import type { ImageFormat, ImageSize } from '../utils/util';
import { GuildFeatures, PremiumTiers } from '@biscuitland/api-types'; import { GuildFeatures, PremiumTiers } from '@biscuitland/api-types';
@ -69,6 +74,9 @@ import { Widget } from './widget';
import { Sticker } from './sticker'; import { Sticker } from './sticker';
import { WelcomeScreen } from './welcome'; import { WelcomeScreen } from './welcome';
import { AutoModerationRule } from './automod'; import { AutoModerationRule } from './automod';
import { Webhook } from './webhook';
import { ScheduledEvent } from './scheduled-events';
import Integration from './integration';
/** BaseGuild */ /** BaseGuild */
/** /**
@ -482,6 +490,38 @@ export interface GuildEditOptions extends Partial<GuildCreateOptions> {
premiumProgressBarEnabled?: boolean; premiumProgressBarEnabled?: boolean;
} }
export interface AuditLogResult {
auditLogEntries: {
targetId: string | null;
changes: {
key: DiscordAuditLogChange['key'];
oldValue: DiscordOverwrite[] | Role[] | string | number | boolean | null;
newValue: DiscordOverwrite[] | Role[] | string | number | boolean | null;
}[] | undefined;
userId: string | null;
id: string;
actionType: AuditLogEvents;
options: {
deleteMemberDays: string;
membersRemoved: string;
channelId: string;
messageId: string;
count: string;
id: string;
type: string;
roleName: string;
applicationId: string;
} | null;
reason: string | undefined;
}[];
autoModerationRules: AutoModerationRule[] | undefined;
guildScheduledEvents: ScheduledEvent[] | undefined;
integrations: Integration[];
threads: ThreadChannel[];
users: User[];
webhooks: Webhook[];
}
/** /**
* Represents a guild. * Represents a guild.
* @see {@link BaseGuild}. * @see {@link BaseGuild}.
@ -502,7 +542,7 @@ export class Guild extends BaseGuild implements Model {
this.widgetChannelId = data.widget_channel_id this.widgetChannelId = data.widget_channel_id
? data.widget_channel_id ? data.widget_channel_id
: undefined; : undefined;
this.vefificationLevel = data.verification_level; this.verificationLevel = data.verification_level;
this.defaultMessageNotificationLevel = this.defaultMessageNotificationLevel =
data.default_message_notifications; data.default_message_notifications;
this.explicitContentFilterLevel = data.explicit_content_filter; this.explicitContentFilterLevel = data.explicit_content_filter;
@ -558,7 +598,7 @@ export class Guild extends BaseGuild implements Model {
* @see {@link VerificationLevels} * @see {@link VerificationLevels}
* @link https://discord.com/developers/docs/resources/guild#guild-object-verification-level * @link https://discord.com/developers/docs/resources/guild#guild-object-verification-level
*/ */
vefificationLevel: VerificationLevels; verificationLevel: VerificationLevels;
/** /**
* The default message notification level. * The default message notification level.
@ -1239,6 +1279,60 @@ export class Guild extends BaseGuild implements Model {
return channels.map(channel => ChannelFactory.fromGuildChannel(this.session, channel)); return channels.map(channel => ChannelFactory.fromGuildChannel(this.session, channel));
} }
async fetchAuditLogs(options?: GetAuditLogs): Promise<AuditLogResult> {
const auditLog = await this.session.rest.get<DiscordAuditLog>(GUILD_AUDIT_LOGS(this.id, options));
return {
auditLogEntries: auditLog.audit_log_entries.map(x => ({
targetId: x.target_id,
changes: x.changes?.map(j => ({
key: j.key,
oldValue: j.old_value
? j.key === 'permission_overwrites'
? (j.old_value as DiscordOverwrite[])
: ['$add', '$remove'].includes(j.key)
? (j.old_value as DiscordRole[]).map(j => new Role(this.session, { ...j, permissions: j.permissions || '0' }, this.id))
: j.old_value as string | number | boolean
: null,
newValue: j.new_value
? j.key === 'permission_overwrites'
? (j.new_value as DiscordOverwrite[])
: ['$add', '$remove'].includes(j.key)
? (j.new_value as DiscordRole[]).map(j => new Role(this.session, { ...j, permissions: j.permissions || '0' }, this.id))
: j.new_value as string | number | boolean
: null,
})),
userId: x.user_id,
id: x.id,
actionType: x.action_type,
options: x.options ? {
deleteMemberDays: x.options.delete_member_days,
membersRemoved: x.options.members_removed,
channelId: x.options.channel_id,
messageId: x.options.message_id,
count: x.options.count,
id: x.options.id,
type: x.options.type,
roleName: x.options.role_name,
applicationId: x.options.application_id
} : null,
reason: x.reason,
})),
autoModerationRules: auditLog.auto_moderation_rules?.map(x => new AutoModerationRule(this.session, x)),
guildScheduledEvents: auditLog.guild_scheduled_events?.map(x => new ScheduledEvent(this.session, x)),
integrations: auditLog.integrations.map(x => new Integration(this.session, {
guild_id: this.id,
...x,
})),
threads: auditLog.threads.map(x => ChannelFactory.fromGuildChannel(this.session, x) as ThreadChannel),
users: auditLog.users.map(x => new User(this.session, x)),
webhooks: auditLog.webhooks.map(x => new Webhook(this.session, x)),
}
}
async fetchOwner(): Promise<Member> {
return this.fetchMember(this.ownerId);
}
/** fetches a member */ /** fetches a member */
async fetchMember(memberId: Snowflake): Promise<Member> { async fetchMember(memberId: Snowflake): Promise<Member> {
const member = await this.session.rest.get<DiscordMemberWithUser>( const member = await this.session.rest.get<DiscordMemberWithUser>(