From f31caf5dbb7207660587ab2b6d8405e42566bb8a Mon Sep 17 00:00:00 2001 From: TriForMine Date: Tue, 29 Dec 2020 23:32:50 +0100 Subject: [PATCH] Added await in async function, fixed typos and used inline variable for return --- src/api/controllers/channels.ts | 20 ++++------ src/api/controllers/guilds.ts | 17 ++++---- src/api/controllers/members.ts | 12 +++--- src/api/controllers/messages.ts | 20 +++++----- src/api/controllers/misc.ts | 17 ++++---- src/api/controllers/reactions.ts | 10 ++--- src/api/controllers/roles.ts | 15 +++---- src/api/handlers/channel.ts | 23 ++++------- src/api/handlers/guild.ts | 54 +++++++++++--------------- src/api/handlers/member.ts | 26 ++++++------- src/api/handlers/message.ts | 29 ++++++-------- src/api/handlers/webhook.ts | 26 ++++++------- src/api/structures/channel.ts | 23 +++++------ src/api/structures/message.ts | 15 +++---- src/api/structures/template.ts | 12 +++--- src/bot.ts | 14 +++---- src/interactions/types/embed.ts | 2 +- src/interactions/types/interactions.ts | 8 ++-- src/interactions/types/slash.ts | 7 +--- src/rest/request_manager.ts | 20 ++++------ src/types/channel.ts | 6 +-- src/types/guild.ts | 18 ++++----- src/types/interactions.ts | 4 +- src/util/collection.ts | 6 +-- src/util/permissions.ts | 11 +++--- src/ws/shard.ts | 23 +++++------ src/ws/shard_manager.ts | 33 ++++++---------- 27 files changed, 197 insertions(+), 274 deletions(-) diff --git a/src/api/controllers/channels.ts b/src/api/controllers/channels.ts index cc0f3b7bf..1e36a41e5 100644 --- a/src/api/controllers/channels.ts +++ b/src/api/controllers/channels.ts @@ -1,11 +1,7 @@ -import { eventHandlers } from "../../bot.ts"; -import { - ChannelCreatePayload, - ChannelTypes, - DiscordPayload, -} from "../../types/mod.ts"; -import { structures } from "../structures/structures.ts"; -import { cacheHandlers } from "./cache.ts"; +import {eventHandlers} from "../../bot.ts"; +import {ChannelCreatePayload, ChannelTypes, DiscordPayload,} from "../../types/mod.ts"; +import {structures} from "../structures/mod.ts"; +import {cacheHandlers} from "./cache.ts"; export async function handleInternalChannelCreate(data: DiscordPayload) { if (data.t !== "CHANNEL_CREATE") return; @@ -29,7 +25,7 @@ export async function handleInternalChannelDelete(data: DiscordPayload) { const guild = await cacheHandlers.get("guilds", payload.guild_id); if (guild) { - guild.voiceStates.forEach(async (vs, key) => { + return Promise.all(guild.voiceStates.map(async (vs, key) => { if (vs.channelID !== payload.id) return; // Since this channel was deleted all voice states for this channel should be deleted @@ -39,11 +35,11 @@ export async function handleInternalChannelDelete(data: DiscordPayload) { if (!member) return; eventHandlers.voiceChannelLeave?.(member, vs.channelID); - }); + })) } } - cacheHandlers.delete("channels", payload.id); + await cacheHandlers.delete("channels", payload.id); cacheHandlers.forEach("messages", (message) => { if (message.channelID === payload.id) { cacheHandlers.delete("messages", message.id); @@ -58,7 +54,7 @@ export async function handleInternalChannelUpdate(data: DiscordPayload) { const payload = data.d as ChannelCreatePayload; const cachedChannel = await cacheHandlers.get("channels", payload.id); const channel = await structures.createChannel(payload); - cacheHandlers.set("channels", channel.id, channel); + await cacheHandlers.set("channels", channel.id, channel); if (!cachedChannel) return; diff --git a/src/api/controllers/guilds.ts b/src/api/controllers/guilds.ts index 2f8029c95..c7c1c0c6d 100644 --- a/src/api/controllers/guilds.ts +++ b/src/api/controllers/guilds.ts @@ -1,4 +1,4 @@ -import { eventHandlers } from "../../bot.ts"; +import {eventHandlers} from "../../bot.ts"; import { CreateGuildPayload, DiscordPayload, @@ -7,9 +7,9 @@ import { GuildUpdateChange, UpdateGuildPayload, } from "../../types/mod.ts"; -import { cache } from "../../util/cache.ts"; -import { structures } from "../structures/structures.ts"; -import { cacheHandlers } from "./cache.ts"; +import {cache} from "../../util/cache.ts"; +import {structures} from "../structures/mod.ts"; +import {cacheHandlers} from "./cache.ts"; export async function handleInternalGuildCreate( data: DiscordPayload, @@ -26,10 +26,10 @@ export async function handleInternalGuildCreate( shardID, ); - cacheHandlers.set("guilds", guild.id, guild); + await cacheHandlers.set("guilds", guild.id, guild); - if (cacheHandlers.has("unavailableGuilds", payload.id)) { - cacheHandlers.delete("unavailableGuilds", payload.id); + if (await cacheHandlers.has("unavailableGuilds", payload.id)) { + await cacheHandlers.delete("unavailableGuilds", payload.id); } if (!cache.isReady) return eventHandlers.guildLoaded?.(guild); @@ -52,7 +52,7 @@ export async function handleInternalGuildDelete(data: DiscordPayload) { } }); - cacheHandlers.delete("guilds", payload.id); + await cacheHandlers.delete("guilds", payload.id); if (payload.unavailable) { return cacheHandlers.set("unavailableGuilds", payload.id, Date.now()); @@ -101,7 +101,6 @@ export async function handleInternalGuildUpdate(data: DiscordPayload) { cachedGuild[key] = value; return { key, oldValue: cachedValue, value }; } - return; }).filter((change) => change) as GuildUpdateChange[]; return eventHandlers.guildUpdate?.(cachedGuild, changes); diff --git a/src/api/controllers/members.ts b/src/api/controllers/members.ts index 0ea0a4a7c..46fca022b 100644 --- a/src/api/controllers/members.ts +++ b/src/api/controllers/members.ts @@ -1,4 +1,4 @@ -import { eventHandlers } from "../../bot.ts"; +import {eventHandlers} from "../../bot.ts"; import { DiscordPayload, GuildBanPayload, @@ -6,10 +6,10 @@ import { GuildMemberChunkPayload, GuildMemberUpdatePayload, } from "../../types/mod.ts"; -import { cache } from "../../util/cache.ts"; -import { Collection } from "../../util/collection.ts"; -import { structures } from "../structures/structures.ts"; -import { cacheHandlers } from "./cache.ts"; +import {cache} from "../../util/cache.ts"; +import {Collection} from "../../util/collection.ts"; +import {structures} from "../structures/mod.ts"; +import {cacheHandlers} from "./cache.ts"; export async function handleInternalGuildMemberAdd(data: DiscordPayload) { if (data.t !== "GUILD_MEMBER_ADD") return; @@ -39,7 +39,7 @@ export async function handleInternalGuildMemberRemove(data: DiscordPayload) { eventHandlers.guildMemberRemove?.(guild, payload.user, member); member?.guilds.delete(guild.id); - if (member && !member.guilds.size) cacheHandlers.delete("members", member.id); + if (member && !member.guilds.size) await cacheHandlers.delete("members", member.id); } export async function handleInternalGuildMemberUpdate(data: DiscordPayload) { diff --git a/src/api/controllers/messages.ts b/src/api/controllers/messages.ts index db9ac2f7b..27c9fd216 100644 --- a/src/api/controllers/messages.ts +++ b/src/api/controllers/messages.ts @@ -1,12 +1,12 @@ -import { eventHandlers } from "../../bot.ts"; +import {eventHandlers} from "../../bot.ts"; import { DiscordPayload, MessageCreateOptions, MessageDeleteBulkPayload, MessageDeletePayload, } from "../../types/mod.ts"; -import { structures } from "../structures/structures.ts"; -import { cacheHandlers } from "./cache.ts"; +import {structures} from "../structures/mod.ts"; +import {cacheHandlers} from "./cache.ts"; export async function handleInternalMessageCreate(data: DiscordPayload) { if (data.t !== "MESSAGE_CREATE") return; @@ -39,7 +39,7 @@ export async function handleInternalMessageCreate(data: DiscordPayload) { const message = await structures.createMessage(payload); // Cache the message - cacheHandlers.set("messages", payload.id, message); + await cacheHandlers.set("messages", payload.id, message); eventHandlers.messageCreate?.(message); } @@ -56,7 +56,7 @@ export async function handleInternalMessageDelete(data: DiscordPayload) { await cacheHandlers.get("messages", payload.id), ); - cacheHandlers.delete("messages", payload.id); + await cacheHandlers.delete("messages", payload.id); } export async function handleInternalMessageDeleteBulk(data: DiscordPayload) { @@ -66,13 +66,13 @@ export async function handleInternalMessageDeleteBulk(data: DiscordPayload) { const channel = await cacheHandlers.get("channels", payload.channel_id); if (!channel) return; - payload.ids.forEach(async (id) => { + return Promise.all(payload.ids.map(async (id) => { eventHandlers.messageDelete?.( - { id, channel }, - await cacheHandlers.get("messages", id), + { id, channel }, + await cacheHandlers.get("messages", id), ); - cacheHandlers.delete("messages", id); - }); + await cacheHandlers.delete("messages", id); + })) } export async function handleInternalMessageUpdate(data: DiscordPayload) { diff --git a/src/api/controllers/misc.ts b/src/api/controllers/misc.ts index 8e2ad89df..0b5df7053 100644 --- a/src/api/controllers/misc.ts +++ b/src/api/controllers/misc.ts @@ -1,4 +1,4 @@ -import { eventHandlers, setBotID } from "../../bot.ts"; +import {eventHandlers, setBotID} from "../../bot.ts"; import { DiscordPayload, PresenceUpdatePayload, @@ -8,14 +8,11 @@ import { VoiceStateUpdatePayload, WebhookUpdatePayload, } from "../../types/mod.ts"; -import { cache } from "../../util/cache.ts"; -import { delay } from "../../util/utils.ts"; -import { allowNextShard } from "../../ws/shard_manager.ts"; -import { - initialMemberLoadQueue, - structures, -} from "../structures/structures.ts"; -import { cacheHandlers } from "./cache.ts"; +import {cache} from "../../util/cache.ts"; +import {delay} from "../../util/utils.ts"; +import {allowNextShard} from "../../ws/shard_manager.ts"; +import {initialMemberLoadQueue, structures,} from "../structures/structures.ts"; +import {cacheHandlers} from "./cache.ts"; /** This function is the internal handler for the ready event. Users can override this with controllers if desired. */ export async function handleInternalReady( @@ -54,7 +51,7 @@ export async function handleInternalPresenceUpdate(data: DiscordPayload) { const payload = data.d as PresenceUpdatePayload; const oldPresence = await cacheHandlers.get("presences", payload.user.id); - cacheHandlers.set("presences", payload.user.id, payload); + await cacheHandlers.set("presences", payload.user.id, payload); return eventHandlers.presenceUpdate?.(payload, oldPresence); } diff --git a/src/api/controllers/reactions.ts b/src/api/controllers/reactions.ts index da3c33fe7..428810d15 100644 --- a/src/api/controllers/reactions.ts +++ b/src/api/controllers/reactions.ts @@ -1,12 +1,12 @@ -import { botID, eventHandlers } from "../../bot.ts"; +import {botID, eventHandlers} from "../../bot.ts"; import { BaseMessageReactionPayload, DiscordPayload, MessageReactionPayload, MessageReactionRemoveEmojiPayload, } from "../../types/mod.ts"; -import { structures } from "../structures/structures.ts"; -import { cacheHandlers } from "./cache.ts"; +import {structures} from "../structures/mod.ts"; +import {cacheHandlers} from "./cache.ts"; export async function handleInternalMessageReactionAdd(data: DiscordPayload) { if (data.t !== "MESSAGE_REACTION_ADD") return; @@ -34,7 +34,7 @@ export async function handleInternalMessageReactionAdd(data: DiscordPayload) { : [newReaction]; } - cacheHandlers.set("messages", payload.message_id, message); + await cacheHandlers.set("messages", payload.message_id, message); } if (payload.member && payload.guild_id) { @@ -87,7 +87,7 @@ export async function handleInternalMessageReactionRemove( : [newReaction]; } - cacheHandlers.set("messages", payload.message_id, message); + await cacheHandlers.set("messages", payload.message_id, message); } if (payload.member && payload.guild_id) { diff --git a/src/api/controllers/roles.ts b/src/api/controllers/roles.ts index 16dda7e1c..c45062233 100644 --- a/src/api/controllers/roles.ts +++ b/src/api/controllers/roles.ts @@ -1,11 +1,7 @@ -import { eventHandlers } from "../../bot.ts"; -import { - DiscordPayload, - GuildRoleDeletePayload, - GuildRolePayload, -} from "../../types/mod.ts"; -import { structures } from "../structures/structures.ts"; -import { cacheHandlers } from "./cache.ts"; +import {eventHandlers} from "../../bot.ts"; +import {DiscordPayload, GuildRoleDeletePayload, GuildRolePayload,} from "../../types/mod.ts"; +import {structures} from "../structures/mod.ts"; +import {cacheHandlers} from "./cache.ts"; export async function handleInternalGuildRoleCreate(data: DiscordPayload) { if (data.t !== "GUILD_ROLE_CREATE") return; @@ -15,8 +11,7 @@ export async function handleInternalGuildRoleCreate(data: DiscordPayload) { if (!guild) return; const role = await structures.createRole(payload.role); - const roles = guild.roles.set(payload.role.id, role); - guild.roles = roles; + guild.roles = guild.roles.set(payload.role.id, role); return eventHandlers.roleCreate?.(guild, role); } diff --git a/src/api/handlers/channel.ts b/src/api/handlers/channel.ts index c608c30d8..d4abba77c 100644 --- a/src/api/handlers/channel.ts +++ b/src/api/handlers/channel.ts @@ -1,4 +1,4 @@ -import { RequestManager } from "../../rest/mod.ts"; +import {RequestManager} from "../../rest/mod.ts"; import { ChannelEditOptions, ChannelTypes, @@ -16,13 +16,10 @@ import { RawOverwrite, WebhookPayload, } from "../../types/mod.ts"; -import { endpoints } from "../../util/constants.ts"; -import { - botHasChannelPermissions, - calculateBits, -} from "../../util/permissions.ts"; -import { cacheHandlers } from "../controllers/cache.ts"; -import { structures } from "../structures/structures.ts"; +import {endpoints} from "../../util/constants.ts"; +import {botHasChannelPermissions, calculateBits,} from "../../util/permissions.ts"; +import {cacheHandlers} from "../controllers/cache.ts"; +import {structures} from "../structures/mod.ts"; /** Checks if a channel overwrite for a user id or a role id has permission in this channel */ export function channelOverwriteHasPermission( @@ -303,7 +300,7 @@ export async function getChannelWebhooks(channelID: string) { ) { throw new Error(Errors.MISSING_MANAGE_WEBHOOKS); } - return RequestManager.get(endpoints.CHANNEL_WEBHOOKS(channelID)) as Promise< + return await RequestManager.get(endpoints.CHANNEL_WEBHOOKS(channelID)) as Promise< WebhookPayload[] >; } @@ -461,12 +458,6 @@ export async function isChannelSynced(channelID: string) { ow.id === overwrite.id ); if (!permission) return false; - if ( - overwrite.allow !== permission.allow || overwrite.deny !== permission.deny - ) { - return false; - } - - return true; + return !(overwrite.allow !== permission.allow || overwrite.deny !== permission.deny); }); } diff --git a/src/api/handlers/guild.ts b/src/api/handlers/guild.ts index 597a14094..a11237bb1 100644 --- a/src/api/handlers/guild.ts +++ b/src/api/handlers/guild.ts @@ -1,5 +1,5 @@ -import { identifyPayload } from "../../bot.ts"; -import { RequestManager } from "../../rest/mod.ts"; +import {identifyPayload} from "../../bot.ts"; +import {RequestManager} from "../../rest/mod.ts"; import { AuditLogs, BannedUser, @@ -32,18 +32,13 @@ import { UpdateGuildPayload, UserPayload, } from "../../types/mod.ts"; -import { Collection } from "../../util/collection.ts"; -import { endpoints } from "../../util/constants.ts"; -import { botHasPermission, calculateBits } from "../../util/permissions.ts"; -import { formatImageURL, urlToBase64 } from "../../util/utils.ts"; -import { requestAllMembers } from "../../ws/shard_manager.ts"; -import { cacheHandlers } from "../controllers/cache.ts"; -import { - Guild, - Member, - structures, - Template, -} from "../structures/structures.ts"; +import {Collection} from "../../util/collection.ts"; +import {endpoints} from "../../util/constants.ts"; +import {botHasPermission, calculateBits} from "../../util/permissions.ts"; +import {formatImageURL, urlToBase64} from "../../util/utils.ts"; +import {requestAllMembers} from "../../ws/shard_manager.ts"; +import {cacheHandlers} from "../controllers/cache.ts"; +import {Guild, Member, structures, Template,} from "../structures/structures.ts"; /** Create a new guild. Returns a guild object on success. Fires a Guild Create Gateway event. This endpoint can be used only by bots in less than 10 guilds. */ export async function createServer(options: CreateServerOptions) { @@ -135,8 +130,7 @@ export async function createGuildChannel( type: options?.type || ChannelTypes.GUILD_TEXT, })) as ChannelCreatePayload; - const channel = await structures.createChannel(result); - return channel; + return await structures.createChannel(result); } /** Delete a channel in your server. Bot needs MANAGE_CHANNEL permissions in the server. */ @@ -167,7 +161,7 @@ export async function getChannels(guildID: string, addToCache = true) { return Promise.all(result.map(async (res) => { const channel = await structures.createChannel(res, guildID); if (addToCache) { - cacheHandlers.set("channels", channel.id, channel); + await cacheHandlers.set("channels", channel.id, channel); } return channel; })); @@ -182,7 +176,7 @@ export async function getChannel(channelID: string, addToCache = true) { endpoints.GUILD_CHANNEL(channelID), ) as ChannelCreatePayload; const channel = await structures.createChannel(result, result.guild_id); - if (addToCache) cacheHandlers.set("channels", channel.id, channel); + if (addToCache) await cacheHandlers.set("channels", channel.id, channel); return channel; } @@ -192,7 +186,7 @@ export function swapChannels( channelPositions: PositionSwap[], ) { if (channelPositions.length < 2) { - throw "You must provide atleast two channels to be swapped."; + throw "You must provide at least two channels to be swapped."; } return RequestManager.patch( endpoints.GUILD_CHANNELS(guildID), @@ -216,8 +210,7 @@ export async function getMember( endpoints.GUILD_MEMBER(guildID, id), ) as MemberCreatePayload; - const member = await structures.createMember(data, guildID); - return member; + return await structures.createMember(data, guildID); } /** Returns guild member objects for the specified user by their nickname/username. @@ -310,8 +303,6 @@ export async function createGuildRole( throw new Error(Errors.MISSING_MANAGE_ROLES); } - const bits = calculateBits(options.permissions || []); - const result = await RequestManager.post( endpoints.GUILD_ROLES(guildID), { @@ -410,7 +401,7 @@ export async function pruneMembers(guildID: string, options: PruneOptions) { throw new Error(Errors.MISSING_KICK_MEMBERS); } - RequestManager.post( + return RequestManager.post( endpoints.GUILD_PRUNE(guildID), { ...options, include_roles: options.roles.join(",") }, ); @@ -437,8 +428,8 @@ export function fetchMembers(guild: Guild, options?: FetchMembersOptions) { options.limit = options.userIDs.length; } - return new Promise((resolve) => { - requestAllMembers(guild, resolve, options); + return new Promise(async (resolve) => { + await requestAllMembers(guild, resolve, options); }) as Promise>; } @@ -565,8 +556,8 @@ export async function getBan(guildID: string, memberID: string) { throw new Error(Errors.MISSING_BAN_MEMBERS); } - return RequestManager.get( - endpoints.GUILD_BAN(guildID, memberID), + return await RequestManager.get( + endpoints.GUILD_BAN(guildID, memberID), ) as Promise; } @@ -694,11 +685,10 @@ export async function createGuildFromTemplate( data.icon = await urlToBase64(data.icon); } - const guild = await RequestManager.post( - endpoints.GUILD_TEMPLATE(templateCode), - data, + return await RequestManager.post( + endpoints.GUILD_TEMPLATE(templateCode), + data, ) as Promise; - return guild; } /** diff --git a/src/api/handlers/member.ts b/src/api/handlers/member.ts index dd4508af1..3fdb0d563 100644 --- a/src/api/handlers/member.ts +++ b/src/api/handlers/member.ts @@ -1,5 +1,5 @@ -import { botID } from "../../bot.ts"; -import { RequestManager } from "../../rest/mod.ts"; +import {botID} from "../../bot.ts"; +import {RequestManager} from "../../rest/mod.ts"; import { DMChannelCreatePayload, EditMemberOptions, @@ -8,16 +8,12 @@ import { ImageSize, MessageContent, } from "../../types/mod.ts"; -import { endpoints } from "../../util/constants.ts"; -import { - botHasPermission, - higherRolePosition, - highestRole, -} from "../../util/permissions.ts"; -import { formatImageURL, urlToBase64 } from "../../util/utils.ts"; -import { cacheHandlers } from "../controllers/cache.ts"; -import { Member, structures } from "../structures/structures.ts"; -import { sendMessage } from "./channel.ts"; +import {endpoints} from "../../util/constants.ts"; +import {botHasPermission, higherRolePosition, highestRole,} from "../../util/permissions.ts"; +import {formatImageURL, urlToBase64} from "../../util/utils.ts"; +import {cacheHandlers} from "../controllers/cache.ts"; +import {Member, structures} from "../structures/structures.ts"; +import {sendMessage} from "./channel.ts"; /** The users custom avatar or the default avatar if you don't have a member object. */ export function rawAvatarURL( @@ -127,10 +123,10 @@ export async function sendDirectMessage( { recipient_id: memberID }, ) as DMChannelCreatePayload; // Channel create event will have added this channel to the cache - cacheHandlers.delete("channels", dmChannelData.id); + await cacheHandlers.delete("channels", dmChannelData.id); const channel = await structures.createChannel(dmChannelData); // Recreate the channel and add it undert he users id - cacheHandlers.set("channels", memberID, channel); + await cacheHandlers.set("channels", memberID, channel); dmChannel = channel; } @@ -260,7 +256,7 @@ export async function editBotProfile(username?: string, avatarURL?: string) { } const avatar = avatarURL ? await urlToBase64(avatarURL) : undefined; - RequestManager.patch( + return RequestManager.patch( endpoints.USER_BOT, { username: username?.trim(), diff --git a/src/api/handlers/message.ts b/src/api/handlers/message.ts index 0a12a8d55..b39f8de80 100644 --- a/src/api/handlers/message.ts +++ b/src/api/handlers/message.ts @@ -1,16 +1,11 @@ -import { botID } from "../../bot.ts"; -import { RequestManager } from "../../rest/mod.ts"; -import { - Errors, - MessageContent, - MessageCreateOptions, - UserPayload, -} from "../../types/mod.ts"; -import { endpoints } from "../../util/constants.ts"; -import { botHasChannelPermissions } from "../../util/permissions.ts"; -import { delay } from "../../util/utils.ts"; -import { cacheHandlers } from "../controllers/cache.ts"; -import { Message, structures } from "../structures/structures.ts"; +import {botID} from "../../bot.ts"; +import {RequestManager} from "../../rest/mod.ts"; +import {Errors, MessageContent, MessageCreateOptions, UserPayload,} from "../../types/mod.ts"; +import {endpoints} from "../../util/constants.ts"; +import {botHasChannelPermissions} from "../../util/permissions.ts"; +import {delay} from "../../util/utils.ts"; +import {cacheHandlers} from "../controllers/cache.ts"; +import {Message, structures} from "../structures/structures.ts"; /** Delete a message with the channel id and message id only. */ export async function deleteMessageByID( @@ -68,7 +63,7 @@ export async function pin(channelID: string, messageID: string) { ) { throw new Error(Errors.MISSING_MANAGE_MESSAGES); } - RequestManager.put(endpoints.CHANNEL_MESSAGE(channelID, messageID)); + return RequestManager.put(endpoints.CHANNEL_MESSAGE(channelID, messageID)); } /** Unpin a message in a channel. Requires MANAGE_MESSAGES. */ @@ -82,7 +77,7 @@ export async function unpin(channelID: string, messageID: string) { ) { throw new Error(Errors.MISSING_MANAGE_MESSAGES); } - RequestManager.delete( + return RequestManager.delete( endpoints.CHANNEL_MESSAGE(channelID, messageID), ); } @@ -134,9 +129,7 @@ export async function addReactions( ordered = false, ) { if (!ordered) { - reactions.forEach((reaction) => - addReaction(channelID, messageID, reaction) - ); + await Promise.all(reactions.map(reaction => addReaction(channelID, messageID, reaction))) } else { for (const reaction of reactions) { await addReaction(channelID, messageID, reaction); diff --git a/src/api/handlers/webhook.ts b/src/api/handlers/webhook.ts index c08fa8099..2ad1f52cd 100644 --- a/src/api/handlers/webhook.ts +++ b/src/api/handlers/webhook.ts @@ -1,5 +1,5 @@ -import { botID } from "../../bot.ts"; -import { RequestManager } from "../../rest/mod.ts"; +import {botID} from "../../bot.ts"; +import {RequestManager} from "../../rest/mod.ts"; import { CreateSlashCommandOptions, EditSlashCommandOptions, @@ -13,11 +13,11 @@ import { WebhookCreateOptions, WebhookPayload, } from "../../types/mod.ts"; -import { cache } from "../../util/cache.ts"; -import { endpoints } from "../../util/constants.ts"; -import { botHasChannelPermissions } from "../../util/permissions.ts"; -import { urlToBase64 } from "../../util/utils.ts"; -import { structures } from "../structures/structures.ts"; +import {cache} from "../../util/cache.ts"; +import {endpoints} from "../../util/constants.ts"; +import {botHasChannelPermissions} from "../../util/permissions.ts"; +import {urlToBase64} from "../../util/utils.ts"; +import {structures} from "../structures/mod.ts"; /** Create a new webhook. Requires the MANAGE_WEBHOOKS permission. Returns a webhook object on success. Webhook names follow our naming restrictions that can be found in our Usernames and Nicknames documentation, with the following additional stipulations: * @@ -46,12 +46,12 @@ export async function createWebhook( throw new Error(Errors.INVALID_WEBHOOK_NAME); } - return RequestManager.post( - endpoints.CHANNEL_WEBHOOKS(channelID), - { - ...options, - avatar: options.avatar ? await urlToBase64(options.avatar) : undefined, - }, + return await RequestManager.post( + endpoints.CHANNEL_WEBHOOKS(channelID), + { + ...options, + avatar: options.avatar ? await urlToBase64(options.avatar) : undefined, + }, ) as Promise; } diff --git a/src/api/structures/channel.ts b/src/api/structures/channel.ts index 20e5f9e86..a8eeba173 100644 --- a/src/api/structures/channel.ts +++ b/src/api/structures/channel.ts @@ -1,16 +1,11 @@ -import { - ChannelCreatePayload, - ChannelType, - MessageContent, - RawOverwrite, -} from "../../types/mod.ts"; -import { cache } from "../../util/cache.ts"; -import { Collection } from "../../util/collection.ts"; -import { createNewProp } from "../../util/utils.ts"; -import { cacheHandlers } from "../controllers/cache.ts"; -import { sendMessage } from "../handlers/channel.ts"; -import { Guild } from "./guild.ts"; -import { Message } from "./message.ts"; +import {ChannelCreatePayload, ChannelType, MessageContent, RawOverwrite,} from "../../types/mod.ts"; +import {cache} from "../../util/cache.ts"; +import {Collection} from "../../util/collection.ts"; +import {createNewProp} from "../../util/utils.ts"; +import {cacheHandlers} from "../controllers/cache.ts"; +import {sendMessage} from "../handlers/channel.ts"; +import {Guild} from "./guild.ts"; +import {Message} from "./message.ts"; const baseChannel: Partial = { get guild() { @@ -62,7 +57,7 @@ export async function createChannel( nsfw: createNewProp(data.nsfw || false), }); - cacheHandlers.set("channels", data.id, channel); + await cacheHandlers.set("channels", data.id, channel); return channel as Channel; } diff --git a/src/api/structures/message.ts b/src/api/structures/message.ts index 4c889e161..c1c88f3b5 100644 --- a/src/api/structures/message.ts +++ b/src/api/structures/message.ts @@ -11,9 +11,9 @@ import { Reference, UserPayload, } from "../../types/mod.ts"; -import { cache } from "../../util/cache.ts"; -import { createNewProp } from "../../util/utils.ts"; -import { sendMessage } from "../handlers/channel.ts"; +import {cache} from "../../util/cache.ts"; +import {createNewProp} from "../../util/utils.ts"; +import {sendMessage} from "../handlers/channel.ts"; import { addReaction, addReactions, @@ -24,10 +24,10 @@ import { removeReaction, removeReactionEmoji, } from "../handlers/message.ts"; -import { Channel } from "./channel.ts"; -import { Guild } from "./guild.ts"; -import { Member } from "./member.ts"; -import { Role } from "./role.ts"; +import {Channel} from "./channel.ts"; +import {Guild} from "./guild.ts"; +import {Member} from "./member.ts"; +import {Role} from "./role.ts"; const baseMessage: Partial = { get channel() { @@ -127,6 +127,7 @@ export async function createMessage(data: MessageCreateOptions) { message_reference: messageReference, edited_timestamp: editedTimestamp, referenced_message: referencedMessageID, + member, ...rest } = data; diff --git a/src/api/structures/template.ts b/src/api/structures/template.ts index faafdda83..f1b64d519 100644 --- a/src/api/structures/template.ts +++ b/src/api/structures/template.ts @@ -1,7 +1,7 @@ -import { GuildTemplate, UserPayload } from "../../types/mod.ts"; -import { cache } from "../../util/cache.ts"; -import { createNewProp } from "../../util/utils.ts"; -import { Guild } from "./guild.ts"; +import {GuildTemplate, UserPayload} from "../../types/mod.ts"; +import {cache} from "../../util/cache.ts"; +import {createNewProp} from "../../util/utils.ts"; +import {Guild} from "./guild.ts"; const baseTemplate: any = { get sourceGuild() { @@ -28,7 +28,7 @@ export function createTemplate( restProps[key] = createNewProp((rest as any)[key]); } - const template = Object.create(baseTemplate, { + return Object.create(baseTemplate, { ...restProps, usageCount: createNewProp(sourceGuildID), creatorID: createNewProp(creatorID), @@ -38,8 +38,6 @@ export function createTemplate( serializedSourceGuild: createNewProp(serializedSourceGuild), isDirty: createNewProp(isDirty), }); - - return template; } export interface Template { diff --git a/src/bot.ts b/src/bot.ts index 366cf0272..e9a13d28a 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -1,11 +1,7 @@ -import { RequestManager } from "./rest/mod.ts"; -import { - BotConfig, - DiscordBotGatewayData, - EventHandlers, -} from "./types/mod.ts"; -import { baseEndpoints, endpoints, GATEWAY_VERSION } from "./util/constants.ts"; -import { spawnShards } from "./ws/shard_manager.ts"; +import {RequestManager} from "./rest/mod.ts"; +import {BotConfig, DiscordBotGatewayData, EventHandlers,} from "./types/mod.ts"; +import {baseEndpoints, endpoints, GATEWAY_VERSION} from "./util/constants.ts"; +import {spawnShards} from "./ws/shard_manager.ts"; export let authorization = ""; export let botID = ""; @@ -106,7 +102,7 @@ export async function startBigBrainBot(data: BigBrainBotConfig) { ) as DiscordBotGatewayData; if (!data.wsURL) proxyWSURL = botGatewayData.url; - spawnShards( + await spawnShards( botGatewayData, identifyPayload, data.firstShardID, diff --git a/src/interactions/types/embed.ts b/src/interactions/types/embed.ts index 08522ab54..0bc98cd45 100644 --- a/src/interactions/types/embed.ts +++ b/src/interactions/types/embed.ts @@ -7,7 +7,7 @@ export interface Embed { description?: string; /** The url of embed */ url?: string; - /** The timestap of the embed content */ + /** The timestamp of the embed content */ timestamp?: string; /** The color code of the embed */ color?: number; diff --git a/src/interactions/types/interactions.ts b/src/interactions/types/interactions.ts index 8b7d0a68c..f6ac86648 100644 --- a/src/interactions/types/interactions.ts +++ b/src/interactions/types/interactions.ts @@ -1,6 +1,6 @@ -import { Embed } from "./embed.ts"; -import { MemberCreatePayload } from "./member.ts"; -import { AllowedMentions } from "./misc.ts"; +import {Embed} from "./embed.ts"; +import {MemberCreatePayload} from "./member.ts"; +import {AllowedMentions} from "./misc.ts"; export interface Interaction { /** The id of the interaction */ @@ -29,7 +29,7 @@ export interface SlashCommandInteractionData { } export interface SlashCommandInteractionDataOption { - /** The name of the parammeter */ + /** The name of the parameter */ name: string; /** The value of the pair */ value?: any; diff --git a/src/interactions/types/slash.ts b/src/interactions/types/slash.ts index 36386fd7c..36b0f7d31 100644 --- a/src/interactions/types/slash.ts +++ b/src/interactions/types/slash.ts @@ -1,13 +1,10 @@ -import { - InteractionResponseType, - SlashCommandCallbackData, -} from "./interactions.ts"; +import {InteractionResponseType, SlashCommandCallbackData,} from "./interactions.ts"; export interface CreateSlashCommandOptions { /** The name of the slash command. */ name: string; /** The description of the slash command. */ - description: String; + description: string; /** If a guildID is provided, this will be a GUILD command. If none is provided it will be a GLOBAL command. */ guildID?: string; /** The options for this command */ diff --git a/src/rest/request_manager.ts b/src/rest/request_manager.ts index bce07eee5..4ea106fe8 100644 --- a/src/rest/request_manager.ts +++ b/src/rest/request_manager.ts @@ -1,13 +1,7 @@ -import { authorization, eventHandlers } from "../bot.ts"; -import { Errors, HttpResponseCode, RequestMethods } from "../types/mod.ts"; -import { - API_VERSION, - BASE_URL, - baseEndpoints, - IMAGE_BASE_URL, - USER_AGENT, -} from "../util/constants.ts"; -import { delay } from "../util/utils.ts"; +import {authorization, eventHandlers} from "../bot.ts"; +import {Errors, HttpResponseCode, RequestMethods} from "../types/mod.ts"; +import {API_VERSION, BASE_URL, baseEndpoints, IMAGE_BASE_URL, USER_AGENT,} from "../util/constants.ts"; +import {delay} from "../util/utils.ts"; const pathQueues: { [key: string]: QueuedRequest[] } = {}; const ratelimitedPaths = new Map(); @@ -41,7 +35,7 @@ async function processRateLimitedPaths() { }); await delay(1000); - processRateLimitedPaths(); + return processRateLimitedPaths(); } function addToQueue(request: QueuedRequest) { @@ -115,7 +109,7 @@ async function processQueue() { } if (Object.keys(pathQueues).length) { - cleanupQueues(); + await cleanupQueues(); } else queueInProcess = false; } } @@ -215,7 +209,7 @@ async function runMethod( }); } - // No proxy so we need to handl all rate limiting and such + // No proxy so we need to handle all rate limiting and such return new Promise((resolve, reject) => { const callback = async () => { try { diff --git a/src/types/channel.ts b/src/types/channel.ts index 6c116b853..170946598 100644 --- a/src/types/channel.ts +++ b/src/types/channel.ts @@ -1,5 +1,5 @@ -import { Overwrite, RawOverwrite } from "./guild.ts"; -import { Embed } from "./message.ts"; +import {Overwrite, RawOverwrite} from "./guild.ts"; +import {Embed} from "./message.ts"; export interface ChannelEditOptions { /** 2-100 character channel name. All */ @@ -87,7 +87,7 @@ export enum ChannelTypes { GROUP_DM, /** An organizational category that contains channels */ GUILD_CATEGORY, - /** A channel that users can follow and crosspost into their own server. */ + /** A channel that users can follow and cross post into their own server. */ GUILD_NEWS, /** A channel in which game developers can sell their game on Discord. */ GUILD_STORE, diff --git a/src/types/guild.ts b/src/types/guild.ts index 013404bb3..44dde4480 100644 --- a/src/types/guild.ts +++ b/src/types/guild.ts @@ -1,11 +1,11 @@ -import { Guild } from "../api/structures/mod.ts"; -import { ChannelCreatePayload, ChannelTypes } from "./channel.ts"; -import { Emoji, StatusType } from "./discord.ts"; -import { MemberCreatePayload } from "./member.ts"; -import { Activity } from "./message.ts"; -import { Permission } from "./permission.ts"; -import { ClientStatusPayload } from "./presence.ts"; -import { RoleData } from "./role.ts"; +import {Guild} from "../api/structures/mod.ts"; +import {ChannelCreatePayload, ChannelTypes} from "./channel.ts"; +import {Emoji, StatusType} from "./discord.ts"; +import {MemberCreatePayload} from "./member.ts"; +import {Activity} from "./message.ts"; +import {Permission} from "./permission.ts"; +import {ClientStatusPayload} from "./presence.ts"; +import {RoleData} from "./role.ts"; export interface GuildRolePayload { /** The id of the guild */ @@ -357,7 +357,7 @@ export interface VanityInvite { } export interface GuildEmbed { - /** Whether the embed is enbaled. */ + /** Whether the embed is enabled. */ enabled: boolean; } diff --git a/src/types/interactions.ts b/src/types/interactions.ts index 986aaf6b8..c03256557 100644 --- a/src/types/interactions.ts +++ b/src/types/interactions.ts @@ -1,4 +1,4 @@ -import { MemberCreatePayload } from "./member.ts"; +import {MemberCreatePayload} from "./member.ts"; export interface InteractionCommandPayload { /** id of the interaction */ @@ -13,7 +13,7 @@ export interface InteractionCommandPayload { channel_id: string; /** guild member data for the invoking user */ member: MemberCreatePayload; - /** a contintuation token for responding to the interaction */ + /** a continuation token for responding to the interaction */ token: string; } diff --git a/src/util/collection.ts b/src/util/collection.ts index 9576512e0..3395719d4 100644 --- a/src/util/collection.ts +++ b/src/util/collection.ts @@ -1,12 +1,12 @@ -import { chooseRandom } from "./utils.ts"; +import {chooseRandom} from "./utils.ts"; export class Collection extends Map { maxSize?: number; set(key: K, value: V) { // When this collection is maxSizeed make sure we can add first - if (this.maxSize || this.maxSize === 0) { - if (this.size >= this.maxSize) return this; + if ((this.maxSize || this.maxSize === 0) && this.size >= this.maxSize) { + return this; } return super.set(key, value); diff --git a/src/util/permissions.ts b/src/util/permissions.ts index 5417e8393..64ecc8d06 100644 --- a/src/util/permissions.ts +++ b/src/util/permissions.ts @@ -1,7 +1,7 @@ -import { cacheHandlers } from "../api/controllers/cache.ts"; -import { Guild, Role } from "../api/structures/structures.ts"; -import { botID } from "../bot.ts"; -import { Permission, Permissions, RawOverwrite } from "../types/mod.ts"; +import {cacheHandlers} from "../api/controllers/cache.ts"; +import {Guild, Role} from "../api/structures/structures.ts"; +import {botID} from "../bot.ts"; +import {Permission, Permissions, RawOverwrite} from "../types/mod.ts"; /** Checks if the member has this permission. If the member is an owner or has admin perms it will always be true. */ export async function memberIDHasPermission( @@ -191,8 +191,7 @@ export async function hasChannelPermissions( if (permissions.every((perm) => allowedPermissions.has(perm))) return true; // Some permission was not explicitly allowed so we default to checking role perms directly - const hasPerms = await memberIDHasPermission(memberID, guild.id, permissions); - return hasPerms; + return await memberIDHasPermission(memberID, guild.id, permissions); } /** This function converts a bitwise string to permission strings */ diff --git a/src/ws/shard.ts b/src/ws/shard.ts index b21f48655..64a270e5e 100644 --- a/src/ws/shard.ts +++ b/src/ws/shard.ts @@ -1,9 +1,4 @@ -import { - botGatewayData, - eventHandlers, - IdentifyPayload, - proxyWSURL, -} from "../bot.ts"; +import {botGatewayData, eventHandlers, IdentifyPayload, proxyWSURL,} from "../bot.ts"; import { DiscordBotGatewayData, DiscordHeartbeatPayload, @@ -11,9 +6,9 @@ import { GatewayOpcode, ReadyPayload, } from "../types/mod.ts"; -import { BotStatusRequest, delay } from "../util/utils.ts"; -import { decompressWith } from "./deps.ts"; -import { handleDiscordPayload } from "./shard_manager.ts"; +import {BotStatusRequest, delay} from "../util/utils.ts"; +import {decompressWith} from "./deps.ts"; +import {handleDiscordPayload} from "./shard_manager.ts"; const basicShards = new Map(); const heartbeating = new Map(); @@ -247,7 +242,7 @@ async function heartbeat( // We lost socket connection between heartbeats, resume connection if (shard.ws.readyState === WebSocket.CLOSED) { shard.needToResume = true; - resumeConnection(data, payload, shard.id); + await resumeConnection(data, payload, shard.id); heartbeating.delete(shard.id); return; } @@ -289,7 +284,7 @@ async function heartbeat( }, ); await delay(interval); - heartbeat(shard, interval, payload, data); + return heartbeat(shard, interval, payload, data); } async function resumeConnection( @@ -309,7 +304,7 @@ async function resumeConnection( eventHandlers.debug?.({ type: "gatewayResume", data: { shardID: shard.id } }); // Run it once - createShard(data, payload, true, shard.id); + await createShard(data, payload, true, shard.id); // Then retry every 15 seconds await delay(1000 * 15); if (shard.needToResume) resumeConnection(data, payload, shardID); @@ -335,7 +330,7 @@ export function requestGuildMembers( if (!processQueue) { processQueue = true; - processGatewayQueue(); + return processGatewayQueue(); } return; } @@ -419,7 +414,7 @@ async function processGatewayQueue() { await delay(1500); - processGatewayQueue(); + await processGatewayQueue(); } export function botGatewayStatusRequest(payload: BotStatusRequest) { diff --git a/src/ws/shard_manager.ts b/src/ws/shard_manager.ts index ed5b5bf9d..2b60377fa 100644 --- a/src/ws/shard_manager.ts +++ b/src/ws/shard_manager.ts @@ -1,19 +1,10 @@ -import { controllers } from "../api/controllers/mod.ts"; -import { Guild } from "../api/structures/structures.ts"; -import { eventHandlers, IdentifyPayload } from "../bot.ts"; -import { - DiscordBotGatewayData, - DiscordPayload, - FetchMembersOptions, - GatewayOpcode, -} from "../types/mod.ts"; -import { cache } from "../util/cache.ts"; -import { BotStatusRequest, delay } from "../util/utils.ts"; -import { - botGatewayStatusRequest, - createShard, - requestGuildMembers, -} from "./mod.ts"; +import {controllers} from "../api/controllers/mod.ts"; +import {Guild} from "../api/structures/guild.ts"; +import {eventHandlers, IdentifyPayload} from "../bot.ts"; +import {DiscordBotGatewayData, DiscordPayload, FetchMembersOptions, GatewayOpcode,} from "../types/mod.ts"; +import {cache} from "../util/cache.ts"; +import {BotStatusRequest, delay} from "../util/utils.ts"; +import {botGatewayStatusRequest, createShard, requestGuildMembers,} from "./mod.ts"; let createNextShard = true; @@ -38,9 +29,9 @@ export async function spawnShards( data.shards > lastShardID ? data.shards : lastShardID, ]; // Start The shard - createShard(data, payload, false, shardID); + await createShard(data, payload, false, shardID); // Spawn next shard - spawnShards( + await spawnShards( data, payload, shardID + 1, @@ -54,7 +45,7 @@ export async function spawnShards( if (createNextShard) { createNextShard = false; // Start the next few shards based on max concurrency - spawnShards( + await spawnShards( data, payload, shardID, @@ -65,7 +56,7 @@ export async function spawnShards( } await delay(1000); - spawnShards(data, payload, shardID, lastShardID, skipChecks); + await spawnShards(data, payload, shardID, lastShardID, skipChecks); } export async function handleDiscordPayload( @@ -77,7 +68,7 @@ export async function handleDiscordPayload( switch (data.op) { case GatewayOpcode.HeartbeatACK: - // Incase the user wants to listen to heartbeat responses + // In case the user wants to listen to heartbeat responses return eventHandlers.heartbeat?.(); case GatewayOpcode.Dispatch: if (!data.t) return;