【问题标题】:Having a bot send an embed using a player command让机器人使用播放器命令发送嵌入
【发布时间】:2018-05-02 10:46:47
【问题描述】:

我再次需要帮助来创建我的不和谐机器人。我正在尝试让机器人使用命令发送嵌入。我的代码太复杂,无法通过此消息发送,因为我在该命令中具有所有额外功能,所以我只想说命令应该是什么样子;

/embed [title]; [description]

在标题和描述之前是

setAuthor(`${message.author.username}`, message.author.displayAvatarURL)

这样嵌入的作者就会出现。关于如何做到这一点的任何想法?

【问题讨论】:

  • 如果我的回答有帮助,请告诉我!

标签: node.js discord.js


【解决方案1】:

首先,您可以使用正则表达式来解析命令中的文本:

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。其他一切都应该相同。

【讨论】:

  • 你可以编辑它以匹配最新版本的discord js
  • @Quark-epoch 我更新了问题,现在应该可以了 :) 如果您遇到任何问题,请告诉我
猜你喜欢
  • 1970-01-01
  • 2023-03-30
  • 2019-06-29
  • 2020-10-05
  • 2019-05-24
  • 2023-01-13
  • 2021-06-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多