提问者:小点点

将过去的消息提取到文件中


我目前正在尝试给我的bot添加一个特性,通过一个通道获取该通道中的所有消息,如果可能的话,将其输出到一个TXT文件中。(我是JS和nodeJS的初学者,但我已经开发这个机器人快一年了,所以我对它的工作原理有了相当的了解,不过我还在学习。)

我目前有它设置,所以当我发送一个命令在不和,它将获取一个通道的最新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条消息,直到它找到第一条消息,并将其输出到具有:格式的文本文件中。有没有一个很好的指南来遵循这个或者我应该做什么的一个基本的概述?提前谢谢!


共1个答案

匿名用户

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

这里有些参考

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

null

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