'How to get the message content from a Discord message URL?
Let's say user x sends a message in channel x. In channel y, someone sends the message link of what was said in channel x by user x and for ease of use, the Discord bot makes an embedded message with the description as the linked message content and such.
For better understanding, please refer to the image linked.
Solution 1:[1]
You can get the message id within the sent link. After getting the id, you can fetch the message (or get it in the cache), using the MessageManager accessible from TextChannel.messages property and display the content.
Here's an example:
const messageLink = <Message>.content;
const messageId = messageLink.split('/')[messageLink.split('/').length - 1]; // The id of the message is in the last position in the link
const resolvedMessage = await <TextChannel>.messages.fetch(messageid);
<TextChannel>.send(resolvedMessage.content);
An other solution is to match the link with a regex, and get the id with a group.
const discordLinkReg = /https:\/\/discord\.com\/channels\/\d{18}\/\d{18}\/(\d{18})/g;
const messageId = discordLinkReg.exec(<Message>.content)[1]; // 0 is the link, 1 the first group
const resolvedMessage = await <TextChannel>.messages.fetch(messageid);
<TextChannel>.send(resolvedMessage.content);
To get the content of messages for any guild (apart the guilds the bot isn't on) you can use regexes groups, like so:
const discordLinkReg = /https?:(?:www\.)?\/\/discord(?:app)?\.com\/channels\/(\d{18})\/(\d{18})\/(\d{18})/g;
// Make sure the content will always be a discord link.
const parsed = discordLinkReg.exec(someWayToGetContent());
const messageId = parsed[3];
const channelid = parsed[2];
const guildId = parsed[1];
// Or shorter
const [, guildId, channelId, messageId] = discordLinkReg.exec(someWaytoGetContent());
const guild = await <Client>.guilds.fetch(guildId);
const channel = await <Client>.channels.fetch(channelId);
const message = await channel.messages.fetch(messageId);
await channel.send(`Oh, got this: ${message.content}`);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
