如何在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 definedcasestatements.- We wrap this check in an
ifblock 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
相关产品推荐
相关产品推荐

