fix: finalizing permission plugin

This commit is contained in:
Skillz4Killz
2021-12-22 16:07:57 +00:00
committed by GitHub
parent 6bf83812ea
commit 4b7b9c2658
14 changed files with 261 additions and 229 deletions
@@ -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(),
}
);
@@ -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) => {
+2 -10
View File
@@ -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<Message>(
export async function editMessage(bot: Bot, channelId: bigint, messageId: bigint, content: EditMessage) {
const result = await bot.rest.runMethod<Message>(
bot.rest,
"patch",
bot.constants.endpoints.CHANNEL_MESSAGE(channelId, messageId),
+2 -30
View File
@@ -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<Message>(
bot.rest,
"post",
@@ -170,3 +141,4 @@ export async function sendMessage(bot: Bot, channelId: bigint, content: string |
return bot.transformers.message(bot, result);
}
-18
View File
@@ -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<User>(bot.rest, "patch", bot.constants.endpoints.USER_BOT, {
-1
View File
@@ -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) {
+9 -12
View File
@@ -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<Webhook>(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<Webhook>(
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);
}
+19 -6
View File
@@ -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<undefined>(
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<undefined>(bot.rest, "delete", url);
}
+80 -101
View File
@@ -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<Message>(
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<Message>(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);
}
+19 -7
View File
@@ -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<Message>(
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<Message>(bot.rest, "get", url);
return bot.transformers.message(bot, result);
}
+1 -35
View File
@@ -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;
+7 -2
View File
@@ -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<AllowedMentions, "users" | "roles"> & {
/** 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<Attachment, "id"> & { id: bigint })[] | null;
/** The components you would like to have sent in this message */
components?: MessageComponents;
}
+3
View File
@@ -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<Omit<ExecuteWebhook, "wait">>;
+92
View File
@@ -0,0 +1,92 @@
import { GAMER_TOKEN } from "./configs.ts";
import { createGatewayManager, GatewayManager } from "./mod.ts";
function spawnGateway(shardId: number, options: Partial<GatewayManager>) {
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<string>) {
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,
});
}
};