Roast Biter
Roast Biter

Reputation: 681

How to retrieve all messages in a Twilio Programmable Chat Channel?

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

  });

This is listed as the way in Twilio docs to retrieve the most recent messages. I tried it and the maximum number of messages it displays are not even like 100, it just shows me the last 30 messages in the conversation.

Is there a way to retrieve and display all the messages in a Twilio Programmable Chat channel ( private or otherwise )?

Upvotes: 0

Views: 1881

Answers (2)

philnash
philnash

Reputation: 73029

Twilio developer evangelist here.

When you make a request to channel.getMessages() there are a few things you can do to get more than the default previous 30 messages.

First, you can pass a pageSize to get more messages from each request. pageSize is 30 by default and can be up to (I think) 100.

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

If you want to go beyond 100 messages then you will notice from the docs that getMessages returns a Promise that resolves to a Paginator<Messages>. The Paginator object has an items property that you've already used to access the messages. It also has hasNextPage and hasPrevPage properties, that tell you whether there are more messages available.

There are also nextPage and prevPage functions that return the next or previous page of the Paginator you are using.

So, in your example, you can fetch and print all the messages in a channel like so:

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

Let me know if that helps at all.

Upvotes: 1

charmful0x
charmful0x

Reputation: 153

As there is no Syntax error in your code, then it's highly likely a rate limit API related. Consider checking Twilio docs, type of APIs limits (free vs paid subscriptions)

Upvotes: 0

Related Questions