Skip to content
This repository has been archived by the owner on Oct 15, 2024. It is now read-only.

Fonctions utilitaires en rapport avec les messages Discord #217

Closed
wants to merge 14 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 11 additions & 9 deletions src/commands/forum/[sub-commands]/resolve.cmd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@ import { commands } from "#/configs/message/command";
import { ChannelType, ForumChannel } from "discord.js";
import { logger } from "#/utils/logger";
import { userWithId } from "#/utils/discord/user";
import { trustDiscordLinks } from "../forum.const";
import { extractDiscordLink } from "#/utils/message/message.util";
import type { DiscordMessage } from "#/utils/message/message.type";

export const execute: CommandExecute = async(command) => {

const channel = command.channel;

if (channel?.type !== ChannelType.PublicThread || !(channel.parent instanceof ForumChannel)) {
Expand All @@ -21,28 +23,28 @@ export const execute: CommandExecute = async(command) => {

const answerLink = command.options.getString(commands.forum.subcmds.resolve.options.answer.name, true);

if (!answerLink.match(trustDiscordLinks)) {
const message: DiscordMessage | null = extractDiscordLink(answerLink);

if (!message) {
void command.reply({
embeds: [simpleEmbed(commands.forum.exec.resolve.isntDiscordMessageLink, "error")],
ephemeral: true
});
return;
}

const ids = [...answerLink.match(/(\d+)/g) ?? []];

if (ids[0] !== channel.guildId || ids[1] !== channel.id) {
if (message.guildID !== channel.guildId || message.channelID !== channel.id) {
void command.reply({
embeds: [simpleEmbed(commands.forum.exec.resolve.badLocation, "error")],
ephemeral: true
});
return;
}

let message: Message<true>;
let fetchedMessage: Message;

try {
message = await channel.messages.fetch(ids[2]);
fetchedMessage = await channel.messages.fetch(message.messageID);
} catch (error) {
void command.reply({
embeds: [simpleEmbed(commands.forum.exec.resolve.unknownMessage, "error")],
Expand All @@ -51,15 +53,15 @@ export const execute: CommandExecute = async(command) => {
return;
}

if (!message.pinnable) {
if (!fetchedMessage.pinnable) {
void command.reply({
embeds: [simpleEmbed(commands.forum.exec.resolve.unpinnableMessage, "error")],
ephemeral: true
});
return;
}

await message.pin();
await fetchedMessage.pin();
await command.reply({
embeds: [simpleEmbed(msgParams(commands.forum.exec.resolve.succes, [answerLink]))]
});
Expand Down
2 changes: 2 additions & 0 deletions src/commands/forum/forum.builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import type { GuildsCommand } from "#/utils/handler/command/command.type";

export const guilds: GuildsCommand = ["pro"];

export const enableInDev = true;

export const slashCommand: SlashCommandDefition = new SlashCommandBuilder()
.setName(commands.forum.name)
.setDescription(commands.forum.description)
Expand Down
32 changes: 32 additions & 0 deletions src/utils/message/_test/extract-discord-link.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { describe, it, expect } from "vitest";
import { extractDiscordLink } from "#/utils/message";

describe("extractDiscordLink function", () => {
it("should correctly extract discord canary link", () => {
expect(extractDiscordLink("https://canary.discord.com/channels/732251741999071303/973634573936246834/1128283771691601942")).toEqual({
guildID: "732251741999071303",
channelID: "973634573936246834",
messageID: "1128283771691601942"
});
});

it("should correctly extract discord ptb link", () => {
expect(extractDiscordLink("https://canary.discord.com/channels/732251741999071303/977731788002697326/1119643273695346820")).toEqual({
guildID: "732251741999071303",
channelID: "977731788002697326",
messageID: "1119643273695346820"
});
});

it("should correctly extract discord link", () => {
expect(extractDiscordLink("https://discord.com/channels/732251741999071303/786216771723198514/803532192793493544")).toEqual({
guildID: "732251741999071303",
channelID: "786216771723198514",
messageID: "803532192793493544"
});
});

it("should return empty array when no discord link is found", () => {
expect(extractDiscordLink("https://www.youtube.com/watch?v=dQw4w9WgXcQ")).toStrictEqual([]);
});
});
25 changes: 25 additions & 0 deletions src/utils/message/_test/get-message-instance.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { describe, expect, it } from "vitest";
import { getMessageFromLink } from "#/utils/message";
import { Message } from "discord.js";

describe("isDiscordLink function", () => {
it("should return instance of Message", async() => {
const message = await getMessageFromLink("https://discord.com/channels/732251741999071303/786216771723198514/803532192793493544");
expect(message).toBeInstanceOf(Message);
});

it("should return instance of Message with PTB link", async() => {
const message = await getMessageFromLink("https://ptb.discord.com/channels/732251741999071303/786216771723198514/803532192793493544");
expect(message).toBeInstanceOf(Message);
});

it("should return instance of Message with Canary link", async() => {
const message = await getMessageFromLink("https://canary.discord.com/channels/732251741999071303/786216771723198514/803532192793493544");
expect(message).toBeInstanceOf(Message);
});

it("should return null when the link is not a discord link", async() => {
const message = await getMessageFromLink("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
expect(message).toBe(null);
});
});
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
import { msgParams } from "./message.util";
import { msgParams } from "#/utils/message";

describe("msgParams function", () => {
it("should correctly replace placeholders with provided words", () => {
Expand Down
2 changes: 1 addition & 1 deletion src/utils/message/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export { msgParams } from "./message.util";
export { msgParams, extractDiscordLink, getMessageFromLink } from "./message.util";
9 changes: 9 additions & 0 deletions src/utils/message/message.type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import type { Snowflake } from "discord.js";

export const discordLinkRegex = /http(s?):\/\/(www\.|canary\.|ptb\.)?discord.com\/channels(\/\d*){3}/gi;

export type DiscordMessage = {
guildID: Snowflake;
channelID: Snowflake;
messageID: Snowflake;
}
38 changes: 38 additions & 0 deletions src/utils/message/message.util.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,47 @@
import type { Message } from "discord.js";
import type { DiscordMessage } from "./message.type";
import { client } from "#/client";
import { messageUrlRegex } from "#/events/message-link-reaction/message-link-reaction.const";

export const msgParams = (message: string, params: (string | number)[]): string => {
const words = message.match(/{[^}]+}/g);

if (words) for (let i = 0; i < params.length; i++) {
message = message.replace(words[i], String(params[i]));
}

return message;
};

export const extractDiscordLink = (content: string): DiscordMessage | null => {
if (!content.match(messageUrlRegex)) return null;
const [guildID, channelID, messageID] = [...content.match(/(\d+)/g) ?? []];
if (!guildID || !channelID || !messageID) return null;

return {
guildID,
channelID,
messageID
};
};

export const getMessageFromLink = async(link: string): Promise<Message<true> | null> => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suite aux modifications de extractDiscordLink, cette fonction devrait être bien plus simple car elle n'a plus à gérer la logique d'extraction.

const ids = [...link.match(/(\d+)/g) ?? []];

if (ids.length !== 3) return null;

const guildId = ids[0];
const channelId = ids[1];
const messageId = ids[2];
Comment on lines +29 to +35
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

La manière de parse est pourrait être amélioré :

const content = `
	Hello World!
 	https://canary.discord.com/channels/732251741999071303/786216771723198514/803532192793493544
  	are you ok ?
   	https://canary.discord.com/channels/732251741999071303/786216771723198514/803532192793493544
`;

const matchs = [...content.matchAll(/\/\d+\/\d+\/\d+/g)].map(element => {
  const [guildID, channelID, messageID] = [...element[0].matchAll(/\d+/g)].map(e => e[0]);
  
  return { guildID, channelID, messageID };
});

console.log(matchs);


const guild = await client.guilds.fetch(guildId);
if (!guild) return null;

const channel = await guild.channels.fetch(channelId);
if (!channel || !channel.isTextBased()) return null;

const message = await channel.messages.fetch(messageId);
if (!message) return null;

return message;
};