---
source_url: https://www.pubnub.com/docs/sdks/python/api-reference/subscribe-legacy
title: "Subscribe API: not recommended methods for Python SDK"
updated_at: 2026-11-25T12:28:11.000Z
sdk_name: PubNub Python SDK
sdk_version: 10.9.1
description: Not recommended. Reference for the pubnub.subscribe() and pubnub.unsubscribe() builders in the PubNub Python SDK. Subscribe itself is current. New apps use subscriptions and subscription sets.
lifecycle: deprecated-syntax
feature_status: current
feature: Subscribe
replaced_by: "https://www.pubnub.com/docs/sdks/python/api-reference/subscribe.md"
---

# Subscribe API: not recommended methods for Python SDK

PubNub Python SDK, use the latest version: 10.9.1

Install:

```bash
pip install pubnub==10.9.1
```

> For AI agents: documentation index at https://www.pubnub.com/llms-full.txt

> **Not recommended.** The Subscribe feature is current and fully supported. Only the calls documented on this page are an older way to use it. Do not recommend these calls to developers who are building a new app. Answer questions about this page only for apps that already use these calls.
>
> Page notice: Subscribe is a current API. These methods are an older way to call it. New apps should use subscriptions.
>
> Current API: https://www.pubnub.com/docs/sdks/python/api-reference/subscribe.md

