Introduction to the PubNub Chat SDK
The PubNub Chat SDK, available for TypeScript and JavaScript applications, exposes a set of APIs designed to make it easy to add powerful and flexible chat features to your app with minimum development. Chat options like quoting, mentioning users, channel references, threads, read receipts, and typing indicators are supported natively by the SDK, letting you build a full-fledged app quickly.
Please refer to our documentation and sample chat app to get started with the Chat SDK. Our tutorial will walk you through the basic functionality of the Chat SDK and touch on some more advanced features whilst our hosted demo will show the Chat SDK in action.
This how-to is part of a series of posts diving into some of the more powerful features of the PubNub Chat SDK. The series can be read in any order, but the list of related articles is below:
- How to Manage User Channel Membership with the Chat SDK
- How to Add Reactions and Emojis to Messages with the Chat SDK
- How to Create Threads and Quote Messages with the Chat SDK
- How to Mention Users and Channels with the Chat SDK
Managing User Channel Memberships
The Chat SDK defines several types that are important to understand channel membership:
- Users represent individuals taking part in a conversation.
- Channels represent a conversation between multiple users. The documentation uses the analogy that each channel represents a single ‘chat room.’ Channels can be direct (i.e., a 1:1 conversation between just two users, ‘group’ (i.e., between multiple named users), or ‘public.’
- Memberships represent a relationship between Users and Channels with optional accompanying metadata.
This guide will discuss how to create and manage those channel memberships.
How users join a channel
There are multiple ways that a user can become a member of a channel. When direct or group channels are created, the user(s) in that conversation are specified as arguments during creation.
In the example below, taken from the documentation, the two users ‘agent-007’ and ‘agent-008’ are made members of channel ‘group-chat-1’
// reference both agents you want to talk to
const user1 = await chat.getUser("agent-007")
const user2 = await chat.getUser("agent-008")
// add the channel ID, name, and topic
const { channel, hostMembership, inviteeMembership } = await chat.createGroupConversation(
{
users:
[
user1,
user2
],
channelId: "group-chat-1"
…
}
)
You can query whether a user is a member of a channel in a number of ways, and you can find full details in the documentation for channel membership. For example, to get the members of the channel we just created:
// reference the "channel" object
const channel = await chat.getChannel("group-chat-1")
const members = await channel.getMembers()
// members contains both users, so members.total === 2
If users are not assigned to a channel during its creation, they can join or leave later using the corresponding join() and leave() methods, allowing you to have dynamic channels. Users can also be invited to become a member of a channel.
You can see this behavior in the short demo below. Since this is a live, working demo, notice that your channel membership will persist even after you refresh the page.
Interactive Demo
If the embedded content is not available on this page, it can also be viewed at https://chat-sdk-how-to-membership.netlify.app/
The code that drives this demo is available on GitHub, but the key points are:
Ensure you have an instance of the Chat object instantiated in your app
const chat = await Chat.init({
publishKey: "YOUR_PUBLISH_KEY",
subscribeKey: "YOUR_SUBSCRIBE_KEY",
userId: "YOUR_USER_ID",
})
There are a lot of possible parameters you can pass to the Chat SDK, but for channel membership, you do not need anything more than the standard publish key, subscribe key, and user ID. If all of this is new to you, and you’re not sure where to get started, please check out the initial configuration section in our documentation.
Join a channel. This code also registers to receive membership updates, which is discussed in the next section.
async function join(channelName: string)
{
if (chat)
{
const channel = await chat.getChannel(channelName)
const channelMembership = await channel?.join(() => null)
channelMembership?.membership.streamUpdates(async (membership) => {
// Stream updates on the channel as follows
console.log(membership)
})
// For brevity, ignore that this call could contain multiple pages of memberships
const {memberships} = await chat.currentUser.getMemberships()
setMyMemberships(memberships)
}
}
As mentioned in the code comments above, the call to user.getMemberships() may contain paginated data if there are too many channels.
The code which powers the ‘leave channel’ buttons in the demo is as follows:
async function leave(channelName: string)
{
if (chat)
{
const channel = await chat.getChannel(channelName)
await channel?.leave();
// For brevity, ignore that this call could contain multiple pages of memberships
const {memberships} = await chat.currentUser.getMemberships()
setMyMemberships(memberships)
}
}
To keep the demo simple, there is only a single user, and only the user’s own membership is considered. In a real application, you will have multiple users, each with their own channel memberships. A more realistic demo is available for our Chat SDK and is discussed at the bottom of this guide.
Channel membership metadata
The Membership object allows you to specify custom metadata related to the association between the channel and user; for example, if this was a chat related to a support inquiry, you might store the user’s role as a {role: ‘support technician’}.
Metadata can be declared when the membership is created or can be updated at any point by the individual user.
To keep track of when membership metadata is updated, the Chat SDK provides the streamUpdates() and streamUpdatesOn() methods for the Membership object.
As shown in the earlier demo, you can track changes to the membership metadata as follows:
channelMembership?.membership.streamUpdates(async (membership) => {
// Stream updates on the channel as follows
console.log(membership)
})
Why should users join a channel?
One assumption would be that users need to join a channel to receive messages on that channel, but this is not the case. To receive messages on a channel, you can invoke the connect() method, where you can provide a callback to be invoked whenever a message is received. If you were not made a member of a channel when it was created, you would need to call connect() separately, but calling join() will invoke connect() for you automatically.
If you are familiar with PubNub, this connect() call is analogous to subscribe() and addListener().
So, why should you join a channel? Joining a channel and the associated channel memberships are fundamental to how the Chat SDK understands user relationships, so it is required to use many more powerful SDK features, such as read receipts, mentioning users, unread message counts, moderation, and the typing indicator.
Membership Summary
- What is it? A relationship between a User and a Channel, with customizable metadata.
- How is a membership created? Users can be associated with a channel during its creation, or they can join themselves or be invited by others to a channel after it has been created.
- How is a membership destroyed? Users can leave a channel at any time
- How is a membership tracked? Members of a channel can be queried with getter functions, and you can be notified of changes by registering for updates.
- Common Pitfalls: Membership does not always mean you will receive messages on a channel; take care to read the documentation when you need to call connect() separately.
- Any other restrictions? Although you can join ‘public’ channels, several features, such as read receipts or the typing indicator, are not supported for this type of channel.
- What features are required on the PubNub Keyset? Be sure to enable App Context on your keyset.
Demo: User Channel Membership in Action
Our Chat SDK Demo for Mobile, available as a hosted demo with full source code available on GitHub, uses Membership to manage User conversations. You should also see the demo rendered in an iFrame at the bottom of this section.
Follow these steps to see memberships used in our demo:
- Log in to the application, choosing a random user id for each of the two devices.
- Create a group by clicking on the ‘new chat’ icon, then selecting ‘Create group chat’
- Choose the two user IDs you just logged in as, and assign a name for the group.
- Behind the scenes the application has created a membership to associate each of the two users with the newly created group.
- Enter the group conversation by clicking on the entity that was created under the ‘Groups’ section.
- Tap on the name of the group at the top of the screen to see your user’s chat settings (as shown in the left hand image, above)
- Notice how this user’s name is a ‘Member’ of the chat.
- Notice that if you back out of the conversation or even log out of and back into the app, the reactions are retained and read from the message history.
If the embedded content is not available on this page, it can also be viewed at https://pubnubdevelopers.github.io/Chat-SDK-Demo/mobile/
How can PubNub help you?
This article was originally published on PubNub.com
Our platform helps developers build, deliver, and manage real-time interactivity for web apps, mobile apps, and IoT devices.
The foundation of our platform is the industry's largest and most scalable real-time edge messaging network. With over 15 points-of-presence worldwide supporting 800 million monthly active users, and 99.999% reliability, you'll never have to worry about outages, concurrency limits, or any latency issues caused by traffic spikes.
Experience PubNub
Check out Live Tour to understand the essential concepts behind every PubNub-powered app in less than 5 minutes
Get Setup
Sign up for a PubNub account for immediate access to PubNub keys for free
Get Started
The PubNub docs will get you up and running, regardless of your use case or SDK
Top comments (0)