From 4b7b9c2658cbf6b32050444a34ffa31fecf201a0 Mon Sep 17 00:00:00 2001 From: Skillz4Killz <23035000+Skillz4Killz@users.noreply.github.com> Date: Wed, 22 Dec 2021 16:07:57 +0000 Subject: [PATCH] fix: finalizing permission plugin --- .../commands/editInteractionResponse.ts | 18 +- .../followups/editFollowupMessage.ts | 16 +- src/helpers/messages/editMessage.ts | 12 +- src/helpers/messages/sendMessage.ts | 32 +--- src/helpers/misc/editBotProfile.ts | 18 -- src/helpers/oauth/getApplicationInfo.ts | 1 - src/helpers/webhooks/createWebhook.ts | 21 +- src/helpers/webhooks/deleteWebhookMessage.ts | 25 ++- src/helpers/webhooks/editWebhookMessage.ts | 181 ++++++++---------- src/helpers/webhooks/getWebhookMessage.ts | 26 ++- src/helpers/webhooks/sendWebhook.ts | 36 +--- src/types/webhooks/editWebhookMessage.ts | 9 +- src/types/webhooks/executeWebhook.ts | 3 + worker.ts | 92 +++++++++ 14 files changed, 261 insertions(+), 229 deletions(-) create mode 100644 worker.ts diff --git a/src/helpers/interactions/commands/editInteractionResponse.ts b/src/helpers/interactions/commands/editInteractionResponse.ts index b4c32c347..80b2109e3 100644 --- a/src/helpers/interactions/commands/editInteractionResponse.ts +++ b/src/helpers/interactions/commands/editInteractionResponse.ts @@ -18,12 +18,22 @@ export async function editInteractionResponse(bot: Bot, token: string, options: allowed_mentions: options.allowedMentions ? { parse: options.allowedMentions.parse, - roles: options.allowedMentions.roles, - users: options.allowedMentions.users, + roles: options.allowedMentions.roles?.map((id) => id.toString()), + users: options.allowedMentions.users?.map((id) => id.toString()), replied_user: options.allowedMentions.repliedUser, } : undefined, - attachments: options.attachments, + attachments: options.attachments?.map((attachment) => ({ + id: attachment.id.toString(), + filename: attachment.filename, + content_type: attachment.contentType, + size: attachment.size, + url: attachment.url, + proxy_url: attachment.proxyUrl, + height: attachment.height, + width: attachment.width, + ephemeral: attachment.ephemeral, + })), components: options.components?.map((component) => ({ type: component.type, components: component.components.map((subcomponent) => { @@ -79,7 +89,7 @@ export async function editInteractionResponse(bot: Bot, token: string, options: }; }), })), - message_id: options.messageId, + message_id: options.messageId?.toString(), } ); diff --git a/src/helpers/interactions/followups/editFollowupMessage.ts b/src/helpers/interactions/followups/editFollowupMessage.ts index 173e64927..0ec094846 100644 --- a/src/helpers/interactions/followups/editFollowupMessage.ts +++ b/src/helpers/interactions/followups/editFollowupMessage.ts @@ -22,12 +22,22 @@ export async function editFollowupMessage( allowed_mentions: options.allowedMentions ? { parse: options.allowedMentions.parse, - roles: options.allowedMentions.roles, - users: options.allowedMentions.users, + roles: options.allowedMentions.roles?.map((id) => id.toString()), + users: options.allowedMentions.users?.map((id) => id.toString()), replied_user: options.allowedMentions.repliedUser, } : undefined, - attachments: options.attachments, + attachments: options.attachments?.map((attachment) => ({ + id: attachment.id.toString(), + filename: attachment.filename, + content_type: attachment.contentType, + size: attachment.size, + url: attachment.url, + proxy_url: attachment.proxyUrl, + height: attachment.height, + width: attachment.width, + ephemeral: attachment.ephemeral, + })), components: options.components?.map((component) => ({ type: component.type, components: component.components.map((subcomponent) => { diff --git a/src/helpers/messages/editMessage.ts b/src/helpers/messages/editMessage.ts index 05feb4360..7737438ae 100644 --- a/src/helpers/messages/editMessage.ts +++ b/src/helpers/messages/editMessage.ts @@ -4,16 +4,8 @@ import type { Bot } from "../../bot.ts"; import { MessageComponentTypes } from "../../types/messages/components/messageComponentTypes.ts"; /** Edit the message. */ -export async function editMessage(bot: Bot, channelId: bigint, messageId: bigint, content: string | EditMessage) { - if (typeof content === "string") content = { content }; - - content.embeds?.splice(10); - - if (content.content && content.content.length > 2000) { - throw new Error(bot.constants.Errors.MESSAGE_MAX_LENGTH); - } - - const result = await bot.rest.runMethod( +export async function editMessage(bot: Bot, channelId: bigint, messageId: bigint, content: EditMessage) { + const result = await bot.rest.runMethod( bot.rest, "patch", bot.constants.endpoints.CHANNEL_MESSAGE(channelId, messageId), diff --git a/src/helpers/messages/sendMessage.ts b/src/helpers/messages/sendMessage.ts index fbc498223..b58479f24 100644 --- a/src/helpers/messages/sendMessage.ts +++ b/src/helpers/messages/sendMessage.ts @@ -5,36 +5,7 @@ import type { Bot } from "../../bot.ts"; import { MessageComponentTypes } from "../../types/messages/components/messageComponentTypes.ts"; /** Send a message to the channel. Requires SEND_MESSAGES permission. */ -export async function sendMessage(bot: Bot, channelId: bigint, content: string | CreateMessage) { - if (typeof content === "string") content = { content }; - - // Use ... for content length due to unicode characters and js .length handling - if (content.content && !bot.utils.validateLength(content.content, { max: 2000 })) { - throw new Error(bot.constants.Errors.MESSAGE_MAX_LENGTH); - } - - if (content.allowedMentions) { - if (content.allowedMentions.users?.length) { - if (content.allowedMentions.parse?.includes(AllowedMentionsTypes.UserMentions)) { - content.allowedMentions.parse = content.allowedMentions.parse.filter((p) => p !== "users"); - } - - if (content.allowedMentions.users.length > 100) { - content.allowedMentions.users = content.allowedMentions.users.slice(0, 100); - } - } - - if (content.allowedMentions.roles?.length) { - if (content.allowedMentions.parse?.includes(AllowedMentionsTypes.RoleMentions)) { - content.allowedMentions.parse = content.allowedMentions.parse.filter((p) => p !== "roles"); - } - - if (content.allowedMentions.roles.length > 100) { - content.allowedMentions.roles = content.allowedMentions.roles.slice(0, 100); - } - } - } - +export async function sendMessage(bot: Bot, channelId: bigint, content: CreateMessage) { const result = await bot.rest.runMethod( bot.rest, "post", @@ -170,3 +141,4 @@ export async function sendMessage(bot: Bot, channelId: bigint, content: string | return bot.transformers.message(bot, result); } + diff --git a/src/helpers/misc/editBotProfile.ts b/src/helpers/misc/editBotProfile.ts index eb55b1a2e..0307c3ab4 100644 --- a/src/helpers/misc/editBotProfile.ts +++ b/src/helpers/misc/editBotProfile.ts @@ -6,24 +6,6 @@ import type { Bot } from "../../bot.ts"; * NOTE: username: if changed may cause the bot's discriminator to be randomized. */ export async function editBotProfile(bot: Bot, options: { username?: string; botAvatarURL?: string | null }) { - // Nothing was edited - if (!options.username && options.botAvatarURL === undefined) return; - // Check username requirements if username was provided - if (options.username) { - if (options.username.length > 32) { - throw new Error(Errors.USERNAME_MAX_LENGTH); - } - if (options.username.length < 2) { - throw new Error(Errors.USERNAME_MIN_LENGTH); - } - if (["@", "#", ":", "```"].some((char) => options.username!.includes(char))) { - throw new Error(Errors.USERNAME_INVALID_CHARACTER); - } - if (["discordtag", "everyone", "here"].includes(options.username)) { - throw new Error(Errors.USERNAME_INVALID_USERNAME); - } - } - const avatar = options?.botAvatarURL ? await bot.utils.urlToBase64(options?.botAvatarURL) : options?.botAvatarURL; const result = await bot.rest.runMethod(bot.rest, "patch", bot.constants.endpoints.USER_BOT, { diff --git a/src/helpers/oauth/getApplicationInfo.ts b/src/helpers/oauth/getApplicationInfo.ts index 963908fc3..31033edaf 100644 --- a/src/helpers/oauth/getApplicationInfo.ts +++ b/src/helpers/oauth/getApplicationInfo.ts @@ -1,6 +1,5 @@ import { Application } from "../../types/applications/application.ts"; import type { Bot } from "../../bot.ts"; -import { SnakeCasedPropertiesDeep } from "../../types/util.ts"; /** Get the applications info */ export async function getApplicationInfo(bot: Bot) { diff --git a/src/helpers/webhooks/createWebhook.ts b/src/helpers/webhooks/createWebhook.ts index 69fb31b4b..a7c70ac6e 100644 --- a/src/helpers/webhooks/createWebhook.ts +++ b/src/helpers/webhooks/createWebhook.ts @@ -8,18 +8,15 @@ import type { Webhook } from "../../types/webhooks/webhook.ts"; * Webhook names cannot be: 'clyde' */ export async function createWebhook(bot: Bot, channelId: bigint, options: CreateWebhook) { - if ( - // Specific usernames that discord does not allow - options.name === "clyde" || - !bot.utils.validateLength(options.name, { min: 2, max: 32 }) - ) { - throw new Error(bot.constants.Errors.INVALID_WEBHOOK_NAME); - } - - const result = await bot.rest.runMethod(bot.rest, "post", bot.constants.endpoints.CHANNEL_WEBHOOKS(channelId), { - ...options, - avatar: options.avatar ? await bot.utils.urlToBase64(options.avatar) : undefined, - }); + const result = await bot.rest.runMethod( + bot.rest, + "post", + bot.constants.endpoints.CHANNEL_WEBHOOKS(channelId), + { + ...options, + avatar: options.avatar ? await bot.utils.urlToBase64(options.avatar) : undefined, + } + ); return bot.transformers.webhook(bot, result); } diff --git a/src/helpers/webhooks/deleteWebhookMessage.ts b/src/helpers/webhooks/deleteWebhookMessage.ts index 6303811ca..0ef747abb 100644 --- a/src/helpers/webhooks/deleteWebhookMessage.ts +++ b/src/helpers/webhooks/deleteWebhookMessage.ts @@ -1,9 +1,22 @@ import type { Bot } from "../../bot.ts"; -export async function deleteWebhookMessage(bot: Bot, webhookId: bigint, webhookToken: string, messageId: bigint) { - await bot.rest.runMethod( - bot.rest, - "delete", - bot.constants.endpoints.WEBHOOK_MESSAGE(webhookId, webhookToken, messageId) - ); +export interface DeleteWebhookMessageOptions { + /** id of the thread the message is in */ + threadId: bigint; +} + +export async function deleteWebhookMessage( + bot: Bot, + webhookId: bigint, + webhookToken: string, + messageId: bigint, + options?: DeleteWebhookMessageOptions +) { + let url = bot.constants.endpoints.WEBHOOK_MESSAGE(webhookId, webhookToken, messageId); + + // QUERY PARAMS + if (options?.threadId) { + url += `?threadId=${options.threadId}`; + } + await bot.rest.runMethod(bot.rest, "delete", url); } diff --git a/src/helpers/webhooks/editWebhookMessage.ts b/src/helpers/webhooks/editWebhookMessage.ts index 4cc4ddb48..3ae2729b6 100644 --- a/src/helpers/webhooks/editWebhookMessage.ts +++ b/src/helpers/webhooks/editWebhookMessage.ts @@ -1,124 +1,103 @@ import type { Message } from "../../types/messages/message.ts"; import type { EditWebhookMessage } from "../../types/webhooks/editWebhookMessage.ts"; import type { Bot } from "../../bot.ts"; -import { AllowedMentionsTypes } from "../../types/messages/allowedMentionsTypes.ts"; import { MessageComponentTypes } from "../../types/messages/components/messageComponentTypes.ts"; -import { hasProperty } from "../../util/utils.ts"; -import { ButtonComponent } from "../../types/messages/components/buttonComponent.ts"; export async function editWebhookMessage( bot: Bot, webhookId: bigint, webhookToken: string, - options: EditWebhookMessage & { messageId?: bigint } + options: EditWebhookMessage & { messageId?: bigint; threadId?: bigint } ) { - if (options.content && options.content.length > 2000) { - throw Error(bot.constants.Errors.MESSAGE_MAX_LENGTH); + let url = options.messageId + ? bot.constants.endpoints.WEBHOOK_MESSAGE(webhookId, webhookToken, options.messageId) + : bot.constants.endpoints.WEBHOOK_MESSAGE_ORIGINAL(webhookId, webhookToken); + + // QUERY PARAMS + if (options.threadId) { + url += `?thread_id=${options.threadId}`; } - if (options.embeds && options.embeds.length > 10) { - options.embeds.splice(10); - } - - if (options.allowedMentions) { - if (options.allowedMentions.users?.length) { - if (options.allowedMentions.parse?.includes(AllowedMentionsTypes.UserMentions)) { - options.allowedMentions.parse = options.allowedMentions.parse.filter((p) => p !== "users"); - } - - if (options.allowedMentions.users.length > 100) { - options.allowedMentions.users = options.allowedMentions.users.slice(0, 100); - } - } - - if (options.allowedMentions.roles?.length) { - if (options.allowedMentions.parse?.includes(AllowedMentionsTypes.RoleMentions)) { - options.allowedMentions.parse = options.allowedMentions.parse.filter((p) => p !== "roles"); - } - - if (options.allowedMentions.roles.length > 100) { - options.allowedMentions.roles = options.allowedMentions.roles.slice(0, 100); - } - } - } - - const result = await bot.rest.runMethod( - bot.rest, - "patch", - options.messageId - ? bot.constants.endpoints.WEBHOOK_MESSAGE(webhookId, webhookToken, options.messageId) - : bot.constants.endpoints.WEBHOOK_MESSAGE_ORIGINAL(webhookId, webhookToken), - { - 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, - components: options.components?.map((component) => ({ - type: component.type, - components: component.components.map((subcomponent) => { - if (subcomponent.type === MessageComponentTypes.InputText) { - return { - type: subcomponent.type, - style: subcomponent.style, - custom_id: subcomponent.customId, - label: subcomponent.label, - placeholder: subcomponent.placeholder, - min_length: subcomponent.minLength ?? subcomponent.required === false ? 0 : subcomponent.minLength, - max_length: subcomponent.maxLength, - }; - } - - if (subcomponent.type === MessageComponentTypes.SelectMenu) - return { - type: subcomponent.type, - custom_id: subcomponent.customId, - placeholder: subcomponent.placeholder, - min_values: subcomponent.minValues, - max_values: subcomponent.maxValues, - options: subcomponent.options.map((option) => ({ - label: option.label, - value: option.value, - description: option.description, - emoji: option.emoji - ? { - id: option.emoji.id?.toString(), - name: option.emoji.name, - animated: option.emoji.animated, - } - : undefined, - default: option.default, - })), - }; + const result = await bot.rest.runMethod(bot.rest, "patch", url, { + content: options.content, + embeds: options.embeds, + file: options.file, + allowed_mentions: options.allowedMentions + ? { + parse: options.allowedMentions.parse, + roles: options.allowedMentions.roles?.map((id) => id.toString()), + users: options.allowedMentions.users?.map((id) => id.toString()), + replied_user: options.allowedMentions.repliedUser, + } + : undefined, + attachments: options.attachments?.map((attachment) => ({ + id: attachment.id.toString(), + filename: attachment.filename, + content_type: attachment.contentType, + size: attachment.size, + url: attachment.url, + proxy_url: attachment.proxyUrl, + height: attachment.height, + width: attachment.width, + ephemeral: attachment.ephemeral, + })), + components: options.components?.map((component) => ({ + type: component.type, + components: component.components.map((subcomponent) => { + if (subcomponent.type === MessageComponentTypes.InputText) { + return { + type: subcomponent.type, + style: subcomponent.style, + custom_id: subcomponent.customId, + label: subcomponent.label, + placeholder: subcomponent.placeholder, + min_length: subcomponent.minLength ?? subcomponent.required === false ? 0 : subcomponent.minLength, + max_length: subcomponent.maxLength, + }; + } + if (subcomponent.type === MessageComponentTypes.SelectMenu) return { type: subcomponent.type, custom_id: subcomponent.customId, - label: subcomponent.label, - style: subcomponent.style, - emoji: - "emoji" in subcomponent && subcomponent.emoji + placeholder: subcomponent.placeholder, + min_values: subcomponent.minValues, + max_values: subcomponent.maxValues, + options: subcomponent.options.map((option) => ({ + label: option.label, + value: option.value, + description: option.description, + emoji: option.emoji ? { - id: subcomponent.emoji.id?.toString(), - name: subcomponent.emoji.name, - animated: subcomponent.emoji.animated, + id: option.emoji.id?.toString(), + name: option.emoji.name, + animated: option.emoji.animated, } : undefined, - url: "url" in subcomponent ? subcomponent.url : undefined, - disabled: "disabled" in subcomponent ? subcomponent.disabled : undefined, + default: option.default, + })), }; - }), - })), - message_id: options.messageId?.toString(), - } - ); + + return { + type: subcomponent.type, + custom_id: subcomponent.customId, + label: subcomponent.label, + style: subcomponent.style, + emoji: + "emoji" in subcomponent && subcomponent.emoji + ? { + id: subcomponent.emoji.id?.toString(), + name: subcomponent.emoji.name, + animated: subcomponent.emoji.animated, + } + : undefined, + url: "url" in subcomponent ? subcomponent.url : undefined, + disabled: "disabled" in subcomponent ? subcomponent.disabled : undefined, + }; + }), + })), + message_id: options.messageId?.toString(), + }); return bot.transformers.message(bot, result); } diff --git a/src/helpers/webhooks/getWebhookMessage.ts b/src/helpers/webhooks/getWebhookMessage.ts index a685ca380..55249dfa5 100644 --- a/src/helpers/webhooks/getWebhookMessage.ts +++ b/src/helpers/webhooks/getWebhookMessage.ts @@ -1,14 +1,26 @@ import type { Message } from "../../types/messages/message.ts"; -import type { SnakeCasedPropertiesDeep } from "../../types/util.ts"; import type { Bot } from "../../bot.ts"; +export interface GetWebhookMessageOptions { + threadId: bigint; +} + /** Returns a previously-sent webhook message from the same token. Returns a message object on success. */ -export async function getWebhookMessage(bot: Bot, webhookId: bigint, webhookToken: string, messageId: bigint) { - const result = await bot.rest.runMethod( - bot.rest, - "get", - bot.constants.endpoints.WEBHOOK_MESSAGE(webhookId, webhookToken, messageId) - ); +export async function getWebhookMessage( + bot: Bot, + webhookId: bigint, + webhookToken: string, + messageId: bigint, + options?: GetWebhookMessageOptions +) { + let url = bot.constants.endpoints.WEBHOOK_MESSAGE(webhookId, webhookToken, messageId); + + // QUERY PARAMS + if (options?.threadId) { + url += `?thread_id=${options.threadId}`; + } + + const result = await bot.rest.runMethod(bot.rest, "get", url); return bot.transformers.message(bot, result); } diff --git a/src/helpers/webhooks/sendWebhook.ts b/src/helpers/webhooks/sendWebhook.ts index b9853630e..83fa12b20 100644 --- a/src/helpers/webhooks/sendWebhook.ts +++ b/src/helpers/webhooks/sendWebhook.ts @@ -5,41 +5,6 @@ import type { ExecuteWebhook } from "../../types/webhooks/executeWebhook.ts"; /** Send a webhook with webhook Id and webhook token */ export async function sendWebhook(bot: Bot, webhookId: bigint, webhookToken: string, options: ExecuteWebhook) { - // DEFAULT TO TRUE - options.wait = options.wait ?? true; - - if (!options.content && !options.file && !options.embeds) { - throw new Error(bot.constants.Errors.INVALID_WEBHOOK_OPTIONS); - } - - if (options.content && options.content.length > 2000) { - throw Error(bot.constants.Errors.MESSAGE_MAX_LENGTH); - } - - options.embeds?.splice(10); - - if (options.allowedMentions) { - if (options.allowedMentions.users?.length) { - if (options.allowedMentions.parse?.includes(AllowedMentionsTypes.UserMentions)) { - options.allowedMentions.parse = options.allowedMentions.parse.filter((p) => p !== "users"); - } - - if (options.allowedMentions.users.length > 100) { - options.allowedMentions.users = options.allowedMentions.users.slice(0, 100); - } - } - - if (options.allowedMentions.roles?.length) { - if (options.allowedMentions.parse?.includes(AllowedMentionsTypes.RoleMentions)) { - options.allowedMentions.parse = options.allowedMentions.parse.filter((p) => p !== "roles"); - } - - if (options.allowedMentions.roles.length > 100) { - options.allowedMentions.roles = options.allowedMentions.roles.slice(0, 100); - } - } - } - const allowedMentions = options.allowedMentions ? { parse: options.allowedMentions.parse, @@ -65,6 +30,7 @@ export async function sendWebhook(bot: Bot, webhookId: bigint, webhookToken: str file: options.file, embeds: options.embeds, allowed_mentions: allowedMentions, + component: options.components, } ); if (!options.wait) return; diff --git a/src/types/webhooks/editWebhookMessage.ts b/src/types/webhooks/editWebhookMessage.ts index 352c93288..46c4fb55b 100644 --- a/src/types/webhooks/editWebhookMessage.ts +++ b/src/types/webhooks/editWebhookMessage.ts @@ -13,9 +13,14 @@ export interface EditWebhookMessage { /** The contents of the file being sent/edited */ file?: FileContent | FileContent[] | null; /** Allowed mentions for the message */ - allowedMentions?: AllowedMentions | null; + allowedMentions?: Omit & { + /** Array of role_ids to mention (Max size of 100) */ + roles?: bigint[]; + /** Array of user_ids to mention (Max size of 100) */ + users?: bigint[]; + }; /** Attached files to keep */ - attachments?: Attachment | null; + attachments?: (Omit & { id: bigint })[] | null; /** The components you would like to have sent in this message */ components?: MessageComponents; } diff --git a/src/types/webhooks/executeWebhook.ts b/src/types/webhooks/executeWebhook.ts index 34772774e..a52f0ad80 100644 --- a/src/types/webhooks/executeWebhook.ts +++ b/src/types/webhooks/executeWebhook.ts @@ -2,6 +2,7 @@ import { Embed } from "../embeds/embed.ts"; import { AllowedMentions } from "../messages/allowedMentions.ts"; import { FileContent } from "../discordeno/fileContent.ts"; import { SnakeCasedPropertiesDeep } from "../util.ts"; +import { MessageComponents } from "../messages/components/messageComponents.ts"; /** https://discord.com/developers/docs/resources/webhook#execute-webhook */ export interface ExecuteWebhook { @@ -28,6 +29,8 @@ export interface ExecuteWebhook { /** Array of user_ids to mention (Max size of 100) */ users?: bigint[]; }; + /** the components to include with the message */ + components: MessageComponents; } export type DiscordExecuteWebhook = SnakeCasedPropertiesDeep>; diff --git a/worker.ts b/worker.ts new file mode 100644 index 000000000..4c54bc84a --- /dev/null +++ b/worker.ts @@ -0,0 +1,92 @@ +import { GAMER_TOKEN } from "./configs.ts"; +import { createGatewayManager, GatewayManager } from "./mod.ts"; + +function spawnGateway(shardId: number, options: Partial) { + const gateway = createGatewayManager({ + // LOAD DATA FROM DISCORDS RECOMMENDATIONS OR YOUR OWN CUSTOM ONES HERE + shardsRecommended: options.shardsRecommended, + sessionStartLimitTotal: options.sessionStartLimitTotal, + sessionStartLimitRemaining: options.sessionStartLimitRemaining, + sessionStartLimitResetAfter: options.sessionStartLimitResetAfter, + maxConcurrency: options.maxConcurrency, + maxShards: options.maxShards, + // SET STARTING SHARD ID + firstShardId: shardId, + // SET LAST SHARD ID + lastShardId: options.lastShardId ?? shardId, + // THE AUTHORIZATION WE WILL USE ON OUR EVENT HANDLER PROCESS + secretKey: "ifj893rhjn238uf9wev", + token: GAMER_TOKEN, + intents: ["GuildMessages", "Guilds"], + handleDiscordPayload: async function (_, data, shardId) { + // TODO: CHANGE FROM SENDING THROUGH HTTP TO USING A WS FOR FASTER PROCESSING! OR HTTP3 OR WHATEVER! + // TRIGGER RAW EVENT + if (!data.t) return; + + // IF FINAL SHARD BECAME READY TRIGGER NEXT WORKER + if (data.t === "READY") { + if (shardId === gateway.lastShardId) { + // @ts-ignore + postMessage( + JSON.stringify({ + type: "ALL_SHARDS_READY", + }) + ); + } + } + // await fetch(`${EVENT_HANDLER_URL}:${EVENT_HANDLER_PORT}`, { + // headers: { + // Authorization: gateway.secretKey, + // }, + // method: "POST", + // body: JSON.stringify({ + // shardId, + // data, + // }), + // }) + // // BELOW IS FOR DENO MEMORY LEAK + // .then((res) => res.text()) + // .catch(() => null); + }, + }); + + // START THE GATEWAY + gateway.spawnShards(gateway, shardId); + + return gateway; +} + +interface IdentifyPayload { + type: "IDENTIFY"; + shardId: number; + shards: number; + sessionStartLimit: { + total: number; + remaining: number; + resetAfter: number; + maxConcurrency: number; + }; + shardsRecommended: number; + sessionStartLimitTotal: number; + sessionStartLimitRemaining: number; + sessionStartLimitResetAfter: number; + maxConcurrency: number; + maxShards: number; + lastShardId: number; +} +// @ts-ignore +self.onmessage = function (message: MessageEvent) { + const data = JSON.parse(message.data) as IdentifyPayload; + + if (data.type === "IDENTIFY") { + spawnGateway(data.shardId, { + shardsRecommended: data.shardsRecommended, + sessionStartLimitTotal: data.sessionStartLimitTotal, + sessionStartLimitRemaining: data.sessionStartLimitRemaining, + sessionStartLimitResetAfter: data.sessionStartLimitResetAfter, + maxConcurrency: data.maxConcurrency, + maxShards: data.maxShards, + lastShardId: data.lastShardId, + }); + } +};