Check user presence
PubNub lets you track the online and offline status of users and devices in real time. You can see who is online, when a user joins or leaves a channel, and which channels a user is subscribed to. Learn the basics in Presence fundamentals.
Subscription with Presence
To receive Presence events, you subscribe with Presence and have Presence enabled on your keyset. Make sure you configure Presence to track Presence-related events for all or selected channels (through Presence Management rules).
Before you begin, make sure you have initialized PubNub with your keys. The code below prints a list of all users who are online on the chats.public.release_announcements
channel.
User ID / UUID
User ID is also referred to as UUID
/uuid
in some APIs and server responses but holds the value of the userId
parameter you set during initialization.
- JavaScript
- Swift
- Objective-C
- Java
- C#
- Python
- Dart
- Kotlin
pubnub.hereNow(
{
channels: ["chats.public.release_announcements"]
},
function (status, response) {
console.log(status, response);
}
);
pubnub.hereNow(on: ["chats.public.release_announcements"]),
includeUUIDs: true, also: true { result in
switch result {
case let .success(response):
print("Successful hereNow Response: \(response)")
case let .failure(error):
print("Failed hereNow Response: \(error.localizedDescription)")
}
})
[self.pubnub hereNowForChannel: @[@"chats.public.release_announcements"]
withVerbosity:PNHereNowState
completion:^(PNPresenceChannelHereNowResult *result, PNErrorStatus *status) {
// parse the HereNow result parameter
}];
pubnub.hereNow()
.channels(Arrays.asList("chats.public.release_announcements"))
.includeState(true)
.async(result -> {
result.onSuccess(res -> {
for (PNHereNowChannelData channelData : res.getChannels().values()) {
System.out.println("---");
System.out.println("channel:" + channelData.getChannelName());
System.out.println("occupancy: " + channelData.getOccupancy());
System.out.println("occupants:");
for (PNHereNowOccupantData occupant : channelData.getOccupants()) {
System.out.println("uuid: " + occupant.getUuid()
+ " state: " + occupant.getState());
}
show all 20 linespubnub.HereNow()
.Channels(new string[] {"chats.public.release_announcements"})
.IncludeState(true)
.Execute(new PNHereNowResultEx((result, status) => {
if (status.Error) {
Console.WriteLine("HereNow error: " + status);
}
else if (result.Channels != null && result.Channels.Count > 0) {
foreach (KeyValuePair<string, PNHereNowChannelData> kvp in result.Channels) {
PNHereNowChannelData channelData = kvp.Value;
Console.WriteLine("---");
Console.WriteLine("channel:" + channelData.ChannelName);
Console.WriteLine("occupancy:" + channelData.Occupancy);
Console.WriteLine("Occupants:");
show all 27 linesdef here_now_callback(result, status):
if status.is_error():
print("here_now error: %s" % status)
return
for channel_data in result.channels:
print("---")
print("channel: %s" % channel_data.channel_name)
print("occupancy: %s" % channel_data.occupancy)
print("occupants: %s" % channel_data.channel_name)
for occupant in channel_data.occupants:
print("uuid: %s, state: %s" % (occupant.uuid, occupant.state))
show all 19 linesvar result = await pubnub.hereNow(channels: {'chats.public.release_announcements'});
pubnub.hereNow(
channels = listOf("chats.public.release_announcements"),
includeUUIDs = true,
includeState = true
).async { result, status ->
if (status.error) {
// handle error
status.exception?.printStackTrace()
return@async
}
result!!.channels.values.forEach { channelData ->
println("---")
println("Channel: ${channelData.channelName}")
println("Occupancy: ${channelData.occupancy}")
println("Occupants:")
show all 20 linesPresence relies on presence events that PubNub sends automatically when a user’s state changes. You can react to these events by adding a handler dedicated to presence events.
Subscription with Presence
To receive Presence events, you subscribe with Presence and have Presence enabled on your keyset. Make sure you configure Presence to track Presence-related events for all or selected channels (through Presence Management rules).
PubNub sends presence events on a presence channel, not on the channel where the change happens. A presence channel is created automatically for every regular channel.
If you need real‑time presence changes, enable presence when you subscribe to the regular channel.
- JavaScript
- Swift
- Objective-C
- Java
- C#
- Python
- Dart
- Kotlin
// subscribe to a single channel without presence
pubnub.subscribe({channels: ["chats_inbox.user_1905"]});
// subscribe to multiple channels with presence
pubnub.subscribe({
channels: [
"chats_guilds.mages_guild",
"alerts.system",
"geolocation.data"
],
withPresence: true
});
pubnub.subscribe(
to: ["chats.public.release_announcements"],
withPresence: true
)
[self.pubnub subscribeToChannels: @[@"chats_guilds.mages_guild", @"chats_inbox.user_1905"] withPresence:YES];
pubnub.subscribe()
.channels(Arrays.asList("chats.public.release_announcements"))
.withPresence().execute();
Subscription subscription1 = pubnub.Channel("chats.public.release_announcements").Subscription(SubscriptionOptions.ReceivePresenceEvents)
subscription1.Subscribe<object>()
subscription = pubnub.channel_group('chats.public.release_announcements').subscription(with_presence = True)
subscription.subscribe()
var channel = "chats.public.release_announcements";
var subscription = pubnub.subscribe(channels: {channel}, withPresence: true);
pubnub.subscribe(
channels = listOf("chats.public.release_announcements")
withPresence = true
)
As part of user presence, you can set a custom dynamic state, such as a score or mood indicator, for users in your channels. This state persists only while the user is subscribed to a channel. When the user disconnects, the custom data is removed.
If you don't want to lose any additional data about your users and channels, consider adding metadata.