Set and get presence state
This guide shows you how to attach custom presence state to a User ID on a channel, and how to read it back. Presence must be enabled on the keyset, and new keysets have it enabled by default. Presence state is custom data such as a mood, a game score, or a typing indicator. It exists only while the User ID stays subscribed to that channel. PubNub doesn't persist it, and disconnecting clears it. For anything that needs to survive a disconnect, use App Context instead.
When Access Manager is enabled, Get State and Set State both require read permission on the channel.
Set state, then read it back
Call Set State with the User ID's current channel and a state object. By default, the state applies to the current client's own User ID. Get State then reads it back for any User ID, not just your own, which is how other clients learn about it outside of a state-change event.
- JavaScript
- Python
- Java
- Kotlin
- C#
- Go
- Swift
1
1my_state = {"mood": "pumped", "isTyping": False}
2
3set_envelope = pubnub.set_state() \
4 .channels(["chats.room1"]) \
5 .state(my_state) \
6 .sync()
7
8get_envelope = pubnub.get_state() \
9 .channels(["chats.room1"]) \
10 .uuid("anotherUserId") \
11 .sync()
1
1
1
1
1
Most other SDKs document the same two calls in the Presence section of their API reference, for example PHP or Ruby.
Setting state overwrites the User ID's entire existing state on that channel. To change one field and keep the rest, send the full state object back, not just the field that changed. Keep the payload small, because state travels on every Here Now response and every state-change event that carries it.
Set state for a channel group
Pass a channel group instead of, or alongside, a channel list to apply the same state to every channel in the group in one call.
No JavaScript example here. Showing C#:
- C#
- Kotlin
1
1
Related tasks
- Receive presence events. Get the
state-changeevent that fires when a state you set changes. - Get online users in a channel. Fetch every occupant's state in one
Here Nowcall instead of oneGet Statecall per User ID. - Presence. How presence state relates to occupancy, events, and membership.
- App Context. Store structured metadata that needs to survive a disconnect.