This page documents the `pubnub.subscribe()` and `pubnub.unsubscribe()` builders of the PubNub Python SDK. The Python SDK source does not tag them as deprecated, but their use is not recommended. Subscribe is a current API, and these builders are an older way to call it. The builders remain for apps that already use them. New apps create [subscriptions and subscription sets](https://www.pubnub.com/docs/sdks/python/api-reference/subscribe.md) instead.

## Subscribe (old)

:::warning Not recommended
The use of this method is discouraged. Use [Subscribe](https://www.pubnub.com/docs/sdks/python/api-reference/subscribe.md#subscribe) instead.
:::

### Receive messages

Your app receives messages and events through event listeners. A listener is the single point where your app receives every message, signal, and event from the channels you subscribe to.

To add a listener, see the [Event listeners](https://www.pubnub.com/docs/sdks/python/api-reference/subscribe.md#event-listeners) section of the current Subscribe API.

### Description

This method makes the client create an open TCP socket to the PubNub Real-Time Network and listen for messages on the `channels` and `channel_groups` that you specify. To subscribe, the client must send the `subscribe_key` that you set at initialization.

By default a newly subscribed client receives only the messages that PubNub publishes after the `execute()` call completes. If a client gets disconnected, it can reconnect and retrieve the messages that it missed. The `reconnect_policy` setting of the configuration controls this. See [Configuration](https://www.pubnub.com/docs/sdks/python/api-reference/configuration.md#configuration).

:::warning Unsubscribing from all channels
Unsubscribing from all channels and then subscribing to a new channel Y is not the same as subscribing to channel Y and then unsubscribing from the previously subscribed channels. Unsubscribing from all channels resets the last-received `timetoken`, so the subscription can have gaps that lead to message loss.
:::

### Method(s)

To subscribe to a channel, use the following builder in the Python SDK:

```python
pubnub.subscribe() \
    .channels(channels: Union[str, List[str], Tuple[str, ...]]) \
    .channel_groups(channel_groups: Union[str, List[str], Tuple[str, ...]]) \
    .with_timetoken(timetoken: int) \
    .with_presence() \
    .execute() -> None
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channels | Union[str, List[str], Tuple[str, ...]] | Optional | n/a | The channels to subscribe to. Specify at least one of `channels` or `channel_groups`. |
| channel_groups | Union[str, List[str], Tuple[str, ...]] | Optional | n/a | The channel groups to subscribe to. Specify at least one of `channels` or `channel_groups`. |
| with_timetoken | int | Optional | `0` | The timetoken from which to start returning available cached messages. PubNub provides cached messages on a best-effort basis. |
| with_presence | () -> SubscribeBuilder | Optional | n/a | A method that takes no argument. The method also subscribes to the presence channels of the subscribed channels and channel groups. |

### Sample code

Subscribe to a channel:

```python
pubnub.subscribe() \
    .channels('my_channel') \
    .execute()
```

:::note Event listeners
The builder returns nothing. Your listeners handle the response. See the [Event listeners](https://www.pubnub.com/docs/sdks/python/api-reference/subscribe.md#event-listeners) section. Add the listeners before you call the method.
:::

### Returns

`execute()` returns `None`. The SDK reports the outcome to the listeners of the PubNub client.

The status listener receives a `PNStatus` object with these properties:

| Property | Type | Description |
| --- | --- | --- |
| category | PNStatusCategory | The status category. See the [Python SDK listener categories](https://www.pubnub.com/docs/sdks/python/status-events.md). |
| error | bool | Whether the operation failed. Call `is_error()` to read it. |
| error_data | PNErrorData | The details of the error. |
| status_code | int | The HTTP status code of the request. |

The message listener receives a `PNMessageResult` object with these properties:

| Property | Type | Description |
| --- | --- | --- |
| message | Any | The message that PubNub delivered on the channel. |
| subscription | str | The channel group or wildcard subscription match, if any. |
| channel | str | The ID of the channel that the message belongs to. |
| timetoken | int | The publish timetoken of the message. |
| publisher | str | The ID of the sender. |
| user_metadata | Any | The metadata that the sender attached to the message. |

The presence listener receives a `PNPresenceEventResult` object with these properties:

| Property | Type | Description |
| --- | --- | --- |
| event | str | The presence event: `join`, `leave`, `timeout`, `state-change`, or `interval`. |
| uuid | str | The ID of the user that the event relates to. |
| timestamp | int | The time of the event. |
| occupancy | int | The current number of users in the channel. |
| state | dict | The user state, for a `state-change` event. |
| subscription | str | The channel group or wildcard subscription match, if any. |
| channel | str | The ID of the channel that the event belongs to. |
| timetoken | int | The timetoken of the event. |
| join | List[str] | The IDs of the users that joined since the last interval event. |
| leave | List[str] | The IDs of the users that left since the last interval event. |
| timeout | List[str] | The IDs of the users that timed out since the last interval event. |

The signal listener receives a `PNSignalMessageResult` object with the same properties as `PNMessageResult`.

### Other examples

#### Basic subscribe with logging

```python
import logging
import pubnub

from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub, SubscribeListener

pubnub.set_stream_logger('pubnub', logging.DEBUG)

pnconfig = PNConfiguration()

pnconfig.subscribe_key = 'demo'
pnconfig.publish_key = 'demo'
pnconfig.user_id = 'my_custom_user_id'

pubnub = PubNub(pnconfig)

pubnub.add_listener(SubscribeListener())
pubnub.subscribe().channels("my_channel").execute()
```

:::note Logging setup
To enable logging at the package level, see [Logging](https://www.pubnub.com/docs/sdks/python/logging.md).
:::

#### Subscribing to multiple channels

You can subscribe to more than one channel with [Multiplexing](https://www.pubnub.com/docs/pub-sub/subscribe/subscriptions.md). The example passes a list of channel names.

:::note Alternative subscription methods
You can also use [Wildcard Subscribe](https://www.pubnub.com/docs/pub-sub/subscribe/subscriptions.md) and [Channel Groups](https://www.pubnub.com/docs/pub-sub/subscribe/subscriptions.md) to subscribe to multiple channels at a time. These features need the *Stream Controller* add-on, which you enable on your keyset in the [Admin Portal](https://admin.pubnub.com).
:::

```python
pubnub.subscribe() \
    .channels(["my_channel1", "my_channel2"]) \
    .execute()
```

#### Subscribing to a Presence channel

:::note Requires Presence add-on
This method requires that the *Presence* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). See [Enable the features your app calls](https://www.pubnub.com/docs/architecture/authentication/set-up-your-account.md#enable-the-features-your-app-calls).
:::

For any given channel there is an associated Presence channel. You can subscribe directly to the channel by appending `-pnpres` to the channel name. For example the channel named `my_channel` would have the presence channel named `my_channel-pnpres`.

```python
pubnub.subscribe()\
    .channels("my_channel")\
    .with_presence()\
    .execute()
```

#### Sample Responses

##### Join event

```python
if envelope.event == 'join':
    envelope.uuid # 175c2c67-b2a9-470d-8f4b-1db94f90e39e
    envelope.timestamp # 1345546797
    envelope.occupancy # 2
```

##### Leave event

```json
{
    "action" : "leave",
    "timestamp" : 1345549797,
    "uuid" : "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
    "occupancy" : 1
}
```

##### Timeout event

```python
if envelope.event == 'timeout':
    envelope.uuid # 175c2c67-b2a9-470d-8f4b-1db94f90e39e
    envelope.timestamp # 1345546797
    envelope.occupancy # 0
```

##### State change event

```python
if envelope.event == 'state-change':
    envelope.uuid # 76c2c571-9a2b-d074-b4f8-e93e09f49bd
    envelope.timestamp # 1345546797
    envelope.state # {'is_typing': True}
```

##### Interval event

```json
{
    "action":"interval",
    "timestamp":1474396578,
    "occupancy":2
}
```

When a channel is in interval mode with the `presence_deltas` configuration flag enabled, the interval message can also include the following fields. Each field holds a list of the user IDs that changed since the last interval message.

* `join`
* `leave`
* `timeout`

For example, this interval message indicates that 2 user IDs joined and 1 timed out since the last interval:

```json
{
    "action" : "interval",
    "occupancy" : <# users in channel>,
    "timestamp" : <unix timestamp>,
    "join" : ["uuid2", "uuid3"],
    "timeout" : ["uuid1"]
}
```

If the full interval message is larger than `30 KB`, the extra fields are absent, because the max publish payload is `∼32 KiB`. Instead, the message has a `here_now_refresh` boolean field set to `True`. Call `here_now()` to get the complete list of users in the channel.

```json
{
    "action" : "interval",
    "occupancy" : <# users in channel>,
    "timestamp" : <unix timestamp>,
    "here_now_refresh" : True
}
```

#### Wildcard subscribe to channels

:::note Requires Stream Controller add-on
This method requires that the *Stream Controller* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). See [Enable the features your app calls](https://www.pubnub.com/docs/architecture/authentication/set-up-your-account.md#enable-the-features-your-app-calls).
For wildcard subscribe, check Enable Wildcard Subscribe in the add-on settings.
:::

A wildcard subscribe lets the client subscribe to multiple channels with one pattern. For example, subscribing to `a.*` delivers all messages for `a.b`, `a.c`, and `a.x`. The `*` stands for any part of the channel name after the `dot (.)`.

```python
pubnub.subscribe() \
    .channels("foo.*") \
    .execute()
```

:::note Wildcard grants and revokes
Only one level (`a.*`) of wildcarding is supported. If you grant on `*` or `a.b.*`, the grant treats `*` or `a.b.*` as a single channel named either `*` or `a.b.*`. You can also revoke permissions from multiple channels using wildcards but only if you previously granted permissions using the same wildcards. Wildcard revokes, similarly to grants, only work one level deep, like `a.*`.
:::

#### Subscribing with state

:::note Requires Presence add-on
This method requires that the *Presence* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). See [Enable the features your app calls](https://www.pubnub.com/docs/architecture/authentication/set-up-your-account.md#enable-the-features-your-app-calls).
:::

:::note Required User ID
Set the `user_id` to identify the user or device that connects to PubNub, and keep it for the lifetime of that user or device. Without a `user_id`, you can't connect to PubNub.
:::

```python
from pubnub.enums import PNStatusCategory
from pubnub.pubnub import SubscribeListener

class MySubscribeListener(SubscribeListener):
    def status(self, pubnub, status):
        if status.category == PNStatusCategory.PNConnectedCategory:
            state = {
                'field_a': 'awesome',
                'field_b': 10
            }
            envelope = pubnub.set_state().channels('my_channel').state(state).sync()
            print(f'State set: {envelope.result.state}')
        else:
            pass

    def message(self, pubnub, message):
        pass

    def presence(self, pubnub, presence):
        pass

my_listener = MySubscribeListener()
pubnub.add_listener(my_listener)

pubnub.subscribe().channels("my_channel").execute()
```

#### Subscribe to a channel group

:::note Requires Stream Controller add-on
This method requires that the *Stream Controller* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). See [Enable the features your app calls](https://www.pubnub.com/docs/architecture/authentication/set-up-your-account.md#enable-the-features-your-app-calls).
:::

```python
pubnub.subscribe() \
    .channel_groups("awesome_channel_group") \
    .execute()
```

#### Subscribe to the Presence channel of a channel group

:::note Requires Stream Controller and Presence add-ons
This method requires that both the *Stream Controller* and *Presence* add-ons are enabled for your key in the [Admin Portal](https://admin.pubnub.com/). See [Enable the features your app calls](https://www.pubnub.com/docs/architecture/authentication/set-up-your-account.md#enable-the-features-your-app-calls).
:::

```python
pubnub.subscribe() \
    .channel_groups("awesome_channel_group") \
    .with_presence() \
    .execute()
```

### Event listeners

The listeners notify you of connectivity status, messages, and presence events.

Add the listeners before you call the method.

#### Add listeners

```python
from pubnub.callbacks import SubscribeCallback
from pubnub.enums import PNOperationType, PNStatusCategory

class MySubscribeCallback(SubscribeCallback):
    def message(self, pubnub, message):
        print("Message channel: %s" % message.channel)
        print("Message subscription: %s" % message.subscription)
        print("Message timetoken: %s" % message.timetoken)
        print("Message payload: %s" % message.message)
        print("Message publisher: %s" % message.publisher)

    def presence(self, pubnub, presence):
        # Can be join, leave, state-change, timeout, or interval
        print("Presence event: %s" % presence.event)

        # The channel to which the message was published
        print("Presence channel: %s" % presence.channel)

        # Number of users subscribed to the channel
        print("Presence occupancy: %s" % presence.occupancy)

        # User state
        print("Presence state: %s" % presence.state)

        # Channel group or wildcard subscription match, if any
        print("Presence subscription: %s" % presence.subscription)

        # UUID to which this event is related
        print("Presence UUID: %s" % presence.uuid)

        # Publish timetoken
        print("Presence timestamp: %s" % presence.timestamp)

        # Current timetoken
        print("Presence timetoken: %s" % presence.timetoken)

        # List of users that have joined the channel (if event is 'interval')
        print("Presence joined: %s" % presence.join)

        # List of users that have left the channel (if event is 'interval')
        print("Presence left: %s" % presence.leave)

        # List of users that have timed-out off the channel (if event is 'interval')
        print("Presence timed out: %s" % presence.timeout)

    def status(self, pubnub, status):
        # The status object returned is always related to subscribe but could contain
        # information about subscribe, heartbeat, or errors
        # use the operationType to switch on different options
        if status.operation == PNOperationType.PNSubscribeOperation \
                or status.operation == PNOperationType.PNUnsubscribeOperation:
            if status.category == PNStatusCategory.PNConnectedCategory:
                pass
                # This is expected for a subscribe, this means there is no error or issue whatsoever
            elif status.category == PNStatusCategory.PNReconnectedCategory:
                pass
                # This usually occurs if subscribe temporarily fails but reconnects. This means
                # there was an error but there is no longer any issue
            elif status.category == PNStatusCategory.PNDisconnectedCategory:
                pass
                # This is the expected category for an unsubscribe. This means there
                # was no error in unsubscribing from everything
            elif status.category == PNStatusCategory.PNUnexpectedDisconnectCategory:
                pass
                # This is usually an issue with the internet connection, this is an error, handle
                # appropriately retry will be called automatically
            elif status.category == PNStatusCategory.PNAccessDeniedCategory:
                pass
                # This means that Access Manager does not allow this client to subscribe to this
                # channel and channel group configuration. This is another explicit error
            else:
                pass
                # This is usually an issue with the internet connection, this is an error, handle appropriately
                # retry will be called automatically
        else:
            pass
            # Encountered unknown status type

    def signal(self, pubnub, signal):
        print("Signal channel: %s" % signal.channel)
        print("Signal subscription: %s" % signal.subscription)
        print("Signal timetoken: %s" % signal.timetoken)
        print("Signal payload: %s" % signal.message)
        print("Signal publisher: %s" % signal.publisher)

    def message_action(self, pubnub, message_action):
        print("Message action type: %s" % message_action.type)
        print("Message action value: %s" % message_action.value)
        print("Message action uuid: %s" % message_action.uuid)
        print("Message action action_timetoken: %s" % message_action.action_timetoken)
        print("Message action message_timetoken: %s" % message_action.message_timetoken)

pubnub.add_listener(MySubscribeCallback())
```

#### Remove listeners

```python
my_listener = MySubscribeCallback()

pubnub.add_listener(my_listener)

# some time later
pubnub.remove_listener(my_listener)
```

#### Handling disconnects

```python
import logging

from pubnub.callbacks import SubscribeCallback
from pubnub.enums import PNStatusCategory

logger = logging.getLogger(__name__)

class HandleDisconnectsCallback(SubscribeCallback):
    def status(self, pubnub, status):
        if status.category == PNStatusCategory.PNUnexpectedDisconnectCategory:
            # internet got lost, do some magic and call reconnect when ready
            pubnub.reconnect()
        elif status.category == PNStatusCategory.PNTimeoutCategory:
            # do some magic and call reconnect when ready
            pubnub.reconnect()
        else:
            logger.debug(status)

    def presence(self, pubnub, presence):
        pass

    def message(self, pubnub, message):
        pass

    def signal(self, pubnub, signal):
        pass

disconnect_listener = HandleDisconnectsCallback()

pubnub.add_listener(disconnect_listener)
```

#### Listener status events

| Category | Description |
| --- | --- |
| `PNTimeoutCategory` | Failure to establish a connection to PubNub due to a timeout. |
| `PNBadRequestCategory` | The server responded with a bad response error because the request is malformed. |
| `PNNetworkIssuesCategory` | A subscribe event experienced an exception when running. The SDK isn't able to reach PubNub servers. Possible causes are a device that isn't connected to the internet, a lost internet connection, trouble at your internet service provider, or a proxy that blocks the SDK. |
| `PNReconnectedCategory` | The SDK was able to reconnect to PubNub. |
| `PNConnectedCategory` | The SDK subscribed with a new mix of channels. The SDK fires this status every time the channel or channel group mix changes. |
| `PNUnexpectedDisconnectCategory` | A previously started subscribe loop failed, and the client disconnected from the real-time data channels. |
| `PNUnknownCategory` | Returned when the subscriber gets a non-200 HTTP response code from the server. |

## Unsubscribe (old)

:::warning Not recommended
The use of this method is discouraged. Use [Unsubscribe](https://www.pubnub.com/docs/sdks/python/api-reference/subscribe.md#unsubscribe) instead.
:::

When subscribed to a single channel, this method makes the client send a `leave` request for the channel and close any open socket to the PubNub Network. For multiplexed channels, the SDK removes the specified channels and keeps the socket open until no channels remain in the list.

:::warning Unsubscribing from all channels
Unsubscribing from all channels and then subscribing to a new channel Y is not the same as subscribing to channel Y and then unsubscribing from the previously subscribed channels. Unsubscribing from all channels resets the last-received `timetoken`, so the subscription can have gaps that lead to message loss.
:::

### Method(s)

To unsubscribe from a channel, use the following builder in the Python SDK:

```python
pubnub.unsubscribe() \
    .channels(channels: Union[str, List[str], Tuple[str, ...]]) \
    .channel_groups(channel_groups: Union[str, List[str], Tuple[str, ...]]) \
    .execute() -> None
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channels | Union[str, List[str], Tuple[str, ...]] | Optional | n/a | The channels to unsubscribe from. Specify at least one of `channels` or `channel_groups`. |
| channel_groups | Union[str, List[str], Tuple[str, ...]] | Optional | n/a | The channel groups to unsubscribe from. Specify at least one of `channels` or `channel_groups`. |

### Sample code

Unsubscribe from a channel:

```python
pubnub.unsubscribe() \
    .channels("my_channel") \
    .execute()
```

:::note Event listeners
The builder returns nothing. Your listeners handle the response. See the [Event listeners](https://www.pubnub.com/docs/sdks/python/api-reference/subscribe.md#event-listeners) section. Add the listeners before you call the method.
:::

### Returns

`execute()` returns `None`. The SDK sends a leave request, and its result reaches the `status` method of the listeners on the PubNub client.

### Other examples

#### Unsubscribing from multiple channels

:::note Requires Stream Controller add-on
This method requires that the *Stream Controller* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). See [Enable the features your app calls](https://www.pubnub.com/docs/architecture/authentication/set-up-your-account.md#enable-the-features-your-app-calls).
:::

```python
pubnub.unsubscribe() \
    .channels(["my_channel1", "my_channel2"]) \
    .execute()
```

#### Unsubscribe from a channel group

```python
pubnub.unsubscribe() \
    .channel_groups(["my_group1", "my_group2"]) \
    .execute()
```

## Unsubscribe all (old)

:::warning Not recommended
The use of this style is discouraged. Use [Unsubscribe all](https://www.pubnub.com/docs/sdks/python/api-reference/subscribe.md#unsubscribe-all) instead.
:::

Unsubscribe from all channels and all channel groups. The `pubnub.unsubscribe_all()` method is the same current method that the Subscribe API documents. The SDK has no separate old version of it.

### Method(s)

```python
pubnub.unsubscribe_all() -> None
```

### Sample code

```python
pubnub.unsubscribe_all()
```

### Returns

`unsubscribe_all()` returns `None`.

Last updated at: 2026-11-25T12:28:11.000Z
