You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord.js v14:带选项选择的Slash Command嵌入消息开发求助

Discord.js v14 带选项的Slash Command实现对应嵌入消息发送

实现步骤

  1. 注册带选项的Slash Command
    定义命令结构,添加String类型的选项并设置多个可选值(choices),让用户选择要发送的嵌入类型。

  2. 创建对应选项的Embed消息
    为每个选项提前定义好包含标题、描述、颜色等内容的Embed对象。

  3. 处理交互并发送对应Embed
    在命令的交互处理函数中,获取用户选择的选项值,匹配对应的Embed并发送。

完整代码示例

const { SlashCommandBuilder, EmbedBuilder, Client, GatewayIntentBits } = require('discord.js');

// 初始化客户端
const client = new Client({ intents: [GatewayIntentBits.Guilds] });

// 定义命令
const embedCommand = new SlashCommandBuilder()
  .setName('send-embed')
  .setDescription('选择要发送的嵌入消息类型')
  .addStringOption(option =>
    option.setName('type')
      .setDescription('选择嵌入消息类型')
      .setRequired(true)
      .addChoices(
        { name: '帮助信息', value: 'help' },
        { name: '服务器规则', value: 'rules' },
        { name: '活动公告', value: 'event' }
      )
  );

// 预定义各个选项对应的Embed
const embeds = {
  help: new EmbedBuilder()
    .setTitle('帮助中心')
    .setDescription('这里是服务器的帮助信息,如有问题可联系管理员')
    .setColor('#00ff00')
    .addFields(
      { name: '命令列表', value: '!help 查看所有命令' },
      { name: '支持渠道', value: '私信管理员获取支持' }
    ),
  rules: new EmbedBuilder()
    .setTitle('服务器规则')
    .setDescription('请遵守以下规则,违规将被处罚')
    .setColor('#ff0000')
    .addFields(
      { name: '禁止刷屏', value: '请勿在频道内重复发送相同内容' },
      { name: '友好交流', value: '禁止辱骂、歧视其他成员' }
    ),
  event: new EmbedBuilder()
    .setTitle('本周活动')
    .setDescription('本周六晚8点将举办游戏联机活动,欢迎参与')
    .setColor('#0000ff')
    .addFields(
      { name: '活动地点', value: '语音频道「游戏联机」' },
      { name: '报名方式', value: '在本消息下回复「报名」即可' }
    )
};

// 监听命令交互
client.on('interactionCreate', async interaction => {
  if (!interaction.isChatInputCommand()) return;

  if (interaction.commandName === 'send-embed') {
    // 获取用户选择的选项值
    const embedType = interaction.options.getString('type');
    // 获取对应的Embed
    const selectedEmbed = embeds[embedType];

    if (selectedEmbed) {
      // 发送Embed消息
      await interaction.reply({ embeds: [selectedEmbed] });
    } else {
      // 处理未知选项的情况
      await interaction.reply({ content: '未知的嵌入类型,请重新选择', ephemeral: true });
    }
  }
});

// 登录客户端
client.login('你的机器人Token');

注意事项

  • 确保机器人已启用Guilds权限,且已将命令注册到对应的服务器(或全局注册)。
  • 可根据需求扩展选项和对应的Embed内容,比如添加更多字段、图片、脚注等。
  • 使用ephemeral: true可让错误提示仅对用户可见,避免频道内冗余信息。

内容的提问来源于stack exchange,提问作者Allen Playz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 06:30:14