1

What is a correct way to synchronize Twilio chat consumption horizon and send an email notification with a list of new messages from our own server?

I can use kind of pre-hooks / post-hooks for new messages, but I don't want to keep every message and its reading status in my database.

Is there a smarter way to set up notifications on my server?

1 Answers1

4

Twilio developer evangelist here.

You wouldn't need to store all of this. You can just use the REST API to get all of this information.

What you need to do is store your user's Channel Member Sid. You can then make a call to the Member resource and get their last_consumed_message_index.

With the index, which is an integer representing index of the last message the member has read within the channel, you can then call on the Message resource to list all the messages since that index. In Node, that would be so

service
  .channels(CHANNEL_SID)
  .members(MEMBER_SID)
  .fetch()
  .then(member => {
    const lastConsumedMessageIndex = member.lastConsumedMessageIndex;
    return service.channels(CHANNEL_SID).messages.list({
      pageSize: lastConsumedMessageIndex,
      limit: lastConsumedMessageIndex
    });
  })
  .then(messages => {
    console.log(messages);
    // do something with unread messages
  })
  .catch(error => {
    console.error(error);
  });

Let me know if that helps at all.

philnash
  • 70,667
  • 10
  • 60
  • 88
  • Thank you @philnash . So, i should store all channels and channel members SID? And than, for example, every 5 minutes i should check if there any new messages, and send notifications? Hmm... – Anton Konyushevskiy Dec 18 '17 at 16:07
  • Oh, I'd probably still use the webhooks to trigger notification, but if you have the channel and member SIDs then you don't need to store all the messages too. – philnash Dec 19 '17 at 01:22
  • Got you, so i store all channels and members SID's and then on webhook new message check lastconsumedindex for this channel for every member, correct? – Anton Konyushevskiy Dec 19 '17 at 16:29
  • 1
    I'd probably try both methods actually. I'm not sure how often you want to be sending email notifications about this. I don't really know your full use case, so I wouldn't presume to understand how and when you send the notifications. Either way, you should only need to store channel and member sids. – philnash Dec 19 '17 at 22:43
  • Thank you for your help. About my use case, i'm trying to build messenger between users on existing web app. My idea is send notification by email, if somebody send message to user that currently offline (ideally not more often than every 5-10 minutes). – Anton Konyushevskiy Dec 21 '17 at 05:28
  • Makes sense. I think at this point the coding isn't going to be the hard part, so I'd just try a couple of ways and see how well they work with your user experience. Hope it goes well! – philnash Dec 21 '17 at 05:31