首页 > 解决方案 > 将过去的消息提取到文件中

问题描述

我目前正在尝试向我的机器人添加一项功能,以通过一个通道并获取该通道中的所有消息,如果可能的话将其输出到 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 条消息,直到它遇到第一条消息,并将其输出到具有<user>: <message>格式的文本文件中。是否有一个很好的指南可以遵循这个或我应该做什么的基本纲要?提前致谢!

标签: javascriptnode.jsdiscorddiscord.js

解决方案


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

这里有一些参考

另外,为了帮助您理解其逻辑,一些代码示例:

// 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();
<section></section>

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

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


推荐阅读