Threaded messaging on pubnub

Viewed 280

We want to create threads for messages within a chat channel on Pubnub. For example, someone could respond to a specific message in a channel by 'creating a thread' and starting to chat. Is there a prescribed way to model this behavior? If so, can you please reference documentation?

This is the behavior you see in slack, for reference.

2 Answers

There's no ready-made solution documented for threaded messaging. However, building a hierarchical relationship between messages could be achieved by tagging them with metadata (using PN Objects and/or MessageActions) and then some coding on your end to maintain and handle their relationship.

You could use the time token of the thread's first message as the key, group messages based on it, and use the messages' own time tokens to generate the order for the UI.

https://www.pubnub.com/docs/sdks/javascript/api-reference/publish-and-subscribe#methods

Here's the high-level design for doing this:

  • A message is published to a channel with the name chat_11223344 (channel name uses chat_ as a prefix for all chat channels and a generated id - keeping it short here but you can use a uuid generator for this). That publish returns a publish timetoken, something like this: 16183330926487763.
  • Using PN Objects, your display name for the channel can be set along with a description.
  • In your chat UI, you allow a person to create a thread on that message. The message gets published to a channel named chat_11223344.16183330926487763 , using the publish timetoken of the top-level message as the "sub-channel" name.
  • So that you can easily identify top-level messages that are threaded, you would add a MessageAction to that message when the first "threaded" message is published. You may also want to add custom Channel Metadata (PN Objects, again) to add a "isThreaded":true key/value.

So with PubNub you can append meta data to either the message itself or PubNub has a section called meta (https://www.pubnub.com/docs/sdks/javascript/api-reference/publish-and-subscribe#methods).

An example payload could be:

{
  "type":"message",
  "payload":"What do people want for lunch? Pizza?",
  "sender":"me",
  "sent":1618336638,
  "messageActive":true,
  "channel":"main",
  "messageID":"main.abc123"
}

where abc123 is a uuid that references that message. When someone wants to thread a message you can append "threaded":true variable to the object.

    {
      ...
      "messageID":"main.abc123",
      "threaded":true,
      ...
    }

Now your UI knows that there is a breakout thread, using main.abc123.thread as the channelID for that specific thread. Your app then subscribes to the new channel main.abc123.thread and you can use fetchMessages(); to get history messages as well as new real time messages.

Related