Merge pull request #981 from discordeno/toJSON

.toJSON()
This commit is contained in:
ITOH
2021-05-23 17:28:51 +02:00
committed by GitHub
6 changed files with 208 additions and 0 deletions
+35
View File
@@ -24,6 +24,39 @@ import { DiscordenoVoiceState } from "./voice_state.ts";
const CHANNEL_SNOWFLAKES = ["id", "guildId", "lastMessageId", "ownerId", "applicationId", "parentId"];
const baseChannel: Partial<DiscordenoChannel> = {
toJSON() {
return {
id: this.id?.toString(),
type: this.type,
guildId: this.guildId?.toString(),
position: this.position,
permissionOverwrites: this.permissionOverwrites?.map((o) => ({
...o,
id: o.id.toString(),
allow: o.allow.toString(),
deny: o.deny.toString(),
})),
name: this.name,
topic: this.topic,
nsfw: this.nsfw,
lastMessageId: this.lastMessageId?.toString(),
bitrate: this.bitrate,
userLimit: this.userLimit,
rateLimitPerUser: this.rateLimitPerUser,
recipients: this.recipients,
icon: this.icon,
ownerId: this.ownerId,
applicationId: this.applicationId,
parentId: this.parentId,
lastPinTimestamp: this.lastPinTimestamp ? new Date(this.lastPinTimestamp).toISOString() : undefined,
rtcRegion: this.rtcRegion,
videoQualityMode: this.videoQualityMode,
messageCount: this.messageCount,
memberCount: this.memberCount,
threadMetadata: this.threadMetadata,
member: this.member,
} as Channel;
},
get guild() {
return cache.guilds.get(this.guildId!);
},
@@ -177,4 +210,6 @@ export interface DiscordenoChannel
edit(options: ModifyChannel, reason?: string): ReturnType<typeof editChannel>;
/** Create a new channel with the same properties */
clone(reason?: string): ReturnType<typeof cloneChannel>;
/** Returns the Channel object json value */
toJSON(): Channel;
}
+56
View File
@@ -63,6 +63,60 @@ export const guildToggles = {
};
const baseGuild: Partial<DiscordenoGuild> = {
toJSON() {
return {
shardId: this.shardId!,
id: this.id?.toString(),
name: this.name,
icon: this.icon,
iconHash: undefined,
splash: this.splash,
discoverySplash: this.discoverySplash,
owner: this.owner,
ownerId: this.ownerId?.toString(),
permissions: this.permissions,
region: this.region,
afkChannelId: this.afkChannelId?.toString(),
afkTimeout: this.afkTimeout,
widgetEnabled: this.widgetEnabled,
widgetChannelId: this.widgetChannelId?.toString(),
verificationLevel: this.verificationLevel,
defaultMessageNotifications: this.defaultMessageNotifications,
explicitContentFilter: this.explicitContentFilter,
roles: this.roles?.map((r) => r.toJSON()) || [],
emojis: this.emojis?.array() || [],
features: this.features,
mfaLevel: this.mfaLevel,
applicationId: this.applicationId?.toString(),
systemChannelId: this.systemChannelId?.toString(),
systemChannelFlags: this.systemChannelFlags,
rulesChannelId: this.rulesChannelId?.toString(),
joinedAt: this.joinedAt ? new Date(this.joinedAt).toISOString() : undefined,
large: this.large,
unavailable: this.unavailable,
memberCount: this.memberCount,
voiceStates: this.voiceStates,
members: this.members,
channels: this.channels,
threads: this.threads,
presences: this.presences,
maxPresences: this.maxPresences,
maxMembers: this.maxMembers,
vanityUrlCode: this.vanityUrlCode,
description: this.description,
banner: this.banner,
premiumTier: this.premiumTier,
premiumSubscriptionCount: this.premiumSubscriptionCount,
preferredLocale: this.preferredLocale,
publicUpdatesChannelId: this.publicUpdatesChannelId?.toString(),
maxVideoChannelUsers: this.maxVideoChannelUsers,
approximateMemberCount: this.approximateMemberCount,
approximatePresenceCount: this.approximatePresenceCount,
welcomeScreen: this.welcomeScreen,
nsfwLevel: this.nsfwLevel,
stageInstances: this.stageInstances,
} as Guild & { shardId: number };
},
get members() {
return cache.members.filter((member) => member.guilds.has(this.id!));
},
@@ -375,4 +429,6 @@ export interface DiscordenoGuild
unban(memberId: bigint): ReturnType<typeof unbanMember>;
/** Get all the invites for this guild. Requires MANAGE_GUILD permission */
invites(): ReturnType<typeof getInvites>;
/** Get the JSON version of the Guild object used to create this. Includes the shardId as well */
toJSON(): Guild & { shardId: number };
}
+28
View File
@@ -100,6 +100,32 @@ const baseMember: Partial<DiscordenoMember> = {
get animatedAvatar() {
return Boolean(this.bitfield! & memberToggles.animatedAvatar);
},
toJSON() {
return (this.guilds?.map((g) => ({
user: {
id: this.id?.toString(),
username: this.username,
discriminator: this.discriminator?.toString(),
avatar: this.avatar,
bot: this.bot,
system: this.system,
mfaEnabled: this.mfaEnabled,
locale: this.locale,
verified: this.verified,
email: this.email,
flags: this.flags,
premiumType: this.premiumType,
publicFlags: this.publicFlags,
},
nick: g.nick,
roles: g.roles.map((id) => id.toString()),
joinedAt: g.joinedAt ? new Date(g.joinedAt).toISOString() : undefined,
premiumSince: g.premiumSince,
deaf: g.deaf,
mute: g.mute,
pending: g.pending,
})) || []) as (GuildMemberWithUser & { guildId: string })[];
},
};
export async function createDiscordenoMember(
@@ -220,4 +246,6 @@ export interface DiscordenoMember extends Omit<User, "discriminator" | "id"> {
addRole(guildId: bigint, roleId: bigint, reason?: string): ReturnType<typeof addRole>;
/** Remove a role from the member */
removeRole(guildId: bigint, roleId: bigint, reason?: string): ReturnType<typeof removeRole>;
/** Converts to a json object */
toJSON(): (GuildMemberWithUser & { guildId: string })[];
}
+50
View File
@@ -143,6 +143,54 @@ const baseMessage: Partial<DiscordenoMessage> = {
get pinned() {
return Boolean(this.bitfield! & messageToggles.pinned);
},
toJSON() {
return {
id: this.id?.toString(),
channelId: this.channelId?.toString(),
guildId: this.guildId?.toString(),
author: {
id: this.authorId?.toString(),
username: this.tag?.substring(0, this.tag.length - 5),
discriminator: this.tag?.substring(this.tag.length - 4),
avatar: this.member?.avatar,
bot: this.member?.bot,
system: this.member?.system,
mfaEnabled: this.member?.mfaEnabled,
locale: this.member?.locale,
verified: this.member?.verified,
email: this.member?.email,
flags: this.member?.flags,
premiumType: this.member?.premiumType,
publicFlags: this.member?.publicFlags,
},
member: this.member,
content: this.content,
timestamp: this.timestamp ? new Date(this.timestamp).toISOString() : undefined,
editedTimestamp: this.editedTimestamp ? new Date(this.editedTimestamp).toISOString() : undefined,
tts: this.tts,
mentionEveryone: this.mentionEveryone,
mentions: this.mentions,
mentionRoles: this.mentionRoles,
mentionChannels: this.mentionChannels,
attachments: this.attachments,
embeds: this.embeds,
reactions: this.reactions,
nonce: this.nonce,
pinned: this.pinned,
webhookId: this.webhookId,
type: this.type,
activity: this.activity,
application: this.application,
applicationId: this.applicationId,
messageReference: this.messageReference,
flags: this.flags,
stickers: this.stickers,
referencedMessage: this.referencedMessage,
interaction: this.interaction,
thread: this.thread,
components: this.components,
} as Message;
},
};
export async function createDiscordenoMessage(data: Message) {
@@ -314,4 +362,6 @@ export interface DiscordenoMessage
removeReactionEmoji(reaction: string): ReturnType<typeof removeReactionEmoji>;
/** Removes a reaction from the given user on this message, defaults to bot */
removeReaction(reaction: string, userId?: bigint): ReturnType<typeof removeReaction>;
/** Convert to json */
toJSON(): Message;
}
+20
View File
@@ -84,6 +84,24 @@ const baseRole: Partial<DiscordenoRole> = {
get isNitroBoostRole() {
return Boolean(this.bitfield! & roleToggles.isNitroBoostRole);
},
toJSON() {
return {
guildId: this.guildId?.toString(),
id: this.id?.toString(),
name: this.name,
color: this.color,
hoist: this.hoist,
position: this.position,
permissions: this.permissions?.toString(),
managed: this.managed,
mentionable: this.mentionable,
tags: {
botId: this.botId?.toString(),
integrationId: this.integrationId?.toString(),
premiumSubscriber: this.isNitroBoostRole,
},
} as Role & { guildId: string };
},
};
// deno-lint-ignore require-await
@@ -155,4 +173,6 @@ export interface DiscordenoRole extends Omit<Role, "tags" | "id"> {
higherThanRole(roleId: bigint, position?: number): boolean;
/** Checks if the role has a higher position than the given member */
higherThanMember(memberId: bigint): Promise<boolean>;
/** Convert to json friendly role with guild id */
toJSON(): Role & { guildId: string };
}
+19
View File
@@ -57,6 +57,23 @@ const baseRole: Partial<DiscordenoVoiceState> = {
get suppress() {
return Boolean(this.bitfield! & voiceStateToggles.suppress);
},
toJSON() {
return {
guildId: this.guildId?.toString(),
channelId: this.channelId?.toString(),
userId: this.userId?.toString(),
member: this.member,
sessionId: this.sessionId,
deaf: this.deaf,
mute: this.mute,
selfDeaf: this.selfDeaf,
selfMute: this.selfMute,
selfStream: this.selfStream,
selfVideo: this.selfVideo,
suppress: this.suppress,
requestToSpeakTimestamp: this.requestToSpeakTimestamp,
} as VoiceState;
}
};
// deno-lint-ignore require-await
@@ -109,4 +126,6 @@ export interface DiscordenoVoiceState extends Omit<VoiceState, "channelId" | "gu
};
/** The guild where this role is. If undefined, the guild is not cached */
guild?: DiscordenoGuild;
/** Converts to the raw JSON format. */
toJSON(): VoiceState;
}