---
source_url: https://www.pubnub.com/docs/sdks/asyncio/api-reference/presence
title: Presence API for Python-Asyncio SDK
updated_at: 2026-05-27T17:01:39.718Z
sdk_name: PubNub Python Asyncio SDK
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# Presence API for Python-Asyncio SDK

PubNub Python Asyncio SDK

Install:

```bash
pip install pubnub
```

Presence lets you track which users and devices are online and store custom state. 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](https://www.pubnub.com/docs/general/presence/overview).

## Here now

:::warning Requires Presence
This method requires that the Presence add-on is [enabled](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) for your key in the [Admin Portal](https://admin.pubnub.com/). For information on how to receive presence events and what those events are, refer to [Presence Events](https://www.pubnub.com/docs/general/presence/presence-events#subscribe-to-presence-channel).
:::

Use `here_now()` to get who is on a channel (UUIDs) and how many users are subscribed (occupancy).

:::note Cache
This method has a 3-second response cache time.
:::

### Method(s)

Use the following method in the Python SDK:

```python
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 | Optional | `None` | Channels to query for details. |
| channel_groups | String | Optional | `None` | Channel groups to query for details. Wildcards aren't supported. |
| include_state | Boolean | Optional | `False` | Whether the response should include the presence state for users on channels and channel groups. |
| include_uuids | Boolean | Optional | `True` | Whether the response should include the UUIDs of connected clients. |

### Sample code

#### Get a list of UUIDs subscribed to channel

:::tip 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.
:::

```python
import asyncio
import os
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub_asyncio import PubNubAsyncio
from pubnub.exceptions import PubNubException

async def get_here_now(pubnub: PubNubAsyncio):
    try:
        # Get a list of UUIDs subscribed to channels
        envelope = await pubnub.here_now() \
            .channels(['cool_channel1', 'cool_channel2']) \
            .include_uuids(True) \
            .future()

        if envelope.status.is_error():
            print("Error retrieving here_now data")
            return

        for channel_data in envelope.result.channels:
            print("---")
            print(f"Channel: {channel_data.channel_name}")
            print(f"Occupancy: {channel_data.occupancy}")
            for occupant in channel_data.occupants:
                print(f"UUID: {occupant.uuid}, State: {occupant.state}")

    except PubNubException as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)

    # Configuration for PubNub instance
    pn_config = PNConfiguration()
    pn_config.subscribe_key = os.getenv('SUBSCRIBE_KEY', 'demo')
    pn_config.user_id = "my_custom_user_id"

    pubnub = PubNubAsyncio(pn_config)

    try:
        loop.run_until_complete(get_here_now(pubnub))
    finally:
        loop.run_until_complete(pubnub.stop())
        loop.close()
```

### Returns

The `here_now()` operation returns a `PNHereNowResult` with the following fields:

| Field | Type | Description |
| --- | --- | --- |
| `total_channels` | Int | Total number of channels. |
| `total_occupancy` | Int | Total occupancy count across all channels. |
| `channels` | Dictionary | Dictionary mapping channel names (String) to `PNHereNowChannelData` objects. |

#### PNHereNowChannelData

| Field | Type | Description |
| --- | --- | --- |
| `channel_name` | String | Channel name. |
| `occupancy` | Int | Occupancy of the channel. |
| `occupants` | List | List of `PNHereNowOccupantData` objects. |

#### PNHereNowOccupantData

| Field | Type | Description |
| --- | --- | --- |
| `uuid` | String | UUID of the user. |
| `state` | Dictionary | Presence state for the user. |

#### Returning state

:::warning Requires Presence
This method requires that the Presence add-on is [enabled](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) for your key in the [Admin Portal](https://admin.pubnub.com/). For information on how to receive presence events and what those events are, refer to [Presence Events](https://www.pubnub.com/docs/general/presence/presence-events#subscribe-to-presence-channel).
:::

```python
envelope = await pubnub.here_now() \
    .channels("my_channel") \
    .include_uuids(True) \
    .include_state(True) \
    .future()
```

##### Example response

```python
{
    total_channels: 1,
    channels: [{
        channel_name: "my_channel",
        occupancy: 1,
        occupants: [{
            uuid: "myUuid1"
            state: {
                "abcd": {
                    "age": 15
                }
            }
        }]
    }],
    total_occupancy: 1
}
```

#### Return occupancy only

:::warning Requires Presence
This method requires that the Presence add-on is [enabled](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) for your key in the [Admin Portal](https://admin.pubnub.com/). For information on how to receive presence events and what those events are, refer to [Presence Events](https://www.pubnub.com/docs/general/presence/presence-events#subscribe-to-presence-channel).
:::

To return only `occupancy` for a channel, set `include_uuids` and `include_state` to `False`:

```python
envelope = await pubnub.here_now() \
    .channels("my_channel") \
    .include_uuids(False) \
    .include_state(False) \
    .future()
```

##### Example response

```python
{
    total_channels: 1,
    channels: [{
        channel_name: "my_channel",
        occupancy: 3,
        occupants: []
    }],
    total_occupancy: 3
}
```

#### Here now for channel groups

```python
envelope = await pubnub.here_now() \
    .channel_groups(['cg1', 'cg2', 'cg3']) \
    .include_uuids(True) \
    .include_state(True) \
    .future()
```

##### Example response

```python
{
    total_channels: 1,
    channels: [
        {
            channel_name: "my_channel",
            occupancy: 1,
            occupants: [{
                uuid: "143r34f34t34fq34q34q3",
                state: None
            }]
        },
        {
            occupancy: 1,
            occupants: [{
                uuid: "123123234t234f34fq3dq",
                state: None
            }]
        },
        {
            occupancy: 1,
            occupants: [{
                uuid: "23f34d3f4rq34r34rq23q",
                state: None
            }]
        },
        {
            occupancy: 1,
            occupants: [{
                uuid: "w34tcw45t45tcw435tww3",
                state: None
            }]
        }
    ],
    total_occupancy: 4
}
```

## Where now

:::warning Requires Presence
This method requires that the Presence add-on is [enabled](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) for your key in the [Admin Portal](https://admin.pubnub.com/). For information on how to receive presence events and what those events are, refer to [Presence Events](https://www.pubnub.com/docs/general/presence/presence-events#subscribe-to-presence-channel).
:::

Use `where_now()` to get the list of channels a UUID is subscribed to.

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

### Method(s)

Use the following method in the Python SDK:

```python
pubnub.where_now() \
    .uuid(String)
```

| Parameter | Description |
| --- | --- |
| `uuid`Type: String | `uuid` to get info on. |

### Sample code

```python
envelope = await pubnub.where_now() \
    .future()
```

### Returns

The `where_now()` operation returns a `PNWhereNowResult` which contains the following fields:

| 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

```python
envelope = await pubnub.where_now() \
    .uuid('some-other-uuid') \
    .future()
```

## User state

:::warning Requires Presence
This method requires that the Presence add-on is [enabled](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) for your key in the [Admin Portal](https://admin.pubnub.com/). For information on how to receive presence events and what those events are, refer to [Presence Events](https://www.pubnub.com/docs/general/presence/presence-events#subscribe-to-presence-channel).
:::

Clients can set a dynamic custom state (for example, score, game state, or location) for their users on one or more channels. The state exists while the user stays subscribed.

The state isn't persisted. When the client disconnects, the state is lost. For more information, refer to [Presence State](https://www.pubnub.com/docs/general/presence/presence-state).

:::note Presence state format
Presence state must be a `dict`. When calling `set_state`, supply an initialized, serializable `dict`.
:::

### Method(s)

#### Set state

```python
pubnub.set_state() \
    .channels(String|List|Tuple) \
    .channel_groups(String|List|Tuple) \
    .state(Dictionary)
```

| Parameter | Description |
| --- | --- |
| `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

```python
pubnub.get_state() \
    .channels(String|List|Tuple) \
    .channel_groups(String|List|Tuple) \
    .uuid(String)
```

| Parameter | Description |
| --- | --- |
| `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

```python
my_state = {
    'age': 20
}
envelope = await pubnub.set_state() \
    .channels(['ch1', 'ch2', 'ch3']) \
    .state(my_state) \
    .future()
```

#### Get state

```python
envelope = await pubnub.get_state() \
    .channels(['ch1', 'ch2', 'ch3']) \
    .uuid('such_uuid') \
    .future()
```

### Returns

#### The set_state() operation returns a PNSetStateResult which contains the following fields

| Field | Type | Description |
| --- | --- | --- |
| `state` | Dictionary | Dictionary of UUIDs and the user states. |

#### The get_state() operation returns a PNGetStateResult which contains the following fields

| Field | Type | Description |
| --- | --- | --- |
| `channels` | Dictionary | Dictionary of `channels` and the user states. |

### Other examples

#### Set state for channels in channel group

```python
my_state = {
    'age': 20
}
envelope = await pubnub.set_state().channel_groups(['gr1', 'gr2', 'gr3']).state(my_state).future()
```

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

```python
{
    first  : "Robert",
    last   : "Plant",
    age    : 59,
    region : "UK"
}
```