PubNub Logo Docs
Support Contact Sales Login Try Our APIs

›CHANNELS

Collapse all
Dark mode

Back to Home

Overview

  • In-App Chat

Chat Components

  • Overview
  • REACT

    • React Components

    ANDROID

    • Getting Started
    • UI Components
    • UI Theming
    • Data Components
    • Chat Provider
    • Message Reactions
    • Message Menu

    IOS

    • Getting Started
    • UI Components
    • UI Theming
    • Data Components
    • Chat Provider

SDKs

  • Overview
  • USERS

    • Setup
    • Metadata
    • Permissions
    • Presence
    • Mentions

    CHANNELS

    • Types and Names
    • Metadata
    • Subscriptions
    • Memberships

    MESSAGES

    • Sending Messages
    • Message History
    • Unread Counts
    • File Upload
    • Typing Indicators
    • Read Receipts
    • Emoji Reactions
    • Update Messages
    • Delete Messages
    • External Storage

    PUSH NOTIFICATIONS

    • Overview

    MODERATION

    • Profanity Filters
    • Flag Messages
    • Ban Users
    • Mute Users
    • Spam Prevention

    INTEGRATIONS

    • Overview
    • Content Moderation
    • Image Moderation
    • Language Translation
    • Chatbots
    • GIFs
    • Stickers

Moderation Dashboard

  • Overview
  • Getting Started
  • FEATURES

    • Automatic Text Moderation
    • Automatic Image Moderation
    • Manual Message Moderation
    • Manual User Moderation
    • User Management
    • Channel Management
  • Required Configuration

Debug Console
Network Status

Channel memberships

PubNub allows you to store the association between users and channels so clients can get channel memberships for a user, or show members in a channel. Memberships are user-channel associations, not subscriptions. Users don't need to join a channel to subscribe and start exchanging messages on it, but it can be a helpful mechanism for your application to use.

Add members to a channel

To add one or more users to a single channel, as you might do when adding a new team channel, add those users to the channel's members with setChannelMembers(), like so:

You can also use setChannelMembers() to update the custom metadata for existing channel members.

JavaScript
Swift
Objective-C
C#

Go to SDK

pubnub.objects.setChannelMembers({
channel: "channel-1",
uuids: [
"johndoe_1",
{ id: "janedoe_1", custom: { trialPeriod: true } },
],
});

Go to SDK

let newMembership = PubNubMembershipMetadataBase(
uuidMetadataId: "janedoe_1", channelMetadataId: "channel-1"
)

pubnub.setMemberships(
channel: newMembership.channelMetadataId,
uuids: [newMembership]
) { result in
switch result {
case let .success(response):
print("The channel memberships for the uuid \(response.memberships)")
if let nextPage = response.next {
print("The next page used for pagination: \(nextPage)")
}
case let .failure(error):
print("Update Memberships request failed with error: \(error.localized### Description)")
}
}

Go to SDK

NSArray<NSDictionary *> *uuids = @[
@{ @"uuid": @"johndoe_1" }
@{ @"uuid": @"janedoe_1", @"custom": @{ @"trialPeriod": @YES } }
];

self.client.objects().setChannelMembers(@"channel-1")
.uuids(uuids)
.includeFields(PNChannelMemberCustomField | PNChannelMemberUserField)
.performWithCompletion(^(PNManageChannelMembersStatus *status) {
if (!status.isError) {
/**
* Channel's members successfully set.
* Result object has following information:
* result.data.members - list of existing channel's members,
* result.data.next - cursor bookmark for fetching the next page,
* result.data.prev - cursor bookmark for fetching the previous page,
* result.data.totalCount - total number of channel's members.
*/

} else {
/**
* Handle channel's members set error. Check 'category' property to find out possible
* issue because of which request did fail.
*
* Request can be resent using: [status retry]
*/

}
});

Go to SDK

List<PNChannelMember> setMemberChannelList = new List<PNChannelMember>();
if (!string.IsNullOrEmpty(setMemberChUuid))
{
setMemberChannelList.Add(new PNChannelMember() { Uuid = "johndoe_1" } );
setMemberChannelList.Add(new PNChannelMember() { Uuid = "janedoe_1", Custom = new Dictionary<string, object>() { { "trialPeriod", true } } });
}
PNResult<PNChannelMembersResult> setChannelMembersResponse = await pubnub.SetChannelMembers()
.Channel(setmemberChMetadataId)
.Uuids(setMemberChannelList)
.Include(new PNChannelMemberField[] { PNChannelMemberField.CUSTOM, PNChannelMemberField.UUID, PNChannelMemberField.UUID_CUSTOM })
.IncludeCount(true)
.ExecuteAsync();
PNChannelMembersResult setChannelMembersResult = setChannelMembersResponse.Result;
PNStatus status2 = setChannelMembersResponse.Status;

