如何通过消息创建嵌入?

时间:2021-03-16 18:04:55

标签: discord.js

我有以下名为 say 的命令,它使用以下语法生成嵌入:!say hello, It's a test,#000000

它工作得很好,但问题是我希望它更容易创建嵌入,以便任何特权用户可以在不知道命令语法的情况下创建嵌入,并使我更容易维护所有阵营embed 可以处理而无需将它们分配给变量。

const Discord = require("discord.js");

module.exports.run = async (client, msg, args) => {
    let [Title,Description,Color] = args;
    let embed = new Discord.MessageEmbed()
    .setColor(Color)
    .setTitle(Title)
    .setDescription(Description)

    msg.channel.send(embed);
}

module.exports.help = {
    name: "embed"
}

1 个答案:

答案 0 :(得分:0)

实现这一目标的最佳方法是使用 MessageEmbed 接受对象作为数据的特权。

所以我的解决方案将具有以下语法:

!say {
  "title": "hello",
  "description": "It's a test",
  "color": 000000
}

以及 MessageEmbed 可以采用的许多其他属性。

<块引用>

有用的链接: Embed builder

背后的代码将处理我们的参数并将它们转换为嵌入

const rawJson = args.join(" ") || "";

let json = {};
try {
  json = JSON.parse(rawJson);
} catch (err) {
  message.reply(`${err}`);
}
if (!json) return;

const content = json.content || json.text || json.plainText || "";
//In case the thumbnail comes as a string {json.thumbnail = "test.com/image.png"} so we assign it into the url of the thumbnail
if (typeof json.thumbnail === "string") {
  json.thumbnail = { url: json.thumbnail };
}
//Same here
if (typeof json.image === "string") {
  json.image = { url: json.image };
}

message.channel.send(content, { embed: json }).catch((err) => {
  message.reply(`${err}`)
});