First, here is how you can use regex to parse text in a command:
case /^\/embed \[[\w ]+\]; \[[\w ]+\]$/.test(command):
sendEmbed(message);
break;
This Regular Expression (/^\/embed \[[\w ]+\]; \[[\w ]+\]$/) can be broken down as follows:
- the beginning
/^ and end $/ pieces mean we're trying to match an entire string / command.
/embed matches the exact text "embed"
\[[\w ]+\] is used for the title and for the description, and matches text within square brackets "[]", where the text is letters (uppercase or lowercase), numbers, underscore, or a space. If you need more characters like "!" or "-", I can show you how to add those.
.test(command) is testing that the Regular Expression matches the text from the command, and returns a boolean (true / false).
So now you put that regex checking code in your message / command listener and then call your send embed function (I named it sendEmbed) like this:
// set message listener
client.on('message', message => {
let command = message.content;
// match commands like /embed [title]; [description]
// first \w+ is for the title, 2nd is for description
if ( /^\/embed \[[\w ]+\]; \[[\w ]+\]$/.test(command) )
sendEmbed(message);
});
function sendEmbed(message) {
let command = message.content;
let channel = message.channel;
let author = message.author;
// get title string coordinates in command
let titleStart = command.indexOf('[');
let titleEnd = command.indexOf(']');
let title = command.substr(titleStart + 1, titleEnd - titleStart - 1);
// get description string coordinates in command
// -> (start after +1 so we don't count '[' or ']' twice)
let descStart = command.indexOf('[', titleStart + 1);
let descEnd = command.indexOf(']', titleEnd + 1);
let description = command.substr(descStart + 1, descEnd - descStart - 1);
// next create rich embed
let embed = new Discord.RichEmbed({
title: title,
description: description
});
// set author based of passed-in message
embed.setAuthor(author.username, author.displayAvatarURL);
// send embed to channel
channel.send(embed);
}
Let me know if you have questions!
Update Jan 2021
In the latest version of Discord js (as of Jan 2021), you'll have to create an embed like this:
const embed = new MessageEmbed()
.setTitle(title)
.setDescription(description)
.setAuthor(author.username, author.displayAvatarURL);
See example Embed in docs here. Everything else should be the same.