Presence API for PubNub Python SDK
Presence enables you to track the online and offline status of users and devices in real time and store custom state information. Presence provides authoritative information on:
- When a user has joined or left a channel
- Who, and how many, users are subscribed to a particular channel
- Which channel(s) an individual user is subscribed to
- Associated state information for these users
Learn more about our Presence feature here.
Request execution and return values
You can decide whether to perform the Python SDK operations synchronously or asynchronously.
-
.sync()
returns anEnvelope
object, which has two fields:Envelope.result
, whose type differs for each API, andEnvelope.status
of typePnStatus
.pubnub.publish() \
.channel("myChannel") \
.message("Hello from PubNub Python SDK") \
.sync() -
.pn_async(callback)
returnsNone
and passes the values ofEnvelope.result
andEnvelope.status
to a callback you must define beforehand.def my_callback_function(result, status):
print(f'TT: {result.timetoken}, status: {status.category.name}')
pubnub.publish() \
.channel("myChannel") \
.message("Hello from PubNub Python SDK") \
.pn_async(my_callback_function)
Here Now
Requires Presence add-on
This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
You can obtain information about the current state of a channel including a list of unique user-ids currently subscribed to the channel and the total occupancy count of the channel by calling the here_now()
function in your application.
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:
pubnub.here_now() \
.channels(String|List|Tuple) \
.channel_groups(String|List|Tuple) \
.include_state(Boolean) \
.include_uuids(Boolean)
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
channels | String | List | Tuple | Optional | The channels to get the here now details. | |
channel_groups | String | List | Tuple | Optional | The channel groups to get the here now details. | |
include_state | Boolean | Optional | False | If True , the response will include the presence states of the users for channels/channelGroups. |
include_uuids | Boolean | Optional | True | If True , the response will include the UUIDs of the connected clients. |
Basic Usage
Get a list of UUIDs subscribed to channel
- Builder Pattern
- Named Arguments
def here_now_callback(result, status):
if status.is_error():
# handle error
return
for channel_data in result.channels:
print("---")
print(f"channel: {channel_data.channel_name}")
print(f"occupancy: {channel_data.occupancy}")
print(f"occupants: {channel_data.channel_name}")
for occupant in channel_data.occupants:
print(f"uuid: {occupant.uuid}, state: {occupant.state}")
pubnub.here_now()\
show all 18 lineshere_now = pubnub.here_now(channels["my_channel", "demo"], include_uuids=True).sync()
if not here_now.status.is_error():
for channel_data in here_now.result.channels:
print(f"channel: {channel_data.channel_name}")
print(f"occupancy: {channel_data.occupancy}")
print(f"occupants: {channel_data.channel_name}")
for occupant in channel_data.occupants:
print(f"uuid: {occupant.uuid}, state: {occupant.state}")
Returns
The here_now()
operation returns an Envelope
which contains the following fields:
Field | Type | Description |
---|---|---|
result | PNHereNowResult | A detailed object containing the result of the operation. |
status | PNStatus | A status object with additional information. |
PNHereNowResult
Field | Type | Description |
---|---|---|
total_channels | Int | Total channels . |
total_occupancy | Int | Total occupancy |
channels | Dictionary | A dictionary with values of PNHereNowChannelData for each channel. |
PNHereNowChannelData
Field | Type | Description |
---|---|---|
channel_name | String | channel name. |
occupancy | Int | occupancy of the channel . |
occupants | List | A list of PNHereNowOccupantData . |
PNHereNowOccupantData
Field | Type | Description |
---|---|---|
uuid | String | uuid of the user. |
state | Dictionary | state of the user. |
Other Examples
Returning State
Requires Presence add-on
This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
envelope = pubnub.here_now() \
.channels("my_channel") \
.include_uuids(True) \
.include_state(True) \
.sync()
Example Response
{
total_channels: 1,
channels: [{
channel_name: "my_channel",
occupancy: 1,
occupants: [{
uuid: "myUuid1"
state: {
"abcd": {
"age": 15
}
}
}]
}],
total_occupancy: 1
show all 16 linesReturn Occupancy Only
Requires Presence add-on
This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
You can return only the occupancy
information for a single channel by specifying the channel and setting UUIDs
to False
:
envelope = pubnub.here_now() \
.channels("my_channel") \
.include_uuids(False) \
.include_state(False) \
.sync()
Example Response
{
total_channels: 1,
channels: [{
channel_name: "my_channel",
occupancy: 3,
occupants: []
}],
total_occupancy: 3
}
Here Now for Channel Groups
envelope = pubnub.here_now() \
.channel_groups(['cg1', 'cg2', 'cg3']) \
.include_uuids(True) \
.include_state(True) \
.sync()
Example Response
{
total_channels: 1,
channels: [
{
channel_name: "my_channel",
occupancy: 1,
occupants: [{
uuid: "143r34f34t34fq34q34q3",
state: None
}]
},
{
occupancy: 1,
occupants: [{
uuid: "123123234t234f34fq3dq",
show all 35 linesWhere Now
Requires Presence add-on
This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
You can obtain information about the current list of channels to which a UUID is subscribed to by calling the where_now()
function in your application.
Timeout events
If the app is killed/crashes and restarted (or the page containing the PubNub instance is refreshed on the browser) 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:
pubnub.where_now() \
.uuid(String)
Parameter | Type | Required | Description |
---|---|---|---|
uuid | String | Optional | uuid to get info on. |
Basic Usage
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
envelope = pubnub.where_now().sync()
Returns
The where_now()
operation returns an Envelope
which contains the following fields:
Field | Type | Description |
---|---|---|
result | PNWhereNowResult | A detailed object containing the result of the operation. |
status | PNStatus | A status object with additional information. |
PNWhereNowResult
Field | Type | Description |
---|---|---|
channels | List | The list of channels where the UUID is present. |
Other Examples
Obtain information about the current list of channels of some other UUID
- Builder Pattern
- Named Arguments
envelope = pubnub.where_now() \
.uuid('some-other-uuid') \
.sync()
envelope = pubnub.where_now(uuid='some-other-uuid').sync()
User State
Requires Presence add-on
This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
The state API is used to set/get key/value pairs specific to a subscriber uuid
.
State information is supplied as a JSON object of key/value pairs.
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
pubnub.set_state() \
.channels(String|List|Tuple) \
.channel_groups(String|List|Tuple) \
.state(Dictionary)
Parameter | Type | Required | Description |
---|---|---|---|
channels | String | List | Tuple | Optional | channels to set state . |
channel_groups | String | List | Tuple | Optional | channel groups to set state . |
state | Dictionary | Optional | state to set. |
Get State
pubnub.get_state() \
.channels(String|List|Tuple) \
.channel_groups(String|List|Tuple) \
.uuid(String)
Parameter | Type | Required | Description |
---|---|---|---|
channels | String | List | Tuple | Optional | channels to get state . |
channel_groups | String | List | Tuple | Optional | channel groups to get state . |
uuid | String | Optional | uuid to get state from. |
Basic Usage
Set State
- Builder Pattern
- Named Arguments
my_state = {
'age': 20
}
envelope = pubnub.set_state() \
.channels(['ch1', 'ch2', 'ch3']) \
.state(my_state) \
.sync()
envelope = pubnub.set_state(channels=['ch1', 'ch2', 'ch3'], state={'age': 20}).sync()
Get State
- Builder Pattern
- Named Arguments
envelope = pubnub.get_state() \
.channels(['ch1', 'ch2', 'ch3']) \
.uuid('such_uuid') \
.sync()
envelope = pubnub.get_state(channels=['ch1', 'ch2', 'ch3'], uuid='such_uuid').sync()
Returns
The set_state()
operation returns an Envelope
which contains the following fields:
Field | Type | Description |
---|---|---|
result | PNSetStateResult | A detailed object containing the result of the operation. |
status | PNStatus | A status object with additional information. |
PNSetStateResult
Field | Type | Description |
---|---|---|
state | Dictionary | Dictionary of UUIDs and the user states. |
The get_state()
operation returns an Envelope
which contains the following fields:
Field | Type | Description |
---|---|---|
result | PNGetStateResult | A detailed object containing the result of the operation. |
status | PNStatus | A status object with additional information. |
PNGetStateResult
Field | Type | Description |
---|---|---|
channels | Dictionary | Dictionary of channels and the user states. |
Other Examples
Set state for channels in channel group
- Builder Pattern
- Named Arguments
my_state = {
'age': 20
}
envelope = pubnub.set_state() \
.channel_groups(['gr1', 'gr2', 'gr3']) \
.state(my_state) \
.sync()
envelope = pubnub.set_state(channel_groups=['gr1', 'gr2', 'gr3'], state={'age': 20}).sync()
The above code would return the following response to the client:
{
first : "Robert",
last : "Plant",
age : 59,
region : "UK"
}