Presence API for Python SDK

Presence lets you track who is online or offline and store custom state information. Presence shows:

  • When a user has joined or left a channel
  • How many users are subscribed to a particular channel (occupancy)
  • Which channels a user or device is subscribed to
  • Presence state associated with these users

Learn more about our Presence feature in the Presence overview.

Request execution and return values

You can decide whether to perform the Python SDK operations synchronously or asynchronously.

  • .sync() returns an Envelope object, which has two fields: Envelope.result, whose type differs for each API, and Envelope.status of type PnStatus.

    1pubnub.publish() \
    2 .channel("myChannel") \
    3 .message("Hello from PubNub Python SDK") \
    4 .sync()
  • .pn_async(callback) returns None and passes the values of Envelope.result and Envelope.status to a callback you must define beforehand.

    1def my_callback_function(result, status):
    2 print(f'TT: {result.timetoken}, status: {status.category.name}')
    3
    4pubnub.publish() \
    5 .channel("myChannel") \
    6 .message("Hello from PubNub Python SDK") \
    7 .pn_async(my_callback_function)

Here now​

Requires Presence

This method requires that the Presence add-on is enabled for your key in the Admin Portal.

For information on how to receive presence events and what those events are, refer to Presence Events.

This method returns information about the current state of a channel, including a list of unique user IDs (universally unique identifiers, UUIDs) currently subscribed to the channel and the total occupancy count of the channel.

Cache

This method has a 3-second response cache time.

Method(s)​

To call Here Now you can use the following method(s) in the Python SDK:

1pubnub.here_now() \
2 .channels(String|List|Tuple) \
3 .channel_groups(String|List|Tuple) \
4 .include_state(Boolean) \
5 .include_uuids(Boolean) \
6 .limit(Integer) \
7 .offset(Integer)
* required
ParameterDescription
channels
Type: String | List | Tuple
Default:
n/a
The channels to get the here now details.
channel_groups
Type: String | List | Tuple
Default:
n/a
The channel groups to get the here now details. Wildcards are not supported.
include_state
Type: Boolean
Default:
False
If True, the response will include the presence states of the users for channels/channelGroups.
include_uuids
Type: Boolean
Default:
True
If True, the response will include the UUIDs of the connected clients.
limit
Type: Integer
Default:
1000
Maximum number of occupants to return per channel. Valid range: 0-1000. Use 0 to get occupancy counts without user details.
offset
Type: Integer
Default:
None
Zero-based starting index for pagination. Returns occupants starting from this position in the list. Must be >= 0. Requires limit > 0. Use with limit to paginate through large occupant lists.

Sample code​

Get a list of UUIDs subscribed to channel​

Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
1import os
2from pubnub.pnconfiguration import PNConfiguration
3from pubnub.pubnub import PubNub
4
5
6def main():
7 # Configuration for PubNub instance
8 pn_config = PNConfiguration()
9 pn_config.subscribe_key = os.getenv('SUBSCRIBE_KEY', 'demo')
10 pn_config.user_id = os.getenv('USER_ID', 'my_custom_user_id')
11
12 # Initialize PubNub client
13 pubnub = PubNub(pn_config)
14
15 # Get here_now details
show all 36 lines

Returns​

The here_now() operation returns an Envelope which contains the following fields:

FieldTypeDescription
resultPNHereNowResultA detailed object containing the result of the operation.
statusPNStatusA status object with additional information.

PNHereNowResult​

FieldTypeDescription
total_channelsIntTotal channels.
total_occupancyIntTotal occupancy
channelsDictionaryA dictionary with values of PNHereNowChannelData for each channel.

PNHereNowChannelData​

FieldTypeDescription
channel_nameStringchannel name.
occupancyIntoccupancy of the channel.
occupantsListA list of PNHereNowOccupantData.

PNHereNowOccupantData​

FieldTypeDescription
uuidStringuuid of the user.
stateDictionarystate of the user.

Other examples​

Returning state​

Requires Presence

This method requires that the Presence add-on is enabled for your key in the Admin Portal.

For information on how to receive presence events and what those events are, refer to Presence Events.

