Presence API for Python-Asyncio SDK
The Presence API of the PubNub SDK for Python-Asyncio reports which users are online on a channel, which channels a user is on, and the presence state of users. To learn more about Presence as a feature, see the Presence overview.
A builder sends its request when you await its future(). A request that fails, or fails validation, does not raise an exception. future() resolves with a PubNubAsyncioException whose result is None and whose status holds the error. Call is_error() on the awaited value before you read result.
Here now
Presence add-on
This method requires that the Presence add-on is enabled for your key in the Admin Portal.
Requires Presence add-on
This method requires that the Presence add-on is enabled for your key in the Admin Portal. See Enable the features your app calls.
here_now() returns the User IDs that are present on channels and channel groups, and the occupancy of each channel, with a PubNub client for Python-Asyncio.
When Access Manager is enabled, calling Here Now requires read permission on the queried channel.
Cache
This method has a 3-second response cache time.
channels#- Channel names to return the occupancy and occupants of. When
channelsandchannel_groupsare both empty, the SDK requests the occupancy of every channel on the key. channel_groups#- Channel group names to return the occupancy and occupants of. Wildcards are not supported.
include_state#- Whether the response includes the presence state of each occupant.
include_uuids#- Whether the response lists the User IDs of the occupants of each channel. Set to
Falseto receive only the occupancy counts. limit#Here Nowaccepts alimitof up to 1,000 occupants per channel, and you paginate past that withoffset. Settinglimitto0returns only the occupancy count, without the list of occupants.offset#- Zero-based position of the first occupant to return. Use it with
limitto page through the occupants of a channel. The SDK sendsoffsetonly when it is set.
The keyword arguments of here_now() are channels, channel_groups, include_state and include_uuids. Set limit and offset with the builder methods.
Sample code
Returns
here_now() resolves with an AsyncioEnvelope whose result is a PNHereNowResult with the total channel count, the total occupancy, and the occupants of each channel, and whose status is a PNStatus.
PNHereNowResult
total_channels#- Number of channels in the response.
total_occupancy#- Total number of occupants across those channels.
channels#- One
PNHereNowChannelDatafor each channel.
PNHereNowChannelData
PNHereNowOccupantsData
Other examples
Examples for Here now
Syntax
1await pubnub.here_now() \
2 .channels(channels: Union[str, List[str]]) \
3 .channel_groups(channel_groups: Union[str, List[str]]) \
4 .include_state(include_state: bool) \
5 .include_uuids(include_uuids: bool) \
6 .limit(limit: int) \
7 .offset(offset: int) \
8 .future() -> AsyncioEnvelope
Get a list of UUIDs subscribed to channel
Get a list of UUIDs subscribed to channel
1envelope = await pubnub.here_now() \
2 .channels(["my_channel", "my_channel_2"]) \
3 .include_uuids(True) \
4 .future()
5
6if envelope.status.is_error():
7 print("Error retrieving here_now data")
8 return
9
10for channel_data in envelope.result.channels:
11 print("---")
12 print(f"Channel: {channel_data.channel_name}")
13 print(f"Occupancy: {channel_data.occupancy}")
14 for occupant in channel_data.occupants:
15 print(f"UUID: {occupant.uuid}, State: {occupant.state}")
Returning state
Returning state
1envelope = await pubnub.here_now() \
2 .channels("my_channel") \
3 .include_uuids(True) \
4 .include_state(True) \
5 .future()
6if envelope.is_error():
7 print(f"Error: {envelope.status.error_data}")
Returning state - Example response
Example response
1# Example of envelope.result
2{
3 "total_channels": 1,
4 "channels": [{
5 "channel_name": "my_channel",
6 "occupancy": 1,
7 "occupants": [{
8 "uuid": "myUuid1",
9 "state": {
10 "abcd": {
11 "age": 15
12 }
13 }
14 }]
15 }],
show all 17 linesReturn occupancy only
Return occupancy only
1envelope = await pubnub.here_now() \
2 .channels("my_channel") \
3 .include_uuids(False) \
4 .include_state(False) \
5 .future()
6if envelope.is_error():
7 print(f"Error: {envelope.status.error_data}")
Return occupancy only - Example response
Example response
1# Example of envelope.result
2{
3 "total_channels": 1,
4 "channels": [{
5 "channel_name": "my_channel",
6 "occupancy": 3,
7 "occupants": []
8 }],
9 "total_occupancy": 3
10}
Channel group usage
Channel group usage
1envelope = await pubnub.here_now() \
2 .channel_groups(['cg1', 'cg2', 'cg3']) \
3 .include_uuids(True) \
4 .include_state(True) \
5 .future()
6if envelope.is_error():
7 print(f"Error: {envelope.status.error_data}")
Channel group usage - Example response
Example response
1# Example of envelope.result
2{
3 "total_channels": 3,
4 "channels": [
5 {
6 "channel_name": "my_channel_1",
7 "occupancy": 1,
8 "occupants": [{"uuid": "User1", "state": None}]
9 },
10 {
11 "channel_name": "my_channel_2",
12 "occupancy": 1,
13 "occupants": [{"uuid": "User1", "state": None}]
14 },
15 {
show all 22 linesWhere now
Presence add-on
This method requires that the Presence add-on is enabled for your key in the Admin Portal.
Requires Presence add-on
This method requires that the Presence add-on is enabled for your key in the Admin Portal. See Enable the features your app calls.
where_now() returns the channels that a User ID is present on, with a PubNub client for Python-Asyncio.
Where Now requires no channel-level permission when Access Manager is enabled because it looks up a User ID rather than a channel.
uuid#- User ID to list the channels of. When omitted, the SDK uses the
user_idof the PubNub client. The keyword argument ofwhere_now()isuser_id.
Sample code
Returns
where_now() resolves with an AsyncioEnvelope whose result is a PNWhereNowResult with the IDs of the channels where the user is present, and whose status is a PNStatus.
PNWhereNowResult
channels#- The channels where the User ID is present.
Other examples
Examples for Where now
Syntax
1await pubnub.where_now() \
2 .uuid(uuid: str) \
3 .future() -> AsyncioEnvelope
Get a list of channels a UUID is subscribed to
Get a list of channels a UUID is subscribed to
1envelope = await pubnub.where_now() \
2 .future()
3if envelope.is_error():
4 print(f"Error: {envelope.status.error_data}")
Obtain information about the current list of channels of some other UUID
Obtain information about the current list of channels of some other UUID
1envelope = await pubnub.where_now() \
2 .uuid('some-other-uuid') \
3 .future()
4if envelope.is_error():
5 print(f"Error: {envelope.status.error_data}")
Set state
Presence add-on
This method requires that the Presence add-on is enabled for your key in the Admin Portal.
Requires Presence add-on
This method requires that the Presence add-on is enabled for your key in the Admin Portal. See Enable the features your app calls.
set_state() sets the presence state of the current User ID of a PubNub client for Python-Asyncio on channels and channel groups.
Presence state is custom data, such as a score, a game state, or a location. PubNub holds it for a User ID on a channel while the User ID stays subscribed. PubNub doesn't persist presence state, and disconnecting a client clears it. Setting presence state overwrites the entire existing state of the User ID on that channel, so send the full state object, not only the field that changed. To learn more, see Set and get presence state.
When Access Manager is enabled, Get State and Set State both require read permission on the channel.
channelsrequired#- Channel names to set the presence state on. The SDK refuses a call that has
channel_groupsand nochannels, so always providechannels. A call with neither fails validation with the messageChannel or group missing. channel_groups#- Channel group names to set the presence state on. Wildcards are not supported. A call with
channel_groupsand nochannelsfails validation with the messageState setter for channel groups is not supported yet. staterequired#- Presence state to set, as a JSON-serializable object. The SDK accepts only a
dict. A call withstatemissing or not adictfails validation with the messageState missing or not a dict.
The keyword arguments of set_state() are channels, channel_groups and state.
Sample code
Returns
set_state() resolves with an AsyncioEnvelope whose result is a PNSetStateResult with the state that PubNub stored for the user, and whose status is a PNStatus.
PNSetStateResult
state#- The presence state that PubNub stored for the User ID.
Other examples
Examples for Set state
Syntax
1await pubnub.set_state() \
2 .channels(channels: Union[str, List[str]]) \
3 .channel_groups(channel_groups: Union[str, List[str]]) \
4 .state(state: Dict[str, Any]) \
5 .future() -> AsyncioEnvelope
Basic usage
1my_state = {
2 'age': 20
3}
4envelope = await pubnub.set_state() \
5 .channels(['ch1', 'ch2', 'ch3']) \
6 .state(my_state) \
7 .future()
8if envelope.is_error():
9 print(f"Error: {envelope.status.error_data}")
Set state for channels in channel group
Set state for channels in channel group
1my_state = {
2 'age': 20
3}
4envelope = await pubnub.set_state() \
5 .channels(['ch1']) \
6 .channel_groups(['gr1', 'gr2', 'gr3']) \
7 .state(my_state) \
8 .future()
9if envelope.is_error():
10 print(f"Error: {envelope.status.error_data}")
Get state
Presence add-on
This method requires that the Presence add-on is enabled for your key in the Admin Portal.
Requires Presence add-on
This method requires that the Presence add-on is enabled for your key in the Admin Portal. See Enable the features your app calls.
get_state() reads the presence state of a User ID on channels and channel groups, using a PubNub client for Python-Asyncio.
Presence state is custom data, such as a score, a game state, or a location. PubNub holds it for a User ID on a channel while the User ID stays subscribed. PubNub doesn't persist presence state, and disconnecting a client clears it. To learn more, see Set and get presence state.
When Access Manager is enabled, Get State and Set State both require read permission on the channel.
channels#- Channel names to read the presence state from. Provide
channels,channel_groups, or both. A call with neither fails validation with the messageChannel or group missing. channel_groups#- Channel group names to read the presence state from. Wildcards are not supported.
uuid#- User ID to read the presence state of. When omitted, the SDK uses the
user_idof the PubNub client.
The keyword arguments of get_state() are channels, channel_groups and uuid.
Sample code
Returns
get_state() resolves with an AsyncioEnvelope whose result is a PNGetStateResult with the state of the user, grouped by channel, and whose status is a PNStatus.
PNGetStateResult
channels#- The presence state of the User ID, keyed by channel name.
Examples for Get state
Syntax
1await pubnub.get_state() \
2 .channels(channels: Union[str, List[str]]) \
3 .channel_groups(channel_groups: Union[str, List[str]]) \
4 .uuid(uuid: str) \
5 .future() -> AsyncioEnvelope
Basic usage
1envelope = await pubnub.get_state() \
2 .channels(['ch1', 'ch2', 'ch3']) \
3 .uuid('such_uuid') \
4 .future()
5if envelope.is_error():
6 print(f"Error: {envelope.status.error_data}")
Receive presence events
with_presence=True makes a subscription in the Python-Asyncio SDK deliver join, leave, timeout, interval and state-change events to its on_presence callback.
Presence events require the Presence add-on to be enabled for your key. The callback receives a PNPresenceEventResult with the attributes event, channel, subscription, timetoken, timestamp, uuid, occupancy, state, join, leave and timeout. The event attribute holds the action.
Events for join, leave and timeout carry uuid and occupancy. A state-change event carries uuid and state. An interval event carries occupancy and the optional lists join, leave and timeout.
Up to the Announce Max threshold, a channel emits individual join, leave, and timeout events. Above it, the channel emits periodic interval events instead, while state-change stays individual in both modes.
To learn more about subscriptions and event listeners, see Publish & Subscribe.
Sample code
Examples for Receive presence events
Basic usage
1def on_presence(listener):
2 def presence_callback(presence):
3 print(f"\033[0;32mPresence received on: {listener}: \t{presence.uuid} {presence.event}s "
4 f"{presence.subscription or presence.channel}\033[0m")
5 return presence_callback
6
7subscription = pubnub.channel("my_channel").subscription(with_presence=True)
8subscription.on_presence = on_presence('presence_listener')
9
10subscription.subscribe()