1

哟,所以我试图将我的清除命令读取到我正在构建的不和谐机器人中,它一直声称该号码无效。

基本上它在代码响应中抛出第一个错误。

有谁知道我在代码中搞砸了什么?对于这方面的任何帮助,我将不胜感激。

这是我的purge.js代码:

const Discord = require('discord.js');
const { Command } = require('discord.js-commando');

module.exports = class PurgeCommand extends Command {
    constructor(client) {
        super(client, {
            name: 'purge',
            aliases: ['p', 'c', 'clean'],
            group: 'admin',
            memberName: 'purge',
            description: 'Purge some messages from a Text Channel.',
            examples: ['purge 5'],
            guildOnly: true,
            throttling: {
                usages: 1,
                duration: 3
            },
            clientPermissions: ['MANAGE_CHANNELS'],
            userPermissions: ['MANAGE_CHANNELS'],

            args: [
                {
                    key: 'amount',
                    label: 'number',
                    prompt: 'Please input a number between 0 and 100.',
                    type: 'integer'
                }
            ]
        });
    }

    run(message, args) {
        const amount = parseInt(args[0]) + 1;

        if (isNaN(amount)) {
            return message.reply('```css\n[ERROR] Please provide a valid number.\n```');
        } else if (amount <= 0 || amount > 100) {
            return message.reply('```css\n[ERROR] You need to input a number between 0 and 100.\n```');
        }

        message.channel.bulkDelete(amount, true).then(deletedMessages => {
                var botMessages = deletedMessages.filter(m => m.author.bot);
                var userPins = deletedMessages.filter(m => m.pinned);
                var userMessages = deletedMessages.filter(m => !m.author.bot);

                const embed = new Discord.MessagEmbed()
                    .setTitle("Purge Command Issued")
                    .setDescription('The following messages have been purged.')
                    .setColor('RANDOM')
                    .setFooter('TwitchBot | twitchbot.newhorizon.dev', 'https://images-ext-2.discordapp.net/external/6vZM6YeZGzfxd4PF_aw3UnNHZafkdNlRoLp46YJ7hkU/%3Fsize%3D256/https/cdn.discordapp.com/avatars/779442792324661249/26206ede07f20447bf380df44b429db7.png')
                    .setThumbnail('https://images-ext-2.discordapp.net/external/6vZM6YeZGzfxd4PF_aw3UnNHZafkdNlRoLp46YJ7hkU/%3Fsize%3D256/https/cdn.discordapp.com/avatars/779442792324661249/26206ede07f20447bf380df44b429db7.png')
                    .setTimestamp()
                    .setURL("https://twitchbot.newhorizon.dev")
                    .addField("Bot Messages Purged", botMessages.size, false)
                    .addField("User Pins Purged", userPins.size, false)
                    .addField("User Messages Purged", userMessages.size, false)
                    .addField("Total Messages Purged", deletedMessages.size, false);

                message.channel.send(embed);
            })
            .then(console.log(args[0]))
            .catch(err => {
                console.error(err);
                message.channel.send('There was an error with the command! Please contact a developer via our Discord!');
            });
    }
};

我正在运行node:12.0.0discord.js:12.5.1如果有帮助的话。

- 编辑 -

从顶部删除以下代码:

        if (isNaN(amount)) {
            return message.reply('```css\n[ERROR] Please provide a valid number.\n```');
        } else if (amount <= 0 || amount > 100) {
            return message.reply('```css\n[ERROR] You need to input a number between 0 and 100.\n```');
        }

