正在删除 discord.js 个文本频道中的所有消息

Deleting all messages in discord.js text channel

好的,所以我搜索了一段时间,但没有找到有关如何删除不和谐频道中所有消息的任何信息。我所说的所有消息是指在该频道中写过的每条消息。有什么线索吗?

Discord 不允许机器人删除超过 100 条消息,因此您无法删除频道中的每条消息。您可以使用 BulkDelete 删除少于 100 条消息。

示例:

const Discord = require("discord.js");
const client = new Discord.Client();
const prefix = "!";

client.on("ready" () => {
    console.log("Successfully logged into client.");
});

client.on("message", msg => {
    if (msg.content.toLowerCase().startsWith(prefix + "clearchat")) {
        async function clear() {
            msg.delete();
            const fetched = await msg.channel.fetchMessages({limit: 99});
            msg.channel.bulkDelete(fetched);
        }
        clear();
    }
});

client.login("BOT_TOKEN");

注意,它必须在异步函数中才能使 await 工作。

这是我的改进版本,速度更快,让您知道它何时在控制台中完成,但您必须 运行 它为您在频道中使用的每个用户名(如果您更改了您的用户名某点):

// Turn on Developer Mode under User Settings > Appearance > Developer Mode (at the bottom)
// Then open the channel you wish to delete all of the messages (could be a DM) and click the three dots on the far right.
// Click "Copy ID" and paste that instead of LAST_MESSAGE_ID.
// Copy / paste the below script into the JavaScript console.

var before = 'LAST_MESSAGE_ID';
var your_username = ''; //your username
var your_discriminator = ''; //that 4 digit code e.g. username#1234
var foundMessages = false;
clearMessages = function(){
    const authToken = document.body.appendChild(document.createElement`iframe`).contentWindow.localStorage.token.replace(/"/g, "");
    const channel = window.location.href.split('/').pop();
    const baseURL = `https://discordapp.com/api/channels/${channel}/messages`;
    const headers = {"Authorization": authToken };

    let clock = 0;
    let interval = 500;

    function delay(duration) {
          return new Promise((resolve, reject) => {
              setTimeout(() => resolve(), duration);
          });
    }

    fetch(baseURL + '?before=' + before + '&limit=100', {headers})
    .then(resp => resp.json())
    .then(messages => {
        return Promise.all(messages.map((message) => {
            before = message.id;
            foundMessages = true;

            if (
                message.author.username == your_username
                && message.author.discriminator == your_discriminator
            ) {
                return delay(clock += interval).then(() => fetch(`${baseURL}/${message.id}`, {headers, method: 'DELETE'}));
            }
        }));
    }).then(() => {

        if (foundMessages) {
            foundMessages = false;
            clearMessages();
        } else {
            console.log('DONE CHECKING CHANNEL!!!')
        }

    });
}
clearMessages();

我找到的上一个脚本,用于在没有机器人的情况下删除您自己的消息...

// Turn on Developer Mode under User Settings > Appearance > Developer Mode (at the bottom)
// Then open the channel you wish to delete all of the messages (could be a DM) and click the three dots on the far right.
// Click "Copy ID" and paste that instead of LAST_MESSAGE_ID.
// Copy / paste the below script into the JavaScript console.
// If you're in a DM you will receive a 403 error for every message the other user sent (you don't have permission to delete their messages).

var before = 'LAST_MESSAGE_ID';
clearMessages = function(){
    const authToken = document.body.appendChild(document.createElement`iframe`).contentWindow.localStorage.token.replace(/"/g, "");
    const channel = window.location.href.split('/').pop();
    const baseURL = `https://discordapp.com/api/channels/${channel}/messages`;
    const headers = {"Authorization": authToken };

    let clock = 0;
    let interval = 500;

    function delay(duration) {
        return new Promise((resolve, reject) => {
            setTimeout(() => resolve(), duration);
        });
    }

    fetch(baseURL + '?before=' + before + '&limit=100', {headers})
        .then(resp => resp.json())
        .then(messages => {
        return Promise.all(messages.map((message) => {
            before = message.id;
            return delay(clock += interval).then(() => fetch(`${baseURL}/${message.id}`, {headers, method: 'DELETE'}));
        }));
    }).then(() => clearMessages());
}
clearMessages();

参考:https://gist.github.com/IMcPwn/0c838a6248772c6fea1339ddad503cce

试试这个

async () => {
  let fetched;
  do {
    fetched = await channel.fetchMessages({limit: 100});
    message.channel.bulkDelete(fetched);
  }
  while(fetched.size >= 2);
}

这将适用于 discord.js 版本 12.2.0 只需将其放入客户端的消息事件中 并键入命令:!nuke-this-channel 频道上的每条消息都将被擦除 然后,将发布一个金正恩表情包。

if (msg.content.toLowerCase() == '!nuke-this-channel') {
    async function wipe() {
        var msg_size = 100;
        while (msg_size == 100) {
            await msg.channel.bulkDelete(100)
        .then(messages => msg_size = messages.size)
        .catch(console.error);
        }
        msg.channel.send(`<@${msg.author.id}>\n> ${msg.content}`, { files: ['http://www.quickmeme.com/img/cf/cfe8938e72eb94d41bbbe99acad77a50cb08a95e164c2b7163d50877e0f86441.jpg'] })
    }
    wipe()
}

只要您的机器人具有适当的权限,这就可以正常工作。

module.exports = {
    name: "clear",
    description: "Clear messages from the channel.",
    args: true,
    usage: "<number greater than 0, less than 100>",
    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!"
            );
        });
    },
};

如果您没有阅读 DiscordJS 文档,您应该有一个 index.js 文件,看起来有点像这样:

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);

这里是 but with some changes from

(async () => {
  let deleted;
  do {
    deleted = await channel.bulkDelete(100);
  } while (deleted.size != 0);
})();

另一种方法可能是 cloning 频道并删除包含您要删除的消息的频道:

// Clears all messages from a channel by cloning channel and deleting old channel
async function clearAllMessagesByCloning(channel) {
    // Clone channel
    const newChannel = await channel.clone()
    console.log(newChannel.id) // Do with this new channel ID what you want

    // Delete old channel
    channel.delete()
}

我更喜欢这种方法而不是此线程中列出的方法,因为它很可能需要更少的时间来处理并且(我猜)使 Discord API 承受的压力更小。此外,channel.bulkDelete() 只能删除超过两周的消息,这意味着您将无法删除 every 个频道消息,以防您的频道有消息超过两周。

可能的缺点是频道改变 id。如果您依赖于将 id 存储在数据库等中,请不要忘记使用新克隆频道的 id 更新这些文档!