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

discord.js命令选项字符串调用toLowerCase()致机器人崩溃问题排查

解决Discord机器人中toLowerCase()调用导致的TypeError问题

报错原因

当interaction.options.getString("favourite-pet")返回null时(比如用户未提供该选项,或选项未设置为必填),直接调用.toLowerCase()会触发TypeError: Cannot read properties of null (reading 'toLowerCase'),导致机器人崩溃。

修复方案

方案1:先检查值是否存在

先将选项值存入变量,判断其不为null/undefined后再调用方法:

const pet = interaction.options.getString("favourite-pet");
if (pet && pet.toLowerCase() === "dog") {
    const embed = new EmbedBuilder()
      .setTitle("No way dogs my fav too")
      .setDescription(" i cant believe we both love dogs")
      .setColor("Orange");

    interaction.reply({ embeds: [embed] });
}

方案2:使用可选链操作符

利用?.可选链语法,当左侧值为null/undefined时,表达式直接返回undefined,避免报错:

if (interaction.options.getString("favourite-pet")?.toLowerCase() === "dog") {
    const embed = new EmbedBuilder()
      .setTitle("No way dogs my fav too")
      .setDescription(" i cant believe we both love dogs")
      .setColor("Orange");

    interaction.reply({ embeds: [embed] });
}

方案3:设置选项为必填(推荐)

如果该选项是命令必须的参数,在定义命令时将其设为必填,确保用户必须输入,从根源避免null的情况:

// 命令定义示例
const { SlashCommandBuilder } = require('discord.js');

const command = new SlashCommandBuilder()
  .setName("your-command-name")
  .setDescription("Share your favourite pet")
  .addStringOption(option => 
    option.setName("favourite-pet")
      .setDescription("Your favourite pet")
      .setRequired(true) // 标记为必填选项
  );

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 12:22:34