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

如何在discord.js中创建case语句?结合现有代码实现输入响应

如何基于用户输入构建Discord Bot的Case语句

看你提供的代码,我发现几个需要修正的小问题:比如拼写错误(messege应该是message)、把Java的System.out.println用到了JavaScript环境里(Discord Bot需要用专属的消息发送方法),还有变量定义的语法错误,以及重复的message事件监听会导致逻辑混乱。

我帮你重构了代码,既能处理help命令引导用户,又能根据用户输入的数字返回对应结果,一起来看看:

// 定义命令前缀,后续修改更方便
const prefix = '!';

// 合并成单个message事件监听,避免重复处理消息
bot.on('message', (message) => {
  // 忽略机器人自身发送的消息,防止无限循环
  if (message.author.bot) return;

  // 处理help命令
  if (message.content === `${prefix}help`) {
    message.channel.send('With what may you like help?');
    message.reply('Enter 1 to get the server IP');
    message.reply('Enter 2 to get the store link');
    message.reply('Enter 3 to get the Discord instant link');
    return;
  }

  // 解析用户输入的数字选项
  const userInput = message.content.trim();
  const choice = parseInt(userInput);

  // 用switch处理不同输入
  switch (choice) {
    case 1:
      message.reply('The IP of the server is: 123.45.67.89'); // 替换成你的真实服务器IP
      break; // 必须加break,否则会执行后续case的内容
    case 2:
      message.reply('The Store link is: https://your-store-url.com'); // 替换成你的真实商店链接
      break;
    case 3:
      message.reply('Discord instant link: https://discord.gg/your-invite-code'); // 替换成你的真实邀请链接
      break;
    default:
      // 仅当用户输入既不是命令也不是有效数字时,提示帮助
      if (!message.content.startsWith(prefix)) {
        message.reply('Sorry, I don\'t understand that. Type !help to see available options.');
      }
  }
});

关键细节说明:

  • 合并事件监听:把两个bot.on('message')合并成一个,避免同一条消息被重复处理
  • 过滤机器人消息:添加if (message.author.bot) return;,防止机器人响应自己发送的消息
  • 易维护的前缀:用变量定义prefix,后续修改命令前缀只需改这一处
  • 正确的消息发送方式:用Discord.js的message.reply()或message.channel.send()替代Java的输出语句
  • 避免case贯穿:每个case后面都加了break,确保匹配到对应选项后不会执行后续的case逻辑
  • 友好的错误提示:default分支里增加了判断,只在用户输入无效且不是命令时提示帮助

如果需要处理更复杂的多轮对话(比如发送help后等待用户输入),可以使用Discord.js的MessageCollector,但对于当前的需求,上面的代码已经足够简洁好用了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:29:43