refactor: resolve async promises, fixed typos, and used inline variable for return (#299)

* Added await in async function, fixed typos and used inline variable for return

* Added await in async function, fixed typos and used inline variable for return

* Revert "Added await in async function, fixed typos and used inline variable for return"

This reverts commit f31caf5d

* Added await in async function, fixed typos and used inline variable for return

* Fixes format

* Fixes format 2

* Fixes format 4475757

* Fixes format 878757854786312378657865785785785785

* Change return to await

* Fixing more issues

* Fixing even more issues

* Fixing even more issues +

* Fixes format
This commit is contained in:
TriForMine
2020-12-30 09:31:11 +01:00
committed by GitHub
parent 6d7aa35d9c
commit 484f86638f
29 changed files with 126 additions and 141 deletions
+1 -1
View File
@@ -1,7 +1,7 @@
import { PresenceUpdatePayload } from "../../types/mod.ts"; import { PresenceUpdatePayload } from "../../types/mod.ts";
import { cache } from "../../util/cache.ts"; import { cache } from "../../util/cache.ts";
import { Collection } from "../../util/collection.ts"; import { Collection } from "../../util/collection.ts";
import { Channel, Guild, Member, Message } from "../structures/structures.ts"; import { Channel, Guild, Member, Message } from "../structures/mod.ts";
export type TableName = export type TableName =
| "guilds" | "guilds"
+5 -5
View File
@@ -4,7 +4,7 @@ import {
ChannelTypes, ChannelTypes,
DiscordPayload, DiscordPayload,
} from "../../types/mod.ts"; } from "../../types/mod.ts";
import { structures } from "../structures/structures.ts"; import { structures } from "../structures/mod.ts";
import { cacheHandlers } from "./cache.ts"; import { cacheHandlers } from "./cache.ts";
export async function handleInternalChannelCreate(data: DiscordPayload) { export async function handleInternalChannelCreate(data: DiscordPayload) {
@@ -29,7 +29,7 @@ export async function handleInternalChannelDelete(data: DiscordPayload) {
const guild = await cacheHandlers.get("guilds", payload.guild_id); const guild = await cacheHandlers.get("guilds", payload.guild_id);
if (guild) { if (guild) {
guild.voiceStates.forEach(async (vs, key) => { return Promise.all(guild.voiceStates.map(async (vs, key) => {
if (vs.channelID !== payload.id) return; if (vs.channelID !== payload.id) return;
// Since this channel was deleted all voice states for this channel should be deleted // Since this channel was deleted all voice states for this channel should be deleted
@@ -39,11 +39,11 @@ export async function handleInternalChannelDelete(data: DiscordPayload) {
if (!member) return; if (!member) return;
eventHandlers.voiceChannelLeave?.(member, vs.channelID); eventHandlers.voiceChannelLeave?.(member, vs.channelID);
}); }));
} }
} }
cacheHandlers.delete("channels", payload.id); await cacheHandlers.delete("channels", payload.id);
cacheHandlers.forEach("messages", (message) => { cacheHandlers.forEach("messages", (message) => {
if (message.channelID === payload.id) { if (message.channelID === payload.id) {
cacheHandlers.delete("messages", message.id); cacheHandlers.delete("messages", message.id);
@@ -58,7 +58,7 @@ export async function handleInternalChannelUpdate(data: DiscordPayload) {
const payload = data.d as ChannelCreatePayload; const payload = data.d as ChannelCreatePayload;
const cachedChannel = await cacheHandlers.get("channels", payload.id); const cachedChannel = await cacheHandlers.get("channels", payload.id);
const channel = await structures.createChannel(payload); const channel = await structures.createChannel(payload);
cacheHandlers.set("channels", channel.id, channel); await cacheHandlers.set("channels", channel.id, channel);
if (!cachedChannel) return; if (!cachedChannel) return;
+5 -6
View File
@@ -8,7 +8,7 @@ import {
UpdateGuildPayload, UpdateGuildPayload,
} from "../../types/mod.ts"; } from "../../types/mod.ts";
import { cache } from "../../util/cache.ts"; import { cache } from "../../util/cache.ts";
import { structures } from "../structures/structures.ts"; import { structures } from "../structures/mod.ts";
import { cacheHandlers } from "./cache.ts"; import { cacheHandlers } from "./cache.ts";
export async function handleInternalGuildCreate( export async function handleInternalGuildCreate(
@@ -26,10 +26,10 @@ export async function handleInternalGuildCreate(
shardID, shardID,
); );
cacheHandlers.set("guilds", guild.id, guild); await cacheHandlers.set("guilds", guild.id, guild);
if (cacheHandlers.has("unavailableGuilds", payload.id)) { if (await cacheHandlers.has("unavailableGuilds", payload.id)) {
cacheHandlers.delete("unavailableGuilds", payload.id); await cacheHandlers.delete("unavailableGuilds", payload.id);
} }
if (!cache.isReady) return eventHandlers.guildLoaded?.(guild); 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) { if (payload.unavailable) {
return cacheHandlers.set("unavailableGuilds", payload.id, Date.now()); return cacheHandlers.set("unavailableGuilds", payload.id, Date.now());
@@ -101,7 +101,6 @@ export async function handleInternalGuildUpdate(data: DiscordPayload) {
cachedGuild[key] = value; cachedGuild[key] = value;
return { key, oldValue: cachedValue, value }; return { key, oldValue: cachedValue, value };
} }
return;
}).filter((change) => change) as GuildUpdateChange[]; }).filter((change) => change) as GuildUpdateChange[];
return eventHandlers.guildUpdate?.(cachedGuild, changes); return eventHandlers.guildUpdate?.(cachedGuild, changes);
+4 -2
View File
@@ -8,7 +8,7 @@ import {
} from "../../types/mod.ts"; } from "../../types/mod.ts";
import { cache } from "../../util/cache.ts"; import { cache } from "../../util/cache.ts";
import { Collection } from "../../util/collection.ts"; import { Collection } from "../../util/collection.ts";
import { structures } from "../structures/structures.ts"; import { structures } from "../structures/mod.ts";
import { cacheHandlers } from "./cache.ts"; import { cacheHandlers } from "./cache.ts";
export async function handleInternalGuildMemberAdd(data: DiscordPayload) { export async function handleInternalGuildMemberAdd(data: DiscordPayload) {
@@ -39,7 +39,9 @@ export async function handleInternalGuildMemberRemove(data: DiscordPayload) {
eventHandlers.guildMemberRemove?.(guild, payload.user, member); eventHandlers.guildMemberRemove?.(guild, payload.user, member);
member?.guilds.delete(guild.id); 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) { export async function handleInternalGuildMemberUpdate(data: DiscordPayload) {
+6 -6
View File
@@ -5,7 +5,7 @@ import {
MessageDeleteBulkPayload, MessageDeleteBulkPayload,
MessageDeletePayload, MessageDeletePayload,
} from "../../types/mod.ts"; } from "../../types/mod.ts";
import { structures } from "../structures/structures.ts"; import { structures } from "../structures/mod.ts";
import { cacheHandlers } from "./cache.ts"; import { cacheHandlers } from "./cache.ts";
export async function handleInternalMessageCreate(data: DiscordPayload) { export async function handleInternalMessageCreate(data: DiscordPayload) {
@@ -39,7 +39,7 @@ export async function handleInternalMessageCreate(data: DiscordPayload) {
const message = await structures.createMessage(payload); const message = await structures.createMessage(payload);
// Cache the message // Cache the message
cacheHandlers.set("messages", payload.id, message); await cacheHandlers.set("messages", payload.id, message);
eventHandlers.messageCreate?.(message); eventHandlers.messageCreate?.(message);
} }
@@ -56,7 +56,7 @@ export async function handleInternalMessageDelete(data: DiscordPayload) {
await cacheHandlers.get("messages", payload.id), await cacheHandlers.get("messages", payload.id),
); );
cacheHandlers.delete("messages", payload.id); await cacheHandlers.delete("messages", payload.id);
} }
export async function handleInternalMessageDeleteBulk(data: DiscordPayload) { 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); const channel = await cacheHandlers.get("channels", payload.channel_id);
if (!channel) return; if (!channel) return;
payload.ids.forEach(async (id) => { return Promise.all(payload.ids.map(async (id) => {
eventHandlers.messageDelete?.( eventHandlers.messageDelete?.(
{ id, channel }, { id, channel },
await cacheHandlers.get("messages", id), await cacheHandlers.get("messages", id),
); );
cacheHandlers.delete("messages", id); await cacheHandlers.delete("messages", id);
}); }));
} }
export async function handleInternalMessageUpdate(data: DiscordPayload) { export async function handleInternalMessageUpdate(data: DiscordPayload) {
+5 -5
View File
@@ -54,7 +54,7 @@ export async function handleInternalPresenceUpdate(data: DiscordPayload) {
const payload = data.d as PresenceUpdatePayload; const payload = data.d as PresenceUpdatePayload;
const oldPresence = await cacheHandlers.get("presences", payload.user.id); 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); return eventHandlers.presenceUpdate?.(payload, oldPresence);
} }
@@ -113,15 +113,15 @@ export async function handleInternalVoiceStateUpdate(data: DiscordPayload) {
if (cachedState?.channelID !== payload.channel_id) { if (cachedState?.channelID !== payload.channel_id) {
// Either joined or moved channels // Either joined or moved channels
if (payload.channel_id) { if (payload.channel_id) {
cachedState?.channelID if (cachedState?.channelID) { // Was in a channel before
? // Was in a channel before
eventHandlers.voiceChannelSwitch?.( eventHandlers.voiceChannelSwitch?.(
member, member,
payload.channel_id, payload.channel_id,
cachedState.channelID, cachedState.channelID,
) );
: // Was not in a channel before so user just joined } else { // Was not in a channel before so user just joined
eventHandlers.voiceChannelJoin?.(member, payload.channel_id); eventHandlers.voiceChannelJoin?.(member, payload.channel_id);
}
} // Left the channel } // Left the channel
else if (cachedState?.channelID) { else if (cachedState?.channelID) {
guild.voiceStates.delete(payload.user_id); guild.voiceStates.delete(payload.user_id);
+3 -3
View File
@@ -5,7 +5,7 @@ import {
MessageReactionPayload, MessageReactionPayload,
MessageReactionRemoveEmojiPayload, MessageReactionRemoveEmojiPayload,
} from "../../types/mod.ts"; } from "../../types/mod.ts";
import { structures } from "../structures/structures.ts"; import { structures } from "../structures/mod.ts";
import { cacheHandlers } from "./cache.ts"; import { cacheHandlers } from "./cache.ts";
export async function handleInternalMessageReactionAdd(data: DiscordPayload) { export async function handleInternalMessageReactionAdd(data: DiscordPayload) {
@@ -34,7 +34,7 @@ export async function handleInternalMessageReactionAdd(data: DiscordPayload) {
: [newReaction]; : [newReaction];
} }
cacheHandlers.set("messages", payload.message_id, message); await cacheHandlers.set("messages", payload.message_id, message);
} }
if (payload.member && payload.guild_id) { if (payload.member && payload.guild_id) {
@@ -87,7 +87,7 @@ export async function handleInternalMessageReactionRemove(
: [newReaction]; : [newReaction];
} }
cacheHandlers.set("messages", payload.message_id, message); await cacheHandlers.set("messages", payload.message_id, message);
} }
if (payload.member && payload.guild_id) { if (payload.member && payload.guild_id) {
+2 -3
View File
@@ -4,7 +4,7 @@ import {
GuildRoleDeletePayload, GuildRoleDeletePayload,
GuildRolePayload, GuildRolePayload,
} from "../../types/mod.ts"; } from "../../types/mod.ts";
import { structures } from "../structures/structures.ts"; import { structures } from "../structures/mod.ts";
import { cacheHandlers } from "./cache.ts"; import { cacheHandlers } from "./cache.ts";
export async function handleInternalGuildRoleCreate(data: DiscordPayload) { export async function handleInternalGuildRoleCreate(data: DiscordPayload) {
@@ -15,8 +15,7 @@ export async function handleInternalGuildRoleCreate(data: DiscordPayload) {
if (!guild) return; if (!guild) return;
const role = await structures.createRole(payload.role); const role = await structures.createRole(payload.role);
const roles = guild.roles.set(payload.role.id, role); guild.roles = guild.roles.set(payload.role.id, role);
guild.roles = roles;
return eventHandlers.roleCreate?.(guild, role); return eventHandlers.roleCreate?.(guild, role);
} }
+8 -11
View File
@@ -22,7 +22,7 @@ import {
calculateBits, calculateBits,
} from "../../util/permissions.ts"; } from "../../util/permissions.ts";
import { cacheHandlers } from "../controllers/cache.ts"; import { cacheHandlers } from "../controllers/cache.ts";
import { structures } from "../structures/structures.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 */ /** Checks if a channel overwrite for a user id or a role id has permission in this channel */
export function channelOverwriteHasPermission( export function channelOverwriteHasPermission(
@@ -38,8 +38,8 @@ export function channelOverwriteHasPermission(
if (overwrite) { if (overwrite) {
const allowBits = overwrite.allow; const allowBits = overwrite.allow;
const denyBits = overwrite.deny; const denyBits = overwrite.deny;
if (BigInt(denyBits) & BigInt(Permissions[perm])) return false; if (BigInt(denyBits) && BigInt(Permissions[perm])) return false;
if (BigInt(allowBits) & BigInt(Permissions[perm])) return true; if (BigInt(allowBits) && BigInt(Permissions[perm])) return true;
} }
return false; return false;
}); });
@@ -303,7 +303,9 @@ export async function getChannelWebhooks(channelID: string) {
) { ) {
throw new Error(Errors.MISSING_MANAGE_WEBHOOKS); 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[] WebhookPayload[]
>; >;
} }
@@ -461,12 +463,7 @@ export async function isChannelSynced(channelID: string) {
ow.id === overwrite.id ow.id === overwrite.id
); );
if (!permission) return false; if (!permission) return false;
if ( return !(overwrite.allow !== permission.allow ||
overwrite.allow !== permission.allow || overwrite.deny !== permission.deny overwrite.deny !== permission.deny);
) {
return false;
}
return true;
}); });
} }
+11 -21
View File
@@ -38,12 +38,7 @@ import { botHasPermission, calculateBits } from "../../util/permissions.ts";
import { formatImageURL, urlToBase64 } from "../../util/utils.ts"; import { formatImageURL, urlToBase64 } from "../../util/utils.ts";
import { requestAllMembers } from "../../ws/shard_manager.ts"; import { requestAllMembers } from "../../ws/shard_manager.ts";
import { cacheHandlers } from "../controllers/cache.ts"; import { cacheHandlers } from "../controllers/cache.ts";
import { import { Guild, Member, structures, Template } from "../structures/mod.ts";
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. */ /** 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) { export async function createServer(options: CreateServerOptions) {
@@ -135,8 +130,7 @@ export async function createGuildChannel(
type: options?.type || ChannelTypes.GUILD_TEXT, type: options?.type || ChannelTypes.GUILD_TEXT,
})) as ChannelCreatePayload; })) as ChannelCreatePayload;
const channel = await structures.createChannel(result); return await structures.createChannel(result);
return channel;
} }
/** Delete a channel in your server. Bot needs MANAGE_CHANNEL permissions in the server. */ /** 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) => { return Promise.all(result.map(async (res) => {
const channel = await structures.createChannel(res, guildID); const channel = await structures.createChannel(res, guildID);
if (addToCache) { if (addToCache) {
cacheHandlers.set("channels", channel.id, channel); await cacheHandlers.set("channels", channel.id, channel);
} }
return channel; return channel;
})); }));
@@ -182,7 +176,7 @@ export async function getChannel(channelID: string, addToCache = true) {
endpoints.GUILD_CHANNEL(channelID), endpoints.GUILD_CHANNEL(channelID),
) as ChannelCreatePayload; ) as ChannelCreatePayload;
const channel = await structures.createChannel(result, result.guild_id); 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; return channel;
} }
@@ -216,8 +210,7 @@ export async function getMember(
endpoints.GUILD_MEMBER(guildID, id), endpoints.GUILD_MEMBER(guildID, id),
) as MemberCreatePayload; ) as MemberCreatePayload;
const member = await structures.createMember(data, guildID); return await structures.createMember(data, guildID);
return member;
} }
/** Returns guild member objects for the specified user by their nickname/username. /** 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); throw new Error(Errors.MISSING_MANAGE_ROLES);
} }
const bits = calculateBits(options.permissions || []);
const result = await RequestManager.post( const result = await RequestManager.post(
endpoints.GUILD_ROLES(guildID), endpoints.GUILD_ROLES(guildID),
{ {
@@ -410,7 +401,7 @@ export async function pruneMembers(guildID: string, options: PruneOptions) {
throw new Error(Errors.MISSING_KICK_MEMBERS); throw new Error(Errors.MISSING_KICK_MEMBERS);
} }
RequestManager.post( return RequestManager.post(
endpoints.GUILD_PRUNE(guildID), endpoints.GUILD_PRUNE(guildID),
{ ...options, include_roles: options.roles.join(",") }, { ...options, include_roles: options.roles.join(",") },
); );
@@ -428,7 +419,7 @@ export function fetchMembers(guild: Guild, options?: FetchMembersOptions) {
// You can request 1 member without the intent // You can request 1 member without the intent
if ( if (
(!options?.limit || options.limit > 1) && (!options?.limit || options.limit > 1) &&
!(identifyPayload.intents & Intents.GUILD_MEMBERS) !(identifyPayload.intents && Intents.GUILD_MEMBERS)
) { ) {
throw new Error(Errors.MISSING_INTENT_GUILD_MEMBERS); throw new Error(Errors.MISSING_INTENT_GUILD_MEMBERS);
} }
@@ -437,8 +428,8 @@ export function fetchMembers(guild: Guild, options?: FetchMembersOptions) {
options.limit = options.userIDs.length; options.limit = options.userIDs.length;
} }
return new Promise((resolve) => { return new Promise(async (resolve) => {
requestAllMembers(guild, resolve, options); await requestAllMembers(guild, resolve, options);
}) as Promise<Collection<string, Member>>; }) as Promise<Collection<string, Member>>;
} }
@@ -565,7 +556,7 @@ export async function getBan(guildID: string, memberID: string) {
throw new Error(Errors.MISSING_BAN_MEMBERS); throw new Error(Errors.MISSING_BAN_MEMBERS);
} }
return RequestManager.get( return await RequestManager.get(
endpoints.GUILD_BAN(guildID, memberID), endpoints.GUILD_BAN(guildID, memberID),
) as Promise<BannedUser>; ) as Promise<BannedUser>;
} }
@@ -694,11 +685,10 @@ export async function createGuildFromTemplate(
data.icon = await urlToBase64(data.icon); data.icon = await urlToBase64(data.icon);
} }
const guild = await RequestManager.post( return await RequestManager.post(
endpoints.GUILD_TEMPLATE(templateCode), endpoints.GUILD_TEMPLATE(templateCode),
data, data,
) as Promise<CreateGuildPayload>; ) as Promise<CreateGuildPayload>;
return guild;
} }
/** /**
+7 -7
View File
@@ -16,7 +16,7 @@ import {
} from "../../util/permissions.ts"; } from "../../util/permissions.ts";
import { formatImageURL, urlToBase64 } from "../../util/utils.ts"; import { formatImageURL, urlToBase64 } from "../../util/utils.ts";
import { cacheHandlers } from "../controllers/cache.ts"; import { cacheHandlers } from "../controllers/cache.ts";
import { Member, structures } from "../structures/structures.ts"; import { Member, structures } from "../structures/mod.ts";
import { sendMessage } from "./channel.ts"; import { sendMessage } from "./channel.ts";
/** The users custom avatar or the default avatar if you don't have a member object. */ /** The users custom avatar or the default avatar if you don't have a member object. */
@@ -127,10 +127,10 @@ export async function sendDirectMessage(
{ recipient_id: memberID }, { recipient_id: memberID },
) as DMChannelCreatePayload; ) as DMChannelCreatePayload;
// Channel create event will have added this channel to the cache // 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); const channel = await structures.createChannel(dmChannelData);
// Recreate the channel and add it undert he users id // Recreate the channel and add it undert he users id
cacheHandlers.set("channels", memberID, channel); await cacheHandlers.set("channels", memberID, channel);
dmChannel = channel; dmChannel = channel;
} }
@@ -240,9 +240,9 @@ export function moveMember(
/** Modifies the bot's username or avatar. /** Modifies the bot's username or avatar.
* NOTE: username: if changed may cause the bot's discriminator to be randomized. * NOTE: username: if changed may cause the bot's discriminator to be randomized.
*/ */
export async function editBotProfile(username?: string, avatarURL?: string) { export async function editBotProfile(username?: string, botAvatarURL?: string) {
// Nothing was edited // Nothing was edited
if (!username && !avatarURL) return; if (!username && !botAvatarURL) return;
// Check username requirements if username was provided // Check username requirements if username was provided
if (username) { if (username) {
if (username.length > 32) { if (username.length > 32) {
@@ -259,8 +259,8 @@ export async function editBotProfile(username?: string, avatarURL?: string) {
} }
} }
const avatar = avatarURL ? await urlToBase64(avatarURL) : undefined; const avatar = botAvatarURL ? await urlToBase64(botAvatarURL) : undefined;
RequestManager.patch( return RequestManager.patch(
endpoints.USER_BOT, endpoints.USER_BOT,
{ {
username: username?.trim(), username: username?.trim(),
+5 -5
View File
@@ -10,7 +10,7 @@ import { endpoints } from "../../util/constants.ts";
import { botHasChannelPermissions } from "../../util/permissions.ts"; import { botHasChannelPermissions } from "../../util/permissions.ts";
import { delay } from "../../util/utils.ts"; import { delay } from "../../util/utils.ts";
import { cacheHandlers } from "../controllers/cache.ts"; import { cacheHandlers } from "../controllers/cache.ts";
import { Message, structures } from "../structures/structures.ts"; import { Message, structures } from "../structures/mod.ts";
/** Delete a message with the channel id and message id only. */ /** Delete a message with the channel id and message id only. */
export async function deleteMessageByID( export async function deleteMessageByID(
@@ -68,7 +68,7 @@ export async function pin(channelID: string, messageID: string) {
) { ) {
throw new Error(Errors.MISSING_MANAGE_MESSAGES); 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. */ /** Unpin a message in a channel. Requires MANAGE_MESSAGES. */
@@ -82,7 +82,7 @@ export async function unpin(channelID: string, messageID: string) {
) { ) {
throw new Error(Errors.MISSING_MANAGE_MESSAGES); throw new Error(Errors.MISSING_MANAGE_MESSAGES);
} }
RequestManager.delete( return RequestManager.delete(
endpoints.CHANNEL_MESSAGE(channelID, messageID), endpoints.CHANNEL_MESSAGE(channelID, messageID),
); );
} }
@@ -134,8 +134,8 @@ export async function addReactions(
ordered = false, ordered = false,
) { ) {
if (!ordered) { if (!ordered) {
reactions.forEach((reaction) => await Promise.all(
addReaction(channelID, messageID, reaction) reactions.map((reaction) => addReaction(channelID, messageID, reaction)),
); );
} else { } else {
for (const reaction of reactions) { for (const reaction of reactions) {
+2 -2
View File
@@ -17,7 +17,7 @@ import { cache } from "../../util/cache.ts";
import { endpoints } from "../../util/constants.ts"; import { endpoints } from "../../util/constants.ts";
import { botHasChannelPermissions } from "../../util/permissions.ts"; import { botHasChannelPermissions } from "../../util/permissions.ts";
import { urlToBase64 } from "../../util/utils.ts"; import { urlToBase64 } from "../../util/utils.ts";
import { structures } from "../structures/structures.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: /** 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,7 +46,7 @@ export async function createWebhook(
throw new Error(Errors.INVALID_WEBHOOK_NAME); throw new Error(Errors.INVALID_WEBHOOK_NAME);
} }
return RequestManager.post( return await RequestManager.post(
endpoints.CHANNEL_WEBHOOKS(channelID), endpoints.CHANNEL_WEBHOOKS(channelID),
{ {
...options, ...options,
+1 -1
View File
@@ -62,7 +62,7 @@ export async function createChannel(
nsfw: createNewProp(data.nsfw || false), nsfw: createNewProp(data.nsfw || false),
}); });
cacheHandlers.set("channels", data.id, channel); await cacheHandlers.set("channels", data.id, channel);
return channel as Channel; return channel as Channel;
} }
+1
View File
@@ -127,6 +127,7 @@ export async function createMessage(data: MessageCreateOptions) {
message_reference: messageReference, message_reference: messageReference,
edited_timestamp: editedTimestamp, edited_timestamp: editedTimestamp,
referenced_message: referencedMessageID, referenced_message: referencedMessageID,
member,
...rest ...rest
} = data; } = data;
+1 -3
View File
@@ -28,7 +28,7 @@ export function createTemplate(
restProps[key] = createNewProp((rest as any)[key]); restProps[key] = createNewProp((rest as any)[key]);
} }
const template = Object.create(baseTemplate, { return Object.create(baseTemplate, {
...restProps, ...restProps,
usageCount: createNewProp(sourceGuildID), usageCount: createNewProp(sourceGuildID),
creatorID: createNewProp(creatorID), creatorID: createNewProp(creatorID),
@@ -38,8 +38,6 @@ export function createTemplate(
serializedSourceGuild: createNewProp(serializedSourceGuild), serializedSourceGuild: createNewProp(serializedSourceGuild),
isDirty: createNewProp(isDirty), isDirty: createNewProp(isDirty),
}); });
return template;
} }
export interface Template { export interface Template {
+1 -1
View File
@@ -106,7 +106,7 @@ export async function startBigBrainBot(data: BigBrainBotConfig) {
) as DiscordBotGatewayData; ) as DiscordBotGatewayData;
if (!data.wsURL) proxyWSURL = botGatewayData.url; if (!data.wsURL) proxyWSURL = botGatewayData.url;
spawnShards( await spawnShards(
botGatewayData, botGatewayData,
identifyPayload, identifyPayload,
data.firstShardID, data.firstShardID,
+1 -1
View File
@@ -7,7 +7,7 @@ export interface Embed {
description?: string; description?: string;
/** The url of embed */ /** The url of embed */
url?: string; url?: string;
/** The timestap of the embed content */ /** The timestamp of the embed content */
timestamp?: string; timestamp?: string;
/** The color code of the embed */ /** The color code of the embed */
color?: number; color?: number;
+1 -1
View File
@@ -29,7 +29,7 @@ export interface SlashCommandInteractionData {
} }
export interface SlashCommandInteractionDataOption { export interface SlashCommandInteractionDataOption {
/** The name of the parammeter */ /** The name of the parameter */
name: string; name: string;
/** The value of the pair */ /** The value of the pair */
value?: any; value?: any;
+1 -1
View File
@@ -7,7 +7,7 @@ export interface CreateSlashCommandOptions {
/** The name of the slash command. */ /** The name of the slash command. */
name: string; name: string;
/** The description of the slash command. */ /** 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. */ /** If a guildID is provided, this will be a GUILD command. If none is provided it will be a GLOBAL command. */
guildID?: string; guildID?: string;
/** The options for this command */ /** The options for this command */
+4 -4
View File
@@ -41,7 +41,7 @@ async function processRateLimitedPaths() {
}); });
await delay(1000); await delay(1000);
processRateLimitedPaths(); await processRateLimitedPaths();
} }
function addToQueue(request: QueuedRequest) { function addToQueue(request: QueuedRequest) {
@@ -59,7 +59,7 @@ function addToQueue(request: QueuedRequest) {
} }
async function cleanupQueues() { async function cleanupQueues() {
Object.entries(pathQueues).map(([key, value]) => { Object.entries(pathQueues).forEach(([key, value]) => {
if (!value.length) { if (!value.length) {
// Remove it entirely // Remove it entirely
delete pathQueues[key]; delete pathQueues[key];
@@ -115,7 +115,7 @@ async function processQueue() {
} }
if (Object.keys(pathQueues).length) { if (Object.keys(pathQueues).length) {
cleanupQueues(); await cleanupQueues();
} else queueInProcess = false; } else queueInProcess = false;
} }
} }
@@ -215,7 +215,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) => { return new Promise((resolve, reject) => {
const callback = async () => { const callback = async () => {
try { try {
+1 -1
View File
@@ -357,7 +357,7 @@ export interface VanityInvite {
} }
export interface GuildEmbed { export interface GuildEmbed {
/** Whether the embed is enbaled. */ /** Whether the embed is enabled. */
enabled: boolean; enabled: boolean;
} }
+1 -1
View File
@@ -13,7 +13,7 @@ export interface InteractionCommandPayload {
channel_id: string; channel_id: string;
/** guild member data for the invoking user */ /** guild member data for the invoking user */
member: MemberCreatePayload; member: MemberCreatePayload;
/** a contintuation token for responding to the interaction */ /** a continuation token for responding to the interaction */
token: string; token: string;
} }
+1 -1
View File
@@ -72,7 +72,7 @@ export interface CreateSlashCommandOptions {
/** The name of the slash command. */ /** The name of the slash command. */
name: string; name: string;
/** The description of the slash command. */ /** 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. */ /** If a guildID is provided, this will be a GUILD command. If none is provided it will be a GLOBAL command. */
guildID?: string; guildID?: string;
/** The options for this command */ /** The options for this command */
+2 -2
View File
@@ -5,8 +5,8 @@ export class Collection<K, V> extends Map<K, V> {
set(key: K, value: V) { set(key: K, value: V) {
// When this collection is maxSizeed make sure we can add first // When this collection is maxSizeed make sure we can add first
if (this.maxSize || this.maxSize === 0) { if ((this.maxSize || this.maxSize === 0) && this.size >= this.maxSize) {
if (this.size >= this.maxSize) return this; return this;
} }
return super.set(key, value); return super.set(key, value);
+15 -16
View File
@@ -36,15 +36,15 @@ export function memberHasPermission(
) )
// Removes any edge case undefined // Removes any edge case undefined
.filter((id) => id) .filter((id) => id)
.reduce((bits, permissions) => { .reduce((bits, perms) => {
bits |= BigInt(permissions); bits |= BigInt(perms);
return bits; return bits;
}, BigInt(0)); }, BigInt(0));
if (permissionBits & BigInt(Permissions.ADMINISTRATOR)) return true; if (permissionBits && BigInt(Permissions.ADMINISTRATOR)) return true;
return permissions.every((permission) => return permissions.every((permission) =>
permissionBits & BigInt(Permissions[permission]) permissionBits && BigInt(Permissions[permission])
); );
} }
@@ -74,10 +74,10 @@ export async function botHasPermission(
return bits; return bits;
}, BigInt(0)); }, BigInt(0));
if (permissionBits & BigInt(Permissions.ADMINISTRATOR)) return true; if (permissionBits && BigInt(Permissions.ADMINISTRATOR)) return true;
return permissions.every((permission) => return permissions.every((permission) =>
permissionBits & BigInt(Permissions[permission]) permissionBits && BigInt(Permissions[permission])
); );
} }
@@ -134,12 +134,12 @@ export async function hasChannelPermissions(
const denyBits = memberOverwrite.deny; const denyBits = memberOverwrite.deny;
for (const perm of permissions) { for (const perm of permissions) {
// One of the necessary permissions is denied. Since this is main permission we can cancel if its denied. // One of the necessary permissions is denied. Since this is main permission we can cancel if its denied.
if (BigInt(denyBits) & BigInt(Permissions[perm])) return false; if (BigInt(denyBits) && BigInt(Permissions[perm])) return false;
// Already allowed perm // Already allowed perm
if (allowedPermissions.has(perm)) continue; if (allowedPermissions.has(perm)) continue;
// This perm is allowed so we save it // This perm is allowed so we save it
if (BigInt(allowBits) & BigInt(Permissions[perm])) { if (BigInt(allowBits) && BigInt(Permissions[perm])) {
allowedPermissions.add(perm); allowedPermissions.add(perm);
} }
} }
@@ -153,17 +153,17 @@ export async function hasChannelPermissions(
for (const overwrite of rolesOverwrites) { for (const overwrite of rolesOverwrites) {
const allowBits = overwrite.allow; const allowBits = overwrite.allow;
// This perm is allowed so we save it // This perm is allowed so we save it
if (BigInt(allowBits) & BigInt(Permissions[perm])) { if (BigInt(allowBits) && BigInt(Permissions[perm])) {
allowedPermissions.add(perm); allowedPermissions.add(perm);
break; break;
} }
const denyBits = overwrite.deny; const denyBits = overwrite.deny;
// If this role denies it we need to save and check if another role allows it, allows > deny // If this role denies it we need to save and check if another role allows it, allows > deny
if (BigInt(denyBits) & BigInt(Permissions[perm])) { if (BigInt(denyBits) && BigInt(Permissions[perm])) {
// This role denies his perm, but before denying we need to check all other roles if any allow as allow > deny // This role denies his perm, but before denying we need to check all other roles if any allow as allow > deny
const isAllowed = rolesOverwrites.some((o) => const isAllowed = rolesOverwrites.some((o) =>
BigInt(o.allow) & BigInt(Permissions[perm]) BigInt(o.allow) && BigInt(Permissions[perm])
); );
if (isAllowed) continue; if (isAllowed) continue;
// This permission is in fact denied. Since Roles overrule everything below here we can cancel ou here // This permission is in fact denied. Since Roles overrule everything below here we can cancel ou here
@@ -179,9 +179,9 @@ export async function hasChannelPermissions(
// Already allowed perm // Already allowed perm
if (allowedPermissions.has(perm)) continue; if (allowedPermissions.has(perm)) continue;
// One of the necessary permissions is denied. Since everyone overwrite overrides role perms we can cancel here // One of the necessary permissions is denied. Since everyone overwrite overrides role perms we can cancel here
if (BigInt(denyBits) & BigInt(Permissions[perm])) return false; if (BigInt(denyBits) && BigInt(Permissions[perm])) return false;
// This perm is allowed so we save it // This perm is allowed so we save it
if (BigInt(allowBits) & BigInt(Permissions[perm])) { if (BigInt(allowBits) && BigInt(Permissions[perm])) {
allowedPermissions.add(perm); allowedPermissions.add(perm);
} }
} }
@@ -191,15 +191,14 @@ export async function hasChannelPermissions(
if (permissions.every((perm) => allowedPermissions.has(perm))) return true; if (permissions.every((perm) => allowedPermissions.has(perm))) return true;
// Some permission was not explicitly allowed so we default to checking role perms directly // Some permission was not explicitly allowed so we default to checking role perms directly
const hasPerms = await memberIDHasPermission(memberID, guild.id, permissions); return await memberIDHasPermission(memberID, guild.id, permissions);
return hasPerms;
} }
/** This function converts a bitwise string to permission strings */ /** This function converts a bitwise string to permission strings */
export function calculatePermissions(permissionBits: bigint) { export function calculatePermissions(permissionBits: bigint) {
return Object.keys(Permissions).filter((perm) => { return Object.keys(Permissions).filter((perm) => {
if (Number(perm)) return false; if (Number(perm)) return false;
return permissionBits & BigInt(Permissions[perm as Permission]); return permissionBits && BigInt(Permissions[perm as Permission]);
}) as Permission[]; }) as Permission[];
} }
+18 -18
View File
@@ -61,9 +61,9 @@ export async function createShard(
ws.onopen = async () => { ws.onopen = async () => {
if (!resuming) { if (!resuming) {
// Initial identify with the gateway // Initial identify with the gateway
await identify(basicShard, identifyPayload); identify(basicShard, identifyPayload);
} else { } else {
await resume(basicShard, identifyPayload); resume(basicShard, identifyPayload);
} }
}; };
@@ -85,14 +85,14 @@ export async function createShard(
} }
if (typeof message === "string") { if (typeof message === "string") {
const data = JSON.parse(message); const messageData = JSON.parse(message);
if (!data.t) eventHandlers.rawGateway?.(data); if (!messageData.t) eventHandlers.rawGateway?.(messageData);
switch (data.op) { switch (messageData.op) {
case GatewayOpcode.Hello: case GatewayOpcode.Hello:
if (!heartbeating.has(basicShard.id)) { if (!heartbeating.has(basicShard.id)) {
heartbeat( heartbeat(
basicShard, basicShard,
(data.d as DiscordHeartbeatPayload).heartbeat_interval, (messageData.d as DiscordHeartbeatPayload).heartbeat_interval,
identifyPayload, identifyPayload,
data, data,
); );
@@ -116,7 +116,7 @@ export async function createShard(
}, },
); );
// When d is false we need to reidentify // When d is false we need to reidentify
if (!data.d) { if (!messageData.d) {
createShard(data, identifyPayload, false, shardID); createShard(data, identifyPayload, false, shardID);
break; break;
} }
@@ -124,7 +124,7 @@ export async function createShard(
resumeConnection(data, identifyPayload, basicShard.id); resumeConnection(data, identifyPayload, basicShard.id);
break; break;
default: default:
if (data.t === "RESUMED") { if (messageData.t === "RESUMED") {
eventHandlers.debug?.( eventHandlers.debug?.(
{ type: "gatewayResumed", data: { shardID: basicShard.id } }, { type: "gatewayResumed", data: { shardID: basicShard.id } },
); );
@@ -133,14 +133,14 @@ export async function createShard(
break; break;
} }
// Important for RESUME // Important for RESUME
if (data.t === "READY") { if (messageData.t === "READY") {
basicShard.sessionID = (data.d as ReadyPayload).session_id; basicShard.sessionID = (messageData.d as ReadyPayload).session_id;
} }
// Update the sequence number if it is present // Update the sequence number if it is present
if (data.s) basicShard.previousSequenceNumber = data.s; if (messageData.s) basicShard.previousSequenceNumber = messageData.s;
handleDiscordPayload(data, basicShard.id); handleDiscordPayload(messageData, basicShard.id);
break; break;
} }
} }
@@ -247,7 +247,7 @@ async function heartbeat(
// We lost socket connection between heartbeats, resume connection // We lost socket connection between heartbeats, resume connection
if (shard.ws.readyState === WebSocket.CLOSED) { if (shard.ws.readyState === WebSocket.CLOSED) {
shard.needToResume = true; shard.needToResume = true;
resumeConnection(data, payload, shard.id); await resumeConnection(data, payload, shard.id);
heartbeating.delete(shard.id); heartbeating.delete(shard.id);
return; return;
} }
@@ -289,7 +289,7 @@ async function heartbeat(
}, },
); );
await delay(interval); await delay(interval);
heartbeat(shard, interval, payload, data); await heartbeat(shard, interval, payload, data);
} }
async function resumeConnection( async function resumeConnection(
@@ -309,10 +309,10 @@ async function resumeConnection(
eventHandlers.debug?.({ type: "gatewayResume", data: { shardID: shard.id } }); eventHandlers.debug?.({ type: "gatewayResume", data: { shardID: shard.id } });
// Run it once // Run it once
createShard(data, payload, true, shard.id); await createShard(data, payload, true, shard.id);
// Then retry every 15 seconds // Then retry every 15 seconds
await delay(1000 * 15); await delay(1000 * 15);
if (shard.needToResume) resumeConnection(data, payload, shardID); if (shard.needToResume) await resumeConnection(data, payload, shardID);
} }
export function requestGuildMembers( export function requestGuildMembers(
@@ -335,7 +335,7 @@ export function requestGuildMembers(
if (!processQueue) { if (!processQueue) {
processQueue = true; processQueue = true;
processGatewayQueue(); return processGatewayQueue();
} }
return; return;
} }
@@ -419,7 +419,7 @@ async function processGatewayQueue() {
await delay(1500); await delay(1500);
processGatewayQueue(); await processGatewayQueue();
} }
export function botGatewayStatusRequest(payload: BotStatusRequest) { export function botGatewayStatusRequest(payload: BotStatusRequest) {
+5 -5
View File
@@ -1,5 +1,5 @@
import { controllers } from "../api/controllers/mod.ts"; import { controllers } from "../api/controllers/mod.ts";
import { Guild } from "../api/structures/structures.ts"; import { Guild } from "../api/structures/guild.ts";
import { eventHandlers, IdentifyPayload } from "../bot.ts"; import { eventHandlers, IdentifyPayload } from "../bot.ts";
import { import {
DiscordBotGatewayData, DiscordBotGatewayData,
@@ -38,9 +38,9 @@ export async function spawnShards(
data.shards > lastShardID ? data.shards : lastShardID, data.shards > lastShardID ? data.shards : lastShardID,
]; ];
// Start The shard // Start The shard
createShard(data, payload, false, shardID); await createShard(data, payload, false, shardID);
// Spawn next shard // Spawn next shard
spawnShards( await spawnShards(
data, data,
payload, payload,
shardID + 1, shardID + 1,
@@ -54,7 +54,7 @@ export async function spawnShards(
if (createNextShard) { if (createNextShard) {
createNextShard = false; createNextShard = false;
// Start the next few shards based on max concurrency // Start the next few shards based on max concurrency
spawnShards( await spawnShards(
data, data,
payload, payload,
shardID, shardID,
@@ -65,7 +65,7 @@ export async function spawnShards(
} }
await delay(1000); await delay(1000);
spawnShards(data, payload, shardID, lastShardID, skipChecks); await spawnShards(data, payload, shardID, lastShardID, skipChecks);
} }
export async function handleDiscordPayload( export async function handleDiscordPayload(