Discord bot: Respond “Unknown command” when using an incorrectly spelled command

試著忘記壹切 提交于 2021-01-29 12:02:05

问题


I want to have my discord.js bot respond

Unknown command, use c!help for available commands" when doing something like, c!hep (misspelled), or a different type of command not implemented, like, c!youtube, or just flat out random letters like c!rgoiw.

Basically just a response if their message doesn't match any commands available.

I don't have any specific code, I'm just using the const PREFIX = 'c!'; with let args = message.content.substring(PREFIX.length).split(" ") and setting all the commands in a switch(args[0]){ block.

I don't know really anything about coding, all that i've done so far is pretty self explanatory once wrote out, but I don't know what to go for when writing it from scratch.

Haven't seen any threads online about an unknown command response so I'm assuming it might be impossible to do. Thanks

const PREFIX = 'c!';

bot.on('message', message=>{

let args = message.content.substring(PREFIX.length).split(" ")

switch(args[0]){
        case 'example':
        break;
//Code to respond to the prefix with no matching case
  }

})

回答1:


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

A default clause; if provided, this clause is executed if the value of expression doesn't match any of the case clauses.

Example:

switch (expr) {
  case 'Oranges':
    console.log('Oranges are $0.59 a pound.');
    break;
  case 'Mangoes':
  case 'Papayas':
    console.log('Mangoes and papayas are $2.79 a pound.');
    // expected output: "Mangoes and papayas are $2.79 a pound."
    break;
  default:
    console.log('Sorry, we are out of ' + expr + '.');
}

As shown above, if nothing matches (to translate to your use case - if no command is recognized) then execute commands found under default

In other words, your code should be

switch(args[0]){
        case 'example':
        break;
        default: console.log(`Unknown command, use c!help for available  commands`);
  }
})


来源:https://stackoverflow.com/questions/58336435/discord-bot-respond-unknown-command-when-using-an-incorrectly-spelled-command

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!