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

如何让Discord.js v14的/console斜杠命令响应指定字符串?

解决方案:Discord.js v14 /console 斜杠命令实现

问题分析

你的现有代码存在几个关键问题:

  • 错误引入了无关的ms模块(该模块用于处理时间格式,和当前需求不相关)
  • 缺少EmbedBuilder的导入,也未在execute函数中传入client参数
  • 没有实现输入内容的匹配逻辑,也没有发送Embed的核心代码

完整实现代码

const { ApplicationCommandType, ApplicationCommandOptionType, EmbedBuilder } = require('discord.js');

// 定义命令映射表,key为用户输入字符串,value为对应返回内容
const commandMap = {
    'ping': 'pong',
    'hi': 'hello',
    // 可在此处添加更多命令映射
};

module.exports = {
    name: 'console',
    description: 'Developer Mode!',
    voiceChannel: false,
    options: [
        {
            name: 'code',
            description: 'A line of code you wish to execute',
            type: ApplicationCommandOptionType.String,
            required: true,
        }
    ],
    async execute({ inter, client }) {
        // 获取用户输入并转为小写,避免大小写匹配问题
        const userInput = inter.options.getString('code').toLowerCase();
        
        // 构建基础Embed模板
        const embed = new EmbedBuilder()
            .setColor('#5679EF')
            .setAuthor({ 
                name: client.user.username, 
                iconURL: client.user.displayAvatarURL({ size: 1024, dynamic: true }) 
            })
            .setTitle("💻 Console");

        // 判断输入是否在命令映射表中
        if (commandMap.hasOwnProperty(userInput)) {
            embed.setDescription(`**输入**: ${userInput}\n**输出**: ${commandMap[userInput]}`);
        } else {
            // 未匹配到命令时返回提示
            embed.setDescription(`⚠️ 未知命令:${userInput}\n当前支持的命令:${Object.keys(commandMap).join(', ')}`);
        }

        // 发送Embed回复用户
        await inter.reply({ embeds: [embed] });
    },
};

关键修改说明

  • 移除无用的ms模块导入,新增EmbedBuilder的必要导入
  • 新增commandMap对象统一管理命令与返回内容的映射,便于后续扩展
  • 修正选项名称为小写(Discord命令选项名称规范要求)
  • 在execute函数中添加client参数,确保能获取机器人的用户信息
  • 实现输入匹配逻辑,根据是否命中映射表返回对应内容或提示
  • 补充inter.reply代码完成Embed的发送,实现完整的命令响应流程

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 21:36:21