Merge pull request #1120 from TriForMine/fp-attempt-9001

Functional Rewrite: Rewriting helpers
This commit is contained in:
Skillz4Killz
2021-10-23 11:50:26 -04:00
committed by GitHub
170 changed files with 1546 additions and 1325 deletions

View File

@@ -11,46 +11,41 @@ import {
requireChannelPermissions,
highestRole,
higherRolePosition,
requireBotChannelPermissions,
requireBotGuildPermissions,
} from "./util/permissions.ts";
import { getGatewayBot } from "./helpers/misc/get_gateway_bot.ts";
import { checkRateLimits } from "./rest/check_rate_limits.ts";
import { cleanupQueues } from "./rest/cleanup_queues.ts";
import { createRequestBody } from "./rest/create_request_body.ts";
import { processRateLimitedPaths } from "./rest/process_rate_limited_paths.ts";
import { processRequest } from "./rest/process_request.ts";
import { processRequestHeaders } from "./rest/process_request_headers.ts";
import {
checkRateLimits,
processQueue,
cleanupQueues,
createRequestBody,
processRateLimitedPaths,
processRequest,
processRequestHeaders,
runMethod,
processGlobalQueue,
simplifyUrl,
} from "./rest/mod.ts";
import type { RestPayload, RestRateLimitedPath, RestRequest } from "./rest/rest.ts";
import { runMethod } from "./rest/run_method.ts";
import { simplifyUrl } from "./rest/simplify_url.ts";
import { DiscordGatewayIntents } from "./types/gateway/gateway_intents.ts";
import { GetGatewayBot } from "./types/gateway/get_gateway_bot.ts";
import { dispatchRequirements } from "./util/dispatch_requirements.ts";
import { processQueue } from "./rest/process_queue.ts";
import { bigintToSnowflake, snowflakeToBigint } from "./util/bigint.ts";
import { Collection } from "./util/collection.ts";
import type { DiscordenoMember, DiscordenoUser } from "./transformers/member.ts";
import { transformMember, transformUser } from "./transformers/member.ts";
import { SnakeCasedPropertiesDeep } from "./types/util.ts";
import { Channel } from "./types/channels/channel.ts";
import { DiscordenoChannel, transformChannel } from "./transformers/channel.ts";
import { DiscordenoVoiceState, transformVoiceState } from "./transformers/voice_state.ts";
import { transformRole } from "./transformers/role.ts";
import { transformMessage } from "./transformers/message.ts";
import { DiscordenoGuild, transformGuild } from "./transformers/guild.ts";
import type { DiscordenoShard } from "./ws/ws.ts";
import { startGateway } from "./ws/start_gateway.ts";
import { spawnShards } from "./ws/spawn_shards.ts";
import { createShard } from "./ws/create_shard.ts";
import { identify } from "./ws/identify.ts";
import { heartbeat } from "./ws/heartbeat.ts";
import { resharder } from "./ws/resharder.ts";
import { tellClusterToIdentify } from "./ws/tell_cluster_to_identify.ts";
import { log } from "./ws/events.ts";
import { handleOnMessage } from "./ws/handle_on_message.ts";
import { closeWS } from "./ws/close_ws.ts";
import { sendShardMessage } from "./ws/send_shard_message.ts";
import { resume } from "./ws/resume.ts";
import { calculateShardId } from "./util/calculate_shard_id.ts";
import {
DiscordenoMember,
DiscordenoUser,
transformMember,
transformUser,
DiscordenoGuild,
transformGuild,
DiscordenoChannel,
transformChannel,
transformMessage,
transformRole,
DiscordenoVoiceState,
transformVoiceState,
} from "./transformers/mod.ts";
import {
baseEndpoints,
CHANNEL_MENTION_REGEX,
@@ -61,15 +56,27 @@ import {
SLASH_COMMANDS_NAME_REGEX,
USER_AGENT,
} from "./util/constants.ts";
import { GatewayDispatchEventNames, GatewayEventNames, GatewayPayload } from "./types/gateway/gateway_payload.ts";
import { delay, validateSlashOptionChoices, validateSlashOptions } from "./util/utils.ts";
import { iconBigintToHash, iconHashToBigInt } from "./util/hash.ts";
import { Errors } from "./types/discordeno/errors.ts";
import { GatewayDispatchEventNames, GatewayPayload } from "./types/gateway/gateway_payload.ts";
import {
closeWS,
handleOnMessage,
resume,
resharder,
log,
startGateway,
spawnShards,
createShard,
identify,
heartbeat,
tellClusterToIdentify,
sendShardMessage,
DiscordenoShard,
} from "./ws/mod.ts";
import { validateLength } from "./util/validate_length.ts";
import { processGlobalQueue } from "./rest/process_global_queue.ts";
import { ChannelPinsUpdate } from "./types/channels/channel_pins_update.ts";
import { ApplicationCommandTypes, Emoji, IntegrationCreateUpdate } from "./types/mod.ts";
import { ApplicationCommandOption } from "./types/mod.ts";
import { handleGuildLoaded } from "./handlers/guilds/GUILD_LOADED_DD.ts";
import { delay, validateComponents, validateSlashOptionChoices, validateSlashOptions } from "./util/utils.ts";
import { iconBigintToHash, iconHashToBigInt } from "./util/hash.ts";
import { calculateShardId } from "./util/calculate_shard_id.ts";
import {
handleReady,
handleChannelCreate,
@@ -118,9 +125,11 @@ import {
handleIntegrationCreate,
handleIntegrationUpdate,
handleIntegrationDelete,
handleGuildLoaded
} from "./handlers/mod.ts";
import { DiscordenoInteraction, transformInteraction } from "./transformers/interaction.ts";
import { DiscordenoIntegration, transformIntegration } from "./transformers/integration.ts";
import {Emoji} from "./types/emojis/emoji.ts";
import { transformApplication } from "./transformers/application.ts";
import { transformTeam } from "./transformers/team.ts";
import { DiscordenoInvite, transformInvite } from "./transformers/invite.ts";
@@ -239,6 +248,7 @@ export function createEventHandlers(events: Partial<EventHandlers>): EventHandle
function ignore() {}
return {
channelCreate: events.channelCreate ?? ignore,
debug: events.debug ?? ignore,
dispatchRequirements: events.dispatchRequirements ?? ignore,
integrationCreate: events.integrationCreate ?? ignore,
@@ -365,6 +375,9 @@ export function createUtils(options: Partial<HelperUtils>) {
validateLength,
validateSlashOptions,
validateSlashOptionChoices,
requireBotChannelPermissions,
requireBotGuildPermissions,
validateComponents,
};
}
@@ -390,6 +403,9 @@ export interface HelperUtils {
validateLength: typeof validateLength;
validateSlashOptions: typeof validateSlashOptions;
validateSlashOptionChoices: typeof validateSlashOptionChoices;
requireBotChannelPermissions: typeof requireBotChannelPermissions;
requireBotGuildPermissions: typeof requireBotGuildPermissions;
validateComponents: typeof validateComponents;
}
export function createGatewayManager(options: Partial<GatewayManager>): GatewayManager {
@@ -704,6 +720,7 @@ export function createBotConstants() {
CHANNEL_MENTION_REGEX,
DISCORD_SNOWFLAKE_REGEX,
},
Errors,
};
}

View File

@@ -2,7 +2,7 @@ import type { Channel } from "../../types/channels/channel.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { SnakeCasedPropertiesDeep } from "../../types/util.ts";
import { Bot } from "../../bot.ts";
import type { Bot } from "../../bot.ts";
export async function handleChannelCreate(bot: Bot, payload: SnakeCasedPropertiesDeep<DiscordGatewayPayload>) {
const channel = bot.transformers.channel(bot, { channel: payload.d as SnakeCasedPropertiesDeep<Channel> });

View File

@@ -1,6 +1,6 @@
import type { Channel } from "../../types/channels/channel.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { Bot } from "../../bot.ts";
import type { Bot } from "../../bot.ts";
import { DiscordChannelTypes } from "../../types/channels/channel_types.ts";
import { SnakeCasedPropertiesDeep } from "../../types/util.ts";

View File

@@ -1,4 +1,4 @@
import { Bot } from "../../bot.ts";
import type { Bot } from "../../bot.ts";
import type { ChannelPinsUpdate } from "../../types/channels/channel_pins_update.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { SnakeCasedPropertiesDeep } from "../../types/util.ts";

View File

@@ -1,4 +1,4 @@
import { Bot } from "../../bot.ts";
import type { Bot } from "../../bot.ts";
import type { Channel } from "../../types/channels/channel.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { SnakeCasedPropertiesDeep } from "../../types/util.ts";

View File

@@ -1,4 +1,4 @@
import { Bot } from "../../bot.ts";
import type { Bot } from "../../bot.ts";
import type { StageInstance } from "../../types/channels/stage_instance.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { SnakeCasedPropertiesDeep } from "../../types/util.ts";

View File

@@ -1,4 +1,4 @@
import { Bot } from "../../bot.ts";
import type { Bot } from "../../bot.ts";
import type { StageInstance } from "../../types/channels/stage_instance.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { SnakeCasedPropertiesDeep } from "../../types/util.ts";

View File

@@ -1,4 +1,4 @@
import { Bot } from "../../bot.ts";
import type { Bot } from "../../bot.ts";
import type { StageInstance } from "../../types/channels/stage_instance.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { SnakeCasedPropertiesDeep } from "../../types/util.ts";

View File

@@ -1,4 +1,4 @@
import { Bot } from "../../bot.ts";
import type { Bot } from "../../bot.ts";
import type { GuildEmojisUpdate } from "../../types/emojis/guild_emojis_update.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { SnakeCasedPropertiesDeep } from "../../types/util.ts";

View File

@@ -1,4 +1,4 @@
import { Bot } from "../../bot.ts";
import type { Bot } from "../../bot.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { GuildBanAddRemove } from "../../types/guilds/guild_ban_add_remove.ts";
import { SnakeCasedPropertiesDeep } from "../../types/util.ts";

View File

@@ -1,4 +1,4 @@
import { Bot } from "../../bot.ts";
import type { Bot } from "../../bot.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { GuildBanAddRemove } from "../../types/guilds/guild_ban_add_remove.ts";
import { SnakeCasedPropertiesDeep } from "../../types/util.ts";

View File

@@ -1,4 +1,4 @@
import { Bot } from "../../bot.ts";
import type { Bot } from "../../bot.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { Guild } from "../../types/guilds/guild.ts";
import { SnakeCasedPropertiesDeep } from "../../types/util.ts";

View File

@@ -1,4 +1,4 @@
import { Bot } from "../../bot.ts";
import type { Bot } from "../../bot.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { UnavailableGuild } from "../../types/guilds/unavailable_guild.ts";
import { SnakeCasedPropertiesDeep } from "../../types/util.ts";

View File

@@ -1,4 +1,4 @@
import { Bot } from "../../bot.ts";
import type { Bot } from "../../bot.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { GuildIntegrationsUpdate } from "../../types/integrations/guild_integrations_update.ts";
import { SnakeCasedPropertiesDeep } from "../../types/util.ts";

View File

@@ -1,4 +1,4 @@
import { Bot } from "../../bot.ts";
import type { Bot } from "../../bot.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { Guild } from "../../types/guilds/guild.ts";
import { SnakeCasedPropertiesDeep } from "../../types/util.ts";

View File

@@ -1,4 +1,4 @@
import { Bot } from "../../bot.ts";
import type { Bot } from "../../bot.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { Guild } from "../../types/guilds/guild.ts";
import { SnakeCasedPropertiesDeep } from "../../types/util.ts";

View File

@@ -1,8 +1,9 @@
import { cache } from "../../cache.ts";
import {Bot} from "../../bot.ts";
/** Gets an array of all the channels ids that are the children of this category.
* ⚠️ This does not work for custom cache users!
*/
export function categoryChildren(parentChannelId: bigint) {
return cache.channels.filter((channel) => channel.parentId === parentChannelId);
export function categoryChildren(bot: Bot, parentChannelId: bigint) {
// TODO: Cache Filter ?
return bot.cache.channels.filter((channel) => channel.parentId === parentChannelId);
}

View File

@@ -1,18 +1,15 @@
import { cacheHandlers } from "../../cache.ts";
import type { Bot } from "../../bot.ts";
import { DiscordChannelTypes } from "../../types/channels/channel_types.ts";
import type { CreateGuildChannel } from "../../types/guilds/create_guild_channel.ts";
import { Errors } from "../../types/discordeno/errors.ts";
import { calculatePermissions } from "../../util/permissions.ts";
import { helpers } from "../mod.ts";
/** Create a copy of a channel */
export async function cloneChannel(channelId: bigint, reason?: string) {
const channelToClone = await cacheHandlers.get("channels", channelId);
if (!channelToClone) throw new Error(Errors.CHANNEL_NOT_FOUND);
export async function cloneChannel(bot: Bot, channelId: bigint, reason?: string) {
const channelToClone = await bot.cache.channels.get(channelId);
if (!channelToClone) throw new Error(bot.constants.Errors.CHANNEL_NOT_FOUND);
//Check for DM channel
if (channelToClone.type === DiscordChannelTypes.DM || channelToClone.type === DiscordChannelTypes.GroupDm) {
throw new Error(Errors.CHANNEL_NOT_IN_GUILD);
throw new Error(bot.constants.Errors.CHANNEL_NOT_IN_GUILD);
}
const createChannelOptions: CreateGuildChannel = {
@@ -22,11 +19,11 @@ export async function cloneChannel(channelId: bigint, reason?: string) {
permissionOverwrites: channelToClone.permissionOverwrites.map((overwrite) => ({
id: overwrite.id.toString(),
type: overwrite.type,
allow: calculatePermissions(overwrite.allow),
deny: calculatePermissions(overwrite.deny),
allow: bot.utils.calculatePermissions(overwrite.allow),
deny: bot.utils.calculatePermissions(overwrite.deny),
})),
};
//Create the channel (also handles permissions)
return await helpers.createChannel(channelToClone.guildId!, createChannelOptions, reason);
return await bot.helpers.createChannel(bot, channelToClone.guildId!, createChannelOptions, reason);
}

View File

@@ -1,39 +1,42 @@
import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts";
import { structures } from "../../structures/mod.ts";
import type { Channel } from "../../types/channels/channel.ts";
import { DiscordChannelTypes } from "../../types/channels/channel_types.ts";
import type { CreateGuildChannel, DiscordCreateGuildChannel } from "../../types/guilds/create_guild_channel.ts";
import { endpoints } from "../../util/constants.ts";
import { calculateBits, requireOverwritePermissions } from "../../util/permissions.ts";
import { snakelize } from "../../util/utils.ts";
import type { Bot } from "../../bot.ts";
/** Create a channel in your server. Bot needs MANAGE_CHANNEL permissions in the server. */
export async function createChannel(guildId: bigint, options?: CreateGuildChannel, reason?: string) {
if (options?.permissionOverwrites) {
await requireOverwritePermissions(guildId, options.permissionOverwrites);
}
export async function createChannel(bot: Bot, guildId: bigint, options?: CreateGuildChannel, reason?: string) {
if (options?.permissionOverwrites) {
await bot.utils.requireOverwritePermissions(bot, guildId, options.permissionOverwrites);
}
// BITRATES ARE IN THOUSANDS SO IF USER PROVIDES 32 WE CONVERT TO 32000
if (options?.bitrate && options.bitrate < 1000) options.bitrate *= 1000;
// BITRATES ARE IN THOUSANDS SO IF USER PROVIDES 32 WE CONVERT TO 32000
if (options?.bitrate && options.bitrate < 1000) options.bitrate *= 1000;
const result = await rest.runMethod<Channel>(
"post",
endpoints.GUILD_CHANNELS(guildId),
snakelize<DiscordCreateGuildChannel>({
...options,
permissionOverwrites: options?.permissionOverwrites?.map((perm) => ({
...perm,
allow: calculateBits(perm.allow),
deny: calculateBits(perm.deny),
})),
type: options?.type || DiscordChannelTypes.GuildText,
reason,
})
);
const result = await bot.rest.runMethod<Channel>(
bot.rest,
"post",
bot.constants.endpoints.GUILD_CHANNELS(guildId),
options ? {
name: options.name,
topic: options.topic,
bitrate: options.bitrate,
userLimit: options.userLimit,
rateLimitPerUser: options.rateLimitPerUser,
position: options.position,
parentId: options.parentId,
nsfw: options.nsfw,
permission_overwrites: options?.permissionOverwrites?.map((perm) => ({
...perm,
allow: bot.utils.calculateBits(perm.allow),
deny: bot.utils.calculateBits(perm.deny),
})),
type: options?.type || DiscordChannelTypes.GuildText,
reason,
} : {}
);
const discordenoChannel = await structures.createDiscordenoChannel(result);
await cacheHandlers.set("channels", discordenoChannel.id, discordenoChannel);
const discordenoChannel = bot.transformers.channel(result);
await bot.cache.channels.set(discordenoChannel.id, discordenoChannel);
return discordenoChannel;
return discordenoChannel;
}

View File

@@ -1,37 +1,32 @@
import { validateLength } from "../../util/validate_length.ts";
import { Errors } from "../../types/discordeno/errors.ts";
import { rest } from "../../rest/rest.ts";
import { endpoints } from "../../util/constants.ts";
import type { StageInstance } from "../../types/channels/stage_instance.ts";
import { cacheHandlers } from "../../cache.ts";
import type { Bot } from "../../bot.ts";
import { ChannelTypes } from "../../types/channels/channel_types.ts";
import { requireBotChannelPermissions } from "../../util/permissions.ts";
import { PrivacyLevel } from "../../types/channels/privacy_level.ts";
import { snakelize } from "../../util/utils.ts";
/** Creates a new Stage instance associated to a Stage channel. Requires the user to be a moderator of the Stage channel. */
export async function createStageInstance(channelId: bigint, topic: string, privacyLevel?: PrivacyLevel) {
const channel = await cacheHandlers.get("channels", channelId);
export async function createStageInstance(bot: Bot, channelId: bigint, topic: string, privacyLevel?: PrivacyLevel) {
const channel = await bot.cache.channels.get(channelId);
if (channel) {
if (channel.type !== ChannelTypes.GuildStageVoice) {
throw new Error(Errors.CHANNEL_NOT_STAGE_VOICE);
throw new Error(bot.constants.Errors.CHANNEL_NOT_STAGE_VOICE);
}
await requireBotChannelPermissions(channel, ["MANAGE_CHANNELS", "MUTE_MEMBERS", "MOVE_MEMBERS"]);
await bot.utils.requireBotChannelPermissions(bot, channel, ["MANAGE_CHANNELS", "MUTE_MEMBERS", "MOVE_MEMBERS"]);
}
if (!validateLength(topic, { max: 120, min: 1 })) {
throw new Error(Errors.INVALID_TOPIC_LENGTH);
if (!bot.utils.validateLength(topic, { max: 120, min: 1 })) {
throw new Error(bot.constants.Errors.INVALID_TOPIC_LENGTH);
}
return await rest.runMethod<StageInstance>(
return await bot.rest.runMethod<StageInstance>(
bot.rest,
"post",
endpoints.STAGE_INSTANCES,
snakelize({
channelId,
bot.constants.endpoints.STAGE_INSTANCES,
{
channel_id: channelId,
topic,
privacyLevel,
})
privacy_level: privacyLevel,
}
);
}

View File

@@ -1,27 +1,23 @@
import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts";
import { Errors } from "../../types/discordeno/errors.ts";
import { endpoints } from "../../util/constants.ts";
import { requireBotGuildPermissions } from "../../util/permissions.ts";
import type { Bot } from "../../bot.ts";
/** Delete a channel in your server. Bot needs MANAGE_CHANNEL permissions in the server. */
export async function deleteChannel(channelId: bigint, reason?: string) {
export async function deleteChannel(bot: Bot, channelId: bigint, reason?: string) {
const channel = await cacheHandlers.get("channels", channelId);
if (channel?.guildId) {
const guild = await cacheHandlers.get("guilds", channel.guildId);
if (!guild) throw new Error(Errors.GUILD_NOT_FOUND);
if (!guild) throw new Error(bot.constants.Errors.GUILD_NOT_FOUND);
if (guild.rulesChannelId === channelId) {
throw new Error(Errors.RULES_CHANNEL_CANNOT_BE_DELETED);
throw new Error(bot.constants.Errors.RULES_CHANNEL_CANNOT_BE_DELETED);
}
if (guild.publicUpdatesChannelId === channelId) {
throw new Error(Errors.UPDATES_CHANNEL_CANNOT_BE_DELETED);
throw new Error(bot.constants.Errors.UPDATES_CHANNEL_CANNOT_BE_DELETED);
}
await requireBotGuildPermissions(guild, ["MANAGE_CHANNELS"]);
await bot.utils.requireBotGuildPermissions(bot, guild, ["MANAGE_CHANNELS"]);
}
return await rest.runMethod<undefined>("delete", endpoints.CHANNEL_BASE(channelId), { reason });
return await bot.rest.runMethod<undefined>(bot.rest, "delete", bot.constants.endpoints.CHANNEL_BASE(channelId), { reason });
}

View File

@@ -1,14 +1,13 @@
import { rest } from "../../rest/rest.ts";
import { endpoints } from "../../util/constants.ts";
import { requireBotGuildPermissions } from "../../util/permissions.ts";
import type { Bot } from "../../bot.ts";
/** Delete the channel permission overwrites for a user or role in this channel. Requires `MANAGE_ROLES` permission. */
export async function deleteChannelOverwrite(
bot: Bot,
guildId: bigint,
channelId: bigint,
overwriteId: bigint
): Promise<undefined> {
await requireBotGuildPermissions(guildId, ["MANAGE_ROLES"]);
await bot.utils.requireBotGuildPermissions(bot, guildId, ["MANAGE_ROLES"]);
return await rest.runMethod<undefined>("delete", endpoints.CHANNEL_OVERWRITE(channelId, overwriteId));
return await bot.rest.runMethod<undefined>(bot.rest,"delete", bot.constants.endpoints.CHANNEL_OVERWRITE(channelId, overwriteId));
}

View File

@@ -1,21 +1,17 @@
import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts";
import { ChannelTypes } from "../../types/channels/channel_types.ts";
import { Errors } from "../../types/discordeno/errors.ts";
import { endpoints } from "../../util/constants.ts";
import { requireBotChannelPermissions } from "../../util/permissions.ts";
import type { Bot } from "../../bot.ts";
/** Deletes the Stage instance. Requires the user to be a moderator of the Stage channel. */
export async function deleteStageInstance(channelId: bigint) {
const channel = await cacheHandlers.get("channels", channelId);
export async function deleteStageInstance(bot: Bot, channelId: bigint) {
const channel = await bot.cache.channels.get(channelId);
if (channel) {
if (channel.type !== ChannelTypes.GuildStageVoice) {
throw new Error(Errors.CHANNEL_NOT_STAGE_VOICE);
throw new Error(bot.constants.Errors.CHANNEL_NOT_STAGE_VOICE);
}
await requireBotChannelPermissions(channel, ["MUTE_MEMBERS", "MANAGE_CHANNELS", "MOVE_MEMBERS"]);
await bot.utils.requireBotChannelPermissions(bot, channel, ["MUTE_MEMBERS", "MANAGE_CHANNELS", "MOVE_MEMBERS"]);
}
return await rest.runMethod<undefined>("delete", endpoints.STAGE_INSTANCE(channelId));
return await bot.rest.runMethod<undefined>(bot.rest, "delete", bot.constants.endpoints.STAGE_INSTANCE(channelId));
}

View File

@@ -1,21 +1,16 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts";
import type { DiscordenoChannel } from "../../structures/channel.ts";
import { structures } from "../../structures/mod.ts";
import type { Channel } from "../../types/channels/channel.ts";
import type { ModifyChannel } from "../../types/channels/modify_channel.ts";
import { endpoints } from "../../util/constants.ts";
import { calculateBits, requireOverwritePermissions } from "../../util/permissions.ts";
import { snakelize } from "../../util/utils.ts";
import type { Bot } from "../../bot.ts";
import {SnakeCasedPropertiesDeep} from "../../types/util.ts";
/** Update a channel's settings. Requires the `MANAGE_CHANNELS` permission for the guild. */
export async function editChannel(channelId: bigint, options: ModifyChannel, reason?: string) {
const channel = await cacheHandlers.get("channels", channelId);
export async function editChannel(bot: Bot, channelId: bigint, options: ModifyChannel, reason?: string) {
const channel = await bot.cache.channels.get(channelId);
if (channel) {
if (options.permissionOverwrites && Array.isArray(options.permissionOverwrites)) {
await requireOverwritePermissions(channel.guildId, options.permissionOverwrites);
await bot.utils.requireOverwritePermissions(bot, channel.guildId, options.permissionOverwrites);
}
}
@@ -40,16 +35,25 @@ export async function editChannel(channelId: bigint, options: ModifyChannel, rea
request.items.push({ channelId, options, resolve, reject });
if (editChannelProcessing) return;
editChannelProcessing = true;
processEditChannelQueue();
processEditChannelQueue(bot);
});
}
}
const result = await rest.runMethod<Channel>(
const result = await bot.rest.runMethod<SnakeCasedPropertiesDeep<Channel>>(
bot.rest,
"patch",
endpoints.CHANNEL_BASE(channelId),
snakelize({
...options,
bot.constants.endpoints.CHANNEL_BASE(channelId),
{
name: options.name,
topic: options.topic,
bitrate: options.bitrate,
userLimit: options.userLimit,
rateLimitPerUser: options.rateLimitPerUser,
position: options.position,
parentId: options.parentId,
nsfw: options.nsfw,
type: options.type,
permissionOverwrites: options.permissionOverwrites
? options.permissionOverwrites?.map((overwrite) => {
return {
@@ -60,10 +64,10 @@ export async function editChannel(channelId: bigint, options: ModifyChannel, rea
})
: undefined,
reason,
})
}
);
return await structures.createDiscordenoChannel(result);
return bot.transformers.channel(result);
}
interface EditChannelRequest {
@@ -82,7 +86,7 @@ interface EditChannelRequest {
const editChannelNameTopicQueue = new Map<bigint, EditChannelRequest>();
let editChannelProcessing = false;
function processEditChannelQueue() {
function processEditChannelQueue(bot: Bot) {
if (!editChannelProcessing) return;
const now = Date.now();
@@ -99,13 +103,13 @@ function processEditChannelQueue() {
if (!details) return;
await editChannel(details.channelId, details.options)
await bot.helpers.editChannel(bot, details.channelId, details.options)
.then((result) => details.resolve(result))
.catch(details.reject);
const secondDetails = request.items.shift();
if (!secondDetails) return;
await editChannel(secondDetails.channelId, secondDetails.options)
await bot.helpers.editChannel(bot, secondDetails.channelId, secondDetails.options)
.then((result) => secondDetails.resolve(result))
.catch(secondDetails.reject);
return;
@@ -114,7 +118,7 @@ function processEditChannelQueue() {
if (editChannelNameTopicQueue.size) {
setTimeout(() => {
eventHandlers.debug?.("loop", `Running setTimeout in EDIT_CHANNEL file.`);
processEditChannelQueue();
processEditChannelQueue(bot);
}, 60000);
} else {
editChannelProcessing = false;

View File

@@ -1,20 +1,19 @@
import { rest } from "../../rest/rest.ts";
import type { Overwrite } from "../../types/channels/overwrite.ts";
import { endpoints } from "../../util/constants.ts";
import { calculateBits, requireBotGuildPermissions } from "../../util/permissions.ts";
import type { Bot } from "../../bot.ts";
/** Edit the channel permission overwrites for a user or role in this channel. Requires `MANAGE_ROLES` permission. */
export async function editChannelOverwrite(
bot: Bot,
guildId: bigint,
channelId: bigint,
overwriteId: bigint,
options: Omit<Overwrite, "id">
): Promise<undefined> {
await requireBotGuildPermissions(guildId, ["MANAGE_ROLES"]);
await bot.utils.requireBotGuildPermissions(bot, guildId, ["MANAGE_ROLES"]);
return await rest.runMethod<undefined>("put", endpoints.CHANNEL_OVERWRITE(channelId, overwriteId), {
allow: calculateBits(options.allow),
deny: calculateBits(options.deny),
return await bot.rest.runMethod<undefined>(bot.rest,"put", bot.constants.endpoints.CHANNEL_OVERWRITE(channelId, overwriteId), {
allow: bot.utils.calculateBits(options.allow),
deny: bot.utils.calculateBits(options.deny),
type: options.type,
});
}

View File

@@ -1,13 +1,11 @@
import { rest } from "../../rest/rest.ts";
import type { FollowedChannel } from "../../types/channels/followed_channel.ts";
import { endpoints } from "../../util/constants.ts";
import { requireBotChannelPermissions } from "../../util/permissions.ts";
import type { Bot } from "../../bot.ts";
/** Follow a News Channel to send messages to a target channel. Requires the `MANAGE_WEBHOOKS` permission in the target channel. Returns the webhook id. */
export async function followChannel(sourceChannelId: bigint, targetChannelId: bigint) {
await requireBotChannelPermissions(targetChannelId, ["MANAGE_WEBHOOKS"]);
export async function followChannel(bot: Bot, sourceChannelId: bigint, targetChannelId: bigint) {
await bot.utils.requireBotChannelPermissions(bot, targetChannelId, ["MANAGE_WEBHOOKS"]);
const data = await rest.runMethod<FollowedChannel>("post", endpoints.CHANNEL_FOLLOW(sourceChannelId), {
const data = await bot.rest.runMethod<FollowedChannel>(bot.rest,"post", bot.constants.endpoints.CHANNEL_FOLLOW(sourceChannelId), {
webhook_channel_id: targetChannelId,
});

View File

@@ -1,23 +1,21 @@
import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts";
import { structures } from "../../structures/mod.ts";
import type { Bot } from "../../bot.ts";
import type { Channel } from "../../types/channels/channel.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
import { endpoints } from "../../util/constants.ts";
/** Fetches a single channel object from the api.
*
* ⚠️ **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: bigint, addToCache = true) {
const result = await rest.runMethod<Channel>("get", endpoints.CHANNEL_BASE(channelId));
export async function getChannel(bot: Bot, channelId: bigint, addToCache = true) {
const result = await bot.rest.runMethod<Channel>(bot.rest,"get", bot.constants.endpoints.CHANNEL_BASE(channelId));
const discordenoChannel = await structures.createDiscordenoChannel(
result,
result.guildId ? snowflakeToBigint(result.guildId) : undefined
const discordenoChannel = bot.transformers.channel(
{
channel: result,
guildId: result.guildId ? bot.transformers.snowflake(result.guildId) : undefined
}
);
if (addToCache) {
await cacheHandlers.set("channels", discordenoChannel.id, discordenoChannel);
await bot.cache.channels.set(discordenoChannel.id, discordenoChannel);
}
return discordenoChannel;

View File

@@ -1,14 +1,12 @@
import { rest } from "../../rest/rest.ts";
import type { Webhook } from "../../types/webhooks/webhook.ts";
import { Collection } from "../../util/collection.ts";
import { endpoints } from "../../util/constants.ts";
import { requireBotChannelPermissions } from "../../util/permissions.ts";
import type { Bot } from "../../bot.ts";
/** Gets the webhooks for this channel. Requires MANAGE_WEBHOOKS */
export async function getChannelWebhooks(channelId: bigint) {
await requireBotChannelPermissions(channelId, ["MANAGE_WEBHOOKS"]);
export async function getChannelWebhooks(bot: Bot, channelId: bigint) {
await bot.utils.requireBotChannelPermissions(bot, channelId, ["MANAGE_WEBHOOKS"]);
const result = await rest.runMethod<Webhook[]>("get", endpoints.CHANNEL_WEBHOOKS(channelId));
const result = await bot.rest.runMethod<Webhook[]>(bot.rest,"get", bot.constants.endpoints.CHANNEL_WEBHOOKS(channelId));
return new Collection(result.map((webhook) => [webhook.id, webhook]));
}

View File

@@ -1,24 +1,21 @@
import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts";
import { structures } from "../../structures/mod.ts";
import type { Channel } from "../../types/channels/channel.ts";
import { Collection } from "../../util/collection.ts";
import { endpoints } from "../../util/constants.ts";
import type { Bot } from "../../bot.ts";
/** Returns a list of guild channel objects.
*
* ⚠️ **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: bigint, addToCache = true) {
const result = await rest.runMethod<Channel[]>("get", endpoints.GUILD_CHANNELS(guildId));
export async function getChannels(bot: Bot, guildId: bigint, addToCache = true) {
const result = await bot.rest.runMethod<Channel[]>(bot.rest,"get", bot.constants.endpoints.GUILD_CHANNELS(guildId));
return new Collection(
(
await Promise.all(
result.map(async (res) => {
const discordenoChannel = await structures.createDiscordenoChannel(res, guildId);
const discordenoChannel = await bot.transformers.channel({channel: res, guildId});
if (addToCache) {
await cacheHandlers.set("channels", discordenoChannel.id, discordenoChannel);
await bot.cache.channels.set(discordenoChannel.id, discordenoChannel);
}
return discordenoChannel;

View File

@@ -1,11 +1,9 @@
import { rest } from "../../rest/rest.ts";
import { structures } from "../../structures/mod.ts";
import type { Message } from "../../types/messages/message.ts";
import { endpoints } from "../../util/constants.ts";
import type { Bot } from "../../bot.ts";
/** Get pinned messages in this channel. */
export async function getPins(channelId: bigint) {
const result = await rest.runMethod<Message[]>("get", endpoints.CHANNEL_PINS(channelId));
export async function getPins(bot: Bot, channelId: bigint) {
const result = await bot.rest.runMethod<Message[]>(bot.rest,"get", bot.constants.endpoints.CHANNEL_PINS(channelId));
return Promise.all(result.map((res) => structures.createDiscordenoMessage(res)));
return result.map(bot.transformers.message);
}

View File

@@ -1,19 +1,16 @@
import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts";
import { ChannelTypes } from "../../types/channels/channel_types.ts";
import type { ChannelTypes } from "../../types/channels/channel_types.ts";
import type { StageInstance } from "../../types/channels/stage_instance.ts";
import { Errors } from "../../types/discordeno/errors.ts";
import { endpoints } from "../../util/constants.ts";
import type { Bot } from "../../bot.ts";
/** Gets the stage instance associated with the Stage channel, if it exists. */
export async function getStageInstance(channelId: bigint) {
const channel = await cacheHandlers.get("channels", channelId);
export async function getStageInstance(bot: Bot, channelId: bigint) {
const channel = await bot.cache.channels.get(channelId);
if (channel) {
if (channel.type !== ChannelTypes.GuildStageVoice) {
throw new Error(Errors.CHANNEL_NOT_STAGE_VOICE);
throw new Error(bot.constants.Errors.CHANNEL_NOT_STAGE_VOICE);
}
}
return await rest.runMethod<StageInstance>("get", endpoints.STAGE_INSTANCE(channelId));
return await bot.rest.runMethod<StageInstance>(bot.rest,"get", bot.constants.endpoints.STAGE_INSTANCE(channelId));
}

View File

@@ -1,11 +1,11 @@
import { cacheHandlers } from "../../cache.ts";
import type { Bot } from "../../bot.ts";
/** Checks whether a channel is synchronized with its parent/category channel or not. */
export async function isChannelSynced(channelId: bigint) {
const channel = await cacheHandlers.get("channels", channelId);
export async function isChannelSynced(bot: Bot, channelId: bigint) {
const channel = await bot.cache.channels.get(channelId);
if (!channel?.parentId) return false;
const parentChannel = await cacheHandlers.get("channels", channel.parentId);
const parentChannel = await bot.cache.channels.get(channel.parentId);
if (!parentChannel) return false;
return channel.permissionOverwrites?.every((overwrite) => {

View File

@@ -1,17 +1,13 @@
import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts";
import { DiscordChannelTypes } from "../../types/channels/channel_types.ts";
import { Errors } from "../../types/discordeno/errors.ts";
import { endpoints } from "../../util/constants.ts";
import { botHasChannelPermissions } from "../../util/permissions.ts";
import type { Bot } from "../../bot.ts";
/**
* Trigger a typing indicator for the specified channel. Generally bots should **NOT** implement this route.
* However, if a bot is responding to a command and expects the computation to take a few seconds,
* this endpoint may be called to let the user know that the bot is processing their message.
*/
export async function startTyping(channelId: bigint) {
const channel = await cacheHandlers.get("channels", channelId);
export async function startTyping(bot: Bot, channelId: bigint) {
const channel = await bot.cache.channels.get(channelId);
// If the channel is cached, we can do extra checks/safety
if (channel) {
if (
@@ -24,14 +20,14 @@ export async function startTyping(channelId: bigint) {
DiscordChannelTypes.GuildPublicThread,
].includes(channel.type)
) {
throw new Error(Errors.CHANNEL_NOT_TEXT_BASED);
throw new Error(bot.constants.Errors.CHANNEL_NOT_TEXT_BASED);
}
const hasSendMessagesPerm = await botHasChannelPermissions(channelId, ["SEND_MESSAGES"]);
const hasSendMessagesPerm = await bot.utils.botHasChannelPermissions(bots, channelId, ["SEND_MESSAGES"]);
if (!hasSendMessagesPerm) {
throw new Error(Errors.MISSING_SEND_MESSAGES);
throw new Error(bot.constants.Errors.MISSING_SEND_MESSAGES);
}
}
return await rest.runMethod<undefined>("post", endpoints.CHANNEL_TYPING(channelId));
return await bot.rest.runMethod<undefined>(bot.rest,"post", bot.constants.endpoints.CHANNEL_TYPING(channelId));
}

View File

@@ -1,13 +1,18 @@
import { rest } from "../../rest/rest.ts";
import type { ModifyGuildChannelPositions } from "../../types/guilds/modify_guild_channel_position.ts";
import { endpoints } from "../../util/constants.ts";
import { snakelize } from "../../util/utils.ts";
import type { Bot } from "../../bot.ts";
/** Modify the positions of channels on the guild. Requires MANAGE_CHANNELS permisison. */
export async function swapChannels(guildId: bigint, channelPositions: ModifyGuildChannelPositions[]) {
/** Modify the positions of channels on the guild. Requires MANAGE_CHANNELS permission. */
export async function swapChannels(bot: Bot, guildId: bigint, channelPositions: ModifyGuildChannelPositions[]) {
if (channelPositions.length < 2) {
throw "You must provide at least two channels to be swapped.";
}
return await rest.runMethod<undefined>("patch", endpoints.GUILD_CHANNELS(guildId), snakelize(channelPositions));
return await bot.rest.runMethod<undefined>(bot.rest,"patch", bot.constants.endpoints.GUILD_CHANNELS(guildId), channelPositions.map((channelPosition) => {
return {
id: channelPosition.id,
position: channelPosition.position,
lock_positions: channelPosition.lockPositions,
parent_id: channelPosition.parentId
}
}));
}

View File

@@ -1,22 +1,18 @@
import { cacheHandlers } from "../../../cache.ts";
import { rest } from "../../../rest/rest.ts";
import { Errors } from "../../../types/discordeno/errors.ts";
import { endpoints } from "../../../util/constants.ts";
import { requireBotChannelPermissions } from "../../../util/permissions.ts";
import type { Bot } from "../../../bot.ts";
/** Adds a user to a thread. Requires the ability to send messages in the thread. Requires the thread is not archived. */
export async function addToThread(threadId: bigint, userId: bigint) {
const thread = await cacheHandlers.get("threads", threadId);
export async function addToThread(bot: Bot, threadId: bigint, userId: bigint) {
const thread = await bot.cache.threads.get(threadId);
if (thread) {
if (thread.archived) {
throw new Error(Errors.CANNOT_ADD_USER_TO_ARCHIVED_THREADS);
throw new Error(bot.constants.Errors.CANNOT_ADD_USER_TO_ARCHIVED_THREADS);
}
// If a user id is provided SEND_MESSAGES is required.
const channel = await cacheHandlers.get("channels", thread.parentId);
const channel = await bot.cache.channels.get(thread.parentId);
// TODO: does MANAGE_THREADS override this????
if (channel) await requireBotChannelPermissions(channel, ["SEND_MESSAGES"]);
if (channel) await bot.utils.requireBotChannelPermissions(bot, channel, ["SEND_MESSAGES"]);
}
return await rest.runMethod<undefined>("put", endpoints.THREAD_USER(threadId, userId));
return await bot.rest.runMethod<undefined>(bot.rest, "put", bot.constants.endpoints.THREAD_USER(threadId, userId));
}

View File

@@ -1,6 +1,6 @@
import { editThread } from "./edit_thread.ts";
import type { Bot } from "../../../bot.ts";
/** Sets a thread channel to be archived. */
export async function archiveThread(threadId: bigint) {
return await editThread(threadId, { archived: true });
export async function archiveThread(bot: Bot, threadId: bigint) {
return await bot.helpers.editThread(bot, threadId, { archived: true });
}

View File

@@ -1,15 +1,14 @@
import { cacheHandlers } from "../../../cache.ts";
import { rest } from "../../../rest/rest.ts";
import { endpoints } from "../../../util/constants.ts";
import { requireBotGuildPermissions } from "../../../util/permissions.ts";
import type { Bot } from "../../../bot.ts";
/** Delete a thread in your server. Bot needs MANAGE_THREADS permissions in the server. */
export async function deleteThread(threadId: bigint, reason?: string) {
const thread = await cacheHandlers.get("threads", threadId);
export async function deleteThread(bot: Bot, threadId: bigint, reason?: string) {
const thread = await bot.cache.threads.get(threadId);
if (thread) {
const channel = await cacheHandlers.get("channels", thread?.parentId);
if (channel?.guildId) await requireBotGuildPermissions(channel.guildId, ["MANAGE_THREADS"]);
const channel = await bot.cache.channels.get(thread?.parentId);
if (channel?.guildId) await bot.utils.requireBotGuildPermissions(bot, channel.guildId, ["MANAGE_THREADS"]);
}
return await rest.runMethod<undefined>("delete", endpoints.CHANNEL_BASE(threadId), { reason });
return await bot.rest.runMethod<undefined>(bot.rest, "delete", bot.constants.endpoints.CHANNEL_BASE(threadId), {
reason,
});
}

View File

@@ -1,23 +1,21 @@
import { rest } from "../../../rest/rest.ts";
import { ModifyThread } from "../../../types/channels/threads/modify_thread.ts";
import { endpoints } from "../../../util/constants.ts";
import type { ModifyThread } from "../../../types/channels/threads/modify_thread.ts";
import type { Bot } from "../../../bot.ts";
import { channelToThread } from "../../../util/transformers/channel_to_thread.ts";
import { snakelize } from "../../../util/utils.ts";
/** Update a thread's settings. Requires the `MANAGE_CHANNELS` permission for the guild. */
export async function editThread(threadId: bigint, options: ModifyThread, reason?: string) {
export async function editThread(bot: Bot, threadId: bigint, options: ModifyThread, reason?: string) {
// const thread = await cacheHandlers.get("threads", threadId);
// TODO: permission checking
const result = await rest.runMethod(
"patch",
endpoints.CHANNEL_BASE(threadId),
snakelize({
...options,
reason,
})
);
const result = await bot.rest.runMethod(bot.rest, "patch", bot.constants.endpoints.CHANNEL_BASE(threadId), {
name: options.name,
archived: options.archived,
auto_archive_duration: options.autoArchiveDuration,
locked: options.locked,
rate_limit_per_user: options.rateLimitPerUser,
reason,
});
return channelToThread(result);
}

View File

@@ -1,17 +1,18 @@
import { rest } from "../../../rest/rest.ts";
import { ListActiveThreads } from "../../../types/channels/threads/list_active_threads.ts";
import { snowflakeToBigint } from "../../../util/bigint.ts";
import type { Bot } from "../../../bot.ts";
import type { ListActiveThreads } from "../../../types/channels/threads/list_active_threads.ts";
import { Collection } from "../../../util/collection.ts";
import { endpoints } from "../../../util/constants.ts";
import { requireBotChannelPermissions } from "../../../util/permissions.ts";
import { channelToThread } from "../../../util/transformers/channel_to_thread.ts";
/** Returns all active threads in the channel, including public and private threads. Threads are ordered by their id, in descending order. Requires the VIEW_CHANNEL permission. */
export async function getActiveThreads(channelId: bigint) {
await requireBotChannelPermissions(channelId, ["VIEW_CHANNEL"]);
export async function getActiveThreads(bot: Bot, channelId: bigint) {
await bot.utils.requireBotChannelPermissions(bot, channelId, ["VIEW_CHANNEL"]);
// TODO: pagination
const result = (await rest.runMethod("get", endpoints.THREAD_ACTIVE(channelId))) as ListActiveThreads;
const result = (await bot.rest.runMethod(
bot.rest,
"get",
bot.constants.endpoints.THREAD_ACTIVE(channelId)
)) as ListActiveThreads;
const threads = new Collection(
result.threads.map((t) => {
@@ -21,9 +22,9 @@ export async function getActiveThreads(channelId: bigint) {
);
for (const member of result.members) {
const thread = threads.get(snowflakeToBigint(member.id!));
thread?.members.set(snowflakeToBigint(member.userId!), {
userId: snowflakeToBigint(member.userId!),
const thread = threads.get(bot.transformers.snowflake(member.id!));
thread?.members.set(bot.transformers.snowflake(member.userId!), {
userId: bot.transformers.snowflake(member.userId!),
flags: member.flags,
joinTimestamp: Date.parse(member.joinTimestamp),
});

View File

@@ -1,16 +1,13 @@
import { rest } from "../../../rest/rest.ts";
import { ListActiveThreads } from "../../../types/channels/threads/list_active_threads.ts";
import { ListPublicArchivedThreads } from "../../../types/channels/threads/list_public_archived_threads.ts";
import { PermissionStrings } from "../../../types/permissions/permission_strings.ts";
import { snowflakeToBigint } from "../../../util/bigint.ts";
import { Collection } from "../../../util/collection.ts";
import { endpoints } from "../../../util/constants.ts";
import { requireBotChannelPermissions } from "../../../util/permissions.ts";
import type { Bot } from "../../../bot.ts";
import { channelToThread } from "../../../util/transformers/channel_to_thread.ts";
import { snakelize } from "../../../util/utils.ts";
/** Get the archived threads for this channel, defaults to public */
export async function getArchivedThreads(
bot: Bot,
channelId: bigint,
options?: ListPublicArchivedThreads & {
type?: "public" | "private" | "privateJoinedThreads";
@@ -19,18 +16,25 @@ export async function getArchivedThreads(
const permissions = new Set<PermissionStrings>(["READ_MESSAGE_HISTORY"]);
if (options?.type === "private") permissions.add("MANAGE_THREADS");
await requireBotChannelPermissions(channelId, [...permissions]);
await bot.utils.requireBotChannelPermissions(bot, channelId, [...permissions]);
// TODO: pagination
const result = (await rest.runMethod(
const result = (await bot.rest.runMethod(
bot.rest,
"get",
options?.type === "privateJoinedThreads"
? endpoints.THREAD_ARCHIVED_PRIVATE_JOINED(channelId)
? bot.constants.endpoints.THREAD_ARCHIVED_PRIVATE_JOINED(channelId)
: options?.type === "private"
? endpoints.THREAD_ARCHIVED_PRIVATE(channelId)
: endpoints.THREAD_ARCHIVED_PUBLIC(channelId),
snakelize(options ?? {})
? bot.constants.endpoints.THREAD_ARCHIVED_PRIVATE(channelId)
: bot.constants.endpoints.THREAD_ARCHIVED_PUBLIC(channelId),
options
? {
before: options.before,
limit: options.limit,
type: options.type,
}
: {}
)) as ListActiveThreads;
const threads = new Collection(
@@ -41,9 +45,9 @@ export async function getArchivedThreads(
);
for (const member of result.members) {
const thread = threads.get(snowflakeToBigint(member.id!));
thread?.members.set(snowflakeToBigint(member.userId!), {
userId: snowflakeToBigint(member.userId!),
const thread = threads.get(bot.transformers.snowflake(member.id!));
thread?.members.set(bot.transformers.snowflake(member.userId!), {
userId: bot.transformers.snowflake(member.userId!),
flags: member.flags,
joinTimestamp: Date.parse(member.joinTimestamp),
});

View File

@@ -1,29 +1,30 @@
import { cacheHandlers } from "../../../cache.ts";
import { rest } from "../../../rest/rest.ts";
import type { Bot } from "../../../bot.ts";
import { ThreadMember } from "../../../types/channels/threads/thread_member.ts";
import { Errors } from "../../../types/discordeno/errors.ts";
import { DiscordGatewayIntents } from "../../../types/gateway/gateway_intents.ts";
import { Collection } from "../../../util/collection.ts";
import { endpoints } from "../../../util/constants.ts";
import { botHasChannelPermissions } from "../../../util/permissions.ts";
import { threadMemberModified } from "../../../util/transformers/thread_member_modified.ts";
import { ws } from "../../../ws/ws.ts";
/** Returns thread members objects that are members of the thread. */
export async function getThreadMembers(threadId: bigint) {
export async function getThreadMembers(bot: Bot, threadId: bigint) {
// Check if intents is not 0 as proxy ws won't set intents in other instances
if (ws.identifyPayload.intents && !(ws.identifyPayload.intents & DiscordGatewayIntents.GuildMembers)) {
throw new Error(Errors.MISSING_INTENT_GUILD_MEMBERS);
if (
bot.gateway.identifyPayload.intents &&
!(bot.gateway.identifyPayload.intents & DiscordGatewayIntents.GuildMembers)
) {
throw new Error(bot.constants.Errors.MISSING_INTENT_GUILD_MEMBERS);
}
const thread = await cacheHandlers.get("threads", threadId);
const thread = await bot.cache.threads.get(threadId);
if (thread?.isPrivate) {
const channel = await cacheHandlers.get("channels", thread.parentId);
if (channel && !(await botHasChannelPermissions(channel, ["MANAGE_THREADS"])) && !thread.botIsMember)
throw new Error(Errors.CANNOT_GET_MEMBERS_OF_AN_UNJOINED_PRIVATE_THREAD);
const channel = await bot.cache.channels.get(thread.parentId);
if (channel && !(await bot.utils.botHasChannelPermissions(bot, channel, ["MANAGE_THREADS"])) && !thread.botIsMember)
throw new Error(bot.constants.Errors.CANNOT_GET_MEMBERS_OF_AN_UNJOINED_PRIVATE_THREAD);
}
const result = await rest.runMethod<ThreadMember[]>("get", endpoints.THREAD_MEMBERS(threadId));
const result = await bot.rest.runMethod<ThreadMember[]>(
bot.rest,
"get",
bot.constants.endpoints.THREAD_MEMBERS(threadId)
);
const members = result.map((member) => threadMemberModified(member));

View File

@@ -1,14 +1,11 @@
import { cacheHandlers } from "../../../cache.ts";
import { rest } from "../../../rest/rest.ts";
import { Errors } from "../../../types/discordeno/errors.ts";
import { endpoints } from "../../../util/constants.ts";
import type { Bot } from "../../../bot.ts";
/** Adds the bot to the thread. Cannot join an archived thread. */
export async function joinThread(threadId: bigint) {
const thread = await cacheHandlers.get("threads", threadId);
export async function joinThread(bot: Bot, threadId: bigint) {
const thread = await bot.cache.threads.get(threadId);
if (thread?.archived) {
throw new Error(Errors.CANNOT_ADD_USER_TO_ARCHIVED_THREADS);
throw new Error(bot.contants.Errors.CANNOT_ADD_USER_TO_ARCHIVED_THREADS);
}
return await rest.runMethod<undefined>("put", endpoints.THREAD_ME(threadId));
return await bot.rest.runMethod<undefined>(bot.rest, "put", bot.constants.endpoints.THREAD_ME(threadId));
}

View File

@@ -1,12 +1,9 @@
import { cacheHandlers } from "../../../cache.ts";
import { rest } from "../../../rest/rest.ts";
import { Errors } from "../../../types/discordeno/errors.ts";
import { endpoints } from "../../../util/constants.ts";
import type { Bot } from "../../../bot.ts";
/** Removes the bot from a thread. Requires the thread is not archived. */
export async function leaveThread(threadId: bigint) {
const thread = await cacheHandlers.get("threads", threadId);
if (thread?.archived) throw new Error(Errors.CANNOT_LEAVE_ARCHIVED_THREAD);
export async function leaveThread(bot: Bot, threadId: bigint) {
const thread = await bot.cache.threads.get(threadId);
if (thread?.archived) throw new Error(bot.constants.Errors.CANNOT_LEAVE_ARCHIVED_THREAD);
return await rest.runMethod<undefined>("delete", endpoints.THREAD_ME(threadId));
return await bot.rest.runMethod<undefined>(bot.rest, "delete", bot.constants.endpoints.THREAD_ME(threadId));
}

View File

@@ -1,6 +1,6 @@
import { editThread } from "./edit_thread.ts";
import type { Bot } from "../../../bot.ts";
/** Sets a thread channel to be locked. */
export async function lockThread(threadId: bigint) {
return await editThread(threadId, { locked: true });
export async function lockThread(bot: Bot, threadId: bigint) {
return await bot.utils.editThread(bot, threadId, { locked: true });
}

View File

@@ -1,21 +1,16 @@
import { botId } from "../../../bot.ts";
import { cacheHandlers } from "../../../cache.ts";
import { rest } from "../../../rest/rest.ts";
import { Errors } from "../../../types/discordeno/errors.ts";
import { endpoints } from "../../../util/constants.ts";
import { requireBotChannelPermissions } from "../../../util/permissions.ts";
import type { Bot } from "../../../bot.ts";
/** Removes a user from a thread. Requires the MANAGE_THREADS permission or that you are the creator of the thread. Also requires the thread is not archived. */
export async function removeThreadMember(threadId: bigint, userId: bigint) {
const thread = await cacheHandlers.get("threads", threadId);
export async function removeThreadMember(bot: Bot, threadId: bigint, userId: bigint) {
const thread = await bot.cache.threads.get(threadId);
if (thread) {
if (thread.archived) throw new Error(Errors.CANNOT_REMOVE_FROM_ARCHIVED_THREAD);
if (thread.archived) throw new Error(bot.constants.Errors.CANNOT_REMOVE_FROM_ARCHIVED_THREAD);
if (thread.ownerId !== botId) {
const channel = await cacheHandlers.get("channels", thread.parentId);
if (channel) await requireBotChannelPermissions(channel, ["MANAGE_THREADS"]);
if (thread.ownerId !== bot.id) {
const channel = await bot.cache.channels.get(thread.parentId);
if (channel) await bot.utils.requireBotChannelPermissions(bot, channel, ["MANAGE_THREADS"]);
}
}
return await rest.runMethod<undefined>("delete", endpoints.THREAD_USER(threadId, userId));
return await bot.rest.runMethod<undefined>(bot.rest, "delete", bot.constants.endpoints.THREAD_USER(threadId, userId));
}

View File

@@ -1,25 +1,23 @@
import { cacheHandlers } from "../../../cache.ts";
import { rest } from "../../../rest/rest.ts";
import { Channel } from "../../../types/channels/channel.ts";
import { StartThread } from "../../../types/channels/threads/start_thread.ts";
import { Errors } from "../../../types/discordeno/errors.ts";
import { endpoints } from "../../../util/constants.ts";
import { requireBotChannelPermissions } from "../../../util/permissions.ts";
import type { Channel } from "../../../types/channels/channel.ts";
import type { StartThread } from "../../../types/channels/threads/start_thread.ts";
import type { Bot } from "../../../bot.ts";
import { channelToThread } from "../../../util/transformers/channel_to_thread.ts";
import { snakelize } from "../../../util/utils.ts";
/** Creates a new private thread. Returns a thread channel. */
export async function startPrivateThread(channelId: bigint, options: StartThread) {
const channel = await cacheHandlers.get("channels", channelId);
export async function startPrivateThread(bot: Bot, channelId: bigint, options: StartThread) {
const channel = await bot.cache.channels.get(channelId);
if (channel) {
if (!channel.isGuildTextBasedChannel) throw new Error(Errors.INVALID_THREAD_PARENT_CHANNEL_TYPE);
if (!channel.isGuildTextBasedChannel) throw new Error(bot.constants.Errors.INVALID_THREAD_PARENT_CHANNEL_TYPE);
if (channel.isNewsChannel) throw new Error(Errors.GUILD_NEWS_CHANNEL_ONLY_SUPPORT_PUBLIC_THREADS);
if (channel.isNewsChannel) throw new Error(bot.constants.Errors.GUILD_NEWS_CHANNEL_ONLY_SUPPORT_PUBLIC_THREADS);
await requireBotChannelPermissions(channel, ["SEND_MESSAGES", "USE_PRIVATE_THREADS"]);
await bot.utils.requireBotChannelPermissions(bot, channel, ["SEND_MESSAGES", "USE_PRIVATE_THREADS"]);
}
return channelToThread(
await rest.runMethod<Channel>("post", endpoints.THREAD_START_PRIVATE(channelId), snakelize(options))
await bot.rest.runMethod<Channel>(bot.rest, "post", bot.constants.endpoints.THREAD_START_PRIVATE(channelId), {
name: options.name,
auto_archive_duration: options.autoArchiveDuration,
})
);
}

View File

@@ -1,25 +1,28 @@
import { cacheHandlers } from "../../../cache.ts";
import { rest } from "../../../rest/rest.ts";
import { Channel } from "../../../types/channels/channel.ts";
import { StartThread } from "../../../types/channels/threads/start_thread.ts";
import { Errors } from "../../../types/discordeno/errors.ts";
import { endpoints } from "../../../util/constants.ts";
import { requireBotChannelPermissions } from "../../../util/permissions.ts";
import type { Channel } from "../../../types/channels/channel.ts";
import type { StartThread } from "../../../types/channels/threads/start_thread.ts";
import type { Bot } from "../../../bot.ts";
import { channelToThread } from "../../../util/transformers/channel_to_thread.ts";
import { snakelize } from "../../../util/utils.ts";
/** Creates a new public thread from an existing message. Returns a thread channel. */
export async function startThread(channelId: bigint, messageId: bigint, options: StartThread) {
const channel = await cacheHandlers.get("channels", channelId);
export async function startThread(bot: Bot, channelId: bigint, messageId: bigint, options: StartThread) {
const channel = await bot.cache.channels.get(channelId);
if (channel) {
if (!channel.isGuildTextBasedChannel) {
throw new Error(Errors.INVALID_THREAD_PARENT_CHANNEL_TYPE);
throw new Error(bot.constants.Errors.INVALID_THREAD_PARENT_CHANNEL_TYPE);
}
await requireBotChannelPermissions(channel, ["SEND_MESSAGES", "USE_PUBLIC_THREADS"]);
await bot.utils.requireBotChannelPermissions(bot, channel, ["SEND_MESSAGES", "USE_PUBLIC_THREADS"]);
}
return channelToThread(
await rest.runMethod<Channel>("post", endpoints.THREAD_START_PUBLIC(channelId, messageId), snakelize(options))
await bot.rest.runMethod<Channel>(
bot.rest,
"post",
bot.constants.endpoints.THREAD_START_PUBLIC(channelId, messageId),
{
name: options.name,
auto_archive_duration: options.autoArchiveDuration,
}
)
);
}

View File

@@ -1,6 +1,6 @@
import { editThread } from "./edit_thread.ts";
import type { Bot } from "../../../bot.ts";
/** Sets a thread channel to be unarchived. */
export async function unarchiveThread(threadId: bigint) {
return await editThread(threadId, { archived: false });
export async function unarchiveThread(bot: Bot, threadId: bigint) {
return await bot.helpers.editThread(bot, threadId, { archived: false });
}

View File

@@ -1,6 +1,6 @@
import { editThread } from "./edit_thread.ts";
import type { Bot } from "../../../bot.ts";
/** Sets a thread channel to be unlocked. */
export async function unlockThread(threadId: bigint) {
return await editThread(threadId, { locked: false });
export async function unlockThread(bot: Bot, threadId: bigint) {
return await bot.helpers.editThread(bot, threadId, { locked: false });
}

View File

@@ -1,37 +1,35 @@
import { rest } from "../../rest/rest.ts";
import { Errors } from "../../types/discordeno/errors.ts";
import type { StageInstance } from "../../types/channels/stage_instance.ts";
import { endpoints } from "../../util/constants.ts";
import { validateLength } from "../../util/validate_length.ts";
import { cacheHandlers } from "../../cache.ts";
import { requireBotChannelPermissions } from "../../util/permissions.ts";
import { ChannelTypes } from "../../types/channels/channel_types.ts";
import { snakelize } from "../../util/utils.ts";
import type { Bot } from "../../bot.ts";
import type { ChannelTypes } from "../../types/channels/channel_types.ts";
/** Updates fields of an existing Stage instance. Requires the user to be a moderator of the Stage channel. */
export async function updateStageInstance(
bot: Bot,
channelId: bigint,
data: Partial<Pick<StageInstance, "topic" | "privacyLevel">> = {}
) {
const channel = await cacheHandlers.get("channels", channelId);
const channel = await bot.cache.channels.get(channelId);
if (channel) {
if (channel.type !== ChannelTypes.GuildStageVoice) {
throw new Error(Errors.CHANNEL_NOT_STAGE_VOICE);
throw new Error(bot.constants.Errors.CHANNEL_NOT_STAGE_VOICE);
}
await requireBotChannelPermissions(channel, ["MOVE_MEMBERS", "MUTE_MEMBERS", "MANAGE_CHANNELS"]);
await bot.utils.requireBotChannelPermissions(channel, ["MOVE_MEMBERS", "MUTE_MEMBERS", "MANAGE_CHANNELS"]);
}
if (
data?.topic &&
!validateLength(data.topic, {
!bot.utils.validateLength(data.topic, {
min: 1,
max: 120,
})
) {
throw new Error(Errors.INVALID_TOPIC_LENGTH);
throw new Error(bot.constants.Errors.INVALID_TOPIC_LENGTH);
}
return await rest.runMethod<StageInstance>("patch", endpoints.STAGE_INSTANCE(channelId), snakelize(data));
return await bot.rest.runMethod<StageInstance>(bot.rest,"patch", bot.constants.endpoints.STAGE_INSTANCE(channelId), {
topic: data.topic,
privacy_level: data.privacyLevel
});
}

View File

@@ -1,8 +1,6 @@
import { rest } from "../../rest/rest.ts";
import { UpdateOthersVoiceState } from "../../types/guilds/update_others_voice_state.ts";
import type { UpdateOthersVoiceState } from "../../types/guilds/update_others_voice_state.ts";
import type { UpdateSelfVoiceState } from "../../types/guilds/update_self_voice_state.ts";
import { endpoints } from "../../util/constants.ts";
import { hasOwnProperty, snakelize } from "../../util/utils.ts";
import type { Bot } from "../../bot.ts";
/**
* Updates the a user's voice state, defaults to the current user
@@ -19,9 +17,15 @@ export async function updateBotVoiceState(
guildId: bigint,
options: UpdateSelfVoiceState | ({ userId: bigint } & UpdateOthersVoiceState)
) {
return await rest.runMethod(
return await bot.rest.runMethod(
bot.rest,
"patch",
endpoints.UPDATE_VOICE_STATE(guildId, hasOwnProperty(options, "userId") ? options.userId : undefined),
snakelize(options)
bot.constants.endpoints.UPDATE_VOICE_STATE(guildId, bot.utils.hasOwnProperty(options, "userId") ? options.userId : undefined),
{
channel_id: options.channelId,
suppress: options.suppress,
request_to_speak_timestamp: options.requestToSpeakTimestamp,
user_id: options.userId
}
);
}

View File

@@ -1,14 +1,14 @@
import { rest } from "../../rest/rest.ts";
import type { AddGuildDiscoverySubcategory } from "../../types/discovery/add_guild_discovery_subcategory.ts";
import { endpoints } from "../../util/constants.ts";
import { requireBotGuildPermissions } from "../../util/permissions.ts";
import type { Bot } from "../../bot.ts";
import { SnakeCasedPropertiesDeep } from "../../types/util.ts";
/** Add a discovery subcategory to the guild. Requires the `MANAGE_GUILD` permission. */
export async function addDiscoverySubcategory(guildId: bigint, categoryId: number) {
await requireBotGuildPermissions(guildId, ["MANAGE_GUILD"]);
export async function addDiscoverySubcategory(bot: Bot, guildId: bigint, categoryId: number) {
await bot.utils.requireBotGuildPermissions(bot, guildId, ["MANAGE_GUILD"]);
return await rest.runMethod<AddGuildDiscoverySubcategory>(
return await bot.rest.runMethod<SnakeCasedPropertiesDeep<AddGuildDiscoverySubcategory>>(
bot.rest,
"post",
endpoints.DISCOVERY_SUBCATEGORY(guildId, categoryId)
bot.constants.endpoints.DISCOVERY_SUBCATEGORY(guildId, categoryId)
);
}

View File

@@ -1,13 +1,20 @@
import { rest } from "../../rest/rest.ts";
import type { DiscoveryMetadata } from "../../types/discovery/discovery_metadata.ts";
import type { ModifyGuildDiscoveryMetadata } from "../../types/discovery/modify_guild_discovery_metadata.ts";
import { endpoints } from "../../util/constants.ts";
import { requireBotGuildPermissions } from "../../util/permissions.ts";
import { snakelize } from "../../util/utils.ts";
import { SnakeCasedPropertiesDeep } from "../../types/util.ts";
import type { Bot } from "../../bot.ts";
/** Modify the discovery metadata for the guild. Requires the MANAGE_GUILD permission. Returns the updated discovery metadata object on success. */
export async function editDiscovery(guildId: bigint, data: ModifyGuildDiscoveryMetadata) {
await requireBotGuildPermissions(guildId, ["MANAGE_GUILD"]);
export async function editDiscovery(bot: Bot, guildId: bigint, data: ModifyGuildDiscoveryMetadata) {
await bot.utils.requireBotGuildPermissions(bot, guildId, ["MANAGE_GUILD"]);
return await rest.runMethod<DiscoveryMetadata>("patch", endpoints.DISCOVERY_METADATA(guildId), snakelize(data));
return await bot.rest.runMethod<SnakeCasedPropertiesDeep<DiscoveryMetadata>>(
bot.rest,
"patch",
bot.constants.endpoints.DISCOVERY_METADATA(guildId),
{
primary_category_id: data.primaryCategoryId,
keywords: data.keywords,
emoji_discoverability_enabled: data.emojiDiscoverabilityEnabled,
}
);
}

View File

@@ -1,11 +1,14 @@
import { rest } from "../../rest/rest.ts";
import type { DiscoveryMetadata } from "../../types/discovery/discovery_metadata.ts";
import { endpoints } from "../../util/constants.ts";
import { requireBotGuildPermissions } from "../../util/permissions.ts";
import { SnakeCasedPropertiesDeep } from "../../types/util.ts";
import type { Bot } from "../../bot.ts";
/** Returns the discovery metadata object for the guild. Requires the `MANAGE_GUILD` permission. */
export async function getDiscovery(guildId: bigint) {
await requireBotGuildPermissions(guildId, ["MANAGE_GUILD"]);
export async function getDiscovery(bot: Bot, guildId: bigint) {
await bot.utils.requireBotGuildPermissions(bot, guildId, ["MANAGE_GUILD"]);
return await rest.runMethod<DiscoveryMetadata>("get", endpoints.DISCOVERY_METADATA(guildId));
return await bot.rest.runMethod<SnakeCasedPropertiesDeep<DiscoveryMetadata>>(
bot.rest,
"get",
bot.constants.endpoints.DISCOVERY_METADATA(guildId)
);
}

View File

@@ -1,11 +1,17 @@
import { rest } from "../../rest/rest.ts";
import type { DiscoveryCategory } from "../../types/discovery/discovery_category.ts";
import { Collection } from "../../util/collection.ts";
import { endpoints } from "../../util/constants.ts";
import type { Bot } from "../../bot.ts";
import { SnakeCasedPropertiesDeep } from "../../types/util.ts";
/** Returns a Collection (mapped by Id of the discovery category object) of discovery category objects that can be used when editing guilds */
export async function getDiscoveryCategories() {
const result = await rest.runMethod<DiscoveryCategory[]>("get", endpoints.DISCOVERY_CATEGORIES);
export async function getDiscoveryCategories(bot: Bot) {
const result = await bot.rest.runMethod<SnakeCasedPropertiesDeep<DiscoveryCategory>[]>(
bot.rest,
"get",
bot.constants.endpoints.DISCOVERY_CATEGORIES
);
return new Collection<number, DiscoveryCategory>(result.map((category) => [category.id, category]));
return new Collection<number, SnakeCasedPropertiesDeep<DiscoveryCategory>>(
result.map((category) => [category.id, category])
);
}

View File

@@ -1,10 +1,12 @@
import { rest } from "../../rest/rest.ts";
import { endpoints } from "../../util/constants.ts";
import { requireBotGuildPermissions } from "../../util/permissions.ts";
import type { Bot } from "../../bot.ts";
/** Removes a discovery subcategory from the guild. Requires the MANAGE_GUILD permission. Returns a 204 No Content on success. */
export async function removeDiscoverySubcategory(guildId: bigint, categoryId: number) {
await requireBotGuildPermissions(guildId, ["MANAGE_GUILD"]);
export async function removeDiscoverySubcategory(bot: Bot, guildId: bigint, categoryId: number) {
await bot.utils.requireBotGuildPermissions(bot, guildId, ["MANAGE_GUILD"]);
return await rest.runMethod<undefined>("delete", endpoints.DISCOVERY_SUBCATEGORY(guildId, categoryId));
return await bot.rest.runMethod<undefined>(
bot.rest,
"delete",
bot.constants.endpoints.DISCOVERY_SUBCATEGORY(guildId, categoryId)
);
}

View File

@@ -1,9 +1,13 @@
import { rest } from "../../rest/rest.ts";
import type { ValidateDiscoverySearchTerm } from "../../types/discovery/validate_discovery_search_term.ts";
import { endpoints } from "../../util/constants.ts";
import type { Bot } from "../../bot.ts";
import { SnakeCasedPropertiesDeep } from "../../types/util.ts";
export async function validDiscoveryTerm(term: string) {
const result = await rest.runMethod<ValidateDiscoverySearchTerm>("get", endpoints.DISCOVERY_VALID_TERM, { term });
export async function validDiscoveryTerm(bot: Bot, term: string) {
const result = await bot.rest.runMethod<SnakeCasedPropertiesDeep<ValidateDiscoverySearchTerm>>(
"get",
bot.constants.endpoints.DISCOVERY_VALID_TERM,
{ term }
);
return result.valid;
}

View File

@@ -1,27 +1,28 @@
import { rest } from "../../rest/rest.ts";
import { CreateGuildEmoji } from "../../types/emojis/create_guild_emoji.ts";
import type { CreateGuildEmoji } from "../../types/emojis/create_guild_emoji.ts";
import type { Emoji } from "../../types/emojis/emoji.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
import { endpoints } from "../../util/constants.ts";
import { requireBotGuildPermissions } from "../../util/permissions.ts";
import { urlToBase64 } from "../../util/utils.ts";
import type { Bot } from "../../bot.ts";
import type { SnakeCasedPropertiesDeep } from "../../types/util.ts";
/** Create an emoji in the server. Emojis and animated emojis have a maximum file size of 256kb. Attempting to upload an emoji larger than this limit will fail and return 400 Bad Request and an error message, but not a JSON status code. If a URL is provided to the image parameter, Discordeno will automatically convert it to a base64 string internally. */
export async function createEmoji(guildId: bigint, name: string, image: string, options: CreateGuildEmoji) {
await requireBotGuildPermissions(guildId, ["MANAGE_EMOJIS"]);
export async function createEmoji(bot: Bot, guildId: bigint, name: string, image: string, options: CreateGuildEmoji) {
await bot.utils.requireBotGuildPermissions(bot, guildId, ["MANAGE_EMOJIS"]);
if (image && !image.startsWith("data:image/")) {
image = await urlToBase64(image);
image = await bot.utils.urlToBase64(image);
}
const emoji = await rest.runMethod<Emoji>("post", endpoints.GUILD_EMOJIS(guildId), {
...options,
name,
image,
});
const emoji = await bot.rest.runMethod<SnakeCasedPropertiesDeep<Emoji>>(
"post",
bot.constants.endpoints.GUILD_EMOJIS(guildId),
{
...options,
name,
image,
}
);
return {
...emoji,
id: snowflakeToBigint(emoji.id!),
id: bot.transformers.snowflake(emoji.id!),
};
}

View File

@@ -1,10 +1,10 @@
import { rest } from "../../rest/rest.ts";
import { endpoints } from "../../util/constants.ts";
import { requireBotGuildPermissions } from "../../util/permissions.ts";
import type { Bot } from "../../bot.ts";
/** Delete the given emoji. Requires the MANAGE_EMOJIS permission. Returns 204 No Content on success. */
export async function deleteEmoji(guildId: bigint, id: bigint, reason?: string) {
await requireBotGuildPermissions(guildId, ["MANAGE_EMOJIS"]);
export async function deleteEmoji(bot: Bot, guildId: bigint, id: bigint, reason?: string) {
await bot.utils.requireBotGuildPermissions(bot, guildId, ["MANAGE_EMOJIS"]);
return await rest.runMethod<undefined>("delete", endpoints.GUILD_EMOJI(guildId, id), { reason });
return await bot.rest.runMethod<undefined>(bot.rest, "delete", bot.constants.endpoints.GUILD_EMOJI(guildId, id), {
reason,
});
}

View File

@@ -1,12 +1,15 @@
import { rest } from "../../rest/rest.ts";
import type { Emoji } from "../../types/emojis/emoji.ts";
import type { ModifyGuildEmoji } from "../../types/emojis/modify_guild_emoji.ts";
import { endpoints } from "../../util/constants.ts";
import { requireBotGuildPermissions } from "../../util/permissions.ts";
import type { Bot } from "../../bot.ts";
import type { SnakeCasedPropertiesDeep } from "../../types/util.ts";
/** Modify the given emoji. Requires the MANAGE_EMOJIS permission. */
export async function editEmoji(guildId: bigint, id: bigint, options: ModifyGuildEmoji) {
await requireBotGuildPermissions(guildId, ["MANAGE_EMOJIS"]);
export async function editEmoji(bot: Bot, guildId: bigint, id: bigint, options: ModifyGuildEmoji) {
await bot.utils.requireBotGuildPermissions(bot, guildId, ["MANAGE_EMOJIS"]);
return await rest.runMethod<Emoji>("patch", endpoints.GUILD_EMOJI(guildId, id), options);
return await bot.rest.runMethod<SnakeCasedPropertiesDeep<Emoji>>(
"patch",
bot.constants.endpoints.GUILD_EMOJI(guildId, id),
options
);
}

View File

@@ -1,22 +1,20 @@
import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts";
import type { Emoji } from "../../types/emojis/emoji.ts";
import { Errors } from "../../types/discordeno/errors.ts";
import { endpoints } from "../../util/constants.ts";
import type { Bot } from "../../bot.ts";
/**
* Returns an emoji for the given guild and emoji Id.
*
* ⚠️ **If you need this, you are probably doing something wrong. Always use cache.guilds.get()?.emojis
*/
export async function getEmoji(guildId: bigint, emojiId: bigint, addToCache = true) {
const result = await rest.runMethod<Emoji>("get", endpoints.GUILD_EMOJI(guildId, emojiId));
export async function getEmoji(bot: Bot, guildId: bigint, emojiId: bigint, addToCache = true) {
const result = await bot.rest.runMethod<Emoji>("get", bot.constants.endpoints.GUILD_EMOJI(guildId, emojiId));
if (addToCache) {
const guild = await cacheHandlers.get("guilds", guildId);
const guild = await bot.cache.guilds.get(guildId);
if (!guild) throw new Error(Errors.GUILD_NOT_FOUND);
guild.emojis.set(emojiId, result);
await cacheHandlers.set("guilds", guildId, guild);
await bot.cache.guilds.set(guildId, guild);
}
return result;

View File

@@ -1,30 +1,26 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts";
import type { Bot } from "../../bot.ts";
import type { Emoji } from "../../types/emojis/emoji.ts";
import { Errors } from "../../types/discordeno/errors.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
import { Collection } from "../../util/collection.ts";
import { endpoints } from "../../util/constants.ts";
/**
* Returns a list of emojis for the given guild.
*
* ⚠️ **If you need this, you are probably doing something wrong. Always use cache.guilds.get()?.emojis
*/
export async function getEmojis(guildId: bigint, addToCache = true) {
const result = await rest.runMethod<Emoji[]>("get", endpoints.GUILD_EMOJIS(guildId));
export async function getEmojis(bot: Bot, guildId: bigint, addToCache = true) {
const result = await bot.rest.runMethod<Emoji[]>(bot.rest, "get", bot.constants.endpoints.GUILD_EMOJIS(guildId));
if (addToCache) {
const guild = await cacheHandlers.get("guilds", guildId);
const guild = await bot.cache.guilds.get("guilds", guildId);
if (!guild) throw new Error(Errors.GUILD_NOT_FOUND);
result.forEach((emoji) => {
eventHandlers.debug?.("loop", `Running forEach loop in get_emojis file.`);
guild.emojis.set(snowflakeToBigint(emoji.id!), emoji);
bot.events.debug("loop", `Running forEach loop in get_emojis file.`);
guild.emojis.set(bot.transformers.snowflake(emoji.id!), emoji);
});
await cacheHandlers.set("guilds", guildId, guild);
await bot.cache.guilds.set(guildId, guild);
}
return new Collection(result.map((e) => [e.id!, e]));

View File

@@ -1,22 +1,28 @@
import { botId } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts";
import { structures } from "../../structures/mod.ts";
import type { CreateGuild } from "../../types/guilds/create_guild.ts";
import type { Guild } from "../../types/guilds/guild.ts";
import { endpoints } from "../../util/constants.ts";
import { snakelize } from "../../util/utils.ts";
import { getMember } from "../members/get_member.ts";
import type { Bot } from "../../bot.ts";
/** Create a new guild. Returns a guild object on success. Fires a Guild Create Gateway event. This endpoint can be used only by bots in less than 10 guilds. */
export async function createGuild(options: CreateGuild) {
const result = await rest.runMethod<Guild>("post", endpoints.GUILDS, snakelize(options));
export async function createGuild(bot: Bot, options: CreateGuild) {
const result = await bot.rest.runMethod<Guild>(bot.rest, "post", bot.constants.endpoints.GUILDS, {
name: options.name,
afk_channel_id: options.afkChannelId,
afk_timeout: options.afkTimeout,
channels: options.channels,
default_message_notifications: options.defaultMessageNotifications,
explicit_content_filter: options.explicitContentFilter,
icon: options.icon,
roles: options.roles,
system_channel_flags: options.systemChannelFlags,
system_channel_id: options.systemChannelId,
verification_level: options.verificationLevel,
});
const guild = await structures.createDiscordenoGuild(result, 0);
const guild = bot.transformers.guild(bot, { guild: result, shardId: 0 });
// MANUALLY CACHE THE GUILD
await cacheHandlers.set("guilds", guild.id, guild);
await bot.cache.guilds.set(guild.id, guild);
// MANUALLY CACHE THE BOT
await getMember(guild.id, botId);
await bot.helpers.getMember(bot, guild.id, bot.id);
return guild;
}

View File

@@ -1,7 +1,6 @@
import { rest } from "../../rest/rest.ts";
import { endpoints } from "../../util/constants.ts";
import type { Bot } from "../../bot.ts";
/** Delete a guild permanently. User must be owner. Returns 204 No Content on success. Fires a Guild Delete Gateway event. */
export async function deleteGuild(guildId: bigint) {
return await rest.runMethod<undefined>("delete", endpoints.GUILDS_BASE(guildId));
export async function deleteGuild(bot: Bot, guildId: bigint) {
return await bot.rest.runMethod<undefined>(bot.rest, "delete", bot.constants.endpoints.GUILDS_BASE(guildId));
}

View File

@@ -1,34 +1,29 @@
import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts";
import { structures } from "../../structures/mod.ts";
import type { Bot } from "../../bot.ts";
import type { Guild } from "../../types/guilds/guild.ts";
import type { ModifyGuild } from "../../types/guilds/modify_guild.ts";
import { endpoints } from "../../util/constants.ts";
import { requireBotGuildPermissions } from "../../util/permissions.ts";
import { snakelize, urlToBase64 } from "../../util/utils.ts";
import { ws } from "../../ws/ws.ts";
/** Modify a guilds settings. Requires the MANAGE_GUILD permission. */
export async function editGuild(guildId: bigint, options: ModifyGuild) {
await requireBotGuildPermissions(guildId, ["MANAGE_GUILD"]);
export async function editGuild(bot: Bot, guildId: bigint, options: ModifyGuild) {
await bot.utils.requireBotGuildPermissions(bot, guildId, ["MANAGE_GUILD"]);
if (options.icon && !options.icon.startsWith("data:image/")) {
options.icon = await urlToBase64(options.icon);
options.icon = await bot.utils.urlToBase64(options.icon);
}
if (options.banner && !options.banner.startsWith("data:image/")) {
options.banner = await urlToBase64(options.banner);
options.banner = await bot.utils.urlToBase64(options.banner);
}
if (options.splash && !options.splash.startsWith("data:image/")) {
options.splash = await urlToBase64(options.splash);
options.splash = await bot.utils.urlToBase64(options.splash);
}
const result = await rest.runMethod<Guild>("patch", endpoints.GUILDS_BASE(guildId), snakelize(options));
const result = await bot.rest.runMethod<Guild>(bot.rest, "patch", bot.constants.endpoints.GUILDS_BASE(guildId), {});
const cached = await cacheHandlers.get("guilds", guildId);
return structures.createDiscordenoGuild(
result,
cached?.shardId || Number((BigInt(result.id) >> 22n % BigInt(ws.botGatewayData.shards)).toString())
);
const cached = await bot.cache.guilds.get(guildId);
return bot.transformers.guild(bot, {
guild: result,
shardId:
cached?.shardId || Number((BigInt(result.id) >> 22n % BigInt(bot.gateway.botGatewayData.shards)).toString()),
});
}

View File

@@ -1,9 +1,18 @@
import { rest } from "../../rest/rest.ts";
import type { ModifyGuildWelcomeScreen } from "../../types/guilds/modify_guild_welcome_screen.ts";
import type { WelcomeScreen } from "../../types/guilds/welcome_screen.ts";
import { endpoints } from "../../util/constants.ts";
import { snakelize } from "../../util/utils.ts";
import type { Bot } from "../../bot.ts";
export async function editWelcomeScreen(guildId: bigint, options: ModifyGuildWelcomeScreen) {
return await rest.runMethod<WelcomeScreen>("patch", endpoints.GUILD_WELCOME_SCREEN(guildId), snakelize(options));
export async function editWelcomeScreen(bot: Bot, guildId: bigint, options: ModifyGuildWelcomeScreen) {
return await bot.rest.runMethod<WelcomeScreen>("patch", bot.constants.endpoints.GUILD_WELCOME_SCREEN(guildId), {
enabled: options.enabled,
welcomeScreen: options.welcomeScreen?.map((welcomeScreen) => {
return {
channel_id: welcomeScreen.channelId,
description: welcomeScreen.description,
emoji_id: welcomeScreen.emojiId,
emoji_name: welcomeScreen.emojiName,
};
}),
description: options.description,
});
}

View File

@@ -1,13 +1,11 @@
import { rest } from "../../rest/rest.ts";
import type { GuildWidget } from "../../types/guilds/guild_widget.ts";
import { endpoints } from "../../util/constants.ts";
import { requireBotGuildPermissions } from "../../util/permissions.ts";
import type { Bot } from "../../bot.ts";
/** Modify a guild widget object for the guild. Requires the MANAGE_GUILD permission. */
export async function editWidget(guildId: bigint, enabled: boolean, channelId?: string | null) {
await requireBotGuildPermissions(guildId, ["MANAGE_GUILD"]);
export async function editWidget(bot: Bot, guildId: bigint, enabled: boolean, channelId?: string | null) {
await bot.utils.requireBotGuildPermissions(bot, guildId, ["MANAGE_GUILD"]);
return await rest.runMethod<GuildWidget>("patch", endpoints.GUILD_WIDGET(guildId), {
return await bot.rest.runMethod<GuildWidget>(bot.rest, "patch", bot.constants.endpoints.GUILD_WIDGET(guildId), {
enabled,
channel_id: channelId,
});

View File

@@ -1,20 +1,15 @@
import { rest } from "../../rest/rest.ts";
import type { AuditLog } from "../../types/audit_log/audit_log.ts";
import type { GetGuildAuditLog } from "../../types/audit_log/get_guild_audit_log.ts";
import { endpoints } from "../../util/constants.ts";
import { requireBotGuildPermissions } from "../../util/permissions.ts";
import { snakelize } from "../../util/utils.ts";
import type { Bot } from "../../bot.ts";
/** Returns the audit logs for the guild. Requires VIEW AUDIT LOGS permission */
export async function getAuditLogs(guildId: bigint, options?: GetGuildAuditLog) {
await requireBotGuildPermissions(guildId, ["VIEW_AUDIT_LOG"]);
export async function getAuditLogs(bot: Bot, guildId: bigint, options?: GetGuildAuditLog) {
await bot.utils.requireBotGuildPermissions(bot, guildId, ["VIEW_AUDIT_LOG"]);
return await rest.runMethod<AuditLog>(
"get",
endpoints.GUILD_AUDIT_LOGS(guildId),
snakelize({
...options,
limit: options?.limit && options.limit >= 1 && options.limit <= 100 ? options.limit : 50,
})
);
return await bot.rest.runMethod<AuditLog>(bot.rest, "get", bot.constants.endpoints.GUILD_AUDIT_LOGS(guildId), {
user_id: options.userId,
action_type: options.actionType,
before: options.before,
limit: options?.limit && options.limit >= 1 && options.limit <= 100 ? options.limit : 50,
});
}

View File

@@ -1,8 +1,7 @@
import { rest } from "../../rest/rest.ts";
import type { VoiceRegion } from "../../types/voice/voice_region.ts";
import { endpoints } from "../../util/constants.ts";
import type { Bot } from "../../bot.ts";
/** Returns an array of voice regions that can be used when creating servers. */
export async function getAvailableVoiceRegions() {
return await rest.runMethod<VoiceRegion>("get", endpoints.VOICE_REGIONS);
export async function getAvailableVoiceRegions(bot: Bot) {
return await bot.rest.runMethod<VoiceRegion>(bot.rest, "get", bot.constants.endpoints.VOICE_REGIONS);
}

View File

@@ -1,11 +1,9 @@
import { rest } from "../../rest/rest.ts";
import type { Ban } from "../../types/guilds/ban.ts";
import { endpoints } from "../../util/constants.ts";
import { requireBotGuildPermissions } from "../../util/permissions.ts";
import type { Bot } from "../../bot.ts";
/** Returns a ban object for the given user or a 404 not found if the ban cannot be found. Requires the BAN_MEMBERS permission. */
export async function getBan(guildId: bigint, memberId: bigint) {
await requireBotGuildPermissions(guildId, ["BAN_MEMBERS"]);
export async function getBan(bot: Bot, guildId: bigint, memberId: bigint) {
await bot.utils.requireBotGuildPermissions(bot, guildId, ["BAN_MEMBERS"]);
return await rest.runMethod<Ban>("get", endpoints.GUILD_BAN(guildId, memberId));
return await bot.rest.runMethod<Ban>(bot.rest, "get", bot.constants.endpoints.GUILD_BAN(guildId, memberId));
}

View File

@@ -1,15 +1,12 @@
import { rest } from "../../rest/rest.ts";
import type { Ban } from "../../types/guilds/ban.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
import type { Bot } from "../../bot.ts";
import { Collection } from "../../util/collection.ts";
import { endpoints } from "../../util/constants.ts";
import { requireBotGuildPermissions } from "../../util/permissions.ts";
/** Returns a list of ban objects for the users banned from this guild. Requires the BAN_MEMBERS permission. */
export async function getBans(guildId: bigint) {
await requireBotGuildPermissions(guildId, ["BAN_MEMBERS"]);
export async function getBans(bot: Bot, guildId: bigint) {
await bot.utils.requireBotGuildPermissions(bot, guildId, ["BAN_MEMBERS"]);
const results = await rest.runMethod<Ban[]>("get", endpoints.GUILD_BANS(guildId));
const results = await bot.rest.runMethod<Ban[]>(bot.rest, "get", bot.constants.endpoints.GUILD_BANS(guildId));
return new Collection<bigint, Ban>(results.map((res) => [snowflakeToBigint(res.user.id), res]));
return new Collection<bigint, Ban>(results.map((res) => [bot.transformers.snowflake(res.user.id), res]));
}

View File

@@ -1,9 +1,5 @@
import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts";
import { structures } from "../../structures/mod.ts";
import type { Guild } from "../../types/guilds/guild.ts";
import { endpoints } from "../../util/constants.ts";
import { ws } from "../../ws/ws.ts";
import type { Bot } from "../../bot.ts";
/**
* ⚠️ **If you need this, you are probably doing something wrong. Always use cache.guilds.get()
@@ -13,23 +9,24 @@ import { ws } from "../../ws/ws.ts";
* So it does not cache the guild, you must do it manually.
* */
export async function getGuild(
bot: Bot,
guildId: bigint,
options: { counts?: boolean; addToCache?: boolean } = {
counts: true,
addToCache: true,
}
) {
const result = await rest.runMethod<Guild>("get", endpoints.GUILDS_BASE(guildId), {
const result = await bot.rest.runMethod<Guild>(bot.rest, "get", bot.constants.endpoints.GUILDS_BASE(guildId), {
with_counts: options.counts,
});
const guild = await structures.createDiscordenoGuild(
result,
Number((BigInt(guildId) >> 22n) % BigInt(ws.botGatewayData.shards))
);
const guild = await bot.transformers.guild(bot, {
guild: result,
shardId: Number((BigInt(guildId) >> 22n) % BigInt(ws.botGatewayData.shards)),
});
if (options.addToCache) {
await cacheHandlers.set("guilds", guild.id, guild);
await bot.cache.guilds.set(guild.id, guild);
}
return guild;

View File

@@ -1,8 +1,7 @@
import { rest } from "../../rest/rest.ts";
import type { GuildPreview } from "../../types/guilds/guild_preview.ts";
import { endpoints } from "../../util/constants.ts";
import type { Bot } from "../../bot.ts";
/** Returns the guild preview object for the given id. If the bot is not in the guild, then the guild must be Discoverable. */
export async function getGuildPreview(guildId: bigint) {
return await rest.runMethod<GuildPreview>("get", endpoints.GUILD_PREVIEW(guildId));
export async function getGuildPreview(bot: Bot, guildId: bigint) {
return await bot.rest.runMethod<GuildPreview>(bot.rest, "get", bot.constants.endpoints.GUILD_PREVIEW(guildId));
}

View File

@@ -1,20 +1,26 @@
import { rest } from "../../rest/rest.ts";
import { Errors } from "../../types/discordeno/errors.ts";
import type { GetGuildPruneCountQuery } from "../../types/guilds/get_guild_prune_count.ts";
import { endpoints } from "../../util/constants.ts";
import { requireBotGuildPermissions } from "../../util/permissions.ts";
import { snakelize } from "../../util/utils.ts";
import type { Bot } from "../../bot.ts";
/** Check how many members would be removed from the server in a prune operation. Requires the KICK_MEMBERS permission */
export async function getPruneCount(guildId: bigint, options?: GetGuildPruneCountQuery) {
if (options?.days && options.days < 1) throw new Error(Errors.PRUNE_MIN_DAYS);
export async function getPruneCount(bot: Bot, guildId: bigint, options?: GetGuildPruneCountQuery) {
if (options?.days && options.days < 1) throw new Error(bot.constants.Errors.PRUNE_MIN_DAYS);
if (options?.days && options.days > 30) {
throw new Error(Errors.PRUNE_MAX_DAYS);
throw new Error(bot.constants.Errors.PRUNE_MAX_DAYS);
}
await requireBotGuildPermissions(guildId, ["KICK_MEMBERS"]);
await bot.utils.requireBotGuildPermissions(guildId, ["KICK_MEMBERS"]);
const result = await rest.runMethod("get", endpoints.GUILD_PRUNE(guildId), snakelize(options ?? {}));
const result = await bot.rest.runMethod(
bot.rest,
"get",
bot.constants.endpoints.GUILD_PRUNE(guildId),
options
? {
days: options.days,
include_roles: options.includeRoles,
}
: {}
);
return result.pruned as number;
}

View File

@@ -1,13 +1,12 @@
import { rest } from "../../rest/rest.ts";
import type { InviteMetadata } from "../../types/invites/invite_metadata.ts";
import { endpoints } from "../../util/constants.ts";
import type { Bot } from "../../bot.ts";
/** Returns the code and uses of the vanity url for this server if it is enabled else `code` will be null. Requires the `MANAGE_GUILD` permission. */
export async function getVanityURL(guildId: bigint) {
return await rest.runMethod<
export async function getVanityURL(bot: Bot, guildId: bigint) {
return await bot.rest.runMethod<
| (Partial<InviteMetadata> & Pick<InviteMetadata, "uses" | "code">)
| {
code: null;
}
>("get", endpoints.GUILD_VANITY_URL(guildId));
>(bot.rest, "get", bot.constants.endpoints.GUILD_VANITY_URL(guildId));
}

View File

@@ -1,11 +1,14 @@
import { rest } from "../../rest/rest.ts";
import type { VoiceRegion } from "../../types/voice/voice_region.ts";
import { Collection } from "../../util/collection.ts";
import { endpoints } from "../../util/constants.ts";
import type { Bot } from "../../bot.ts";
/** Returns a list of voice region objects for the guild. Unlike the similar /voice route, this returns VIP servers when the guild is VIP-enabled. */
export async function getVoiceRegions(guildId: bigint) {
const result = await rest.runMethod<VoiceRegion[]>("get", endpoints.GUILD_REGIONS(guildId));
export async function getVoiceRegions(boot: Bot, guildId: bigint) {
const result = await bot.rest.runMethod<VoiceRegion[]>(
bot.rest,
"get",
bot.constants.endpoints.GUILD_REGIONS(guildId)
);
return new Collection<string, VoiceRegion>(result.map((region) => [region.id, region]));
}

View File

@@ -1,7 +1,10 @@
import { rest } from "../../rest/rest.ts";
import type { WelcomeScreen } from "../../types/guilds/welcome_screen.ts";
import { endpoints } from "../../util/constants.ts";
import type { Bot } from "../../bot.ts";
export async function getWelcomeScreen(guildId: bigint) {
return await rest.runMethod<WelcomeScreen>("get", endpoints.GUILD_WELCOME_SCREEN(guildId));
export async function getWelcomeScreen(bot: Bot, guildId: bigint) {
return await bot.rest.runMethod<WelcomeScreen>(
bot.rset,
"get",
bot.constants.endpoints.GUILD_WELCOME_SCREEN(guildId)
);
}

View File

@@ -1,16 +1,17 @@
import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts";
import type { GuildWidgetDetails } from "../../types/guilds/guild_widget_details.ts";
import { Errors } from "../../types/discordeno/errors.ts";
import { endpoints } from "../../util/constants.ts";
import type { Bot } from "../../bot.ts";
/** Returns the widget for the guild. */
export async function getWidget(guildId: bigint, options?: { force: boolean }) {
export async function getWidget(bot: Bot, guildId: bigint, options?: { force: boolean }) {
if (!options?.force) {
const guild = await cacheHandlers.get("guilds", guildId);
if (!guild) throw new Error(Errors.GUILD_NOT_FOUND);
if (!guild?.widgetEnabled) throw new Error(Errors.GUILD_WIDGET_NOT_ENABLED);
const guild = await bot.cacahe.guilds.get(guildId);
if (!guild) throw new Error(bot.constants.Errors.GUILD_NOT_FOUND);
if (!guild?.widgetEnabled) throw new Error(bot.constants.Errors.GUILD_WIDGET_NOT_ENABLED);
}
return await rest.runMethod<GuildWidgetDetails>("get", `${endpoints.GUILD_WIDGET(guildId)}.json`);
return await bot.rest.runMethod<GuildWidgetDetails>(
bot.rest,
"get",
`${bot.constants.endpoints.GUILD_WIDGET(guildId)}.json`
);
}

View File

@@ -1,15 +1,17 @@
import { cacheHandlers } from "../../cache.ts";
import type { Bot } from "../../bot.ts";
import type { GetGuildWidgetImageQuery } from "../../types/guilds/get_guild_widget_image.ts";
import { Errors } from "../../types/discordeno/errors.ts";
import { endpoints } from "../../util/constants.ts";
/** Returns the widget image URL for the guild. */
export async function getWidgetImageURL(guildId: bigint, options?: GetGuildWidgetImageQuery & { force?: boolean }) {
export async function getWidgetImageURL(
bot: Bot,
guildId: bigint,
options?: GetGuildWidgetImageQuery & { force?: boolean }
) {
if (!options?.force) {
const guild = await cacheHandlers.get("guilds", guildId);
if (!guild) throw new Error(Errors.GUILD_NOT_FOUND);
if (!guild.widgetEnabled) throw new Error(Errors.GUILD_WIDGET_NOT_ENABLED);
const guild = await bot.cache.guilds.get(guildId);
if (!guild) throw new Error(bot.constants.Errors.GUILD_NOT_FOUND);
if (!guild.widgetEnabled) throw new Error(bot.constants.Errors.GUILD_WIDGET_NOT_ENABLED);
}
return `${endpoints.GUILD_WIDGET(guildId)}.png?style=${options?.style ?? "shield"}`;
return `${bot.constants.endpoints.GUILD_WIDGET(guildId)}.png?style=${options?.style ?? "shield"}`;
}

View File

@@ -1,11 +1,9 @@
import { rest } from "../../rest/rest.ts";
import type { GuildWidget } from "../../types/guilds/guild_widget.ts";
import { endpoints } from "../../util/constants.ts";
import { requireBotGuildPermissions } from "../../util/permissions.ts";
import type { Bot } from "../../bot.ts";
/** Returns the guild widget object. Requires the MANAGE_GUILD permission. */
export async function getWidgetSettings(guildId: bigint) {
await requireBotGuildPermissions(guildId, ["MANAGE_GUILD"]);
export async function getWidgetSettings(bot: Bot, guildId: bigint) {
await bot.utils.requireBotGuildPermissions(guildId, ["MANAGE_GUILD"]);
return await rest.runMethod<GuildWidget>("get", endpoints.GUILD_WIDGET(guildId));
return await bot.rest.runMethod<GuildWidget>(bot.rest, "get", bot.constants.endpoints.GUILD_WIDGET(guildId));
}

View File

@@ -1,11 +1,10 @@
import type { DiscordImageFormat } from "../../types/misc/image_format.ts";
import type { DiscordImageSize } from "../../types/misc/image_size.ts";
import { endpoints } from "../../util/constants.ts";
import { iconBigintToHash } from "../../util/hash.ts";
import { formatImageURL } from "../../util/utils.ts";
import type { Bot } from "../../bot.ts";
/** The full URL of the banner from Discords CDN. Undefined if no banner is set. */
export function guildBannerURL(
bot: Bot,
id: bigint,
options: {
banner?: string | bigint;
@@ -15,12 +14,12 @@ export function guildBannerURL(
}
) {
return options.banner
? formatImageURL(
endpoints.GUILD_BANNER(
? bot.utils.formatImageURL(
bot.constants.endpoints.GUILD_BANNER(
id,
typeof options.banner === "string"
? options.banner
: iconBigintToHash(options.banner, options.animated ?? true)
: bot.utils.iconBigintToHash(options.banner, options.animated ?? true)
),
options.size || 128,
options.format

View File

@@ -1,11 +1,10 @@
import type { DiscordImageFormat } from "../../types/misc/image_format.ts";
import type { DiscordImageSize } from "../../types/misc/image_size.ts";
import { endpoints } from "../../util/constants.ts";
import { iconBigintToHash } from "../../util/hash.ts";
import { formatImageURL } from "../../util/utils.ts";
import type { Bot } from "../../bot.ts";
/** The full URL of the icon from Discords CDN. Undefined when no icon is set. */
export function guildIconURL(
bot: Bot,
id: bigint,
options: {
icon?: string | bigint;
@@ -15,10 +14,12 @@ export function guildIconURL(
}
) {
return options.icon
? formatImageURL(
endpoints.GUILD_ICON(
? bot.utils.formatImageURL(
bot.constants.endpoints.GUILD_ICON(
id,
typeof options.icon === "string" ? options.icon : iconBigintToHash(options.icon, options.animated ?? true)
typeof options.icon === "string"
? options.icon
: bot.utils.iconBigintToHash(options.icon, options.animated ?? true)
),
options.size || 128,
options.format

View File

@@ -1,11 +1,10 @@
import type { DiscordImageFormat } from "../../types/misc/image_format.ts";
import type { DiscordImageSize } from "../../types/misc/image_size.ts";
import { endpoints } from "../../util/constants.ts";
import { iconBigintToHash } from "../../util/hash.ts";
import { formatImageURL } from "../../util/utils.ts";
import type { Bot } from "../../bot.ts";
/** The full URL of the splash from Discords CDN. Undefined if no splash is set. */
export function guildSplashURL(
bot: Bot,
id: bigint,
options: {
splash?: string | bigint;
@@ -15,12 +14,12 @@ export function guildSplashURL(
}
) {
return options.splash
? formatImageURL(
endpoints.GUILD_SPLASH(
? bot.utils.formatImageURL(
bot.constants.endpoints.GUILD_SPLASH(
id,
typeof options.splash === "string"
? options.splash
: iconBigintToHash(options.splash, options.animated ?? true)
: bot.utils.iconBigintToHash(options.splash, options.animated ?? true)
),
options.size || 128,
options.format

View File

@@ -1,7 +1,6 @@
import { rest } from "../../rest/rest.ts";
import { endpoints } from "../../util/constants.ts";
import type { Bot } from "../../bot.ts";
/** Leave a guild */
export async function leaveGuild(guildId: bigint) {
return await rest.runMethod<undefined>("delete", endpoints.GUILD_LEAVE(guildId));
export async function leaveGuild(bot: Bot, guildId: bigint) {
return await bot.rest.runMethod<undefined>(bot.rest, "delete", bot.constants.endpoints.GUILD_LEAVE(guildId));
}

View File

@@ -1,10 +1,12 @@
import { rest } from "../../rest/rest.ts";
import { endpoints } from "../../util/constants.ts";
import { requireBotGuildPermissions } from "../../util/permissions.ts";
import type { Bot } from "../../bot.ts";
/** Delete the attached integration object for the guild with this id. Requires MANAGE_GUILD permission. */
export async function deleteIntegration(guildId: bigint, id: bigint) {
await requireBotGuildPermissions(guildId, ["MANAGE_GUILD"]);
export async function deleteIntegration(bot: Bot, guildId: bigint, id: bigint) {
await bot.utils.requireBotGuildPermissions(bot, guildId, ["MANAGE_GUILD"]);
return await rest.runMethod<undefined>("delete", endpoints.GUILD_INTEGRATION(guildId, id));
return await bot.rest.runMethod<undefined>(
bot.rest,
"delete",
bot.constants.endpoints.GUILD_INTEGRATION(guildId, id)
);
}

View File

@@ -1,11 +1,14 @@
import { rest } from "../../rest/rest.ts";
import type { Integration } from "../../types/integrations/integration.ts";
import { endpoints } from "../../util/constants.ts";
import { requireBotGuildPermissions } from "../../util/permissions.ts";
import type { Bot } from "../../bot.ts";
import { SnakeCasedPropertiesDeep } from "../../types/util.ts";
/** Returns a list of integrations for the guild. Requires the MANAGE_GUILD permission. */
export async function getIntegrations(guildId: bigint) {
await requireBotGuildPermissions(guildId, ["MANAGE_GUILD"]);
export async function getIntegrations(bot: Bot, guildId: bigint) {
await bot.utils.requireBotGuildPermissions(bot, guildId, ["MANAGE_GUILD"]);
return await rest.runMethod<Integration>("get", endpoints.GUILD_INTEGRATIONS(guildId));
return await bot.rest.runMethod<SnakeCasedPropertiesDeep<Integration>>(
bot.rest,
"get",
bot.constants.endpoints.GUILD_INTEGRATIONS(guildId)
);
}

View File

@@ -1,13 +1,16 @@
import { applicationId } from "../../../bot.ts";
import { rest } from "../../../rest/rest.ts";
import type { Bot } from "../../../bot.ts";
import type { ApplicationCommandPermissions } from "../../../types/interactions/commands/application_command_permissions.ts";
import { endpoints } from "../../../util/constants.ts";
import { snakelize } from "../../../util/utils.ts";
/** Batch edits permissions for all commands in a guild. Takes an array of partial GuildApplicationCommandPermissions objects including `id` and `permissions`. */
export async function batchEditSlashCommandPermissions(
bot: Bot,
guildId: bigint,
options: { id: string; permissions: ApplicationCommandPermissions[] }[]
) {
return await rest.runMethod("put", endpoints.COMMANDS_PERMISSIONS(applicationId, guildId), snakelize(options));
return await bot.rest.runMethod(
bot.rest,
"put",
bot.constants.endpoints.COMMANDS_PERMISSIONS(bot.applicationId, guildId),
options
);
}

View File

@@ -1,9 +1,6 @@
import { applicationId } from "../../../bot.ts";
import { rest } from "../../../rest/rest.ts";
import type { ApplicationCommand } from "../../../types/interactions/commands/application_command.ts";
import type { CreateGlobalApplicationCommand } from "../../../types/interactions/commands/create_global_application_command.ts";
import { endpoints } from "../../../util/constants.ts";
import { snakelize, validateSlashCommands } from "../../../util/utils.ts";
import type { Bot } from "../../../bot.ts";
/**
* There are two kinds of Slash Commands: global commands and guild commands. Global commands are available for every guild that adds your app; guild commands are specific to the guild you specify when making them. Command names are unique per application within each scope (global and guild). That means:
@@ -16,12 +13,15 @@ import { snakelize, validateSlashCommands } from "../../../util/utils.ts";
* Global commands are cached for **1 hour**. That means that new global commands will fan out slowly across all guilds, and will be guaranteed to be updated in an hour.
* Guild commands update **instantly**. We recommend you use guild commands for quick testing, and global commands when they're ready for public use.
*/
export async function createSlashCommand(options: CreateGlobalApplicationCommand, guildId?: bigint) {
[options] = validateSlashCommands([options], true) as CreateGlobalApplicationCommand[];
export async function createSlashCommand(bot: Bot, options: CreateGlobalApplicationCommand, guildId?: bigint) {
[options] = bot.utils.validateSlashCommands([options], true) as CreateGlobalApplicationCommand[];
return await rest.runMethod<ApplicationCommand>(
return await bot.rest.runMethod<ApplicationCommand>(
bot.rest,
"post",
guildId ? endpoints.COMMANDS_GUILD(applicationId, guildId) : endpoints.COMMANDS(applicationId),
snakelize(options)
guildId
? bot.constants.endpoints.COMMANDS_GUILD(bot.applicationId, guildId)
: bot.constants.endpoints.COMMANDS(bot.applicationId),
options
);
}

View File

@@ -1,11 +1,12 @@
import { applicationId } from "../../../bot.ts";
import { rest } from "../../../rest/rest.ts";
import { endpoints } from "../../../util/constants.ts";
import type { Bot } from "../../../bot.ts";
/** Deletes a slash command. */
export async function deleteSlashCommand(id: bigint, guildId?: bigint) {
return await rest.runMethod<undefined>(
export async function deleteSlashCommand(bot: Bot, id: bigint, guildId?: bigint) {
return await bot.rest.runMethod<undefined>(
bot.rest,
"delete",
guildId ? endpoints.COMMANDS_GUILD_ID(applicationId, guildId, id) : endpoints.COMMANDS_ID(applicationId, id)
guildId
? bot.constants.endpoints.COMMANDS_GUILD_ID(bot.applicationId, guildId, id)
: bot.constants.endpoints.COMMANDS_ID(bot.applicationId, id)
);
}

View File

@@ -1,13 +1,12 @@
import { applicationId } from "../../../bot.ts";
import { rest } from "../../../rest/rest.ts";
import { endpoints } from "../../../util/constants.ts";
import type { Bot } from "../../../bot.ts";
/** To delete your response to a slash command. If a message id is not provided, it will default to deleting the original response. */
export async function deleteSlashResponse(token: string, messageId?: bigint) {
return await rest.runMethod<undefined>(
export async function deleteSlashResponse(bot: Bot, token: string, messageId?: bigint) {
return await bot.rest.runMethod<undefined>(
bot.rest,
"delete",
messageId
? endpoints.INTERACTION_ID_TOKEN_MESSAGE_ID(applicationId, token, messageId)
: endpoints.INTERACTION_ORIGINAL_ID_TOKEN(applicationId, token)
? bot.constants.endpoints.INTERACTION_ID_TOKEN_MESSAGE_ID(bot.applicationId, token, messageId)
: bot.constants.endpoints.INTERACTION_ORIGINAL_ID_TOKEN(bot.applicationId, token)
);
}

View File

@@ -1,16 +1,19 @@
import { applicationId } from "../../../bot.ts";
import { rest } from "../../../rest/rest.ts";
import type { ApplicationCommandPermissions } from "../../../types/interactions/commands/application_command_permissions.ts";
import { endpoints } from "../../../util/constants.ts";
import { snakelize } from "../../../util/utils.ts";
import type { Bot } from "../../../bot.ts";
/** Edits command permissions for a specific command for your application in a guild. */
export async function editSlashCommandPermissions(
bot: Bot,
guildId: bigint,
commandId: bigint,
options: ApplicationCommandPermissions[]
) {
return await rest.runMethod("put", endpoints.COMMANDS_PERMISSION(applicationId, guildId, commandId), {
permissions: snakelize(options),
});
return await bot.rest.runMethod(
bot.rest,
"put",
bot.constants.endpoints.COMMANDS_PERMISSION(bot.applicationId, guildId, commandId),
{
permissions: options,
}
);
}

View File

@@ -1,20 +1,15 @@
import { applicationId } from "../../../bot.ts";
import { rest } from "../../../rest/rest.ts";
import { structures } from "../../../structures/mod.ts";
import type { DiscordenoEditWebhookMessage } from "../../../types/discordeno/edit_webhook_message.ts";
import { Errors } from "../../../types/discordeno/errors.ts";
import type { Bot } from "../../../bot.ts";
import { DiscordAllowedMentionsTypes } from "../../../types/messages/allowed_mentions_types.ts";
import { endpoints } from "../../../util/constants.ts";
import { snakelize, validateComponents } from "../../../util/utils.ts";
/** To edit your response to a slash command. If a messageId is not provided it will default to editing the original response. */
export async function editSlashResponse(token: string, options: DiscordenoEditWebhookMessage) {
export async function editSlashResponse(bot: Bot, token: string, options: DiscordenoEditWebhookMessage) {
if (options.content && options.content.length > 2000) {
throw Error(Errors.MESSAGE_MAX_LENGTH);
throw Error(bot.constants.Errors.MESSAGE_MAX_LENGTH);
}
if (options.components?.length) {
validateComponents(options.components);
bot.utils.validateComponents(bot, options.components);
}
if (options.embeds && options.embeds.length > 10) {
@@ -43,17 +38,33 @@ export async function editSlashResponse(token: string, options: DiscordenoEditWe
}
}
const result = await rest.runMethod(
const result = await bot.rest.runMethod(
bot.rest,
"patch",
options.messageId
? endpoints.WEBHOOK_MESSAGE(applicationId, token, options.messageId)
: endpoints.INTERACTION_ORIGINAL_ID_TOKEN(applicationId, token),
snakelize(options)
? bot.constants.endpoints.WEBHOOK_MESSAGE(bot.applicationId, token, options.messageId)
: bot.constants.endpoints.INTERACTION_ORIGINAL_ID_TOKEN(bot.applicationId, token),
{
content: options.content,
embeds: options.embeds,
file: options.file,
allowed_mentions: options.allowedMentions
? {
parse: options.allowedMentions.parse,
roles: options.allowedMentions.roles,
users: options.allowedMentions.users,
replied_user: options.allowedMentions.repliedUser,
}
: undefined,
attachments: options.attachments,
// TODO: Snakelize components??
components: options.components,
message_id: options.messageId,
}
);
// If the original message was edited, this will not return a message
if (!options.messageId) return result as undefined;
const message = await structures.createDiscordenoMessage(result);
return message;
return bot.transformers.message(bot, result);
}

View File

@@ -1,21 +1,18 @@
import { applicationId } from "../../../bot.ts";
import { rest } from "../../../rest/rest.ts";
import type { ApplicationCommand } from "../../../types/interactions/commands/application_command.ts";
import { snowflakeToBigint } from "../../../util/bigint.ts";
import { endpoints } from "../../../util/constants.ts";
import type { Bot } from "../../../bot.ts";
/** Fetchs the global command for the given Id. If a guildId is provided, the guild command will be fetched. */
export async function getSlashCommand(commandId: bigint, guildId?: bigint) {
const result = await rest.runMethod<ApplicationCommand>(
/** Fetches the global command for the given Id. If a guildId is provided, the guild command will be fetched. */
export async function getSlashCommand(bot: Bot, commandId: bigint, guildId?: bigint) {
const result = await bot.rest.runMethod<ApplicationCommand>(
"get",
guildId
? endpoints.COMMANDS_GUILD_ID(applicationId, guildId, commandId)
: endpoints.COMMANDS_ID(applicationId, commandId)
? bot.constants.endpoints.COMMANDS_GUILD_ID(bot.applicationId, guildId, commandId)
: bot.constants.endpoints.COMMANDS_ID(bot.applicationId, commandId)
);
return {
...result,
id: snowflakeToBigint(result.id),
applicationId: snowflakeToBigint(result.applicationId),
id: bot.transformers.snowflake(result.id),
applicationId: bot.transformers.snowflake(result.applicationId),
};
}

View File

@@ -1,12 +1,11 @@
import { applicationId } from "../../../bot.ts";
import { rest } from "../../../rest/rest.ts";
import type { GuildApplicationCommandPermissions } from "../../../types/interactions/commands/guild_application_command_permissions.ts";
import { endpoints } from "../../../util/constants.ts";
import type { Bot } from "../../../bot.ts";
/** Fetches command permissions for a specific command for your application in a guild. Returns a GuildApplicationCommandPermissions object. */
export async function getSlashCommandPermission(guildId: bigint, commandId: bigint) {
return await rest.runMethod<GuildApplicationCommandPermissions>(
export async function getSlashCommandPermission(bot: Bot, guildId: bigint, commandId: bigint) {
return await bot.rest.runMethod<GuildApplicationCommandPermissions>(
bot.rest,
"get",
endpoints.COMMANDS_PERMISSION(applicationId, guildId, commandId)
bot.constants.endpoints.COMMANDS_PERMISSION(bot.applicationId, guildId, commandId)
);
}

View File

@@ -1,12 +1,11 @@
import { applicationId } from "../../../bot.ts";
import { rest } from "../../../rest/rest.ts";
import type { Bot } from "../../../bot.ts";
import type { GuildApplicationCommandPermissions } from "../../../types/interactions/commands/guild_application_command_permissions.ts";
import { endpoints } from "../../../util/constants.ts";
/** Fetches command permissions for all commands for your application in a guild. Returns an array of GuildApplicationCommandPermissions objects. */
export async function getSlashCommandPermissions(guildId: bigint) {
return await rest.runMethod<GuildApplicationCommandPermissions[]>(
export async function getSlashCommandPermissions(bot: Bot, guildId: bigint) {
return await bot.rest.runMethod<GuildApplicationCommandPermissions[]>(
bot.rest,
"get",
endpoints.COMMANDS_PERMISSIONS(applicationId, guildId)
bot.constants.endpoints.COMMANDS_PERMISSIONS(bot.applicationId, guildId)
);
}

View File

@@ -1,21 +1,25 @@
import { applicationId } from "../../../bot.ts";
import { rest } from "../../../rest/rest.ts";
import type { ApplicationCommand } from "../../../types/interactions/commands/application_command.ts";
import { snowflakeToBigint } from "../../../util/bigint.ts";
import { Collection } from "../../../util/collection.ts";
import { endpoints } from "../../../util/constants.ts";
import type { Bot } from "../../../bot.ts";
/** Fetch all of the global commands for your application. */
export async function getSlashCommands(guildId?: bigint) {
const result = await rest.runMethod<ApplicationCommand[]>(
/** Fetch all the global commands for your application. */
export async function getSlashCommands(bot: Bot, guildId?: bigint) {
const result = await bot.rest.runMethod<ApplicationCommand[]>(
bot.rest,
"get",
guildId ? endpoints.COMMANDS_GUILD(applicationId, guildId) : endpoints.COMMANDS(applicationId)
guildId
? bot.constants.endpoints.COMMANDS_GUILD(bot.applicationId, guildId)
: bot.constants.endpoints.COMMANDS(bot.applicationId)
);
return new Collection(
result.map((command) => [
command.name,
{ ...command, id: snowflakeToBigint(command.id), applicationId: snowflakeToBigint(command.applicationId) },
{
...command,
id: bot.transformers.snowflake(command.id),
applicationId: bot.transformers.snowflake(command.applicationId),
},
])
);
}

View File

@@ -1,21 +1,24 @@
import { applicationId } from "../../../bot.ts";
import { rest } from "../../../rest/rest.ts";
import type { ApplicationCommand } from "../../../types/interactions/commands/application_command.ts";
import type { EditGlobalApplicationCommand } from "../../../types/interactions/commands/edit_global_application_command.ts";
import { endpoints } from "../../../util/constants.ts";
import { validateSlashCommands } from "../../../util/utils.ts";
import type { Bot } from "../../../bot.ts";
/**
* Edit an existing slash command. If this command did not exist, it will create it.
*/
export async function upsertSlashCommand(commandId: bigint, options: EditGlobalApplicationCommand, guildId?: bigint) {
[options] = validateSlashCommands([options]);
export async function upsertSlashCommand(
bot: Bot,
commandId: bigint,
options: EditGlobalApplicationCommand,
guildId?: bigint
) {
[options] = bot.utils.validateSlashCommands([options]);
return await rest.runMethod<ApplicationCommand>(
return await bot.rest.runMethod<ApplicationCommand>(
bot.rest,
"patch",
guildId
? endpoints.COMMANDS_GUILD_ID(applicationId, guildId, commandId)
: endpoints.COMMANDS_ID(applicationId, commandId),
? bot.constants.endpoints.COMMANDS_GUILD_ID(bot.applicationId, guildId, commandId)
: bot.constants.endpoints.COMMANDS_ID(bot.applicationId, commandId),
options
);
}

View File

@@ -1,10 +1,7 @@
import { applicationId } from "../../../bot.ts";
import { rest } from "../../../rest/rest.ts";
import type { ApplicationCommand } from "../../../types/interactions/commands/application_command.ts";
import type { EditGlobalApplicationCommand } from "../../../types/interactions/commands/edit_global_application_command.ts";
import { MakeRequired } from "../../../types/util.ts";
import { endpoints } from "../../../util/constants.ts";
import { validateSlashCommands } from "../../../util/utils.ts";
import type { MakeRequired } from "../../../types/util.ts";
import type { Bot } from "../../../bot.ts";
/**
* Bulk edit existing slash commands. If a command does not exist, it will create it.
@@ -12,14 +9,18 @@ import { validateSlashCommands } from "../../../util/utils.ts";
* **NOTE:** Any slash commands that are not specified in this function will be **deleted**. If you don't provide the commandId and rename your command, the command gets a new Id.
*/
export async function upsertSlashCommands(
bot: Bot,
options: MakeRequired<EditGlobalApplicationCommand, "name">[],
guildId?: bigint
) {
options = validateSlashCommands(options) as MakeRequired<EditGlobalApplicationCommand, "name">[];
options = bot.utils.validateSlashCommands(options) as MakeRequired<EditGlobalApplicationCommand, "name">[];
return await rest.runMethod<ApplicationCommand[]>(
return await bot.rest.runMethod<ApplicationCommand[]>(
bot.rest,
"put",
guildId ? endpoints.COMMANDS_GUILD(applicationId, guildId) : endpoints.COMMANDS(applicationId),
guildId
? bot.constants.endpoints.COMMANDS_GUILD(bot.applicationId, guildId)
: bot.constants.endpoints.COMMANDS(bot.applicationId),
options
);
}

View File

@@ -1,12 +1,14 @@
import { applicationId } from "../../bot.ts";
import { rest } from "../../rest/rest.ts";
import { structures } from "../../structures/mod.ts";
import type { Bot } from "../../bot.ts";
import type { Message } from "../../types/messages/message.ts";
import { endpoints } from "../../util/constants.ts";
import type { SnakeCasedPropertiesDeep } from "../../types/util.ts";
/** Returns the initial Interactio response. Functions the same as Get Webhook Message */
export async function getOriginalInteractionResponse(token: string) {
const result = await rest.runMethod<Message>("get", endpoints.INTERACTION_ORIGINAL_ID_TOKEN(applicationId, token));
/** Returns the initial Interaction response. Functions the same as Get Webhook Message */
export async function getOriginalInteractionResponse(bot: Bot, token: string) {
const result = await bot.rest.runMethod<SnakeCasedPropertiesDeep<Message>>(
bot.rest,
"get",
bot.constants.endpoints.INTERACTION_ORIGINAL_ID_TOKEN(bot.applicationId, token)
);
return await structures.createDiscordenoMessage(result);
return bot.transformers.message(bot, result);
}

View File

@@ -1,9 +1,10 @@
import { applicationId, eventHandlers } from "../../bot.ts";
import { cache } from "../../cache.ts";
import { rest } from "../../rest/rest.ts";
import type { DiscordenoInteractionResponse } from "../../types/discordeno/interaction_response.ts";
import { endpoints } from "../../util/constants.ts";
import { snakelize, validateComponents } from "../../util/utils.ts";
import type { Bot } from "../../bot.ts";
import { Embed } from "../../types/embeds/embed.ts";
import { AllowedMentions } from "../../types/messages/allowed_mentions.ts";
import { MessageReference } from "../../types/messages/message_reference.ts";
import { FileContent } from "../../types/discordeno/file_content.ts";
import { MessageComponents } from "../../types/messages/components/message_components.ts";
// TODO: v12 remove | string
/**
@@ -13,12 +14,13 @@ import { snakelize, validateComponents } from "../../util/utils.ts";
* NOTE: By default we will suppress mentions. To enable mentions, just pass any mentions object.
*/
export async function sendInteractionResponse(
bot: Bot,
id: bigint | string,
token: string,
options: DiscordenoInteractionResponse
) {
// TODO: add more options validations
if (options.data?.components) validateComponents(options.data?.components);
if (options.data?.components) bot.utils.validateComponents(bot, options.data?.components);
// If the user wants this as a private message mark it ephemeral
if (options.private) {
@@ -31,8 +33,32 @@ export async function sendInteractionResponse(
}
// If its already been executed, we need to send a followup response
if (cache.executedSlashCommands.has(token)) {
return await rest.runMethod("post", endpoints.WEBHOOK(applicationId, token), snakelize(options.data));
if (bot.cache.executedSlashCommands.has(token)) {
return await bot.rest.runMethod(bot.rest, "post", bot.cosntants.endpoints.WEBHOOK(bot.applicationId, token), {
content: options.data.content,
tts: options.data.tts,
embeds: options.data.embeds,
allowed_mentions: {
parse: options.data.allowedMentions.parse,
roles: options.data.allowedMentions.roles,
users: options.data.allowedMentions.users,
replied_user: options.data.allowedMentions.repliedUser,
},
...(options.data.messageReference?.messageId
? {
message_reference: {
message_id: options.data.messageReference.messageId,
channel_id: options.data.messageReference.channelId,
guild_id: options.data.messageReference.guildId,
fail_if_not_exists: options.data.messageReference.failIfNotExists === true,
},
}
: {}),
file: options.data.file,
// TODO: Snakelize components??
components: options.data.components,
flags: options.data.flags,
});
}
// Expire in 15 minutes
@@ -42,9 +68,34 @@ export async function sendInteractionResponse(
cache.executedSlashCommands.delete(token);
}, 900000);
return await rest.runMethod(
return await bot.rest.runMethod(
bot.rest,
"post",
endpoints.INTERACTION_ID_TOKEN(typeof id === "bigint" ? id : BigInt(id), token),
snakelize(options)
bot.constants.endpoints.INTERACTION_ID_TOKEN(typeof id === "bigint" ? id : bot.transformers.snowflake(id), token),
{
content: options.data.content,
tts: options.data.tts,
embeds: options.data.embeds,
allowed_mentions: {
parse: options.data.allowedMentions.parse,
roles: options.data.allowedMentions.roles,
users: options.data.allowedMentions.users,
replied_user: options.data.allowedMentions.repliedUser,
},
...(options.data.messageReference?.messageId
? {
message_reference: {
message_id: options.data.messageReference.messageId,
channel_id: options.data.messageReference.channelId,
guild_id: options.data.messageReference.guildId,
fail_if_not_exists: options.data.messageReference.failIfNotExists === true,
},
}
: {}),
file: options.data.file,
// TODO: Snakelize components??
components: options.data.components,
flags: options.data.flags,
}
);
}

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