1envelope = pubnub.here_now() \
2 .channels("my_channel") \
3 .include_uuids(True) \
4 .include_state(True) \
5 .sync()
Example response​
1{
2 total_channels: 1,
3 channels: [{
4 channel_name: "my_channel",
5 occupancy: 1,
6 occupants: [{
7 uuid: "myUuid1"
8 state: {
9 "abcd": {
10 "age": 15
11 }
12 }
13 }]
14 }],
15 total_occupancy: 1
show all 16 lines

Return occupancy only​

Requires Presence

This method requires that the Presence add-on is enabled for your key in the Admin Portal.

For information on how to receive presence events and what those events are, refer to Presence Events.

You can return only the occupancy information for a single channel by specifying the channel and setting UUIDs to False:

1envelope = pubnub.here_now() \
2 .channels("my_channel") \
3 .include_uuids(False) \
4 .include_state(False) \
5 .sync()
Example response​
1{
2 total_channels: 1,
3 channels: [{
4 channel_name: "my_channel",
5 occupancy: 3,
6 occupants: []
7 }],
8 total_occupancy: 3
9}

Here now for channel groups​

1envelope = pubnub.here_now() \
2 .channel_groups(['cg1', 'cg2', 'cg3']) \
3 .include_uuids(True) \
4 .include_state(True) \
5 .sync()
Example response​
1{
2 total_channels: 1,
3 channels: [
4 {
5 channel_name: "my_channel",
6 occupancy: 1,
7 occupants: [{
8 uuid: "143r34f34t34fq34q34q3",
9 state: None
10 }]
11 },
12 {
13 occupancy: 1,
14 occupants: [{
15 uuid: "123123234t234f34fq3dq",
show all 35 lines

Paginate through occupants​

Requires Presence

This method requires that the Presence add-on is enabled for your key in the Admin Portal.

For information on how to receive presence events and what those events are, refer to Presence Events.

You can paginate through large occupant lists using limit and offset:

1# Get first 10 occupants
2envelope = pubnub.here_now() \
3 .channels("my_channel") \
4 .limit(10) \
5 .sync()
6
7# Get next 10 occupants (starting from position 10)
8envelope = pubnub.here_now() \
9 .channels("my_channel") \
10 .limit(10) \
11 .offset(10) \
12 .sync()

Where now​

Requires Presence

This method requires that the Presence add-on is enabled for your key in the Admin Portal.

For information on how to receive presence events and what those events are, refer to Presence Events.

This method returns the list of channels a UUID is subscribed to.

Timeout events

If the app restarts (or the page refreshes) within the heartbeat window, no timeout event is generated.

Method(s)​

To call where_now() you can use the following method(s) in the Python SDK:

1pubnub.where_now() \
2 .uuid(String)
* required
ParameterDescription
uuid
Type: String
uuid to get info on.

Sample code​

You simply need to define the uuid and the callback function to be used to send the data to as in the example below.

Get a list of channels a UUID is subscribed to​

1envelope = pubnub.where_now().sync()

Returns​

The where_now() operation returns an Envelope which contains the following fields:

FieldTypeDescription
resultPNWhereNowResultA detailed object containing the result of the operation.
statusPNStatusA status object with additional information.

PNWhereNowResult​

FieldTypeDescription
channelsListThe list of channels where the UUID is present.

Other examples​

Obtain information about the current list of channels of some other UUID​

1envelope = pubnub.where_now() \
2 .uuid('some-other-uuid') \
3 .sync()

User state​

Requires Presence

This method requires that the Presence add-on is enabled for your key in the Admin Portal.

For information on how to receive presence events and what those events are, refer to Presence Events.

Clients can set a dynamic custom state (score, game state, location) for their users on one or more channels and store it on a channel as long as the user stays subscribed.

The state is not persisted, and when the client disconnects, the state data is lost. For more information, refer to Presence State.

Presence state format

Presence state must be expressed as a dict. When calling set_state, be sure to supply an initialized dict which can be serialized.

Method(s)​

Set state​

1pubnub.set_state() \
2 .channels(String|List|Tuple) \
3 .channel_groups(String|List|Tuple) \
4 .state(Dictionary)
* required
ParameterDescription
channels
Type: String | List | Tuple
channels to set state.
channel_groups
Type: String | List | Tuple
channel groups to set state.
state
Type: Dictionary
state to set.

Get state​

1pubnub.get_state() \
2 .channels(String|List|Tuple) \
3 .channel_groups(String|List|Tuple) \
4 .uuid(String)
* required
ParameterDescription
channels
Type: String | List | Tuple
channels to get state.
channel_groups
Type: String | List | Tuple
channel groups to get state.
uuid
Type: String
uuid to get state from.

Sample code​

Set state​

1my_state = {
2 'age': 20
3}
4envelope = pubnub.set_state() \
5 .channels(['ch1', 'ch2', 'ch3']) \
6 .state(my_state) \
7 .sync()

Get state​

1envelope = pubnub.get_state() \
2 .channels(['ch1', 'ch2', 'ch3']) \
3 .uuid('such_uuid') \
4 .sync()

Returns​

The set_state() operation returns an Envelope which contains the following fields:

FieldTypeDescription
resultPNSetStateResultA detailed object containing the result of the operation.
statusPNStatusA status object with additional information.

PNSetStateResult​

FieldTypeDescription
stateDictionaryDictionary of UUIDs and the user states.

The get_state() operation returns an Envelope which contains the following fields:

FieldTypeDescription
resultPNGetStateResultA detailed object containing the result of the operation.
statusPNStatusA status object with additional information.

PNGetStateResult​

FieldTypeDescription
channelsDictionaryDictionary of channels and the user states.

Other examples​

Set state for channels in channel group​

1my_state = {
2 'age': 20
3}
4envelope = pubnub.set_state() \
5 .channel_groups(['gr1', 'gr2', 'gr3']) \
6 .state(my_state) \
7 .sync()

The above code would return the following response to the client:

1{
2 first : "Robert",
3 last : "Plant",
4 age : 59,
5 region : "UK"
6}

Was this page useful?

Last updated on