首页 > 解决方案 > 如何检索 Twilio 可编程聊天频道中的所有消息?

问题描述

    privatechannel.getMessages().then(function (messages) {
    const totalMessages = messages.items.length;
    for (let i = 0; i < totalMessages; i++) {
      const message = messages.items[i];
      console.log('Author:' + messages.author);
      printMessage(message.author, message.body);
    }
    console.log('Total Messages:' + totalMessages);
    deleteNotifs()

  });

这在 Twilio 文档中被列为检索最新消息的方式。我试过了,它显示的最大消息数甚至不是 100 条,它只显示了对话中的最后 30 条消息。

有没有办法在 Twilio 可编程聊天频道(私人或其他)中检索和显示所有消息?

标签: javascriptpythondjangotwiliotwilio-programmable-chat

解决方案


Twilio 开发人员布道者在这里。

当您发出请求时,channel.getMessages()您可以做一些事情来获得超过默认的前 30 条消息。

首先,您可以传递 apageSize以从每个请求中获取更多消息。pageSize默认为 30,最多(我认为)100。

privatechannel.getMessages(100).then(function(messagePaginator) { 
  // deal with the messages
});

如果您想超过 100 条消息,那么您会从getMessages返回 Promise 的文档中注意到,该 Promise 解析为Paginator<Messages>. 该Paginator对象具有items您已用于访问消息的属性。它还具有hasNextPagehasPrevPage属性,可以告诉您是否有更多可用消息。

还有一些函数可以返回您正在使用nextPageprevPage下一页或上一页。Paginator

因此,在您的示例中,您可以像这样获取和打印通道中的所有消息:

const messages = [];
let totalMessages = 0;

function receivedMessagePaginator(messagePaginator) {
  totalMessages += messagePaginator.items.length;
  messagePaginator.items.forEach(function (message) {
    printMessage(message.author, message.body);
    messages.push(message);
  });
  if (messagePaginator.hasNextPage) {
    messagePaginator.nextPage().then(receivedMessagePaginator);
  } else {
    console.log("Total Messages:" + totalMessages);
  }
}

privatechannel.getMessages().then(receivedMessagePaginator);

让我知道这是否有帮助。


推荐阅读