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

如何在Discord机器人中实现「消息包含指定内容则执行操作」功能?

How to Handle Unknown "$" Prefixed Commands in a Discord Bot

Problem Description

I'm developing a Discord bot and want it to automatically reply when users use a command with the "$" prefix that isn't recognized. I need to use a "contains" function for this. Here's my current code:

switch(message.content){ 
  case '$status': message.reply('Online and ready to go!'); break; 
  case 'ping': message.reply('Pong!'); break; 
  case '$help': message.reply('$status - reply \'Online and ready to go!\''); message.reply('$despacito - reply with despacito'); break; 
  case '$despacito': message.reply('https://pbs.twimg.com/media/D-KIbiaWsAAV1-2.jpg'); break; 
  default: console.log('not recognized:' + message.content); 
}

I want to add functionality after the console.log statement: if the message contains "$", reply with "Uh oh, looks like that's not a valid command." How can I implement this?


Solution

Hey there! This is a straightforward fix using JavaScript's includes() method (which is the equivalent of the "contains" function you're thinking of). You just need to add a conditional check inside the default case of your switch statement.

Here's your modified code:

switch(message.content){ 
  case '$status': message.reply('Online and ready to go!'); break; 
  case 'ping': message.reply('Pong!'); break; 
  case '$help': 
    message.reply('$status - reply \'Online and ready to go!\''); 
    message.reply('$despacito - reply with despacito'); 
    break; 
  case '$despacito': message.reply('https://pbs.twimg.com/media/D-KIbiaWsAAV1-2.jpg'); break; 
  default: 
    console.log('not recognized:' + message.content);
    // Check if the message contains the "$" prefix
    if (message.content.includes('$')) {
      message.reply('Uh oh, looks like that\'s not a valid command.');
    }
    break; 
}

Quick Explanation

  • message.content.includes('$') checks if the incoming message string contains the "$" character. This will trigger for any message starting with "$" that didn't match your defined case statements.
  • We wrap this check in an if block right after logging the unrecognized command, so the bot only sends the error reply when the user was trying to use a "$" prefixed command (and not just any random message).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:40:17