Deleting all messages in discord.js text channel

后端 未结 7 1609
梦如初夏
梦如初夏 2021-02-09 18:09

Ok, so I searched for a while, but I couldn\'t find any information on how to delete all messages in a discord channel. And by all messages I mean every single message ever writ

7条回答
  •  面向向阳花
    2021-02-09 18:49

    This will work so long your bot has appropriate permissions.

    module.exports = {
        name: "clear",
        description: "Clear messages from the channel.",
        args: true,
        usage: "",
        execute(message, args) {
            const amount = parseInt(args[0]) + 1;
    
            if (isNaN(amount)) {
                return message.reply("that doesn't seem to be a valid number.");
            } else if (amount <= 1 || amount > 100) {
                return message.reply("you need to input a number between 1 and 99.");
            }
    
            message.channel.bulkDelete(amount, true).catch((err) => {
                console.error(err);
                message.channel.send(
                    "there was an error trying to prune messages in this channel!"
                );
            });
        },
    };
    

    In case you didn't read the DiscordJS docs, you should have an index.js file that looks a little something like this:

    const Discord = require("discord.js");
    const { prefix, token } = require("./config.json");
    
    const client = new Discord.Client();
    client.commands = new Discord.Collection();
    const commandFiles = fs
        .readdirSync("./commands")
        .filter((file) => file.endsWith(".js"));
    
    for (const file of commandFiles) {
        const command = require(`./commands/${file}`);
        client.commands.set(command.name, command);
    }
    
    //client portion:
    
    client.once("ready", () => {
        console.log("Ready!");
    });
    
    client.on("message", (message) => {
        if (!message.content.startsWith(prefix) || message.author.bot) return;
    
        const args = message.content.slice(prefix.length).split(/ +/);
        const commandName = args.shift().toLowerCase();
    
        if (!client.commands.has(commandName)) return;
        const command = client.commands.get(commandName);
    
        if (command.args && !args.length) {
            let reply = `You didn't provide any arguments, ${message.author}!`;
    
            if (command.usage) {
                reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
            }
    
            return message.channel.send(reply);
        }
    
        try {
            command.execute(message, args);
        } catch (error) {
            console.error(error);
            message.reply("there was an error trying to execute that command!");
        }
    });
    
    client.login(token);
    

提交回复
热议问题