Merge branch 'main' into fix-get-message-dm

This commit is contained in:
Skillz4Killz
2021-04-03 23:39:30 -04:00
committed by GitHub
103 changed files with 440 additions and 326 deletions
+2 -1
View File
@@ -1,5 +1,6 @@
import { getGatewayBot } from "./helpers/misc/get_gateway_bot.ts"; import { getGatewayBot } from "./helpers/misc/get_gateway_bot.ts";
import { DiscordGatewayIntents } from "./types/gateway/gateway_intents.ts"; import { DiscordGatewayIntents } from "./types/gateway/gateway_intents.ts";
import { DiscordGetGatewayBot } from "./types/gateway/get_gateway_bot.ts";
import { baseEndpoints, GATEWAY_VERSION } from "./util/constants.ts"; import { baseEndpoints, GATEWAY_VERSION } from "./util/constants.ts";
import { spawnShards } from "./ws/shard_manager.ts"; import { spawnShards } from "./ws/shard_manager.ts";
@@ -14,7 +15,7 @@ export let botGatewayData: DiscordGetGatewayBot;
export let proxyWSURL = `wss://gateway.discord.gg`; export let proxyWSURL = `wss://gateway.discord.gg`;
export let lastShardId = 0; export let lastShardId = 0;
export const identifyPayload: DiscordIdentify = { export const identifyPayload = {
token: "", token: "",
compress: true, compress: true,
properties: { properties: {
+46 -30
View File
@@ -1,24 +1,40 @@
// deno-lint-ignore-file require-await no-explicit-any prefer-const // deno-lint-ignore-file require-await no-explicit-any prefer-const
import { Channel, Guild, Member, Message } from "./structures/mod.ts"; import { Channel, Guild, Member, Message } from "./structures/mod.ts";
import { Emoji } from "./types/emojis/emoji.ts";
import { Collection } from "./util/collection.ts"; import { Collection } from "./util/collection.ts";
export const cache: CacheData = { export const cache = {
isReady: false, isReady: false,
/** All of the guild objects the bot has access to, mapped by their Ids */ /** All of the guild objects the bot has access to, mapped by their Ids */
guilds: new Collection(), guilds: new Collection<string, Guild>(),
/** All of the channel objects the bot has access to, mapped by their Ids */ /** All of the channel objects the bot has access to, mapped by their Ids */
channels: new Collection(), channels: new Collection<string, Channel>(),
/** All of the message objects the bot has cached since the bot acquired `READY` state, mapped by their Ids */ /** All of the message objects the bot has cached since the bot acquired `READY` state, mapped by their Ids */
messages: new Collection(), messages: new Collection<string, Message>(),
/** All of the member objects that have been cached since the bot acquired `READY` state, mapped by their Ids */ /** All of the member objects that have been cached since the bot acquired `READY` state, mapped by their Ids */
members: new Collection(), members: new Collection<string, Member>(),
/** All of the unavailable guilds, mapped by their Ids (id, shardId) */ /** All of the unavailable guilds, mapped by their Ids (id, timestamp) */
unavailableGuilds: new Collection(), unavailableGuilds: new Collection<string, number>(),
/** All of the presence update objects received in PRESENCE_UPDATE gateway event, mapped by their user Id */ /** All of the presence update objects received in PRESENCE_UPDATE gateway event, mapped by their user Id */
presences: new Collection(), presences: new Collection<string, Presence>(),
fetchAllMembersProcessingRequests: new Collection(), fetchAllMembersProcessingRequests: new Collection<
executedSlashCommands: new Collection(), string,
(
value:
| Collection<string, Member>
| PromiseLike<Collection<string, Member>>
) => void
>(),
executedSlashCommands: new Collection<string, string>(),
get emojis() {
return new Collection<string, Emoji>(
this.guilds.reduce(
(a, b) => [...a, ...b.emojis.map((e) => [e.id, e])],
[] as any[]
)
);
},
}; };
export let cacheHandlers = { export let cacheHandlers = {
@@ -62,32 +78,32 @@ export type TableName =
function set( function set(
table: "guilds", table: "guilds",
key: string, key: string,
value: Guild, value: Guild
): Promise<Collection<string, Guild>>; ): Promise<Collection<string, Guild>>;
function set( function set(
table: "channels", table: "channels",
key: string, key: string,
value: Channel, value: Channel
): Promise<Collection<string, Channel>>; ): Promise<Collection<string, Channel>>;
function set( function set(
table: "messages", table: "messages",
key: string, key: string,
value: Message, value: Message
): Promise<Collection<string, Message>>; ): Promise<Collection<string, Message>>;
function set( function set(
table: "members", table: "members",
key: string, key: string,
value: Member, value: Member
): Promise<Collection<string, Member>>; ): Promise<Collection<string, Member>>;
function set( function set(
table: "presences", table: "presences",
key: string, key: string,
value: PresenceUpdatePayload, value: PresenceUpdatePayload
): Promise<Collection<string, PresenceUpdatePayload>>; ): Promise<Collection<string, PresenceUpdatePayload>>;
function set( function set(
table: "unavailableGuilds", table: "unavailableGuilds",
key: string, key: string,
value: number, value: number
): Promise<Collection<string, number>>; ): Promise<Collection<string, number>>;
async function set(table: TableName, key: string, value: any) { async function set(table: TableName, key: string, value: any) {
return cache[table].set(key, value); return cache[table].set(key, value);
@@ -99,11 +115,11 @@ function get(table: "messages", key: string): Promise<Message | undefined>;
function get(table: "members", key: string): Promise<Member | undefined>; function get(table: "members", key: string): Promise<Member | undefined>;
function get( function get(
table: "presences", table: "presences",
key: string, key: string
): Promise<PresenceUpdatePayload | undefined>; ): Promise<PresenceUpdatePayload | undefined>;
function get( function get(
table: "unavailableGuilds", table: "unavailableGuilds",
key: string, key: string
): Promise<Guild | undefined>; ): Promise<Guild | undefined>;
async function get(table: TableName, key: string) { async function get(table: TableName, key: string) {
return cache[table].get(key); return cache[table].get(key);
@@ -111,54 +127,54 @@ async function get(table: TableName, key: string) {
function forEach( function forEach(
table: "guilds", table: "guilds",
callback: (value: Guild, key: string, map: Map<string, Guild>) => unknown, callback: (value: Guild, key: string, map: Map<string, Guild>) => unknown
): void; ): void;
function forEach( function forEach(
table: "unavailableGuilds", table: "unavailableGuilds",
callback: (value: Guild, key: string, map: Map<string, Guild>) => unknown, callback: (value: Guild, key: string, map: Map<string, Guild>) => unknown
): void; ): void;
function forEach( function forEach(
table: "channels", table: "channels",
callback: (value: Channel, key: string, map: Map<string, Channel>) => unknown, callback: (value: Channel, key: string, map: Map<string, Channel>) => unknown
): void; ): void;
function forEach( function forEach(
table: "messages", table: "messages",
callback: (value: Message, key: string, map: Map<string, Message>) => unknown, callback: (value: Message, key: string, map: Map<string, Message>) => unknown
): void; ): void;
function forEach( function forEach(
table: "members", table: "members",
callback: (value: Member, key: string, map: Map<string, Member>) => unknown, callback: (value: Member, key: string, map: Map<string, Member>) => unknown
): void; ): void;
function forEach( function forEach(
table: TableName, table: TableName,
callback: (value: any, key: string, map: Map<string, any>) => unknown, callback: (value: any, key: string, map: Map<string, any>) => unknown
) { ) {
return cache[table].forEach(callback); return cache[table].forEach(callback);
} }
function filter( function filter(
table: "guilds", table: "guilds",
callback: (value: Guild, key: string) => boolean, callback: (value: Guild, key: string) => boolean
): Promise<Collection<string, Guild>>; ): Promise<Collection<string, Guild>>;
function filter( function filter(
table: "unavailableGuilds", table: "unavailableGuilds",
callback: (value: Guild, key: string) => boolean, callback: (value: Guild, key: string) => boolean
): Promise<Collection<string, Guild>>; ): Promise<Collection<string, Guild>>;
function filter( function filter(
table: "channels", table: "channels",
callback: (value: Channel, key: string) => boolean, callback: (value: Channel, key: string) => boolean
): Promise<Collection<string, Channel>>; ): Promise<Collection<string, Channel>>;
function filter( function filter(
table: "messages", table: "messages",
callback: (value: Message, key: string) => boolean, callback: (value: Message, key: string) => boolean
): Promise<Collection<string, Message>>; ): Promise<Collection<string, Message>>;
function filter( function filter(
table: "members", table: "members",
callback: (value: Member, key: string) => boolean, callback: (value: Member, key: string) => boolean
): Promise<Collection<string, Member>>; ): Promise<Collection<string, Member>>;
async function filter( async function filter(
table: TableName, table: TableName,
callback: (value: any, key: string) => boolean, callback: (value: any, key: string) => boolean
) { ) {
return cache[table].filter(callback); return cache[table].filter(callback);
} }
+2 -1
View File
@@ -1,7 +1,8 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { structures } from "../../structures/mod.ts"; import { structures } from "../../structures/mod.ts";
import { DiscordChannel, DiscordGatewayPayload } from "../../types/mod.ts"; import { DiscordChannel } from "../../types/channels/channel.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
export async function handleChannelCreate(data: DiscordGatewayPayload) { export async function handleChannelCreate(data: DiscordGatewayPayload) {
const payload = data.d as DiscordChannel; const payload = data.d as DiscordChannel;
+3 -5
View File
@@ -1,10 +1,8 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { import { DiscordChannel } from "../../types/channels/channel.ts";
DiscordChannel, import { DiscordChannelTypes } from "../../types/channels/channel_types.ts";
DiscordChannelTypes, import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
DiscordGatewayPayload,
} from "../../types/mod.ts";
export async function handleChannelDelete(data: DiscordGatewayPayload) { export async function handleChannelDelete(data: DiscordGatewayPayload) {
const payload = data.d as DiscordChannel; const payload = data.d as DiscordChannel;
+2 -4
View File
@@ -1,9 +1,7 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { import { DiscordChannelPinsUpdate } from "../../types/channels/channel_pins_update.ts";
DiscordChannelPinsUpdate, import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
DiscordGatewayPayload,
} from "../../types/mod.ts";
export async function handleChannelPinsUpdate(data: DiscordGatewayPayload) { export async function handleChannelPinsUpdate(data: DiscordGatewayPayload) {
const payload = data.d as DiscordChannelPinsUpdate; const payload = data.d as DiscordChannelPinsUpdate;
+2 -1
View File
@@ -1,7 +1,8 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { structures } from "../../structures/mod.ts"; import { structures } from "../../structures/mod.ts";
import { DiscordChannel, DiscordGatewayPayload } from "../../types/mod.ts"; import { DiscordChannel } from "../../types/channels/channel.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
export async function handleChannelUpdate(data: DiscordGatewayPayload) { export async function handleChannelUpdate(data: DiscordGatewayPayload) {
const payload = data.d as DiscordChannel; const payload = data.d as DiscordChannel;
@@ -1,4 +1,5 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
export function handleApplicationCommandCreate( export function handleApplicationCommandCreate(
data: DiscordGatewayPayload, data: DiscordGatewayPayload,
@@ -1,4 +1,5 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
export function handleApplicationCommandDelete(data: DiscordGatewayPayload) { export function handleApplicationCommandDelete(data: DiscordGatewayPayload) {
const { const {
@@ -1,4 +1,5 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
export function handleApplicationCommandUpdate(data: DiscordGatewayPayload) { export function handleApplicationCommandUpdate(data: DiscordGatewayPayload) {
const { const {
+2 -4
View File
@@ -1,10 +1,8 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import {
DiscordGatewayPayload,
DiscordGuildEmojisUpdate,
} from "../../types/mod.ts";
import { Collection } from "../../util/collection.ts"; import { Collection } from "../../util/collection.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { DiscordGuildEmojisUpdate } from "../../types/emojis/guild_emojis_update.ts";
export async function handleGuildEmojisUpdate(data: DiscordGatewayPayload) { export async function handleGuildEmojisUpdate(data: DiscordGatewayPayload) {
const payload = data.d as DiscordGuildEmojisUpdate; const payload = data.d as DiscordGuildEmojisUpdate;
+1
View File
@@ -1,5 +1,6 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
export async function handleGuildBanAdd(data: DiscordGatewayPayload) { export async function handleGuildBanAdd(data: DiscordGatewayPayload) {
const payload = data.d as DiscordGuildBanAddRemove; const payload = data.d as DiscordGuildBanAddRemove;
+1
View File
@@ -1,5 +1,6 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
export async function handleGuildBanRemove(data: DiscordGatewayPayload) { export async function handleGuildBanRemove(data: DiscordGatewayPayload) {
const payload = data.d as DiscordGuildBanAddRemove; const payload = data.d as DiscordGuildBanAddRemove;
+4
View File
@@ -2,6 +2,8 @@ import { eventHandlers } from "../../bot.ts";
import { cache, cacheHandlers } from "../../cache.ts"; import { cache, cacheHandlers } from "../../cache.ts";
import { structures } from "../../structures/mod.ts"; import { structures } from "../../structures/mod.ts";
import { basicShards } from "../../ws/shard.ts"; import { basicShards } from "../../ws/shard.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { DiscordGuild } from "../../types/guilds/guild.ts";
export async function handleGuildCreate( export async function handleGuildCreate(
data: DiscordGatewayPayload, data: DiscordGatewayPayload,
@@ -23,6 +25,8 @@ export async function handleGuildCreate(
await cacheHandlers.delete("unavailableGuilds", payload.id); await cacheHandlers.delete("unavailableGuilds", payload.id);
shard.unavailableGuildIds.delete(payload.id); shard.unavailableGuildIds.delete(payload.id);
return eventHandlers.guildAvailable?.(guildStruct);
} }
if (!cache.isReady) return eventHandlers.guildLoaded?.(guildStruct); if (!cache.isReady) return eventHandlers.guildLoaded?.(guildStruct);
+6 -2
View File
@@ -1,6 +1,8 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { basicShards } from "../../ws/shard.ts"; import { basicShards } from "../../ws/shard.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { DiscordUnavailableGuild } from "../../types/guilds/unavailable_guild.ts";
export async function handleGuildDelete( export async function handleGuildDelete(
data: DiscordGatewayPayload, data: DiscordGatewayPayload,
@@ -18,9 +20,11 @@ export async function handleGuildDelete(
if (shard) shard.unavailableGuildIds.add(payload.id); if (shard) shard.unavailableGuildIds.add(payload.id);
await cacheHandlers.set("unavailableGuilds", payload.id, Date.now()); await cacheHandlers.set("unavailableGuilds", payload.id, Date.now());
}
eventHandlers.guildDelete?.(guild); eventHandlers.guildUnavailable?.(guild);
} else {
eventHandlers.guildDelete?.(guild);
}
cacheHandlers.forEach("messages", (message) => { cacheHandlers.forEach("messages", (message) => {
if (message.guildId === payload.id) { if (message.guildId === payload.id) {
@@ -1,5 +1,7 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { DiscordGuildIntegrationsUpdate } from "../../types/guilds/guild_integrations_update.ts";
export async function handleGuildIntegrationsUpdate( export async function handleGuildIntegrationsUpdate(
data: DiscordGatewayPayload, data: DiscordGatewayPayload,
+2
View File
@@ -1,5 +1,7 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { DiscordGuild } from "../../types/guilds/guild.ts";
export async function handleGuildUpdate(data: DiscordGatewayPayload) { export async function handleGuildUpdate(data: DiscordGatewayPayload) {
const payload = data.d as DiscordGuild; const payload = data.d as DiscordGuild;
@@ -1,4 +1,5 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
export function handleIntegrationCreate( export function handleIntegrationCreate(
data: DiscordGatewayPayload, data: DiscordGatewayPayload,
@@ -1,4 +1,5 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
export function handleIntegrationDelete(data: DiscordGatewayPayload) { export function handleIntegrationDelete(data: DiscordGatewayPayload) {
const { const {
@@ -1,4 +1,5 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
export function handleIntegrationUpdate(data: DiscordGatewayPayload) { export function handleIntegrationUpdate(data: DiscordGatewayPayload) {
const { const {
@@ -1,6 +1,7 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { structures } from "../../structures/mod.ts"; import { structures } from "../../structures/mod.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
export async function handleInteractionCreate(data: DiscordGatewayPayload) { export async function handleInteractionCreate(data: DiscordGatewayPayload) {
const payload = data.d as InteractionCommandPayload; const payload = data.d as InteractionCommandPayload;
+2
View File
@@ -1,4 +1,6 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { DiscordInviteCreate } from "../../types/invites/invite_create.ts";
export function handleInviteCreate(payload: DiscordGatewayPayload) { export function handleInviteCreate(payload: DiscordGatewayPayload) {
// TODO: replace with tocamelcase // TODO: replace with tocamelcase
+2
View File
@@ -1,4 +1,6 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { DiscordInviteDelete } from "../../types/invites/invite_delete.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
export function handleInviteDelete(payload: DiscordGatewayPayload) { export function handleInviteDelete(payload: DiscordGatewayPayload) {
const { const {
@@ -1,6 +1,8 @@
import { cache, cacheHandlers } from "../../cache.ts"; import { cache, cacheHandlers } from "../../cache.ts";
import { structures } from "../../structures/mod.ts"; import { structures } from "../../structures/mod.ts";
import { Collection } from "../../util/collection.ts"; import { Collection } from "../../util/collection.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { DiscordGuildMembersChunk } from "../../types/members/guild_members_chunk.ts";
export async function handleGuildMembersChunk(data: DiscordGatewayPayload) { export async function handleGuildMembersChunk(data: DiscordGatewayPayload) {
const payload = data.d as DiscordGuildMembersChunk; const payload = data.d as DiscordGuildMembersChunk;
+2
View File
@@ -1,6 +1,8 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { structures } from "../../structures/mod.ts"; import { structures } from "../../structures/mod.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { DiscordGuildMemberAdd } from "../../types/members/guild_member_add.ts";
export async function handleGuildMemberAdd(data: DiscordGatewayPayload) { export async function handleGuildMemberAdd(data: DiscordGatewayPayload) {
const payload = data.d as DiscordGuildMemberAdd; const payload = data.d as DiscordGuildMemberAdd;
@@ -1,5 +1,7 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { DiscordGuildMemberRemove } from "../../types/members/guild_member_remove.ts";
export async function handleGuildMemberRemove(data: DiscordGatewayPayload) { export async function handleGuildMemberRemove(data: DiscordGatewayPayload) {
const payload = data.d as DiscordGuildMemberRemove; const payload = data.d as DiscordGuildMemberRemove;
@@ -1,6 +1,8 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { structures } from "../../structures/mod.ts"; import { structures } from "../../structures/mod.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { DiscordGuildMemberUpdate } from "../../types/members/guild_member_update.ts";
export async function handleGuildMemberUpdate(data: DiscordGatewayPayload) { export async function handleGuildMemberUpdate(data: DiscordGatewayPayload) {
const payload = data.d as DiscordGuildMemberUpdate; const payload = data.d as DiscordGuildMemberUpdate;
+2
View File
@@ -1,6 +1,8 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { structures } from "../../structures/mod.ts"; import { structures } from "../../structures/mod.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { DiscordMessage } from "../../types/messages/message.ts";
export async function handleMessageCreate(data: DiscordGatewayPayload) { export async function handleMessageCreate(data: DiscordGatewayPayload) {
const payload = data.d as DiscordMessage; const payload = data.d as DiscordMessage;
+2
View File
@@ -1,5 +1,7 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { DiscordMessageDelete } from "../../types/messages/message_delete.ts";
export async function handleMessageDelete(data: DiscordGatewayPayload) { export async function handleMessageDelete(data: DiscordGatewayPayload) {
const payload = data.d as DiscordMessageDelete; const payload = data.d as DiscordMessageDelete;
@@ -1,5 +1,7 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { DiscordMessageDeleteBulk } from "../../types/messages/message_delete_bulk.ts";
export async function handleMessageDeleteBulk(data: DiscordGatewayPayload) { export async function handleMessageDeleteBulk(data: DiscordGatewayPayload) {
const payload = data.d as DiscordMessageDeleteBulk; const payload = data.d as DiscordMessageDeleteBulk;
@@ -1,6 +1,8 @@
import { botId, eventHandlers } from "../../bot.ts"; import { botId, eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { structures } from "../../structures/mod.ts"; import { structures } from "../../structures/mod.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { DiscordMessageReactionAdd } from "../../types/messages/message_reaction_add.ts";
export async function handleMessageReactionAdd(data: DiscordGatewayPayload) { export async function handleMessageReactionAdd(data: DiscordGatewayPayload) {
const payload = data.d as DiscordMessageReactionAdd; const payload = data.d as DiscordMessageReactionAdd;
@@ -1,6 +1,8 @@
import { botId, eventHandlers } from "../../bot.ts"; import { botId, eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { structures } from "../../structures/mod.ts"; import { structures } from "../../structures/mod.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { DiscordMessageReactionRemove } from "../../types/messages/message_reaction_remove.ts";
export async function handleMessageReactionRemove( export async function handleMessageReactionRemove(
data: DiscordGatewayPayload, data: DiscordGatewayPayload,
@@ -1,5 +1,7 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { DiscordMessageReactionRemoveAll } from "../../types/messages/message_reaction_remove_all.ts";
export async function handleMessageReactionRemoveAll( export async function handleMessageReactionRemoveAll(
data: DiscordGatewayPayload, data: DiscordGatewayPayload,
@@ -1,5 +1,7 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { DiscordMessageReactionRemoveEmoji } from "../../types/messages/message_reaction_remove_emoji.ts";
export async function handleMessageReactionRemoveEmoji( export async function handleMessageReactionRemoveEmoji(
data: DiscordGatewayPayload, data: DiscordGatewayPayload,
+2
View File
@@ -1,6 +1,8 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { structures } from "../../structures/mod.ts"; import { structures } from "../../structures/mod.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { DiscordMessage } from "../../types/messages/message.ts";
export async function handleMessageUpdate(data: DiscordGatewayPayload) { export async function handleMessageUpdate(data: DiscordGatewayPayload) {
const payload = data.d as DiscordMessage; const payload = data.d as DiscordMessage;
+2
View File
@@ -1,5 +1,7 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { DiscordPresenceUpdate } from "../../types/misc/presence_update.ts";
export async function handlePresenceUpdate(data: DiscordGatewayPayload) { export async function handlePresenceUpdate(data: DiscordGatewayPayload) {
const payload = data.d as DiscordPresenceUpdate; const payload = data.d as DiscordPresenceUpdate;
+2
View File
@@ -9,6 +9,8 @@ import { initialMemberLoadQueue } from "../../structures/guild.ts";
import { structures } from "../../structures/mod.ts"; import { structures } from "../../structures/mod.ts";
import { delay } from "../../util/utils.ts"; import { delay } from "../../util/utils.ts";
import { allowNextShard, basicShards } from "../../ws/mod.ts"; import { allowNextShard, basicShards } from "../../ws/mod.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { DiscordReady } from "../../types/gateway/ready.ts";
export async function handleReady( export async function handleReady(
data: DiscordGatewayPayload, data: DiscordGatewayPayload,
+2
View File
@@ -1,4 +1,6 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { DiscordTypingStart } from "../../types/misc/typing_start.ts";
export function handleTypingStart(data: DiscordGatewayPayload) { export function handleTypingStart(data: DiscordGatewayPayload) {
eventHandlers.typingStart?.(data.d as DiscordTypingStart); eventHandlers.typingStart?.(data.d as DiscordTypingStart);
+2
View File
@@ -1,5 +1,7 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { DiscordUser } from "../../types/users/user.ts";
export async function handleUserUpdate(data: DiscordGatewayPayload) { export async function handleUserUpdate(data: DiscordGatewayPayload) {
const userData = data.d as DiscordUser; const userData = data.d as DiscordUser;
+1
View File
@@ -1,6 +1,7 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { structures } from "../../structures/mod.ts"; import { structures } from "../../structures/mod.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
export async function handleGuildRoleCreate(data: DiscordGatewayPayload) { export async function handleGuildRoleCreate(data: DiscordGatewayPayload) {
const payload = data.d as DiscordGuildRoleCreateUpdate; const payload = data.d as DiscordGuildRoleCreateUpdate;
+2
View File
@@ -1,5 +1,7 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { DiscordGuildRoleDelete } from "../../types/guilds/guild_role_delete.ts";
export async function handleGuildRoleDelete(data: DiscordGatewayPayload) { export async function handleGuildRoleDelete(data: DiscordGatewayPayload) {
const payload = data.d as DiscordGuildRoleDelete; const payload = data.d as DiscordGuildRoleDelete;
+1
View File
@@ -1,6 +1,7 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { structures } from "../../structures/mod.ts"; import { structures } from "../../structures/mod.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
export async function handleGuildRoleUpdate(data: DiscordGatewayPayload) { export async function handleGuildRoleUpdate(data: DiscordGatewayPayload) {
const payload = data.d as DiscordGuildRoleCreateUpdate; const payload = data.d as DiscordGuildRoleCreateUpdate;
+2
View File
@@ -1,6 +1,8 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { structures } from "../../structures/mod.ts"; import { structures } from "../../structures/mod.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { DiscordVoiceState } from "../../types/voice/voice_state.ts";
export async function handleVoiceStateUpdate(data: DiscordGatewayPayload) { export async function handleVoiceStateUpdate(data: DiscordGatewayPayload) {
const payload = data.d as DiscordVoiceState; const payload = data.d as DiscordVoiceState;
+2
View File
@@ -1,4 +1,6 @@
import { eventHandlers } from "../../bot.ts"; import { eventHandlers } from "../../bot.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { DiscordWebhooksUpdate } from "../../types/webhooks/webhooks_update.ts";
export function handleWebhooksUpdate(data: DiscordGatewayPayload) { export function handleWebhooksUpdate(data: DiscordGatewayPayload) {
const options = data.d as DiscordWebhooksUpdate; const options = data.d as DiscordWebhooksUpdate;
+11 -10
View File
@@ -1,12 +1,10 @@
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts"; import { rest } from "../../rest/rest.ts";
import { structures } from "../../structures/mod.ts"; import { structures } from "../../structures/mod.ts";
import { import { DiscordChannel } from "../../types/channels/channel.ts";
CreateGuildChannel, import { DiscordChannelTypes } from "../../types/channels/channel_types.ts";
DiscordChannel, import { CreateGuildChannel } from "../../types/guilds/create_guild_channel.ts";
DiscordChannelTypes, import { PermissionStrings } from "../../types/permissions/permission_strings.ts";
PermissionStrings,
} from "../../types/mod.ts";
import { endpoints } from "../../util/constants.ts"; import { endpoints } from "../../util/constants.ts";
import { import {
calculateBits, calculateBits,
@@ -17,7 +15,7 @@ import {
export async function createChannel( export async function createChannel(
guildId: string, guildId: string,
name: string, name: string,
options?: CreateGuildChannel, options?: CreateGuildChannel
) { ) {
const requiredPerms: Set<PermissionStrings> = new Set(["MANAGE_CHANNELS"]); const requiredPerms: Set<PermissionStrings> = new Set(["MANAGE_CHANNELS"]);
@@ -28,8 +26,10 @@ export async function createChannel(
await requireBotGuildPermissions(guildId, [...requiredPerms]); await requireBotGuildPermissions(guildId, [...requiredPerms]);
const result = const result = (await rest.runMethod(
(await rest.runMethod("post", endpoints.GUILD_CHANNELS(guildId), { "post",
endpoints.GUILD_CHANNELS(guildId),
{
...options, ...options,
name, name,
permission_overwrites: options?.permissionOverwrites?.map((perm) => ({ permission_overwrites: options?.permissionOverwrites?.map((perm) => ({
@@ -39,7 +39,8 @@ export async function createChannel(
deny: calculateBits(perm.deny), deny: calculateBits(perm.deny),
})), })),
type: options?.type || DiscordChannelTypes.GUILD_TEXT, type: options?.type || DiscordChannelTypes.GUILD_TEXT,
})) as DiscordChannel; }
)) as DiscordChannel;
const channelStruct = await structures.createChannelStruct(result); const channelStruct = await structures.createChannelStruct(result);
await cacheHandlers.set("channels", channelStruct.id, channelStruct); await cacheHandlers.set("channels", channelStruct.id, channelStruct);
+1 -1
View File
@@ -1,6 +1,6 @@
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts"; import { rest } from "../../rest/rest.ts";
import { Errors } from "../../types/mod.ts"; import { Errors } from "../../types/misc/errors.ts";
import { endpoints } from "../../util/constants.ts"; import { endpoints } from "../../util/constants.ts";
import { requireBotGuildPermissions } from "../../util/permissions.ts"; import { requireBotGuildPermissions } from "../../util/permissions.ts";
@@ -1,5 +1,5 @@
import { rest } from "../../rest/rest.ts"; import { rest } from "../../rest/rest.ts";
import { Overwrite } from "../../types/mod.ts"; import { Overwrite } from "../../types/channels/overwrite.ts";
import { endpoints } from "../../util/constants.ts"; import { endpoints } from "../../util/constants.ts";
import { import {
calculateBits, calculateBits,
+1 -1
View File
@@ -1,5 +1,5 @@
import { rest } from "../../rest/rest.ts"; import { rest } from "../../rest/rest.ts";
import { DiscordFollowedChannel } from "../../types/mod.ts"; import { DiscordFollowedChannel } from "../../types/channels/followed_channel.ts";
import { endpoints } from "../../util/constants.ts"; import { endpoints } from "../../util/constants.ts";
import { requireBotChannelPermissions } from "../../util/permissions.ts"; import { requireBotChannelPermissions } from "../../util/permissions.ts";
+5 -6
View File
@@ -1,7 +1,7 @@
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts"; import { rest } from "../../rest/rest.ts";
import { structures } from "../../structures/mod.ts"; import { structures } from "../../structures/mod.ts";
import { DiscordChannel } from "../../types/mod.ts"; import { DiscordChannel } from "../../types/channels/channel.ts";
import { endpoints } from "../../util/constants.ts"; import { endpoints } from "../../util/constants.ts";
/** Fetches a single channel object from the api. /** Fetches a single channel object from the api.
@@ -9,11 +9,10 @@ import { endpoints } from "../../util/constants.ts";
* ⚠️ **If you need this, you are probably doing something wrong. This is not intended for use. Your channels will be cached in your guild.** * ⚠️ **If you need this, you are probably doing something wrong. This is not intended for use. Your channels will be cached in your guild.**
*/ */
export async function getChannel(channelId: string, addToCache = true) { export async function getChannel(channelId: string, addToCache = true) {
const result = const result = (await rest.runMethod(
(await rest.runMethod( "get",
"get", endpoints.CHANNEL_BASE(channelId),
endpoints.CHANNEL_BASE(channelId), )) as DiscordChannel;
)) as DiscordChannel;
const channelStruct = await structures.createChannelStruct( const channelStruct = await structures.createChannelStruct(
result, result,
+1 -1
View File
@@ -1,5 +1,5 @@
import { rest } from "../../rest/rest.ts"; import { rest } from "../../rest/rest.ts";
import { DiscordWebhook } from "../../types/mod.ts"; import { DiscordWebhook } from "../../types/webhooks/webhook.ts";
import { endpoints } from "../../util/constants.ts"; import { endpoints } from "../../util/constants.ts";
import { requireBotChannelPermissions } from "../../util/permissions.ts"; import { requireBotChannelPermissions } from "../../util/permissions.ts";
+5 -6
View File
@@ -1,7 +1,7 @@
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts"; import { rest } from "../../rest/rest.ts";
import { structures } from "../../structures/mod.ts"; import { structures } from "../../structures/mod.ts";
import { DiscordChannel } from "../../types/mod.ts"; import { DiscordChannel } from "../../types/channels/channel.ts";
import { endpoints } from "../../util/constants.ts"; import { endpoints } from "../../util/constants.ts";
/** Returns a list of guild channel objects. /** Returns a list of guild channel objects.
@@ -9,11 +9,10 @@ import { endpoints } from "../../util/constants.ts";
* ⚠️ **If you need this, you are probably doing something wrong. This is not intended for use. Your channels will be cached in your guild.** * ⚠️ **If you need this, you are probably doing something wrong. This is not intended for use. Your channels will be cached in your guild.**
*/ */
export async function getChannels(guildId: string, addToCache = true) { export async function getChannels(guildId: string, addToCache = true) {
const result = const result = (await rest.runMethod(
(await rest.runMethod( "get",
"get", endpoints.GUILD_CHANNELS(guildId),
endpoints.GUILD_CHANNELS(guildId), ) as DiscordChannel[]);
) as DiscordChannel[]);
return Promise.all(result.map(async (res) => { return Promise.all(result.map(async (res) => {
const channelStruct = await structures.createChannelStruct(res, guildId); const channelStruct = await structures.createChannelStruct(res, guildId);
+5 -6
View File
@@ -1,15 +1,14 @@
import { rest } from "../../rest/rest.ts"; import { rest } from "../../rest/rest.ts";
import { structures } from "../../structures/mod.ts"; import { structures } from "../../structures/mod.ts";
import { DiscordMessage } from "../../types/mod.ts"; import { DiscordMessage } from "../../types/messages/message.ts";
import { endpoints } from "../../util/constants.ts"; import { endpoints } from "../../util/constants.ts";
/** Get pinned messages in this channel. */ /** Get pinned messages in this channel. */
export async function getPins(channelId: string) { export async function getPins(channelId: string) {
const result = const result = (await rest.runMethod(
(await rest.runMethod( "get",
"get", endpoints.CHANNEL_PINS(channelId),
endpoints.CHANNEL_PINS(channelId), )) as DiscordMessage[];
)) as DiscordMessage[];
return Promise.all( return Promise.all(
result.map((res) => structures.createMessageStruct(res)), result.map((res) => structures.createMessageStruct(res)),
+2 -1
View File
@@ -1,6 +1,7 @@
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts"; import { rest } from "../../rest/rest.ts";
import { DiscordChannelTypes, Errors } from "../../types/mod.ts"; import { DiscordChannelTypes } from "../../types/channels/channel_types.ts";
import { Errors } from "../../types/misc/errors.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";
+1 -1
View File
@@ -1,5 +1,5 @@
import { rest } from "../../rest/rest.ts"; import { rest } from "../../rest/rest.ts";
import { ModifyGuildChannelPositions } from "../../types/mod.ts"; import { ModifyGuildChannelPositions } from "../../types/guilds/modify_guild_channel_position.ts";
import { endpoints } from "../../util/constants.ts"; import { endpoints } from "../../util/constants.ts";
/** Modify the positions of channels on the guild. Requires MANAGE_CHANNELS permisison. */ /** Modify the positions of channels on the guild. Requires MANAGE_CHANNELS permisison. */
@@ -1,6 +1,7 @@
import { applicationId } from "../../bot.ts"; import { applicationId } from "../../bot.ts";
import { rest } from "../../rest/rest.ts"; import { rest } from "../../rest/rest.ts";
import { structures } from "../../structures/mod.ts"; import { structures } from "../../structures/mod.ts";
import { Errors } from "../../types/misc/errors.ts";
import { endpoints } from "../../util/constants.ts"; import { endpoints } from "../../util/constants.ts";
/** To edit your response to a slash command. If a messageId is not provided it will default to editing the original response. */ /** To edit your response to a slash command. If a messageId is not provided it will default to editing the original response. */
+6 -7
View File
@@ -5,13 +5,12 @@ import { endpoints } from "../../util/constants.ts";
/** Fetch all of the global commands for your application. */ /** Fetch all of the global commands for your application. */
export async function getSlashCommands(guildId?: string) { export async function getSlashCommands(guildId?: string) {
const result = const result = (await rest.runMethod(
(await rest.runMethod( "get",
"get", guildId
guildId ? endpoints.COMMANDS_GUILD(applicationId, guildId)
? endpoints.COMMANDS_GUILD(applicationId, guildId) : endpoints.COMMANDS(applicationId),
: endpoints.COMMANDS(applicationId), )) as SlashCommand[];
)) as SlashCommand[];
return new Collection(result.map((command) => [command.name, command])); return new Collection(result.map((command) => [command.name, command]));
} }
+5 -6
View File
@@ -4,12 +4,11 @@ import { endpoints } from "../../util/constants.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 createGuild(options: CreateServerOptions) { export async function createGuild(options: CreateServerOptions) {
const guild = const guild = (await rest.runMethod(
(await rest.runMethod( "post",
"post", endpoints.GUILDS,
endpoints.GUILDS, options,
options, )) as CreateGuildPayload;
)) as CreateGuildPayload;
return structures.createGuildStruct(guild, 0); return structures.createGuildStruct(guild, 0);
} }
+2 -1
View File
@@ -18,7 +18,8 @@ export async function getAuditLogs(
? AuditLogs[options.action_type] ? AuditLogs[options.action_type]
: undefined, : undefined,
limit: options.limit && options.limit >= 1 && options.limit <= 100 limit: options.limit && options.limit >= 1 && options.limit <= 100
? options.limit : 50, ? options.limit
: 50,
}, },
); );
+4 -5
View File
@@ -7,11 +7,10 @@ import { requireBotGuildPermissions } from "../../util/permissions.ts";
export async function getBans(guildId: string) { export async function getBans(guildId: string) {
await requireBotGuildPermissions(guildId, ["BAN_MEMBERS"]); await requireBotGuildPermissions(guildId, ["BAN_MEMBERS"]);
const results = const results = (await rest.runMethod(
(await rest.runMethod( "get",
"get", endpoints.GUILD_BANS(guildId),
endpoints.GUILD_BANS(guildId), )) as BannedUser[];
)) as BannedUser[];
return new Collection<string, BannedUser>( return new Collection<string, BannedUser>(
results.map((res) => [res.user.id, res]), results.map((res) => [res.user.id, res]),
+1
View File
@@ -1,4 +1,5 @@
import { rest } from "../../rest/rest.ts"; import { rest } from "../../rest/rest.ts";
import { Errors } from "../../types/misc/errors.ts";
import { endpoints } from "../../util/constants.ts"; import { endpoints } from "../../util/constants.ts";
import { requireBotGuildPermissions } from "../../util/permissions.ts"; import { requireBotGuildPermissions } from "../../util/permissions.ts";
import { camelKeysToSnakeCase } from "../../util/utils.ts"; import { camelKeysToSnakeCase } from "../../util/utils.ts";
+1
View File
@@ -1,5 +1,6 @@
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts"; import { rest } from "../../rest/rest.ts";
import { Errors } from "../../types/misc/errors.ts";
import { endpoints } from "../../util/constants.ts"; import { endpoints } from "../../util/constants.ts";
/** Returns the widget for the guild. */ /** Returns the widget for the guild. */
@@ -1,4 +1,5 @@
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { Errors } from "../../types/misc/errors.ts";
import { endpoints } from "../../util/constants.ts"; import { endpoints } from "../../util/constants.ts";
/** Returns the widget image URL for the guild. */ /** Returns the widget image URL for the guild. */
+1
View File
@@ -1,5 +1,6 @@
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts"; import { rest } from "../../rest/rest.ts";
import { Errors } from "../../types/misc/errors.ts";
import { endpoints } from "../../util/constants.ts"; import { endpoints } from "../../util/constants.ts";
import { import {
botHasChannelPermissions, botHasChannelPermissions,
+9 -11
View File
@@ -1,17 +1,15 @@
import { Member } from "../../structures/mod.ts"; import { endpoints } from "../../util/constants.ts";
import { rawAvatarURL } from "./raw_avatar_url.ts"; import { formatImageURL } from "../../util/utils.ts";
/** The users custom avatar or the default avatar */ /** The users custom avatar or the default avatar if you don't have a member object. */
export function avatarURL( export function avatarURL(
member: Member, userId: string,
discriminator: string,
avatar?: string | null,
size: ImageSize = 128, size: ImageSize = 128,
format?: ImageFormats, format?: ImageFormats,
) { ) {
return rawAvatarURL( return avatar
member.id, ? formatImageURL(endpoints.USER_AVATAR(userId, avatar), size, format)
member.discriminator, : endpoints.USER_DEFAULT_AVATAR(Number(discriminator) % 5);
member.avatar,
size,
format,
);
} }
+1
View File
@@ -1,4 +1,5 @@
import { rest } from "../../rest/rest.ts"; import { rest } from "../../rest/rest.ts";
import { Errors } from "../../types/misc/errors.ts";
import { endpoints } from "../../util/constants.ts"; import { endpoints } from "../../util/constants.ts";
import { urlToBase64 } from "../../util/utils.ts"; import { urlToBase64 } from "../../util/utils.ts";
+1
View File
@@ -1,6 +1,7 @@
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts"; import { rest } from "../../rest/rest.ts";
import { structures } from "../../structures/mod.ts"; import { structures } from "../../structures/mod.ts";
import { Errors } from "../../types/misc/errors.ts";
import { endpoints } from "../../util/constants.ts"; import { endpoints } from "../../util/constants.ts";
import { import {
requireBotChannelPermissions, requireBotChannelPermissions,
+5 -1
View File
@@ -1,7 +1,11 @@
import { identifyPayload } from "../../bot.ts"; import { identifyPayload } from "../../bot.ts";
import { Member } from "../../structures/mod.ts"; import { Member } from "../../structures/mod.ts";
import { DiscordGatewayIntents } from "../../types/gateway/gateway_intents.ts";
import { Errors } from "../../types/misc/errors.ts";
import { Collection } from "../../util/collection.ts"; import { Collection } from "../../util/collection.ts";
import { requestAllMembers } from "../../ws/shard_manager.ts"; import { requestAllMembers } from "../../ws/shard_manager.ts";
import { DiscordGatewayIntents } from "../../types/gateway/gateway_intents.ts";
import { Errors } from "../../types/misc/errors.ts";
/** /**
* ⚠️ BEGINNER DEVS!! YOU SHOULD ALMOST NEVER NEED THIS AND YOU CAN GET FROM cache.members.get() * ⚠️ BEGINNER DEVS!! YOU SHOULD ALMOST NEVER NEED THIS AND YOU CAN GET FROM cache.members.get()
@@ -19,7 +23,7 @@ export function fetchMembers(
// 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 && DiscordGatewayIntents.GUILD_MEMBERS)
) { ) {
throw new Error(Errors.MISSING_INTENT_GUILD_MEMBERS); throw new Error(Errors.MISSING_INTENT_GUILD_MEMBERS);
} }
+5 -4
View File
@@ -1,5 +1,4 @@
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { RequestManager } from "../../rest/request_manager.ts";
import { rest } from "../../rest/rest.ts"; import { rest } from "../../rest/rest.ts";
import { structures } from "../../structures/mod.ts"; import { structures } from "../../structures/mod.ts";
import { endpoints } from "../../util/constants.ts"; import { endpoints } from "../../util/constants.ts";
@@ -16,9 +15,11 @@ export async function getMember(
const guild = await cacheHandlers.get("guilds", guildId); const guild = await cacheHandlers.get("guilds", guildId);
if (!guild && !options?.force) return; if (!guild && !options?.force) return;
const data = (await rest.runMethod("get", const data =
endpoints.GUILD_MEMBER(guildId, id), (await rest.runMethod(
)) as MemberCreatePayload; "get",
endpoints.GUILD_MEMBER(guildId, id),
)) as MemberCreatePayload;
const memberStruct = await structures.createMemberStruct(data, guildId); const memberStruct = await structures.createMemberStruct(data, guildId);
await cacheHandlers.set("members", memberStruct.id, memberStruct); await cacheHandlers.set("members", memberStruct.id, memberStruct);
+10 -14
View File
@@ -2,6 +2,9 @@ import { identifyPayload } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts"; import { rest } from "../../rest/rest.ts";
import { Member, structures } from "../../structures/mod.ts"; import { Member, structures } from "../../structures/mod.ts";
import { DiscordGatewayIntents } from "../../types/gateway/gateway_intents.ts";
import { DiscordGuildMember } from "../../types/guilds/guild_member.ts";
import { Errors } from "../../types/misc/errors.ts";
import { Collection } from "../../util/collection.ts"; import { Collection } from "../../util/collection.ts";
import { endpoints } from "../../util/constants.ts"; import { endpoints } from "../../util/constants.ts";
@@ -14,7 +17,7 @@ import { endpoints } from "../../util/constants.ts";
* GW(fetchMembers): 120/m(PER shard) rate limit. Meaning if you have 8 shards your limit is 960/m. * GW(fetchMembers): 120/m(PER shard) rate limit. Meaning if you have 8 shards your limit is 960/m.
*/ */
export async function getMembers(guildId: string, options?: GetMemberOptions) { export async function getMembers(guildId: string, options?: GetMemberOptions) {
if (!(identifyPayload.intents && Intents.GUILD_MEMBERS)) { if (!(identifyPayload.intents && DiscordGatewayIntents.GUILD_MEMBERS)) {
throw new Error(Errors.MISSING_INTENT_GUILD_MEMBERS); throw new Error(Errors.MISSING_INTENT_GUILD_MEMBERS);
} }
@@ -39,19 +42,12 @@ export async function getMembers(guildId: string, options?: GetMemberOptions) {
); );
} }
const result = const result = (await rest.runMethod(
(await rest.runMethod( "get",
"get", `${endpoints.GUILD_MEMBERS(guildId)}?limit=${
`${endpoints.GUILD_MEMBERS(guildId)}?limit=${ membersLeft > 1000 ? 1000 : membersLeft
membersLeft > 1000 }${options?.after ? `&after=${options.after}` : ""}`,
? 1000 )) as DiscordGuildMember[];
: membersLeft
}${
options?.after
? `&after=${options.after}`
: ""
}`,
)) as MemberCreatePayload[];
const memberStructures = await Promise.all( const memberStructures = await Promise.all(
result.map(async (member) => { result.map(async (member) => {
+1
View File
@@ -1,5 +1,6 @@
import { botId } from "../../bot.ts"; import { botId } from "../../bot.ts";
import { rest } from "../../rest/rest.ts"; import { rest } from "../../rest/rest.ts";
import { Errors } from "../../types/misc/errors.ts";
import { endpoints } from "../../util/constants.ts"; import { endpoints } from "../../util/constants.ts";
import { import {
highestRole, highestRole,
+1
View File
@@ -1,4 +1,5 @@
import { rest } from "../../rest/rest.ts"; import { rest } from "../../rest/rest.ts";
import { Errors } from "../../types/misc/errors.ts";
import { endpoints } from "../../util/constants.ts"; import { endpoints } from "../../util/constants.ts";
import { requireBotGuildPermissions } from "../../util/permissions.ts"; import { requireBotGuildPermissions } from "../../util/permissions.ts";
import { camelKeysToSnakeCase } from "../../util/utils.ts"; import { camelKeysToSnakeCase } from "../../util/utils.ts";
-15
View File
@@ -1,15 +0,0 @@
import { endpoints } from "../../util/constants.ts";
import { formatImageURL } from "../../util/utils.ts";
/** The users custom avatar or the default avatar if you don't have a member object. */
export function rawAvatarURL(
userId: string,
discriminator: string,
avatar?: string | null,
size: ImageSize = 128,
format?: ImageFormats,
) {
return avatar
? formatImageURL(endpoints.USER_AVATAR(userId, avatar), size, format)
: endpoints.USER_DEFAULT_AVATAR(Number(discriminator) % 5);
}
+1
View File
@@ -1,4 +1,5 @@
import { rest } from "../../rest/rest.ts"; import { rest } from "../../rest/rest.ts";
import { Errors } from "../../types/misc/errors.ts";
import { endpoints } from "../../util/constants.ts"; import { endpoints } from "../../util/constants.ts";
import { requireBotChannelPermissions } from "../../util/permissions.ts"; import { requireBotChannelPermissions } from "../../util/permissions.ts";
+3 -1
View File
@@ -1,6 +1,8 @@
import { botId } from "../../bot.ts"; import { botId } from "../../bot.ts";
import { rest } from "../../rest/rest.ts"; import { rest } from "../../rest/rest.ts";
import { Message, structures } from "../../structures/mod.ts"; import { Message, structures } from "../../structures/mod.ts";
import { Errors } from "../../types/misc/errors.ts";
import { PermissionStrings } from "../../types/permissions/permission_strings.ts";
import { endpoints } from "../../util/constants.ts"; import { endpoints } from "../../util/constants.ts";
import { requireBotChannelPermissions } from "../../util/permissions.ts"; import { requireBotChannelPermissions } from "../../util/permissions.ts";
@@ -15,7 +17,7 @@ export async function editMessage(
if (typeof content === "string") content = { content }; if (typeof content === "string") content = { content };
const requiredPerms: Permission[] = ["SEND_MESSAGES"]; const requiredPerms: PermissionStrings[] = ["SEND_MESSAGES"];
if (content.tts) requiredPerms.push("SEND_TTS_MESSAGES"); if (content.tts) requiredPerms.push("SEND_TTS_MESSAGES");
+4 -5
View File
@@ -13,11 +13,10 @@ export async function getMessage(channelId: string, id: string) {
]); ]);
} }
const result = const result = (await rest.runMethod(
(await rest.runMethod( "get",
"get", endpoints.CHANNEL_MESSAGE(channelId, id),
endpoints.CHANNEL_MESSAGE(channelId, id), )) as MessageCreateOptions;
)) as MessageCreateOptions;
return structures.createMessageStruct(result); return structures.createMessageStruct(result);
} }
+5 -6
View File
@@ -19,12 +19,11 @@ export async function getMessages(
if (options?.limit && options.limit > 100) return; if (options?.limit && options.limit > 100) return;
const result = const result = (await rest.runMethod(
(await rest.runMethod( "get",
"get", endpoints.CHANNEL_MESSAGES(channelId),
endpoints.CHANNEL_MESSAGES(channelId), options,
options, )) as MessageCreateOptions[];
)) as MessageCreateOptions[];
return Promise.all( return Promise.all(
result.map((res) => structures.createMessageStruct(res)), result.map((res) => structures.createMessageStruct(res)),
+5 -6
View File
@@ -9,12 +9,11 @@ export async function getReactions(
reaction: string, reaction: string,
options?: DiscordGetReactionsParams, options?: DiscordGetReactionsParams,
) { ) {
const users = const users = (await rest.runMethod(
(await rest.runMethod( "get",
"get", endpoints.CHANNEL_MESSAGE_REACTION(channelId, messageId, reaction),
endpoints.CHANNEL_MESSAGE_REACTION(channelId, messageId, reaction), options,
options, )) as UserPayload[];
)) as UserPayload[];
return new Collection(users.map((user) => [user.id, user])); return new Collection(users.map((user) => [user.id, user]));
} }
+4 -5
View File
@@ -4,11 +4,10 @@ import { endpoints } from "../../util/constants.ts";
/** Crosspost a message in a News Channel to following channels. */ /** Crosspost a message in a News Channel to following channels. */
export async function publishMessage(channelId: string, messageId: string) { export async function publishMessage(channelId: string, messageId: string) {
const data = const data = (await rest.runMethod(
(await rest.runMethod( "post",
"post", endpoints.CHANNEL_MESSAGE_CROSSPOST(channelId, messageId),
endpoints.CHANNEL_MESSAGE_CROSSPOST(channelId, messageId), )) as MessageCreateOptions;
)) as MessageCreateOptions;
return structures.createMessageStruct(data); return structures.createMessageStruct(data);
} }
+2 -1
View File
@@ -2,7 +2,8 @@ import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts"; import { rest } from "../../rest/rest.ts";
import { structures } from "../../structures/mod.ts"; import { structures } from "../../structures/mod.ts";
import { DiscordChannelTypes } from "../../types/channels/channel_types.ts"; import { DiscordChannelTypes } from "../../types/channels/channel_types.ts";
import { PermissionStrings } from "../../types/mod.ts"; import { Errors } from "../../types/misc/errors.ts";
import { PermissionStrings } from "../../types/permissions/permission_strings.ts";
import { endpoints } from "../../util/constants.ts"; import { endpoints } from "../../util/constants.ts";
import { requireBotChannelPermissions } from "../../util/permissions.ts"; import { requireBotChannelPermissions } from "../../util/permissions.ts";
-1
View File
@@ -70,7 +70,6 @@ import { getMembersByQuery } from "./members/get_members_by_query.ts";
import { kick, kickMember } from "./members/kick_member.ts"; import { kick, kickMember } from "./members/kick_member.ts";
import { moveMember } from "./members/move_member.ts"; import { moveMember } from "./members/move_member.ts";
import { pruneMembers } from "./members/prune_members.ts"; import { pruneMembers } from "./members/prune_members.ts";
import { rawAvatarURL } from "./members/raw_avatar_url.ts";
import { sendDirectMessage } from "./members/send_direct_message.ts"; import { sendDirectMessage } from "./members/send_direct_message.ts";
import { unban, unbanMember } from "./members/unban_member.ts"; import { unban, unbanMember } from "./members/unban_member.ts";
import { addReaction } from "./messages/add_reaction.ts"; import { addReaction } from "./messages/add_reaction.ts";
+1
View File
@@ -1,5 +1,6 @@
import { botId } from "../../bot.ts"; import { botId } from "../../bot.ts";
import { rest } from "../../rest/rest.ts"; import { rest } from "../../rest/rest.ts";
import { Errors } from "../../types/misc/errors.ts";
import { endpoints } from "../../util/constants.ts"; import { endpoints } from "../../util/constants.ts";
import { import {
isHigherPosition, isHigherPosition,
+1
View File
@@ -1,5 +1,6 @@
import { botId } from "../../bot.ts"; import { botId } from "../../bot.ts";
import { rest } from "../../rest/rest.ts"; import { rest } from "../../rest/rest.ts";
import { Errors } from "../../types/misc/errors.ts";
import { endpoints } from "../../util/constants.ts"; import { endpoints } from "../../util/constants.ts";
import { import {
isHigherPosition, isHigherPosition,
@@ -23,12 +23,11 @@ export async function createGuildTemplate(
throw new Error("The description can only be in between 0-120 characters."); throw new Error("The description can only be in between 0-120 characters.");
} }
const template = const template = (await rest.runMethod(
(await rest.runMethod( "post",
"post", endpoints.GUILD_TEMPLATES(guildId),
endpoints.GUILD_TEMPLATES(guildId), data,
data, )) as GuildTemplate;
)) as GuildTemplate;
return structures.createTemplateStruct(template); return structures.createTemplateStruct(template);
} }
@@ -13,11 +13,10 @@ export async function deleteGuildTemplate(
) { ) {
await requireBotGuildPermissions(guildId, ["MANAGE_GUILD"]); await requireBotGuildPermissions(guildId, ["MANAGE_GUILD"]);
const deletedTemplate = const deletedTemplate = (await rest.runMethod(
(await rest.runMethod( "delete",
"delete", `${endpoints.GUILD_TEMPLATES(guildId)}/${templateCode}`,
`${endpoints.GUILD_TEMPLATES(guildId)}/${templateCode}`, )) as GuildTemplate;
)) as GuildTemplate;
return structures.createTemplateStruct(deletedTemplate); return structures.createTemplateStruct(deletedTemplate);
} }
+5 -6
View File
@@ -22,12 +22,11 @@ export async function editGuildTemplate(
throw new Error("The description can only be in between 0-120 characters."); throw new Error("The description can only be in between 0-120 characters.");
} }
const template = const template = (await rest.runMethod(
(await rest.runMethod( "patch",
"patch", `${endpoints.GUILD_TEMPLATES(guildId)}/${templateCode}`,
`${endpoints.GUILD_TEMPLATES(guildId)}/${templateCode}`, data,
data, )) as GuildTemplate;
)) as GuildTemplate;
return structures.createTemplateStruct(template); return structures.createTemplateStruct(template);
} }
+4 -5
View File
@@ -10,11 +10,10 @@ import { requireBotGuildPermissions } from "../../util/permissions.ts";
export async function getGuildTemplates(guildId: string) { export async function getGuildTemplates(guildId: string) {
await requireBotGuildPermissions(guildId, ["MANAGE_GUILD"]); await requireBotGuildPermissions(guildId, ["MANAGE_GUILD"]);
const templates = const templates = (await rest.runMethod(
(await rest.runMethod( "get",
"get", endpoints.GUILD_TEMPLATES(guildId),
endpoints.GUILD_TEMPLATES(guildId), )) as GuildTemplate[];
)) as GuildTemplate[];
return templates.map((template) => structures.createTemplateStruct(template)); return templates.map((template) => structures.createTemplateStruct(template));
} }
+4 -5
View File
@@ -4,11 +4,10 @@ import { endpoints } from "../../util/constants.ts";
/** Returns the guild template if it exists */ /** Returns the guild template if it exists */
export async function getTemplate(templateCode: string) { export async function getTemplate(templateCode: string) {
const result = const result = (await rest.runMethod(
(await rest.runMethod( "get",
"get", endpoints.GUILD_TEMPLATE(templateCode),
endpoints.GUILD_TEMPLATE(templateCode), ) as GuildTemplate);
) as GuildTemplate);
const template = await structures.createTemplateStruct(result); const template = await structures.createTemplateStruct(result);
return template; return template;
+4 -5
View File
@@ -10,11 +10,10 @@ import { requireBotGuildPermissions } from "../../util/permissions.ts";
export async function syncGuildTemplate(guildId: string, templateCode: string) { export async function syncGuildTemplate(guildId: string, templateCode: string) {
await requireBotGuildPermissions(guildId, ["MANAGE_GUILD"]); await requireBotGuildPermissions(guildId, ["MANAGE_GUILD"]);
const template = const template = (await rest.runMethod(
(await rest.runMethod( "put",
"put", `${endpoints.GUILD_TEMPLATES(guildId)}/${templateCode}`,
`${endpoints.GUILD_TEMPLATES(guildId)}/${templateCode}`, )) as GuildTemplate;
)) as GuildTemplate;
return structures.createTemplateStruct(template); return structures.createTemplateStruct(template);
} }
+1
View File
@@ -1,4 +1,5 @@
import { rest } from "../../rest/rest.ts"; import { rest } from "../../rest/rest.ts";
import { Errors } from "../../types/misc/errors.ts";
import { endpoints } from "../../util/constants.ts"; import { endpoints } from "../../util/constants.ts";
import { requireBotChannelPermissions } from "../../util/permissions.ts"; import { requireBotChannelPermissions } from "../../util/permissions.ts";
import { urlToBase64 } from "../../util/utils.ts"; import { urlToBase64 } from "../../util/utils.ts";
@@ -1,5 +1,6 @@
import { rest } from "../../rest/rest.ts"; import { rest } from "../../rest/rest.ts";
import { structures } from "../../structures/mod.ts"; import { structures } from "../../structures/mod.ts";
import { Errors } from "../../types/misc/errors.ts";
import { endpoints } from "../../util/constants.ts"; import { endpoints } from "../../util/constants.ts";
export async function editWebhookMessage( export async function editWebhookMessage(
+1
View File
@@ -1,5 +1,6 @@
import { rest } from "../../rest/rest.ts"; import { rest } from "../../rest/rest.ts";
import { structures } from "../../structures/mod.ts"; import { structures } from "../../structures/mod.ts";
import { Errors } from "../../types/misc/errors.ts";
import { endpoints } from "../../util/constants.ts"; import { endpoints } from "../../util/constants.ts";
/** Execute a webhook with webhook Id and webhook token */ /** Execute a webhook with webhook Id and webhook token */
+5 -1
View File
@@ -90,7 +90,11 @@ async function handleApplicationCommand(
} }
/** Internal function to verify security. Discord will send bad and good data and this function is important to verify it. If it is not verified properly, Discord will kill your bot. */ /** Internal function to verify security. Discord will send bad and good data and this function is important to verify it. If it is not verified properly, Discord will kill your bot. */
export function verifySecurity(buffer: Uint8Array, signature: string, time: string) { export function verifySecurity(
buffer: Uint8Array,
signature: string,
time: string,
) {
const sig = new Uint8Array(64); const sig = new Uint8Array(64);
const timestamp = new TextEncoder().encode(time); const timestamp = new TextEncoder().encode(time);
+1
View File
@@ -22,6 +22,7 @@ export const rest = {
console.error(error); console.error(error);
}, },
// PLACEHOLDERS TO ALLOW USERS TO CUSTOMIZE // PLACEHOLDERS TO ALLOW USERS TO CUSTOMIZE
debug: function (_type, error) {},
fetching() {}, fetching() {},
fetched() {}, fetched() {},
fetchSuccess() {}, fetchSuccess() {},
+63 -42
View File
@@ -1,18 +1,23 @@
import { Errors } from "../types/misc/errors.ts";
import { IMAGE_BASE_URL } from "../util/constants.ts";
import { API_VERSION } from "../util/constants.ts";
import { BASE_URL } from "../util/constants.ts";
import { rest } from "./rest.ts"; import { rest } from "./rest.ts";
export function runMethod( export function runMethod(
method: RequestMethods, method: "get" | "post" | "put" | "delete" | "patch",
url: string, url: string,
body?: unknown, body?: unknown,
retryCount = 0, retryCount = 0,
bucketId?: string | null, bucketId?: string | null,
) { ) {
rest.eventHandlers.debug?.( rest.eventHandlers.debug?.("requestCreate", {
{ method,
type: "requestCreate", url,
data: { method, url, body, retryCount, bucketId }, body,
}, retryCount,
); bucketId,
});
const errorStack = new Error("Location:"); const errorStack = new Error("Location:");
Error.captureStackTrace(errorStack); Error.captureStackTrace(errorStack);
@@ -45,38 +50,49 @@ export function runMethod(
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
const callback = async () => { const callback = async () => {
try { try {
const rateLimitResetIn = await rest.checkRatelimits(url); const rateLimitResetIn = rest.checkRateLimits(url);
if (rateLimitResetIn) { if (rateLimitResetIn) {
return { rateLimited: rateLimitResetIn, beforeFetch: true, bucketId }; return { rateLimited: rateLimitResetIn, beforeFetch: true, bucketId };
} }
const query = method === "get" && body const query = method === "get" && body
? // deno-lint-ignore no-explicit-any ? // deno-lint-ignore no-explicit-any
Object.entries(body as any).map(([key, value]) => Object.entries(body as any)
// deno-lint-ignore no-explicit-any .map(
`${encodeURIComponent(key)}=${encodeURIComponent(value as any)}` ([key, value]) =>
) `${encodeURIComponent(key)}=${
encodeURIComponent(
value as string | number | boolean,
)
}`,
)
.join("&") .join("&")
: ""; : "";
const urlToUse = method === "get" && query ? `${url}?${query}` : url; const urlToUse = method === "get" && query ? `${url}?${query}` : url;
rest.eventHandlers.debug?.( rest.eventHandlers.debug?.("requestFetch", {
{ method,
type: "requestFetch", url,
data: { method, url, body, retryCount, bucketId }, body,
}, retryCount,
); bucketId,
});
const response = await fetch( const response = await fetch(
urlToUse, urlToUse,
rest.createRequestBody(body, method), rest.createRequestBody(body, method),
); );
rest.eventHandlers.debug?.( rest.eventHandlers.debug?.("requestFetched", {
{ method,
type: "requestFetched", url,
data: { method, url, body, retryCount, bucketId, response }, body,
}, retryCount,
bucketId,
response,
});
const bucketIdFromHeaders = rest.processRequestHeaders(
url,
response.headers,
); );
const bucketIdFromHeaders = rest.processHeaders(url, response.headers);
await rest.handleStatusCode(response, errorStack); await rest.handleStatusCode(response, errorStack);
// Sometimes Discord returns an empty 204 response that can't be made to JSON. // Sometimes Discord returns an empty 204 response that can't be made to JSON.
@@ -88,12 +104,14 @@ export function runMethod(
json.message === "You are being rate limited." json.message === "You are being rate limited."
) { ) {
if (retryCount > 10) { if (retryCount > 10) {
rest.eventHandlers.debug?.( rest.eventHandlers.error?.("globalRateLimit", {
{ method,
type: "error", url,
data: { method, url, body, retryCount, bucketId, errorStack }, body,
}, retryCount,
); bucketId,
errorStack,
});
throw new Error(Errors.RATE_LIMIT_RETRY_MAXED); throw new Error(Errors.RATE_LIMIT_RETRY_MAXED);
} }
@@ -104,20 +122,23 @@ export function runMethod(
}; };
} }
rest.eventHandlers.debug?.( rest.eventHandlers.debug?.("requestSuccess", {
{ method,
type: "requestSuccess", url,
data: { method, url, body, retryCount, bucketId }, body,
}, retryCount,
); bucketId,
});
return resolve(json); return resolve(json);
} catch (error) { } catch (error) {
rest.eventHandlers.debug?.( rest.eventHandlers.error?.("unknown", {
{ method,
type: "error", url,
data: { method, url, body, retryCount, bucketId, errorStack }, body,
}, retryCount,
); bucketId,
errorStack,
});
return reject(error); return reject(error);
} }
}; };
+30 -14
View File
@@ -91,7 +91,7 @@ const baseGuild: Partial<Guild> = {
export async function createGuildStruct( export async function createGuildStruct(
data: CreateGuildPayload, data: CreateGuildPayload,
shardId: number, shardId: number
) { ) {
const { const {
disovery_splash: discoverySplash, disovery_splash: discoverySplash,
@@ -128,16 +128,18 @@ export async function createGuildStruct(
} = data; } = data;
const roles = await Promise.all( const roles = await Promise.all(
data.roles.map((role) => structures.createRoleStruct(role)), data.roles.map((role) => structures.createRoleStruct(role))
); );
await Promise.all(channels.map(async (channel) => { await Promise.all(
const channelStruct = await structures.createChannelStruct( channels.map(async (channel) => {
channel, const channelStruct = await structures.createChannelStruct(
rest.id, channel,
); rest.id
return cacheHandlers.set("channels", channelStruct.id, channelStruct); );
})); return cacheHandlers.set("channels", channelStruct.id, channelStruct);
})
);
const restProps: Record<string, ReturnType<typeof createNewProp>> = {}; const restProps: Record<string, ReturnType<typeof createNewProp>> = {};
for (const key of Object.keys(rest)) { for (const key of Object.keys(rest)) {
@@ -173,11 +175,11 @@ export async function createGuildStruct(
roles: createNewProp(new Collection(roles.map((r: Role) => [r.id, r]))), roles: createNewProp(new Collection(roles.map((r: Role) => [r.id, r]))),
joinedAt: createNewProp(Date.parse(joinedAt)), joinedAt: createNewProp(Date.parse(joinedAt)),
presences: createNewProp( presences: createNewProp(
new Collection(presences.map((p: Presence) => [p.user.id, p])), new Collection(presences.map((p: Presence) => [p.user.id, p]))
), ),
memberCount: createNewProp(memberCount), memberCount: createNewProp(memberCount),
emojis: createNewProp( emojis: createNewProp(
new Collection(emojis.map((emoji) => [emoji.id ?? emoji.name, emoji])), new Collection(emojis.map((emoji) => [emoji.id ?? emoji.name, emoji]))
), ),
voiceStates: createNewProp( voiceStates: createNewProp(
new Collection( new Collection(
@@ -193,12 +195,26 @@ export async function createGuildStruct(
selfMute: vs.self_mute, selfMute: vs.self_mute,
selfStream: vs.self_stream, selfStream: vs.self_stream,
}, },
]), ])
), )
), ),
}); });
initialMemberLoadQueue.set(guild.id, members); // ONLY ADD TO QUEUE WHEN BOT IS NOT FULLY ONLINE
if (!cache.isReady) initialMemberLoadQueue.set(guild.id, members);
// BOT IS ONLINE, JUST DIRECTLY ADD MEMBERS
else {
await Promise.allSettled(
members.map(async (member) => {
const memberStruct = await structures.createMemberStruct(
member,
guild.id
);
return cacheHandlers.set("members", memberStruct.id, memberStruct);
})
);
}
return guild as Guild; return guild as Guild;
} }
+2 -2
View File
@@ -1,8 +1,8 @@
import { cache, cacheHandlers } from "../cache.ts"; import { cache, cacheHandlers } from "../cache.ts";
import { avatarURL } from "../helpers/members/avatar_url.ts";
import { banMember } from "../helpers/members/ban_member.ts"; import { banMember } from "../helpers/members/ban_member.ts";
import { editMember } from "../helpers/members/edit_member.ts"; import { editMember } from "../helpers/members/edit_member.ts";
import { kickMember } from "../helpers/members/kick_member.ts"; import { kickMember } from "../helpers/members/kick_member.ts";
import { rawAvatarURL } from "../helpers/members/raw_avatar_url.ts";
import { sendDirectMessage } from "../helpers/members/send_direct_message.ts"; import { sendDirectMessage } from "../helpers/members/send_direct_message.ts";
import { addRole } from "../helpers/roles/add_role.ts"; import { addRole } from "../helpers/roles/add_role.ts";
import { removeRole } from "../helpers/roles/remove_role.ts"; import { removeRole } from "../helpers/roles/remove_role.ts";
@@ -11,7 +11,7 @@ import { createNewProp } from "../util/utils.ts";
const baseMember: Partial<Member> = { const baseMember: Partial<Member> = {
get avatarURL() { get avatarURL() {
return rawAvatarURL(this.id!, this.discriminator!, this.avatar!); return avatarURL(this.id!, this.discriminator!, this.avatar!);
}, },
get mention() { get mention() {
return `<@!${this.id!}>`; return `<@!${this.id!}>`;
+33 -25
View File
@@ -9,6 +9,7 @@ import { removeAllReactions } from "../helpers/messages/remove_all_reactions.ts"
import { removeReaction } from "../helpers/messages/remove_reaction.ts"; import { removeReaction } from "../helpers/messages/remove_reaction.ts";
import { removeReactionEmoji } from "../helpers/messages/remove_reaction_emoji.ts"; import { removeReactionEmoji } from "../helpers/messages/remove_reaction_emoji.ts";
import { sendMessage } from "../helpers/messages/send_message.ts"; import { sendMessage } from "../helpers/messages/send_message.ts";
import { CHANNEL_MENTION_REGEX } from "../util/constants";
import { createNewProp } from "../util/utils.ts"; import { createNewProp } from "../util/utils.ts";
const baseMessage: Partial<Message> = { const baseMessage: Partial<Message> = {
@@ -29,8 +30,9 @@ const baseMessage: Partial<Message> = {
return this.member?.guilds.get(this.guildId); return this.member?.guilds.get(this.guildId);
}, },
get link() { get link() {
return `https://discord.com/channels/${this.guildId || return `https://discord.com/channels/${this.guildId || "@me"}/${
"@me"}/${this.channelId}/${this.id}`; this.channelId
}/${this.id}`;
}, },
get mentionedRoles() { get mentionedRoles() {
return this.mentionRoleIds?.map((id) => this.guild?.roles.get(id)) || []; return this.mentionRoleIds?.map((id) => this.guild?.roles.get(id)) || [];
@@ -44,12 +46,7 @@ const baseMessage: Partial<Message> = {
// METHODS // METHODS
delete(reason, delayMilliseconds) { delete(reason, delayMilliseconds) {
return deleteMessage( return deleteMessage(this.channelId!, this.id!, reason, delayMilliseconds);
this.channelId!,
this.id!,
reason,
delayMilliseconds,
);
}, },
edit(content) { edit(content) {
return editMessage(this as Message, content); return editMessage(this as Message, content);
@@ -64,19 +61,20 @@ const baseMessage: Partial<Message> = {
return addReactions(this.channelId!, this.id!, reactions, ordered); return addReactions(this.channelId!, this.id!, reactions, ordered);
}, },
reply(content) { reply(content) {
const contentWithMention = typeof content === "string" const contentWithMention =
? { typeof content === "string"
content, ? {
mentions: { repliedUser: true }, content,
replyMessageId: this.id, mentions: { repliedUser: true },
failReplyIfNotExists: false, replyMessageId: this.id,
} failReplyIfNotExists: false,
: { }
...content, : {
mentions: { ...(content.mentions || {}), repliedUser: true }, ...content,
replyMessageId: this.id, mentions: { ...(content.mentions || {}), repliedUser: true },
failReplyIfNotExists: content.failReplyIfNotExists === true, replyMessageId: this.id,
}; failReplyIfNotExists: content.failReplyIfNotExists === true,
};
if (this.guildId) return sendMessage(this.channelId!, contentWithMention); if (this.guildId) return sendMessage(this.channelId!, contentWithMention);
return sendDirectMessage(this.author!.id, contentWithMention); return sendDirectMessage(this.author!.id, contentWithMention);
@@ -134,8 +132,8 @@ export async function createMessageStruct(data: MessageCreateOptions) {
} }
// Discord doesnt give guild id for getMessage() so this will fill it in // Discord doesnt give guild id for getMessage() so this will fill it in
const guildIdFinal = guildId || const guildIdFinal =
(await cacheHandlers.get("channels", channelId))?.guildId || ""; guildId || (await cacheHandlers.get("channels", channelId))?.guildId || "";
const message = Object.create(baseMessage, { const message = Object.create(baseMessage, {
...restProps, ...restProps,
@@ -146,12 +144,22 @@ export async function createMessageStruct(data: MessageCreateOptions) {
mentions: createNewProp(data.mentions.map((m) => m.id)), mentions: createNewProp(data.mentions.map((m) => m.id)),
mentionsEveryone: createNewProp(mentionsEveryone), mentionsEveryone: createNewProp(mentionsEveryone),
mentionRoleIds: createNewProp(mentionRoleIds), mentionRoleIds: createNewProp(mentionRoleIds),
mentionChannelIds: createNewProp(mentionChannelIds.map((m) => m.id)), mentionChannelIds: createNewProp(
[
// Keep any ids that discord sends
...mentionChannelIds,
// Add any other ids that can be validated in a channel mention format
...(rest.content.match(CHANNEL_MENTION_REGEX) || []).map((text) =>
// converts the <#123> into 123
text.substring(2, text.length - 1)
),
].map((m) => m.id)
),
webhookId: createNewProp(webhookId), webhookId: createNewProp(webhookId),
messageReference: createNewProp(messageReference), messageReference: createNewProp(messageReference),
timestamp: createNewProp(Date.parse(data.timestamp)), timestamp: createNewProp(Date.parse(data.timestamp)),
editedTimestamp: createNewProp( editedTimestamp: createNewProp(
editedTimestamp ? Date.parse(editedTimestamp) : undefined, editedTimestamp ? Date.parse(editedTimestamp) : undefined
), ),
}); });
+1 -1
View File
@@ -16,7 +16,7 @@ export interface Identify {
/** Presence structure for initial presence information */ /** Presence structure for initial presence information */
presence?: UpdateStatus; presence?: UpdateStatus;
/** Enables dispatching of guild subscription events (presence and typing events) */ /** Enables dispatching of guild subscription events (presence and typing events) */
guild_subscriptions?: boolean; guildSubscriptions?: boolean;
/** The Gateway Intents you wish to receive */ /** The Gateway Intents you wish to receive */
intents: number; intents: number;
} }
-1
View File
@@ -1,4 +1,3 @@
export interface ListGuildMembers { export interface ListGuildMembers {
/** Max number of members to return (1-1000). Default: 1 */ /** Max number of members to return (1-1000). Default: 1 */
limit?: number; limit?: number;
+1
View File
@@ -1,5 +1,6 @@
import { SnakeCaseProps } from "../util.ts"; import { SnakeCaseProps } from "../util.ts";
import { DiscordVisibilityTypes } from "./visibility_types.ts"; import { DiscordVisibilityTypes } from "./visibility_types.ts";
import { Integration } from "../guilds/integration.ts"
export interface Connection { export interface Connection {
/** id of the connection account */ /** id of the connection account */
+1
View File
@@ -177,3 +177,4 @@ export const endpoints = {
}; };
export const SLASH_COMMANDS_NAME_REGEX = /^[\w-]{1,32}$/; export const SLASH_COMMANDS_NAME_REGEX = /^[\w-]{1,32}$/;
export const CHANNEL_MENTION_REGEX = /<#[0-9]+>/g;

Some files were not shown because too many files have changed in this diff Show More