首先,您可以使用正则表达式来解析命令中的文本:
case /^\/embed \[[\w ]+\]; \[[\w ]+\]$/.test(command):
sendEmbed(message);
break;
这个Regular Expression (/^\/embed \[[\w ]+\]; \[[\w ]+\]$/) 可以分解如下:
- 开头的
/^ 和结尾的$/ 表示我们正在尝试匹配整个字符串/命令。
-
/embed 匹配确切的文本 "embed"
-
\[[\w ]+\] 用于标题和描述,并匹配方括号 "[]" 中的文本,其中文本是字母(大写或小写)、数字、下划线或空格。如果您需要更多字符,例如 "!" 或 "-",我可以向您展示如何添加这些字符。
-
.test(command) 正在测试正则表达式是否与命令中的文本匹配,并返回一个布尔值 (true / false)。
所以现在您将正则表达式检查代码放入您的消息/命令侦听器中,然后像这样调用您的发送嵌入函数(我将其命名为 sendEmbed):
// 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);
}
如果您有任何问题,请告诉我!
2021 年 1 月更新
在最新版本的 Discord js 中(截至 2021 年 1 月),您必须像这样创建嵌入:
const embed = new MessageEmbed()
.setTitle(title)
.setDescription(description)
.setAuthor(author.username, author.displayAvatarURL);
请参阅文档中的示例嵌入 here。其他一切都应该相同。