Remove channel members

You can remove one or more users from a single channel by providing the channel ID and a list of users. The code below deletes the membership to my_channel_2 for the users johndoe_1 and janedoe_1.

JavaScript
Objective-C
Android
C#

Go to SDK

pubnub.objects.removeChannelMembers({
channel: "my_channel_2",
uuids: ["johndoe_1", "janedoe_1"]
}
);

Go to SDK

self.client.objects().removeChannelMembers(@"my_channel_2")
.uuids(@[@"johndoe_1", @"janedoe_1"])
.includeFields(PNChannelMemberCustomField | PNChannelMemberUserField)
.performWithCompletion(^(PNManageChannelMembersStatus *status) {
if (!status.isError) {
/**
* Channel's members successfully removed.
* Result object has following information:
* result.data.members - list of channel's existing members,
* result.data.next - cursor bookmark for fetching the next page,
* result.data.prev - cursor bookmark for fetching the previous page,
* result.data.totalCount - total number of channel's members.
*/

} else {
/**
* Handle channel's members remove error. Check 'category' property to find out possible
* issue because of which request did fail.
*
* Request can be resent using: [status retry]
*/

}
});

Go to SDK

pubnub.removeChannelMembers()
.channel("my_channel_2")
.uuids(Arrays.asList(PNUUID.uuid("johndoe_1"), PNUUID.uuid("janedoe_1")))
.async(new PNCallback<PNRemoveChannelMembersResult>() {
@Override
public void onResponse(@Nullable final PNRemoveChannelMembersResult result, @NotNull final PNStatus status) {
if (status.isError()) {
//handle error
} else {
//handle result
}
}
});

Go to SDK

List<string> removeChannelMemberList = new List<string>();
removeChannelMemberList.Add("johndoe_1");
removeChannelMemberList.Add("janedoe_1");

PNResult<PNChannelMembersResult> removeChannelMembersResponse = await pubnub.RemoveChannelMembers()
.Channel("my_channel_2")
.Uuids(removeChannelMemberList)
.Include(new PNChannelMemberField[] { PNChannelMemberField.CUSTOM, PNChannelMemberField.UUID, PNChannelMemberField.UUID_CUSTOM })
.IncludeCount(true)
.ExecuteAsync();
PNChannelMembersResult removeChannelMembersResult = removeChannelMembersResponse.Result;
PNStatus status = removeChannelMembersResponse.Status;

Add channel memberships

To add one user to several channels, perhaps as part of a new-user onboarding process, add those channels to the user's memberships with setMemberships(), like so:

JavaScript
Swift
Objective-C
C#

Go to SDK

pubnub.objects.setMemberships({
channels: [ "channel-1", { id: "channel-2", custom: { starred: true } }]
});

Go to SDK

let newMembership = PubNubMembershipMetadataBase(
uuidMetadataId: "my_user", channelMetadataId: "channel-1"
)

pubnub.setMemberships(
uuid: newMembership.uuidMetadataId,
channels: [newMembership]
) { result in
switch result {
case let .success(response):
print("The channel memberships for the uuid \(response.memberships)")
if let nextPage = response.next {
print("The next page used for pagination: \(nextPage)")
}
case let .failure(error):
print("Update Memberships request failed with error: \(error.localized### Description)")
}
}

Go to SDK

NSArray<NSDictionary *> *channels = @[
@{ @"channel": @"channel-1" },
@{ @"channel": @"channel-2", @"custom": @{ @"starred": @YES } }
];

self.client.objects().setMemberships()
.uuid(@"uuid")
.channels(channels)
.includeCount(YES)
.limit(40)
.includeFields(NMembershipCustomField | PNMembershipChannelField)
.performWithCompletion(^(PNManageMembershipsStatus *status) {
if (!status.isError) {
/**
* UUID's memberships successfully set.
* Result object has following information:
* status.data.memberships - list of UUID's existing memberships,
* status.data.next - cursor bookmark for fetching the next page,
* status.data.prev - cursor bookmark for fetching the previous page,
* status.data.totalCount - total number of UUID's memberships.
*/

} else {
/**
* Handle UUID's memberships set error. Check 'category' property to find out possible
* issue because of which request did fail.
*
* Request can be resent using: [status retry]
*/

}
});

Go to SDK

