首页 > 解决方案 > 如何在聊天中创建不和谐嵌入?

问题描述

我调用了以下命令,该命令say使用以下语法生成嵌入:!say hello, It's a test,#000000.

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

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"
}

标签: discord.js

解决方案


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

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

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

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

有用的链接: 嵌入构建器

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

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}`)
});


推荐阅读