【问题标题】:How do I make my bot only answer the commands I've coded?如何让我的机器人只回答我编写的命令?
【发布时间】:2020-09-27 19:35:58
【问题描述】:

我的机器人正在回答一些我没有编码的命令。 这是我的代码:

else if (!command === 'cctech' || 'tomorrow'){
         client.commands.get('advance01').execute(message, args); 

我试着穿上这个:

const command = client.commands.get(command);
if (!command) return message.channel.send("Invalid Command.");

但它并没有解决问题。

【问题讨论】:

    标签: javascript discord discord.js


    【解决方案1】:

    这行代码看起来有问题:

    if (!command === 'cctech' || 'tomorrow'){
    
    

    试试这个...

     if (!command === 'cctech' && !command === 'tomorrow'){
    
    

    【讨论】:

    • 我把它改成了那个,我的所有代码都不起作用,机器人根本没有响应我,也没有出现错误消息。
    【解决方案2】:

    问题出在这行代码中:

    if (!command === 'cctech' || 'tomorrow')
    

    首先!command === 'cctech'基本上就是写command的反面是否等于'cctech'。检查两个值是否不相等的正确方法是使用!==

    其次,如果两个输入之一为真,则逻辑 || 运算符将返回 true。一个字符串本身,例如tomorrow,总是真实的。

    if ('random string') console.log("'random string' is truthy");
    
    const str = 'something'
    if (str === 'hello' || 'goodbye') 
      console.log('Even though the first expression is falsy, the second input is a stand alone string, which returns `true`')

    不幸的是,我们不能走这样的捷径,我们必须把整个表达式写两次。此外,您应该使用逻辑 && 运算符,因为在这种情况下 两个 输入都应该为真。

    if (command !== 'cctech' && !command !== 'tomorrow
    

    但是,即使您的方法不是可行的捷径,我们仍有一些方法可以缩短它。想到的两种最佳方式是Array.prototype.includes()RegEx.prototype.test()。这是一个例子:

    const str = 'something';
    if (str !== 'hello' && str !== 'goodbye') 
      console.log('This will work');
    
    // if one of the array elements is the command
    if (!['hello', 'goodbye'].includes(str))
      console.log('This will work too');
    
    // test a RegEx against the command string
    if (!/hello|goodbye/.test(str))
      console.log('This will work as well');

    【讨论】:

      猜你喜欢
      • 2021-11-15
      • 1970-01-01
      • 2020-11-04
      • 1970-01-01
      • 2021-05-11
      • 2019-06-29
      • 1970-01-01
      • 2021-08-03
      • 2020-08-14
      相关资源
      最近更新 更多