List<PNMembership> setMembershipChannelMetadataIdList = new List<PNMembership>();
if (!string.IsNullOrEmpty(seMembershipChannelMetaId))
{
setMembershipChannelMetadataIdList.Add(new PNMembership() { Channel = "channel-1" });
setMembershipChannelMetadataIdList.Add(new PNMembership() { Channel = "channel-2", Custom = new Dictionary<string, object>() { { "starred", true } } });
}

PNResult<PNMembershipsResult> setMembershipsResponse = await pubnub.SetMemberships()
.Uuid("my-uuid")
.Channels(setMembershipChannelMetadataIdList)
.Include(new PNMembershipField[] { PNMembershipField.CUSTOM, PNMembershipField.CHANNEL, PNMembershipField.CHANNEL_CUSTOM })
.IncludeCount(true)
.ExecuteAsync();
PNMembershipsResult setMembershipsResult = setMembershipsResponse.Result;
PNStatus status = setMembershipsResponse.Status;

Remove channel memberships

You can remove a single user from one or more channels, effectively deleting a membership relation between the user and the channels. The code below removes the current user from the channel my_channel_2.

JavaScript
Objective-C
Android
C#

Go to SDK

pubnub.objects.removeMemberships({
channels: ["my_channel_2"]
});

Go to SDK

self.client.objects().removeMemberships()
.uuid(@"uuid")
.channels(@"my_channel_2")
.includeFields(PNMembershipCustomField | PNMembershipChannelField)
.performWithCompletion(^(PNManageMembershipsStatus *status) {
if (!status.isError) {
/**
* UUID's memberships successfully removed.
* Result object has following information:
* status.data.memberships - list of UUID's existing memberships,
* status.data.next - cursor bookmark for fetching the next page,
* status.data.prev - cursor bookmark for fetching the previous page,
* status.data.totalCount - total number of UUID's memberships.
*/

} else {
/**
* Handle UUID's memberships remove error. Check 'category' property to find out possible
* issue because of which request did fail.
*
* Request can be resent using: [status retry]
*/

}
});

Go to SDK

pubnub.removeMemberships()
.channelMemberships(Collections.singletonList(PNChannelMembership.channel("my_channel_2")))
.async(new PNCallback<PNRemoveMembershipResult>() {
@Override
public void onResponse(@Nullable final PNRemoveMembershipResult result, @NotNull final PNStatus status) {
if (status.isError()) {
//handle error
} else {
//handle result
}
}
});

Go to SDK

List<string> removeMembershipList = new List<string>();
if (!string.IsNullOrEmpty(removeMembershipChannelMetaId))
{
removeMembershipList.Add("my_channel_2");
}

PNResult<PNMembershipsResult> removeMembershipsResponse = await pubnub.RemoveMemberships()
.Uuid("uuid")
.Channels(removeMembershipList)
.Include(new PNMembershipField[] { PNMembershipField.CUSTOM, PNMembershipField.CHANNEL, PNMembershipField.CHANNEL_CUSTOM })
.IncludeCount(true)
.ExecuteAsync();
PNMembershipsResult removeMembershipsResult = removeMembershipsResponse.Result;
PNStatus status2 = removeMembershipsResponse.Status;

Membership events

Membership events are generated when memberships are set or removed from the objects database. Object events are disabled by default on new keys. You can enable or disable these events from your key settings in the Admin Portal.

EventDescriptionEvent channel
Membership SetUser-channel association is created or updated.These events are published on {uuid} and {channel}.
Membership RemovedUser-channel association is deleted.These events are published on {uuid} and {channel}.

Membership set event:

{
   "channel":"ch-1",
   "message":{
      "event":"set",
      "type":"membership",
      "data":{
         "channel":{
            "id":"ch-1"
         },
         "uuid":{
            "id":"uuid-1"
         },
         "custom":null,
         "updated":"2020-04-17T19:13:59.40962853Z",
         "eTag":"AY39mJKK//C0VA"
      }
   },
   "subscription":null,
   "timetoken":"15119446002445794"
}

Membership removed event:

{
   "channel":"ch-1",
   "message":{
      "event":"removed",
      "type":"membership",
      "data":{
         "channel":{
            "id":"ch-1"
         },
         "uuid":{
            "id":"uuid-1"
         },
         "custom":null,
         "updated":"2020-04-17T19:13:59.40962853Z",
         "eTag":"AY39mJKK//C0VA"
      }
   },
   "subscription":null,
   "timetoken":"15119446002445794"
}
←SubscriptionsSending Messages→
  • Add members to a channel
  • Remove channel members
  • Add channel memberships
  • Remove channel memberships
  • Membership events
© PubNub Inc. - Privacy Policy