【问题标题】:Fetching past messages into a file将过去的消息提取到文件中
【发布时间】:2020-02-15 21:26:58
【问题描述】:

我目前正在尝试向我的机器人添加一项功能,以通过一个频道并获取该频道中的所有消息,并尽可能将其输出到 TXT 文件中。 (我是 JS 和 nodeJS 的初学者,但我已经开发这个机器人快一年了,所以我对它的工作原理有一个很好的掌握,但仍在学习)

我目前已经设置好了,所以当我在 Discord 中发送命令时,它会获取频道的最新 100 条消息,但目前不会在任何地方输出。

client.on('message', message => {
    if (message.content.toLowerCase() === 'fetchtest') {
        client.channels.get(<channelID>).fetchMessages({ limit: 100 })
            .then(messages => console.log(`Received ${messages.size} messages`))
            .catch(console.error);
    }
});

我需要帮助的是弄清楚如何“循环”代码,以便它保存每 100 条消息,直到它遇到第一条消息,并将其输出到具有 &lt;user&gt;: &lt;message&gt; 格式的文本文件中。是否有一个很好的指南可以遵循这个或我应该做什么的基本纲要?提前致谢!

【问题讨论】:

    标签: javascript node.js discord discord.js


    【解决方案1】:

    基本上,要以一种简单的方式做到这一点,您只需获取第一个请求中返回的集合的第一条消息,获取它的 ID 并将其用作参数 before 的值ChannelLogsQueryOptions(它是您作为参数传递以更改默认消息获取限制的对象)。

    Here some reference

    另外,为了帮助你理解这个逻辑,一些代码示例:

    // Async function to handle promises like synchronous piece of code
    async function loadUsers() {
      let page = 1; // First page (begin point)
      
      // Infinite loop because "we don't know the total of users in the API"
      while(true) {
        // Request to our fake API and getting the only property of the returned JSON that matters to this example
        let userList = (await fetch(`https://reqres.in/api/users?page=${page}`).then( response => response.json())).data;
        
        // Check if we have an empty response or not
        if(userList.length){
          // This is just vanilla JavaScript for inserting some DOM Elements, ignore it, just to add some visual output to this example
          userList.forEach( user => {
            let section = document.querySelector('section'),
                userElement = document.createElement('p');
            
            userElement.innerText = user.email;
            section.appendChild( userElement );
          });
        } else {
          // If we do got an empty response we break out of this loop and the function execution ends
          break;    
        }
        
        // Increment our page number so we can achieve new data, instead of doing the same request
        page++;
      }
    }
    
    // Execute the function declared above
    loadUsers();
    &lt;section&gt;&lt;/section&gt;

    在我的代码示例中,我使用了fake API,它为我提供了每页的信息页面(并且我假装它没有告诉我页面的总数,所以这个 sn-p 最能与你的问题相关)然后我添加收到的每封用户电子邮件,直到我得到一个空响应,这是我的停止条件(也就是打破“while true”无限循环)。

    在您的情况下,做一些与 sn-p 稍微相似的事情,但在 Discord.js 的特定上下文中可能会令人满意地解决您的问题,因为 Discord.js 的文档中似乎没有任何关于检索TextChannel的消息总量。

    【讨论】:

      猜你喜欢
      • 2016-04-22
      • 2019-05-21
      • 2021-10-28
      • 2016-02-13
      • 1970-01-01
      • 2020-11-22
      • 2012-07-23
      • 2014-09-12
      • 1970-01-01
      相关资源
      最近更新 更多