在控制台中显示以下错误:

 TypeError [MESSAGE_BULK_DELETE_TYPE]: The messages must be an Array, Collection, or number.
     at TextChannel.bulkDelete (/app/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:361:11)
     at PurgeCommand.run (/app/commands/admin/purge.js:33:25)
     at CommandoMessage.run (/app/node_modules/discord.js-commando/src/extensions/message.js:222:34)
     at runMicrotasks (<anonymous>)
     at processTicksAndRejections (internal/process/task_queues.js:97:5)
     at async CommandDispatcher.handleMessage (/app/node_modules/discord.js-commando/src/dispatcher.js:143:19) {
   [Symbol(code)]: 'MESSAGE_BULK_DELETE_TYPE'

- -编辑 - -

添加.then(console.log(args[0]))并得到了这个:

 debug: Running command admin:purge.
 undefined
TypeError [MESSAGE_BULK_DELETE_TYPE]: The messages must be an Array, Collection, or number.
     at TextChannel.bulkDelete (/app/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:361:11)
     at PurgeCommand.run (/app/commands/admin/purge.js:33:25)
     at CommandoMessage.run (/app/node_modules/discord.js-commando/src/extensions/message.js:222:34)
     at processTicksAndRejections (internal/process/task_queues.js:97:5)
     at async CommandDispatcher.handleMessage (/app/node_modules/discord.js-commando/src/dispatcher.js:143:19) {
   [Symbol(code)]: 'MESSAGE_BULK_DELETE_TYPE'

}

--- 编辑 03/14/2021 1 ---

好的,所以仍在尝试使其正常工作,这就是我目前拥有的。

const Discord = require('discord.js');
const { Command } = require('discord.js-commando');

module.exports = class PurgeCommand extends Command {
    constructor(client) {
        super(client, {
            name: 'purge',
            aliases: ['p', 'c', 'clean'],
            group: 'mod',
            memberName: 'purge',
            description: 'Purge some messages from a Text Channel.',
            examples: ['purge 5'],
            guildOnly: true,
            throttling: {
                usages: 1,
                duration: 3
            },
            clientPermissions: ['MANAGE_MESSAGES'],
            userPermissions: ['MANAGE_MESSAGES'],

            args: [{
                key: 'purgeamnt',
                label: 'Number',
                prompt: 'Please input a number between 0 and 100.',
                type: 'integer'
            }]
        });
    }

    run(msg, args) {
        let ch = msg.channel;

        var purgeamnt = args[0];
        var purgelimit = Number(purgeamnt) + 1;
        msg.channel.messages.fetch({ limit: purgelimit }).then(messages => {
            msg.channel.bulkDelete(messages).then(deletedMessages => {
                    var botMessages = deletedMessages.filter(m => m.author.bot);
                    var userPins = deletedMessages.filter(m => m.pinned);
                    var userMessages = deletedMessages.filter(m => !m.author.bot);

                    if (purgeamnt <= 0) {
                        return msg.reply('Please input a number between 0 and 100.');
                    } else if (channel => channel.type === 'text') {

                        const embed = new Discord.MessagEmbed()
                            .setAuthor('Twitchbot', 'https://images-ext-2.discordapp.net/external/6vZM6YeZGzfxd4PF_aw3UnNHZafkdNlRoLp46YJ7hkU/%3Fsize%3D256/https/cdn.discordapp.com/avatars/779442792324661249/26206ede07f20447bf380df44b429db7.png')
                            .setTitle("Purge Command Issued")
                            .setDescription('The following messages have been purged.')
                            .setColor('RANDOM')
                            .setFooter('Twitchbot | twitchbot.newhorizon.dev', 'https://images-ext-2.discordapp.net/external/6vZM6YeZGzfxd4PF_aw3UnNHZafkdNlRoLp46YJ7hkU/%3Fsize%3D256/https/cdn.discordapp.com/avatars/779442792324661249/26206ede07f20447bf380df44b429db7.png')
                            .setThumbnail('https://images-ext-2.discordapp.net/external/6vZM6YeZGzfxd4PF_aw3UnNHZafkdNlRoLp46YJ7hkU/%3Fsize%3D256/https/cdn.discordapp.com/avatars/779442792324661249/26206ede07f20447bf380df44b429db7.png')
                            .setTimestamp(new Date().toISOString())
                            .addField("Bot Messages Purged", botMessages.size, false)
                            .addField("User Pins Purged", userPins.size, false)
                            .addField("User Messages Purged", userMessages.size, false)
                            .addField("Total Messages Purged", deletedMessages.size, false);
                        ch.send(embed);
                    }
                })
                .then(console.log(args[0]))
                .catch(err => {
                    console.error(err);
                    ch.send('```css\n[ERROR] ' + err.code + ': [' + err.message + ']\n```');
                })
        });
    }
};

好的,这是它抛出的控制台错误:

2021-03-14T19:21:22.109551+00:00 app[worker.1]: Unhandled rejection: DiscordAPIError: Invalid Form Body
2021-03-14T19:21:22.109553+00:00 app[worker.1]: limit: Value "NaN" is not int.
2021-03-14T19:21:22.114093+00:00 app[worker.1]: DiscordAPIError: Invalid Form Body
2021-03-14T19:21:22.114094+00:00 app[worker.1]: limit: Value "NaN" is not int.
2021-03-14T19:21:22.114095+00:00 app[worker.1]:     at RequestHandler.execute (/app/node_modules/discord.js/src/rest/RequestHandler.js:154:13)
2021-03-14T19:21:22.114095+00:00 app[worker.1]:     at processTicksAndRejections (internal/process/task_queues.js:97:5)
2021-03-14T19:21:22.114096+00:00 app[worker.1]:     at async RequestHandler.push (/app/node_modules/discord.js/src/rest/RequestHandler.js:39:14)
2021-03-14T19:21:22.114096+00:00 app[worker.1]:     at async MessageManager._fetchMany (/app/node_modules/discord.js/src/managers/MessageManager.js:140:18) {
2021-03-14T19:21:22.114097+00:00 app[worker.1]:   method: 'get',
2021-03-14T19:21:22.114097+00:00 app[worker.1]:   path: '/channels/812939122519703572/messages?limit=NaN',
2021-03-14T19:21:22.114098+00:00 app[worker.1]:   code: 50035,
2021-03-14T19:21:22.114098+00:00 app[worker.1]:   httpStatus: 400
2021-03-14T19:21:22.114099+00:00 app[worker.1]: }

--- 编辑 2021 年 3 月 14 日 2 ---

const Discord = require('discord.js');
const { Command } = require('discord.js-commando');

module.exports = class PurgeCommand extends Command {
    constructor(client) {
        super(client, {
            name: 'purge',
            aliases: ['p', 'c', 'clean'],
            group: 'mod',
            memberName: 'purge',
            description: 'Purge some messages from a Text Channel.',
            examples: ['purge 5'],
            guildOnly: true,
            throttling: {
                usages: 1,
                duration: 3
            },
            clientPermissions: ['MANAGE_MESSAGES'],
            userPermissions: ['MANAGE_MESSAGES'],

            args: [{
                key: 'amount',
                label: 'Number',
                prompt: 'Please input a number between 0 and 100.',
                type: 'integer'
            }]
        });
    }

    run(msg, args) {
        let ch = msg.channel;


        const amount = Number(args.amount)
        if (Number.isNaN(amount)) {
            return msg.reply('```css\n[ERROR] Please provide a valid number.\n```')
        }

        if (amount <= 0 || amount > 100) {
            return msg.reply(
                '```css\n[ERROR] You need to input a number between 0 and 100.\n```'
            )
        }

        const limit = amount + 1
        const messages = msg.channel.messages.fetch({ limit })
        const deletedMessages = msg.channel.bulkDelete(messages).then(deletedMessages => {
                var botMessages = deletedMessages.filter(m => m.author.bot);
                var userPins = deletedMessages.filter(m => m.pinned);
                var userMessages = deletedMessages.filter(m => !m.author.bot);

                const embed = new Discord.MessagEmbed()
                embed.setAuthor('Twitchbot', 'https://images-ext-2.discordapp.net/external/6vZM6YeZGzfxd4PF_aw3UnNHZafkdNlRoLp46YJ7hkU/%3Fsize%3D256/https/cdn.discordapp.com/avatars/779442792324661249/26206ede07f20447bf380df44b429db7.png')
                embed.setTitle("Purge Command Issued")
                embed.setDescription('The following messages have been purged.')
                embed.setColor('RANDOM')
                embed.setFooter('Twitchbot | twitchbot.newhorizon.dev', 'https://images-ext-2.discordapp.net/external/6vZM6YeZGzfxd4PF_aw3UnNHZafkdNlRoLp46YJ7hkU/%3Fsize%3D256/https/cdn.discordapp.com/avatars/779442792324661249/26206ede07f20447bf380df44b429db7.png')
                embed.setThumbnail('https://images-ext-2.discordapp.net/external/6vZM6YeZGzfxd4PF_aw3UnNHZafkdNlRoLp46YJ7hkU/%3Fsize%3D256/https/cdn.discordapp.com/avatars/779442792324661249/26206ede07f20447bf380df44b429db7.png')
                embed.setTimestamp(new Date().toISOString())
                embed.addField("Bot Messages Purged", botMessages.size, false)
                embed.addField("User Pins Purged", userPins.size, false)
                embed.addField("User Messages Purged", userMessages.size, false)
                embed.addField("Total Messages Purged", deletedMessages.size, false);
                ch.send(embed = embed);

            })
            .then(console.log(args[0]))
            .catch(err => {
                console.error(err);
                msg.reply('```css\n[ERROR] ' + err.code + ': [' + err.message + ']\n```');
            })
    }
};

--- 编辑 2021 年 3 月 14 日 3 ---

const Discord = require('discord.js');
const { Command } = require('discord.js-commando');

module.exports = class PurgeCommand extends Command {
    constructor(client) {
        super(client, {
            name: 'purge',
            aliases: ['p', 'c', 'clean'],
            group: 'mod',
            memberName: 'purge',
            description: 'Purge some messages from a Text Channel.',
            examples: ['purge 5'],
            guildOnly: true,
            throttling: {
                usages: 1,
                duration: 3
            },
            clientPermissions: ['MANAGE_MESSAGES'],
            userPermissions: ['MANAGE_MESSAGES'],

            args: [{
                key: 'amount',
                label: 'Number',
                prompt: 'Please input a number between 0 and 100.',
                type: 'integer'
            }]
        });
    }

    async run(msg, args) {
        let channel = msg.channel;


        const amount = Number(args.amount)
        if (Number.isNaN(amount)) {
            return msg.reply('```css\n[ERROR] Please provide a valid number.\n```')
        }

        if (amount <= 0 || amount > 100) {
            return msg.reply(
                '```css\n[ERROR] You need to input a number between 0 and 100.\n```'
            )
        }

        const limit = amount + 1
        const messages = await msg.channel.messages.fetch({ limit })
        const deletedMessages = await msg.channel.bulkDelete(messages).then(deletedMessages => {

                var botMessages = deletedMessages.filter(m => m.author.bot);
                var userPins = deletedMessages.filter(m => m.pinned);
                var userMessages = deletedMessages.filter(m => !m.author.bot);

                let embed = new Discord.MessageEmbed();

                embed.setAuthor('Twitchbot', 'https://images-ext-2.discordapp.net/external/6vZM6YeZGzfxd4PF_aw3UnNHZafkdNlRoLp46YJ7hkU/%3Fsize%3D256/https/cdn.discordapp.com/avatars/779442792324661249/26206ede07f20447bf380df44b429db7.png')
                embed.setTitle("Purge Command Issued")
                embed.setDescription('The following messages have been purged.')
                embed.setColor('RANDOM')
                embed.setFooter('Twitchbot | twitchbot.newhorizon.dev', 'https://images-ext-2.discordapp.net/external/6vZM6YeZGzfxd4PF_aw3UnNHZafkdNlRoLp46YJ7hkU/%3Fsize%3D256/https/cdn.discordapp.com/avatars/779442792324661249/26206ede07f20447bf380df44b429db7.png')
                embed.setThumbnail('https://images-ext-2.discordapp.net/external/6vZM6YeZGzfxd4PF_aw3UnNHZafkdNlRoLp46YJ7hkU/%3Fsize%3D256/https/cdn.discordapp.com/avatars/779442792324661249/26206ede07f20447bf380df44b429db7.png')
                embed.setTimestamp(new Date().toISOString())
                embed.addField("Bot Messages Purged", botMessages.size, false)
                embed.addField("User Pins Purged", userPins.size, false)
                embed.addField("User Messages Purged", userMessages.size, false)
                embed.addField("Total Messages Purged", deletedMessages.size, false);
                channel.send(embed = embed);

            })
            .then(console.log())
            .catch(err => {
                console.error(err);
                channel.send('```css\n[ERROR] ' + err.code + ': [' + err.message + ']\n```');
            })
    }
};
4

1 回答 1

1

args是一个对象。因此,您应该使用args.amount(关键是amount)或使用对象解构来获取数量参数。

async run(message, args) {
  const { channel } = message
  const amount = Number(args.amount)
  if (Number.isNaN(amount)) {
    return message.reply(
      '```css\n[ERROR] Please provide a valid number.\n```'
    )
  }

  if (amount <= 0 || amount > 100) {
    return message.reply(
      '```css\n[ERROR] You need to input a number between 0 and 100.\n```'
    )
  }

  const limit = amount + 1
  try {
    const messages = await channel.messages.fetch({ limit })
    const deletedMessages = await channel.bulkDelete(messages)
    const botMessages = deletedMessages.filter(m => m.author.bot)
    const userPins = deletedMessages.filter(m => m.pinned)
    const userMessages = deletedMessages.filter(m => !m.author.bot)
    const embed = new Discord.MessageEmbed()
    // ...
    channel.send(embed)
  } catch (err) {
    console.error(err)
    channel.send(
      '```css\n[ERROR] ' + err.code + ': [' + err.message + ']\n```'
    )
  }
}

有关更多信息,请查看有关使用命令参数的文档。

于 2021-03-14T20:34:47.340 回答