Nikola Andreev
Nikola Andreev

Reputation: 634

Twilio programmable chat get last messages

i want to be able to get the last few messages for a chat service. Here is what i'm trying to achieve.

const TWILIO = require('twilio');
const CHAT_CLIENT = new TWILIO.Twilio(CHAT_ACCOUNT_SID, CHAT_AUTH_TOKEN);
let obj = await CHAT_CLIENT.chat.services(CHAT_SERVICE_SID)
            .channels(MY_CHANEL_SID)
            .messages.page()
let messages = obj['instances']
let nextMessages = await obj.nextPage()

And the code is working, but it returns me the first 50 messages. Yes i have also the next page where will be the next messages, but i want always to receive the last messages first. When the user joins to the chat, he wants to see the last messages, not the first. How i can get them without to make many queries until reach the last page?

Also if someone know how to get the total count of messages for the chat, it would be helpful.

Upvotes: 0

Views: 1445

Answers (1)

Nikola Andreev
Nikola Andreev

Reputation: 634

I found the solution, here is the code.

const TWILIO = require('twilio');
const CHAT_CLIENT = new TWILIO.Twilio(CHAT_ACCOUNT_SID, CHAT_AUTH_TOKEN);
const uri = 'https://chat.twilio.com/v2/Services/' +
      'CHAT_SID/Channels/CHANNEL_SID/Messages?Order=desc';
let response = await CHAT_CLIENT.request({ method: "GET", uri: uri });
let messages = JSON.parse(response .body).messages; // the last 50 messages

Hope to be helpful for someone.

Upvotes: 1

Related Questions