Subscribe API: not recommended methods for Python SDK
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 instead.
Subscribe (old)
Not recommended
The use of this method is discouraged. Use 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 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.
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:
1pubnub.subscribe() \
2 .channels(channels: Union[str, List[str], Tuple[str, ...]]) \
3 .channel_groups(channel_groups: Union[str, List[str], Tuple[str, ...]]) \
4 .with_timetoken(timetoken: int) \
5 .with_presence() \
6 .execute() -> None
channels#- The channels to subscribe to. Specify at least one of
channelsorchannel_groups. channel_groups#- The channel groups to subscribe to. Specify at least one of
channelsorchannel_groups. with_timetoken#- The timetoken from which to start returning available cached messages. PubNub provides cached messages on a best-effort basis.
with_presence#- 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:
1pubnub.subscribe() \
2 .channels('my_channel') \
3 .execute()
Event listeners
The builder returns nothing. Your listeners handle the response. See the 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:
category#- The status category. See the Python SDK listener categories.
error#- Whether the operation failed. Call
is_error()to read it. error_data#- The details of the error.
status_code#- The HTTP status code of the request.
The message listener receives a PNMessageResult object with these properties:
message#- The message that PubNub delivered on the channel.
subscription#- The channel group or wildcard subscription match, if any.
channel#- The ID of the channel that the message belongs to.
timetoken#- The publish timetoken of the message.
publisher#- The ID of the sender.
user_metadata#- The metadata that the sender attached to the message.
The presence listener receives a PNPresenceEventResult object with these properties:
event#- The presence event:
join,leave,timeout,state-change, orinterval. uuid#- The ID of the user that the event relates to.
timestamp#- The time of the event.
occupancy#- The current number of users in the channel.
state#- The user state, for a
state-changeevent. subscription#- The channel group or wildcard subscription match, if any.
channel#- The ID of the channel that the event belongs to.
timetoken#- The timetoken of the event.
join#- The IDs of the users that joined since the last interval event.
leave#- The IDs of the users that left since the last interval event.
timeout#- 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
1import logging
2import pubnub
3
4from pubnub.pnconfiguration import PNConfiguration
5from pubnub.pubnub import PubNub, SubscribeListener
6
7pubnub.set_stream_logger('pubnub', logging.DEBUG)
8
9pnconfig = PNConfiguration()
10
11pnconfig.subscribe_key = 'demo'
12pnconfig.publish_key = 'demo'
13pnconfig.user_id = 'my_custom_user_id'
14
15pubnub = PubNub(pnconfig)
show all 18 linesLogging setup
To enable logging at the package level, see Logging.
Subscribing to multiple channels
You can subscribe to more than one channel with Multiplexing. The example passes a list of channel names.
Alternative subscription methods
You can also use Wildcard Subscribe and Channel Groups 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.
1pubnub.subscribe() \
2 .channels(["my_channel1", "my_channel2"]) \
3 .execute()
Subscribing to a Presence channel
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.
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.
1pubnub.subscribe()\
2 .channels("my_channel")\
3 .with_presence()\
4 .execute()
Sample Responses
Join event
1if envelope.event == 'join':
2 envelope.uuid # 175c2c67-b2a9-470d-8f4b-1db94f90e39e
3 envelope.timestamp # 1345546797
4 envelope.occupancy # 2
Leave event
1{
2 "action" : "leave",
3 "timestamp" : 1345549797,
4 "uuid" : "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
5 "occupancy" : 1
6}
Timeout event
1if envelope.event == 'timeout':
2 envelope.uuid # 175c2c67-b2a9-470d-8f4b-1db94f90e39e
3 envelope.timestamp # 1345546797
4 envelope.occupancy # 0
State change event
1if envelope.event == 'state-change':
2 envelope.uuid # 76c2c571-9a2b-d074-b4f8-e93e09f49bd
3 envelope.timestamp # 1345546797
4 envelope.state # {'is_typing': True}
Interval event
1{
2 "action":"interval",
3 "timestamp":1474396578,
4 "occupancy":2
5}
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.
joinleavetimeout
For example, this interval message indicates that 2 user IDs joined and 1 timed out since the last interval:
1{
2 "action" : "interval",
3 "occupancy" : <# users in channel>,
4 "timestamp" : <unix timestamp>,
5 "join" : ["uuid2", "uuid3"],
6 "timeout" : ["uuid1"]
7}
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.
1{
2 "action" : "interval",
3 "occupancy" : <# users in channel>,
4 "timestamp" : <unix timestamp>,
5 "here_now_refresh" : True
6}
Wildcard subscribe to channels
Requires Stream Controller add-on
This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. See 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 (.).
1pubnub.subscribe() \
2 .channels("foo.*") \
3 .execute()
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
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.
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.
1from pubnub.enums import PNStatusCategory
2from pubnub.pubnub import SubscribeListener
3
4class MySubscribeListener(SubscribeListener):
5 def status(self, pubnub, status):
6 if status.category == PNStatusCategory.PNConnectedCategory:
7 state = {
8 'field_a': 'awesome',
9 'field_b': 10
10 }
11 envelope = pubnub.set_state().channels('my_channel').state(state).sync()
12 print(f'State set: {envelope.result.state}')
13 else:
14 pass
15
show all 25 linesSubscribe to a channel group
Requires Stream Controller add-on
This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. See Enable the features your app calls.
1pubnub.subscribe() \
2 .channel_groups("awesome_channel_group") \
3 .execute()
Subscribe to the Presence channel of a channel group
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. See Enable the features your app calls.
1pubnub.subscribe() \
2 .channel_groups("awesome_channel_group") \
3 .with_presence() \
4 .execute()
Event listeners
The listeners notify you of connectivity status, messages, and presence events.
Add the listeners before you call the method.
Add listeners
1from pubnub.callbacks import SubscribeCallback
2from pubnub.enums import PNOperationType, PNStatusCategory
3
4class MySubscribeCallback(SubscribeCallback):
5 def message(self, pubnub, message):
6 print("Message channel: %s" % message.channel)
7 print("Message subscription: %s" % message.subscription)
8 print("Message timetoken: %s" % message.timetoken)
9 print("Message payload: %s" % message.message)
10 print("Message publisher: %s" % message.publisher)
11
12 def presence(self, pubnub, presence):
13 # Can be join, leave, state-change, timeout, or interval
14 print("Presence event: %s" % presence.event)
15
show all 93 linesRemove listeners
1my_listener = MySubscribeCallback()
2
3pubnub.add_listener(my_listener)
4
5# some time later
6pubnub.remove_listener(my_listener)
Handling disconnects
1import logging
2
3from pubnub.callbacks import SubscribeCallback
4from pubnub.enums import PNStatusCategory
5
6logger = logging.getLogger(__name__)
7
8class HandleDisconnectsCallback(SubscribeCallback):
9 def status(self, pubnub, status):
10 if status.category == PNStatusCategory.PNUnexpectedDisconnectCategory:
11 # internet got lost, do some magic and call reconnect when ready
12 pubnub.reconnect()
13 elif status.category == PNStatusCategory.PNTimeoutCategory:
14 # do some magic and call reconnect when ready
15 pubnub.reconnect()
show all 30 linesListener 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)
Not recommended
The use of this method is discouraged. Use 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.
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:
1pubnub.unsubscribe() \
2 .channels(channels: Union[str, List[str], Tuple[str, ...]]) \
3 .channel_groups(channel_groups: Union[str, List[str], Tuple[str, ...]]) \
4 .execute() -> None
Sample code
Unsubscribe from a channel:
1pubnub.unsubscribe() \
2 .channels("my_channel") \
3 .execute()
Event listeners
The builder returns nothing. Your listeners handle the response. See the 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
Requires Stream Controller add-on
This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. See Enable the features your app calls.
1pubnub.unsubscribe() \
2 .channels(["my_channel1", "my_channel2"]) \
3 .execute()
Unsubscribe from a channel group
1pubnub.unsubscribe() \
2 .channel_groups(["my_group1", "my_group2"]) \
3 .execute()
Unsubscribe all (old)
Not recommended
The use of this style is discouraged. Use 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)
1pubnub.unsubscribe_all() -> None
Sample code
1pubnub.unsubscribe_all()
Returns
unsubscribe_all() returns None.