Starting to convert helpers

This commit is contained in:
TriForMine
2021-10-15 14:53:39 +02:00
parent 823a0754e4
commit 9e664bfcbe
9 changed files with 75 additions and 106 deletions
+33 -55
View File
@@ -11,63 +11,46 @@ import {
requireChannelPermissions, requireChannelPermissions,
highestRole, highestRole,
higherRolePosition, higherRolePosition,
requireBotChannelPermissions
} from "./util/permissions.ts"; } from "./util/permissions.ts";
import { getGatewayBot } from "./helpers/misc/get_gateway_bot.ts"; import { getGatewayBot } from "./helpers/misc/get_gateway_bot.ts";
import { checkRateLimits } from "./rest/check_rate_limits.ts"; import { checkRateLimits, processQueue, cleanupQueues, createRequestBody, processRateLimitedPaths, processRequest, processRequestHeaders, runMethod, processGlobalQueue, simplifyUrl } from "./rest/mod.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 type { RestPayload, RestRateLimitedPath, RestRequest } from "./rest/rest.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 { DiscordGatewayIntents } from "./types/gateway/gateway_intents.ts";
import { GetGatewayBot } from "./types/gateway/get_gateway_bot.ts"; import { GetGatewayBot } from "./types/gateway/get_gateway_bot.ts";
import { dispatchRequirements } from "./util/dispatch_requirements.ts"; import {bigintToSnowflake, snowflakeToBigint} from "./util/bigint.ts";
import { processQueue } from "./rest/process_queue.ts";
import { bigintToSnowflake, snowflakeToBigint } from "./util/bigint.ts";
import { Collection } from "./util/collection.ts"; import { Collection } from "./util/collection.ts";
import type { DiscordenoMember, DiscordenoUser } from "./transformers/member.ts"; import {DiscordenoMember, DiscordenoUser, transformMember, transformUser, DiscordenoGuild, transformGuild, DiscordenoChannel, transformChannel, transformMessage, transformRole, DiscordenoVoiceState, transformVoiceState} from "./transformers/mod.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 { handleDiscordPayload } from "./ws/handle_discord_payload.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 { import {
baseEndpoints, baseEndpoints, CHANNEL_MENTION_REGEX,
CHANNEL_MENTION_REGEX, CONTEXT_MENU_COMMANDS_NAME_REGEX, DISCORD_SNOWFLAKE_REGEX,
CONTEXT_MENU_COMMANDS_NAME_REGEX,
DISCORDENO_VERSION, DISCORDENO_VERSION,
DISCORD_SNOWFLAKE_REGEX,
endpoints, endpoints,
SLASH_COMMANDS_NAME_REGEX, SLASH_COMMANDS_NAME_REGEX,
USER_AGENT, USER_AGENT
} from "./util/constants.ts"; } from "./util/constants.ts";
import { GatewayPayload } from "./types/gateway/gateway_payload.ts"; import {Errors} from "./types/discordeno/errors.ts";
import { delay, validateSlashOptionChoices, validateSlashOptions } from "./util/utils.ts"; import {GatewayPayload} from "./types/gateway/gateway_payload.ts";
import { iconBigintToHash, iconHashToBigInt } from "./util/hash.ts"; import {
import { validateLength } from "./util/validate_length.ts"; closeWS,
import { processGlobalQueue } from "./rest/process_global_queue.ts"; handleOnMessage,
import { ChannelPinsUpdate } from "./types/channels/channel_pins_update.ts"; resume,
resharder,
log,
startGateway,
spawnShards,
createShard,
identify,
heartbeat,
handleDiscordPayload,
tellClusterToIdentify,
sendShardMessage,
DiscordenoShard
} from "./ws/mod.ts";
import {validateLength} from "./util/validate_length.ts";
import {delay, validateSlashOptionChoices, validateSlashOptions} from "./util/utils.ts";
import {iconBigintToHash, iconHashToBigInt} from "./util/hash.ts";
import {calculateShardId} from "./util/calculate_shard_id.ts";
export async function createBot(options: CreateBotOptions) { export async function createBot(options: CreateBotOptions) {
return { return {
@@ -274,6 +257,7 @@ export function createUtils(options: Partial<HelperUtils>) {
validateLength, validateLength,
validateSlashOptions, validateSlashOptions,
validateSlashOptionChoices, validateSlashOptionChoices,
requireBotChannelPermissions,
}; };
} }
@@ -299,6 +283,7 @@ export interface HelperUtils {
validateLength: typeof validateLength; validateLength: typeof validateLength;
validateSlashOptions: typeof validateSlashOptions; validateSlashOptions: typeof validateSlashOptions;
validateSlashOptionChoices: typeof validateSlashOptionChoices; validateSlashOptionChoices: typeof validateSlashOptionChoices;
requireBotChannelPermissions: typeof requireBotChannelPermissions;
} }
export function createGatewayManager(options: Partial<GatewayManager>): GatewayManager { export function createGatewayManager(options: Partial<GatewayManager>): GatewayManager {
@@ -331,7 +316,6 @@ export function createGatewayManager(options: Partial<GatewayManager>): GatewayM
loadingShards: options.loadingShards ?? new Collection(), loadingShards: options.loadingShards ?? new Collection(),
buckets: new Collection(), buckets: new Collection(),
utf8decoder: new TextDecoder(), utf8decoder: new TextDecoder(),
startGateway, startGateway,
spawnShards, spawnShards,
createShard, createShard,
@@ -379,8 +363,8 @@ export interface Transformers {
snowflake: typeof snowflakeToBigint; snowflake: typeof snowflakeToBigint;
channel: typeof transformChannel; channel: typeof transformChannel;
guild: typeof transformGuild; guild: typeof transformGuild;
user: typeof transformUser;
member: typeof transformMember; member: typeof transformMember;
user: typeof transformUser;
message: typeof transformMessage; message: typeof transformMessage;
role: typeof transformRole; role: typeof transformRole;
voiceState: typeof transformVoiceState; voiceState: typeof transformVoiceState;
@@ -389,13 +373,6 @@ export interface Transformers {
export function createTransformers(options: Partial<Transformers>) { export function createTransformers(options: Partial<Transformers>) {
return { return {
snowflake: options.snowflake || snowflakeToBigint, snowflake: options.snowflake || snowflakeToBigint,
channel: options.channel || transformChannel,
guild: options.guild || transformGuild,
user: options.user || transformUser,
member: options.member || transformMember,
message: options.message || transformMessage,
role: options.role || transformRole,
voiceState: options.voiceState || transformVoiceState,
}; };
} }
@@ -554,5 +531,6 @@ export function createBotConstants() {
CHANNEL_MENTION_REGEX, CHANNEL_MENTION_REGEX,
DISCORD_SNOWFLAKE_REGEX, DISCORD_SNOWFLAKE_REGEX,
}, },
Errors
}; };
} }
+4 -6
View File
@@ -1,10 +1,8 @@
import { rest } from "../../rest/rest.ts"; import { Bot } from "../../bot.ts";
import { endpoints } from "../../util/constants.ts";
import { requireBotChannelPermissions } from "../../util/permissions.ts";
/** Create a reaction for the message. Reaction takes the form of **name:id** for custom guild emoji, or Unicode characters. Requires READ_MESSAGE_HISTORY and ADD_REACTIONS */ /** Create a reaction for the message. Reaction takes the form of **name:id** for custom guild emoji, or Unicode characters. Requires READ_MESSAGE_HISTORY and ADD_REACTIONS */
export async function addReaction(channelId: bigint, messageId: bigint, reaction: string) { export async function addReaction(bot: Bot, channelId: bigint, messageId: bigint, reaction: string) {
await requireBotChannelPermissions(channelId, ["ADD_REACTIONS", "READ_MESSAGE_HISTORY"]); await bot.utils.requireBotChannelPermissions(channelId, ["ADD_REACTIONS", "READ_MESSAGE_HISTORY"]);
if (reaction.startsWith("<:")) { if (reaction.startsWith("<:")) {
reaction = reaction.substring(2, reaction.length - 1); reaction = reaction.substring(2, reaction.length - 1);
@@ -12,5 +10,5 @@ export async function addReaction(channelId: bigint, messageId: bigint, reaction
reaction = reaction.substring(3, reaction.length - 1); reaction = reaction.substring(3, reaction.length - 1);
} }
return await rest.runMethod<undefined>("put", endpoints.CHANNEL_MESSAGE_REACTION_ME(channelId, messageId, reaction)); return await bot.rest.runMethod<undefined>(bot.rest, "put", bot.constants.endpoints.CHANNEL_MESSAGE_REACTION_ME(channelId, messageId, reaction));
} }
+5 -5
View File
@@ -1,14 +1,14 @@
import { eventHandlers } from "../../bot.ts"; import {Bot} from "../../bot.ts";
import { addReaction } from "./add_reaction.ts"; import { addReaction } from "./add_reaction.ts";
/** Adds multiple reactions to a message. If `ordered` is true(default is false), it will add the reactions one at a time in the order provided. Note: Reaction takes the form of **name:id** for custom guild emoji, or Unicode characters. Requires READ_MESSAGE_HISTORY and ADD_REACTIONS */ /** Adds multiple reactions to a message. If `ordered` is true(default is false), it will add the reactions one at a time in the order provided. Note: Reaction takes the form of **name:id** for custom guild emoji, or Unicode characters. Requires READ_MESSAGE_HISTORY and ADD_REACTIONS */
export async function addReactions(channelId: bigint, messageId: bigint, reactions: string[], ordered = false) { export async function addReactions(bot: Bot, channelId: bigint, messageId: bigint, reactions: string[], ordered = false) {
if (!ordered) { if (!ordered) {
await Promise.all(reactions.map((reaction) => addReaction(channelId, messageId, reaction))); await Promise.all(reactions.map((reaction) => addReaction(bot, channelId, messageId, reaction)));
} else { } else {
for (const reaction of reactions) { for (const reaction of reactions) {
eventHandlers.debug?.("loop", "Running for of loop in addReactions function."); bot.events.debug?.("loop", "Running for of loop in addReactions function.");
await addReaction(channelId, messageId, reaction); await addReaction(bot, channelId, messageId, reaction);
} }
} }
} }
+5 -8
View File
@@ -1,19 +1,16 @@
import { botId } from "../../bot.ts"; import { Bot } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts";
import { endpoints } from "../../util/constants.ts";
import { requireBotChannelPermissions } from "../../util/permissions.ts";
import { delay } from "../../util/utils.ts"; import { delay } from "../../util/utils.ts";
/** Delete a message with the channel id and message id only. */ /** Delete a message with the channel id and message id only. */
export async function deleteMessage(channelId: bigint, messageId: bigint, reason?: string, delayMilliseconds = 0) { export async function deleteMessage(bot: Bot, channelId: bigint, messageId: bigint, reason?: string, delayMilliseconds = 0) {
const message = await cacheHandlers.get("messages", messageId); const message = await cacheHandlers.get("messages", messageId);
if (message && message.authorId !== botId) { if (message && message.authorId !== bot.id) {
await requireBotChannelPermissions(message.channelId, ["MANAGE_MESSAGES"]); await bot.utils.requireBotChannelPermissions(message.channelId, ["MANAGE_MESSAGES"]);
} }
if (delayMilliseconds) await delay(delayMilliseconds); if (delayMilliseconds) await delay(delayMilliseconds);
return await rest.runMethod<undefined>("delete", endpoints.CHANNEL_MESSAGE(channelId, messageId), { reason }); return await bot.rest.runMethod<undefined>(bot.rest,"delete", bot.constants.endpoints.CHANNEL_MESSAGE(channelId, messageId), { reason });
} }
+5 -8
View File
@@ -1,21 +1,18 @@
import { rest } from "../../rest/rest.ts"; import { Bot } from "../../bot.ts";
import { Errors } from "../../types/discordeno/errors.ts";
import { endpoints } from "../../util/constants.ts";
import { requireBotChannelPermissions } from "../../util/permissions.ts";
/** Delete messages from the channel. 2-100. Requires the MANAGE_MESSAGES permission */ /** Delete messages from the channel. 2-100. Requires the MANAGE_MESSAGES permission */
export async function deleteMessages(channelId: bigint, ids: bigint[], reason?: string) { export async function deleteMessages(bot: Bot, channelId: bigint, ids: bigint[], reason?: string) {
await requireBotChannelPermissions(channelId, ["MANAGE_MESSAGES"]); await bot.utils.requireBotChannelPermissions(channelId, ["MANAGE_MESSAGES"]);
if (ids.length < 2) { if (ids.length < 2) {
throw new Error(Errors.DELETE_MESSAGES_MIN); throw new Error(bot.constants.Errors.DELETE_MESSAGES_MIN);
} }
if (ids.length > 100) { if (ids.length > 100) {
console.warn(`This endpoint only accepts a maximum of 100 messages. Deleting the first 100 message ids provided.`); console.warn(`This endpoint only accepts a maximum of 100 messages. Deleting the first 100 message ids provided.`);
} }
return await rest.runMethod<undefined>("post", endpoints.CHANNEL_BULK_DELETE(channelId), { return await bot.rest.runMethod<undefined>(bot.rest,"post", bot.constants.endpoints.CHANNEL_BULK_DELETE(channelId), {
messages: ids.splice(0, 100), messages: ids.splice(0, 100),
reason, reason,
}); });
+13 -16
View File
@@ -1,45 +1,42 @@
import { botId } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts";
import { structures } from "../../structures/mod.ts";
import { Errors } from "../../types/discordeno/errors.ts";
import { EditMessage } from "../../types/messages/edit_message.ts"; import { EditMessage } from "../../types/messages/edit_message.ts";
import type { Message } from "../../types/messages/message.ts"; import type { Message } from "../../types/messages/message.ts";
import type { PermissionStrings } from "../../types/permissions/permission_strings.ts"; import type { PermissionStrings } from "../../types/permissions/permission_strings.ts";
import { endpoints } from "../../util/constants.ts"; import { validateComponents } from "../../util/utils.ts";
import { requireBotChannelPermissions } from "../../util/permissions.ts"; import {Bot} from "../../bot.ts";
import { snakelize, validateComponents } from "../../util/utils.ts"; import {SnakeCasedPropertiesDeep} from "../../types/util.ts";
/** Edit the message. */ /** Edit the message. */
export async function editMessage(channelId: bigint, messageId: bigint, content: string | EditMessage) { export async function editMessage(bot: Bot, channelId: bigint, messageId: bigint, content: string | EditMessage) {
const message = await cacheHandlers.get("messages", messageId); const message = await cacheHandlers.get("messages", messageId);
if (message) { if (message) {
if (message.authorId !== botId) { if (message.authorId !== bot.id) {
throw new Error("You can only edit a message that was sent by the bot."); throw new Error("You can only edit a message that was sent by the bot.");
} }
const requiredPerms: PermissionStrings[] = ["SEND_MESSAGES"]; const requiredPerms: PermissionStrings[] = ["SEND_MESSAGES"];
await requireBotChannelPermissions(message.channelId, requiredPerms); await bot.utils.requireBotChannelPermissions(message.channelId, requiredPerms);
} }
if (typeof content === "string") content = { content }; if (typeof content === "string") content = { content };
if (content.components?.length) { if (content.components?.length) {
validateComponents(content.components); validateComponents(bot, content.components);
} }
content.embeds?.splice(10); content.embeds?.splice(10);
if (content.content && content.content.length > 2000) { if (content.content && content.content.length > 2000) {
throw new Error(Errors.MESSAGE_MAX_LENGTH); throw new Error(bot.constants.Errors.MESSAGE_MAX_LENGTH);
} }
const result = await rest.runMethod<Message>( const result = await bot.rest.runMethod<SnakeCasedPropertiesDeep<Message>>(
bot.rest,
"patch", "patch",
endpoints.CHANNEL_MESSAGE(channelId, messageId), bot.constants.endpoints.CHANNEL_MESSAGE(channelId, messageId),
snakelize(content) bot.utils.snakelize(content)
); );
return await structures.createDiscordenoMessage(result); return bot.transformers.message(bot, result);
} }
+6 -8
View File
@@ -1,17 +1,15 @@
import { cacheHandlers } from "../../cache.ts"; import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts";
import { structures } from "../../structures/mod.ts";
import type { Message } from "../../types/messages/message.ts"; import type { Message } from "../../types/messages/message.ts";
import { endpoints } from "../../util/constants.ts"; import {Bot} from "../../bot.ts";
import { requireBotChannelPermissions } from "../../util/permissions.ts"; import {SnakeCasedPropertiesDeep} from "../../types/util.ts";
/** Fetch a single message from the server. Requires VIEW_CHANNEL and READ_MESSAGE_HISTORY */ /** Fetch a single message from the server. Requires VIEW_CHANNEL and READ_MESSAGE_HISTORY */
export async function getMessage(channelId: bigint, id: bigint) { export async function getMessage(bot: Bot, channelId: bigint, id: bigint) {
if (await cacheHandlers.has("channels", channelId)) { if (await cacheHandlers.has("channels", channelId)) {
await requireBotChannelPermissions(channelId, ["VIEW_CHANNEL", "READ_MESSAGE_HISTORY"]); await bot.utils.requireBotChannelPermissions(channelId, ["VIEW_CHANNEL", "READ_MESSAGE_HISTORY"]);
} }
const result = await rest.runMethod<Message>("get", endpoints.CHANNEL_MESSAGE(channelId, id)); const result = await bot.rest.runMethod<SnakeCasedPropertiesDeep<Message>>(bot.rest,"get", bot.constants.endpoints.CHANNEL_MESSAGE(channelId, id));
return await structures.createDiscordenoMessage(result); return await bot.transformers.message(bot, result);
} }
+2
View File
@@ -1,9 +1,11 @@
export * from "./check_rate_limits.ts"; export * from "./check_rate_limits.ts";
export * from "./cleanup_queues.ts"; export * from "./cleanup_queues.ts";
export * from "./create_request_body.ts"; export * from "./create_request_body.ts";
export * from "./process_global_queue.ts";
export * from "./process_queue.ts"; export * from "./process_queue.ts";
export * from "./process_rate_limited_paths.ts"; export * from "./process_rate_limited_paths.ts";
export * from "./process_request.ts"; export * from "./process_request.ts";
export * from "./process_request_headers.ts"; export * from "./process_request_headers.ts";
export * from "./rest.ts"; export * from "./rest.ts";
export * from "./run_method.ts"; export * from "./run_method.ts";
export * from "./simplify_url.ts";
+2
View File
@@ -1,3 +1,4 @@
export * from "./close_ws.ts";
export * from "./create_shard.ts"; export * from "./create_shard.ts";
export * from "./events.ts"; export * from "./events.ts";
export * from "./handle_discord_payload.ts"; export * from "./handle_discord_payload.ts";
@@ -7,6 +8,7 @@ export * from "./identify.ts";
export * from "./resharder.ts"; export * from "./resharder.ts";
export * from "./resume.ts"; export * from "./resume.ts";
export * from "./spawn_shards.ts"; export * from "./spawn_shards.ts";
export * from "./send_shard_message.ts";
export * from "./start_gateway_options.ts"; export * from "./start_gateway_options.ts";
export * from "./start_gateway.ts"; export * from "./start_gateway.ts";
export * from "./tell_cluster_to_identify.ts"; export * from "./tell_cluster_to_identify.ts";