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

Discord机器人Switch执行正常后抛出TypeError问题求助

问题修复方案

报错根源

当消息不匹配前缀时,isCommand函数返回布尔值false,而布尔值没有split()方法,导致执行switch(command.split(' ')[0])时抛出TypeError: command.split is not a function。

修复步骤及代码优化

1. 修正isCommand函数

解决前缀长度固定为1的问题,同时增加空值防护:

async function isCommand(msg) {
    const config = await serverConfig.findOne({ _id: msg.guildId + "" }, { prefix: 1 });
    // 防护:如果查询不到配置或前缀为空,直接返回false
    if (!config?.prefix) return false;
    // 用startsWith替代indexOf,可读性更强
    if (msg.content.startsWith(config.prefix)) {
        // 按实际前缀长度截取,适配多字符前缀
        return msg.content.slice(config.prefix.length);
    }
    return false;
}

2. 修正命令处理逻辑

先过滤非命令消息,提前拆分命令与参数,避免重复调用split():

const commandStr = await isCommand(msg);
// 非命令消息直接跳过后续处理
if (!commandStr) return;

// 一次性拆分命令和参数,解构赋值更简洁
const [command, ...args] = commandStr.split(' ');

switch(command) {
    case 'set-prefix':
        msg.reply(`Prefix changed to ${args[0]}`);
        break;
    case 'ignore-channel':
        msg.reply(`Ignoring channel ${args[0]}`);
        break;
    case 'unignore-channel':
        msg.reply(`Channel ${args[0]} unignored`);
        break;
    case 'ignore-badword':
        msg.reply(`Ignoring word ${args[0]}`);
        break;
    case 'unignore-badword':
        msg.reply(`Word ${args[0]} unignored`);
        break;
    case 'add-badword':
        msg.reply(`Added word ${args[0]} to bad words`);
        break;
    case 'remove-badword':
        msg.reply(`Removed word ${args[0]} from bad words`);
        break;    
    default: 
        msg.reply('Command not recognized');
        break;
}

额外优化点

  • 使用模板字符串替代字符串拼接,代码更简洁
  • 提前拆分命令和参数,减少重复的字符串操作
  • 增加数据库查询结果的空值防护,避免潜在的空指针错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 11:10:14