【问题标题】:Deleting all messages in discord.js text channel删除 discord.js 文本通道中的所有消息
【发布时间】:2018-06-22 01:26:28
【问题描述】:

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

【问题讨论】:

    标签: node.js discord discord.js


    【解决方案1】:

    试试这个

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

    【讨论】:

    • 嗯,你明白了,所以,也许你能想办法,另外,删除消息时添加某种回调也不错
    • 在 Discord.js v12 中,将 fetchMessages 更改为 messages.fetch
    【解决方案2】:

    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 必须在异步函数中才能工作。

    【讨论】:

      【解决方案3】:

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

      // 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

      【讨论】:

      • 我很确定这违反了 Discord TOS
      • 你需要告诉我安德烈在哪里;它只会删除您自己的消息,就像您必须手动删除每条消息一样。
      • 嗯,您正在使用用户帐户自动执行某些操作。这是不允许的:support.discordapp.com/hc/en-us/articles/…
      • 大声笑,此脚本不会将帐户转换为自动用户帐户/机器人,如果您不是服务器的管理员/版主,则无法安装机器人轻松删除您的所有来自频道的消息。这更像是从频道中“删除我的所有消息”的黑客行为,因为该功能不存在。
      • This is more like a hack to do a "delete all my messages" 好吧,你刚刚描述了它。这是一个黑客。而且是不允许的。
      【解决方案4】:

      这将适用于 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()
      }
      

      【讨论】:

        【解决方案5】:

        另一种方法是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() 只能删除超过两周的消息,这意味着如果您的频道有超过两周的消息,您将无法删除每条频道消息.

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

        【讨论】:

        • 不是 await channel.delete() 吗?
        • 它不必包含await@nsde,因为我不打算在它删除频道后做任何事情。如果您确实需要仅在 频道被删除之后运行代码,那么我建议使用 await
        【解决方案6】:

        这里是 @Kiyokodyele answer,但与 @user8690818 answer 有一些变化。

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

        【讨论】:

          【解决方案7】:

          只要您的机器人具有适当的权限,这将起作用。

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

          【讨论】:

          • 别让他复制粘贴所有东西,伙计
          • @OctagonalT 是的,你知道,也许那样会很快解决他的问题。让我们来迷惑他,不是吗?
          • 不行,就是不要让他全部复制粘贴,不然他学不会
          猜你喜欢
          • 1970-01-01
          • 2020-10-15
          • 2021-06-28
          • 2021-06-30
          • 2020-07-03
          • 2018-04-29
          • 2020-10-02
          • 2021-10-14
          • 2020-04-16
          相关资源
          最近更新 更多