【问题标题】:Why does bulkDelete not work with no error?为什么 bulkDelete 不能正常工作?
【发布时间】:2022-01-13 18:28:58
【问题描述】:

我尝试查找拼写错误和其他不准确之处,并尝试为 prune 命令添加权限要求,但当我输入金额时,ping pong 和“无效号码”回复仍然有效,但 prune 无效。

详细信息:我正在尝试制作一个可以根据输入进行修剪的 Discord 机器人。我使用 DJS v12 并遵循(编辑)本指南https://v12.discordjs.guide/creating-your-bot/commands-with-user-input.html#number-ranges

if (!msg.content.startsWith(prefix) || msg.author.bot) return;
if (!msg.member.hasPermission("BAN_MEMBERS")) {
  msg.channel.send("You don\'t have permission.");
}
const args = msg.content.slice(prefix.length).trim().split('/ +/');
const cmd = args.shift().toLowerCase();
  if (cmd === `ping`) {
    msg.reply('pong.');
  } else if (cmd === `prune`) {
    if (!msg.guild.me.hasPermission("MANAGE_MESSAGES")) return;
    const amount = parseInt(args[0]) + 1;
    
    if (isNaN(amount)) {
      return msg.reply('Not a valid number.');
    } else if (amount <= 1 || amount > 100) {
      return msg.reply('Please input a number between 1 and 99.');
    }
  msg.channel.bulkDelete(amount, true).catch(err => {
        console.error(err);
        msg.channel.send('Error!');
   });
  }
});

【问题讨论】:

  • 错字:.split('/ +/')应该是.split(/ +/),因为它是一个正则表达式,而if (!msg.guild.me.hasPermission("MANAGE_MESSAGES") return中缺少),所以应该是if (!msg.guild.me.hasPermission("MANAGE_MESSAGES")) return
  • @ZsoltMeszaros 谢谢,我完全错过了 split()。写问题时我也错过了 ) 。但是有一个问题,如果我不加引号,它会起作用吗?
  • 是的,它可以在没有单引号的情况下工作。 / +/ 是一个正则表达式,表示被一个或多个空格分隔。我更喜欢这个而不是单个" ",因为即使用户在参数之间添加了一些不必要的空格,它也会按预期工作。在浏览器的控制台中查看'one two three'.split(' ')'one two three'.split(/ +/) 之间的区别。第一个返回一个包含五个项目的数组(其中两个是空字符串,而第二个返回一个包含三个项目的数组:onetwothree

标签: javascript discord discord.js bots bulk


【解决方案1】:

您的 prune 命令不起作用的原因是您的命令解析。 args 始终为 nullcmd 始终包含整个字符串。

因此,如果您输入$prune 3,您的args 将为空并且cmd 包含prune 3。这就是为什么你的if 在这里:

else if (cmd === `prune`)

不匹配(如果您指定了参数)并且您的 prune 命令永远不会被执行。

要解决这个问题,您需要更改命令解析:

const cmd = msg.content.split(" ")[0].slice(prefix.length);
const args = msg.content.split(" ").slice(1);

注意:您的问题似乎也有错字:

if (!msg.guild.me.hasPermission("MANAGE_MESSAGES") return;
//                           Missing ")" here ----^

所以把那行改成

if (!msg.guild.me.hasPermission("MANAGE_MESSAGES")) return;

【讨论】:

  • 非常感谢。现在可以了!我可以知道如何更多地了解这些东西吗?当我不知道为什么我的 Discord 机器人代码不起作用时,是否有可以参考的来源?
  • @Miku 很高兴我能帮上忙 :) 类似的东西大多来自经验。在这种情况下,我认为在无效命令上没有打印任何内容很奇怪。所以我使用console.log 来验证是否调用了代码块以及我希望其中包含的所有信息。
猜你喜欢
  • 2021-03-25
  • 2016-07-16
  • 2019-01-04
  • 2020-09-03
  • 2016-10-10
  • 2016-10-24
  • 2017-02-27
  • 2017-07-08
  • 2014-11-23
相关资源
最近更新 更多