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

Discord.js v14斜杠命令自定义状态时状态值为null的问题排查

问题分析与解决方案

你的代码里获取到的stat为null,大概率是斜杠命令的参数没有正确注册或者命令未同步到Discord导致的,以下是具体排查和解决步骤:

1. 检查斜杠命令的参数注册

确保你在定义status命令时,参数名称是status且设置为必填。如果参数不是必填,用户未输入时getString('status')就会返回null。正确的命令注册示例:

const { SlashCommandBuilder } = require('discord.js');

module.exports = {
  data: new SlashCommandBuilder()
    .setName('status')
    .setDescription('Ändere den Spielstatus des Bots')
    .addStringOption(option =>
      option.setName('status')
        .setDescription('Der neue Status-Text')
        .setRequired(true)), // 必须设为必填,强制用户输入内容
  async execute(interaction) {
    const stat = interaction.options.getString('status');
    interaction.client.user.setActivity({ name: stat });
    await interaction.reply(`Spielstatus auf ${stat} geändert!`);
    console.log(`Neuer Status: ${stat}`);
  },
};

2. 重新同步命令到Discord

如果你修改了命令的参数定义,必须重新同步命令到Discord平台,否则Discord那边的命令配置还是旧的,导致参数无法正确传递。

同步命令的代码示例(放在单独的文件比如deploy-commands.js里运行):

const { REST, Routes } = require('discord.js');
const { clientId, guildId, token } = require('./config.json'); // 替换成你的配置
const fs = require('node:fs');
const path = require('node:path');

const commands = [];
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
  const filePath = path.join(commandsPath, file);
  const command = require(filePath);
  commands.push(command.data.toJSON());
}

const rest = new REST({ version: '10' }).setToken(token);

// 同步到测试服务器(立即生效)
rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands })
  .then(() => console.log('Server-Befehle erfolgreich aktualisiert'))
  .catch(console.error);

// 同步为全局命令(最多1小时生效)
// rest.put(Routes.applicationCommands(clientId), { body: commands })
//   .then(() => console.log('Globale Befehle erfolgreich aktualisiert'))
//   .catch(console.error);

运行这个文件后,再测试你的/status命令。

3. 其他排查点

  • 确认参数名称完全匹配:代码里的getString('status')必须和注册时的option.setName('status')大小写一致,Discord的参数名称是大小写敏感的。
  • 确保机器人已登录:在client.on('ready')事件里打印client.user.tag,确认client.user不为null,否则无法调用setActivity。

内容的提问来源于stack exchange,提问作者Florian Pufiiiii Riener

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 11:03:25