diff --git a/src/index.ts b/src/index.ts index fac67fd..e05a959 100644 --- a/src/index.ts +++ b/src/index.ts @@ -12,10 +12,12 @@ import Discord, { Events, GatewayIntentBits, type Interaction, + Message, Partials, } from "discord.js"; import CommandHandler from "@/commandHandler"; import { env } from "@/config/env"; +import { suppressGitHubUnfurl } from "./util/suppressGitHubUnfurl"; process.on("unhandledRejection", reason => { console.log("Unhandled Rejection:", reason); @@ -24,8 +26,9 @@ process.on("unhandledRejection", reason => { const client = new Discord.Client({ intents: [ GatewayIntentBits.Guilds, - GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildEmojisAndStickers, + GatewayIntentBits.GuildMessages, + GatewayIntentBits.MessageContent, ], partials: [Partials.Message, Partials.Channel, Partials.Reaction], }); @@ -61,24 +64,16 @@ client.on(Events.InteractionCreate, async (interaction: Interaction) => { client.on(Events.Error, e => { console.error("Discord client error!", e); }); -client.on(Events.MessageCreate, async message => { - if (message.author.bot) return; - - message = await message.fetch(); - for (const embed of message.embeds) { - if (!embed.url) continue; - - const url = new URL(embed.url); - if (url.host !== "github.com") continue; +// Message updates contain full data. Typings are corrected in a newer discord.js version. +client.on(Events.MessageUpdate, async (_, newMessage) => { + if (!newMessage.inGuild()) return; + await suppressGitHubUnfurl(newMessage as Message); +}); - const segments = url.pathname.split("/"); - const githubUrlType: string | undefined = segments[3]; - if (githubUrlType === "tree" || githubUrlType === "blob") { - await message.suppressEmbeds(); - return; - } - } +client.on(Events.MessageCreate, async (message: Message) => { + if (message.author.bot || !message.inGuild()) return; + await suppressGitHubUnfurl(message); }); client.login(env.DISCORD_TOKEN); diff --git a/src/util/suppressGitHubUnfurl.ts b/src/util/suppressGitHubUnfurl.ts new file mode 100644 index 0000000..c868a94 --- /dev/null +++ b/src/util/suppressGitHubUnfurl.ts @@ -0,0 +1,24 @@ +import { Message, MessageFlags, PermissionFlagsBits } from "discord.js"; + +export async function suppressGitHubUnfurl(message: Message) { + if (message.flags.has(MessageFlags.SuppressEmbeds)) return; + const me = await message.guild.members.fetch(message.client.user.id); + + if (!message.channel.permissionsFor(me).has(PermissionFlagsBits.ManageMessages)) { + console.log("Missing permissions to suppress embeds."); + return; + } + + for (const embed of message.embeds) { + if (!embed.url) continue; + const url = new URL(embed.url); + if (url.host !== "github.com") continue; + const segments = url.pathname.split("/"); + const githubUrlType: string | undefined = segments[3]; + + if (githubUrlType === "tree" || githubUrlType === "blob") { + await message.edit({ flags: message.flags.bitfield | MessageFlags.SuppressEmbeds }); + return; + } + } +}