Publish/Subscribe API for Python SDK
PubNub delivers messages worldwide in less than 30 ms. Send a message to one recipient or broadcast to thousands of subscribers.
For higher-level conceptual details on publishing and subscribing, refer to Connection Management and to Publish Messages.
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)
Publish
publish()
sends a message to all channel subscribers. PubNub replicates the message across its points of presence and delivers it to all subscribed clients on that channel.
ObjectNode
The new Jackson parser does not recognize JSONObject. Use ObjectNode instead.
- Prerequisites and limitations
- Security
- Message data
- Size
- Publish rate
- Custom message type
- Best practices
- You must initialize PubNub with the
publishKey
. - You don't have to be subscribed to a channel to publish to it.
- You cannot publish to multiple channels simultaneously.
Secure messages with Transport Layer Security (TLS) or Secure Sockets Layer (SSL) by setting ssl
to true
during initialization. You can also encrypt messages.
The message can contain any JavaScript Object Notation (JSON)-serializable data (objects, arrays, integers, strings). Avoid special classes or functions. Strings can include any UTF‑8 characters.
Don't JSON serialize
You should not JSON serialize the message
and meta
parameters when sending signals, messages, or files as the serialization is automatic. Pass the full object as the message/meta payload and let PubNub handle everything.
The maximum message size is 32 KiB. This includes the escaped character count and the channel name. Aim for under 1,800 bytes for optimal performance.
If your message exceeds the limit, you'll receive a Message Too Large
error. To learn more or calculate payload size, see Message size limits.
You can publish as fast as bandwidth allows. There is a soft throughput limit because messages may drop if subscribers can't keep up.
For example, publishing 200 messages at once may cause the first 100 to drop if a subscriber hasn't received any yet. The in-memory queue stores only 100 messages.
You can optionally provide the custom_message_type
parameter to add your business-specific label or category to the message, for example text
, action
, or poll
.
- Publish to a channel serially (not concurrently).
- Verify a success return code (for example,
[1,"Sent","136074940..."]
). - Publish the next message only after a success return code.
- On failure (
[0,"blah","<timetoken>"]
), retry. - Keep the in-memory queue under 100 messages to avoid drops.
- Throttle bursts to meet latency needs (for example, no more than 5 messages per second).
Method(s)
To Publish a message
you can use the following method(s) in the Python SDK:
pubnub.publish() \
.channel(String) \
.message(Object) \
.custom_message_type(String) \
.should_store(Boolean) \
.meta(Dictionary) \
.use_post(Boolean)
Parameter | Description |
---|---|
channel *Type: String Default: n/a | Destination of message (channel ID). |
message *Type: Object Default: n/a | The payload. |
custom_message_type Type: String Default: n/a | A case-sensitive, alphanumeric string from 3 to 50 characters describing the business-specific label or category of the message. Dashes - and underscores _ are allowed. The value cannot start with special characters or the string pn_ or pn- . Examples: text , action , poll . |
should_store Type: Boolean Default: account default | Store in history |
meta Type: Object Default: None | Meta data object which can be used with the filtering ability. |
Sample code
Publish a message to a channel
Reference code
- Builder Pattern
- Named Arguments
import os
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub
from pubnub.exceptions import PubNubException
def publish_message(pubnub: PubNub):
try:
envelope = pubnub.publish() \
.channel("my_channel") \
.message({
'name': 'Alex',
'online': True
}) \
.custom_message_type("text-message") \
show all 37 linesimport os
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub
from pubnub.exceptions import PubNubException
def publish_message(pubnub: PubNub):
try:
envelope = pubnub.publish(
channel="my_channel",
message={
'name': 'Alex',
'online': True
},
custom_message_type="text-message"
show all 38 linesSubscribe to the channel
Before running the above publish example, either using the Debug Console or in a separate script running in a separate terminal window, subscribe to the same channel that is being published to.
Returns
The publish()
operation returns an Envelope
which contains the following fields:
Field | Type | Description |
---|---|---|
result | PNPublishResult | A string representation of the result and the timetoken when the message was published. |
status | PNStatus | A status object with additional information. |
PNPublishResult
Publish success with timetoken 17193163560057793
Other examples
Publish with metadata
def publish_callback(result, status):
pass
# handle publish result, status always present, result if successful
# status.is_error() to see if error happened
pubnub.publish().channel("my_channel").message(["hello", "there"]) \
.meta({'name': 'Alex'}).pn_async(publish_callback)
Fire
The fire endpoint sends a message to Functions event handlers and Illuminate. The message goes directly to handlers registered on the target channel and triggers their execution. The handler can read the request body. Messages sent via fire()
aren't replicated to subscribers and aren't stored in history.
Method(s)
To Fire a message
you can use the following method(s) in the Python SDK:
pubnub.fire() \
.channel(String) \
.message(Object) \
.use_post(Boolean) \
.meta(Object)
Parameter | Description |
---|---|
channel *Type: String Default: n/a | Destination of message (channel ID). |
message *Type: Object Default: n/a | The payload. |
use_post Type: Boolean Default: False | Use POST to publish. |
meta Type: Object Default: None | Meta data object which can be used with the filtering ability. |
Sample code
Fire a message to a channel
- Builder Pattern
- Named Arguments
envelope = pubnub.fire() \
.channel('my_channel') \
.message('hello there') \
.use_post(True) \
.sync()
print(f'fire timetoken: {envelope.result.timetoken}')
fire = pubnub.fire(channel="my_channel", message='hello there').sync()
print(f'fire timetoken: {fire.result.timetoken}')
Returns
The fire()
operation returns an Envelope
which contains the following fields:
Field | Type | Description |
---|---|---|
result | PNFireResult | A string representation of the result and the timetoken when the message was fired. |
status | PNStatus | A status object with additional information. |
PNFireResult
Fire success with timetoken 17193163560057793
Signal
The signal()
function sends a signal to all subscribers of a channel.
Signals have a 64‑byte payload limit (payload only, not URI or headers). For larger payloads, contact support.
Method(s)
To Signal a message
you can use the following method(s) in the Python SDK:
pubnub.signal() \
.message(Object) \
.custom_message_type(String) \
.channel(String)
Parameter | Description |
---|---|
message *Type: Object | The payload. |
custom_message_type Type: String | A case-sensitive, alphanumeric string from 3 to 50 characters describing the business-specific label or category of the message. Dashes - and underscores _ are allowed. The value cannot start with special characters or the string pn_ or pn- . Examples: text , action , poll . |
channel *Type: String | Destination of message (channel ID). |
Sample code
Signal a message to a channel
- Builder Pattern
- Named Arguments
envelope = pubnub.signal() \
.channel('some_channel') \
.message('foo') \
.custom_message_type('text-message') \
.sync()
signal = pubnub.signal(channel="my_channel", message='hello there', custom_message_type='text-message').sync()
print(f'signal timetoken: {signal.result.timetoken}')
Returns
The signal()
operation returns an Envelope
which contains the following fields:
Field | Type | Description |
---|---|---|
result | PNSignalResult | A string representation of the result and the timetoken when the signal was sent. |
status | PNStatus | A status object with additional information. |
PNSignalResult
Signal success with timetoken 17193165584676126
Subscribe
Subscribe opens a TCP socket and listens for messages and events on a specified entity or set of entities. Configure the subscribeKey
during initialization.
Conceptual overview
For more general information about subscriptions, refer to Subscriptions.
Entities are first-class citizens that provide access to their encapsulated APIs. You can subscribe using the PubNub client object or directly on a specific entity:
ChannelRepresentation
ChannelGroupRepresentation
UserMetadataRepresentation
ChannelMetadataRepresentation
A newly subscribed client receives messages after subscribe()
completes. Enable automatic retries to reconnect and retrieve available messages if a client disconnects.
Subscription scope
Subscriptions let you attach listeners for specific real-time update types. Your app receives messages and events through those listeners. There are two types:
Subscription
: created from an entity and scoped to that entity (for example, a particular channel)SubscriptionSet
: created from the PubNub client and scoped to the client (for example, all subscriptions created on a singlepubnub
object). A set can include one or more subscriptions.
The event listener is a single point through which your app receives all the messages, signals, and events in the entities you subscribed to. For information on adding event listeners, refer to Event listeners.
Create a subscription
An entity-level Subscription
allows you to receive messages and events for only that entity for which it was created. Using multiple entity-level Subscription
s is useful for handling various message/event types differently in each channel.
# entity-based, local-scoped
subscription = pubnub.channel(f'{channel}').subscription(with_presence: bool = False)
Parameter | Description |
---|---|
with_presence Type: bool | Whether presence updates for userId s should be delivered through the listener streams. For information on how to receive presence events and what those events are, refer to Presence Events. |
Create a subscription set
A client-level SubscriptionSet
allows you to receive messages and events for all entities. A single SubscriptionSet
is useful for similarly handling various message/event types in each channel.
# client-based, general-scoped
subscription_set = pubnub.subscription_set(subscriptions: List[PubNubSubscription])
Parameter | Description |
---|---|
subscriptions *Type: List[PubNubSubscription] | Channels/Channel group subscriptions. |
Method(s)
Subscription
and SubscriptionSet
use the same subscribe()
method.
Subscribe
To subscribe, you can use the following method in the Python SDK:
subscription.subscribe(timetoken: Optional[int] = None, region: Optional[str] = None,)
Parameter | Description |
---|---|
timetoken Type: int | Timetoken from which to return any available cached messages. Message retrieval with timetoken is not guaranteed and should only be considered a best-effort service. If the value is not a 17-digit number, the provided value will be ignored. |
region Type: String | The region the message was published in. |
Sample code
# single channel subscription
channel = pubnub.channel(f'{channel}')
t1_subscription = channel.subscription()
t1_subscription.subscribe()
# multiple channel subscription
channel_1 = pubnub.channel(channel).subscription()
channel_2 = pubnub.channel(f'{channel}.2').subscription(with_presence=True)
channel_x = pubnub.channel(f'{channel}.*').subscription(with_presence=True)
group = pubnub.channel_group('group-test').subscription()
subscription_set = pubnub.subscription_set([channel_1, channel_2, channel_x, group])
set_subscription = subscription_set.subscribe()
Returns
The subscribe()
method doesn't have a return value.
Entities
Entities are subscribable objects for which you can receive real-time updates (messages, events, etc).
Create channels
This method returns a local PubNubChannel
entity.
pubnub.channel(String)
Parameter | Description |
---|---|
channel *Type: String | The ID of the channel to create a subscription of. |
Sample code
pubnub.channel(f'{channel1}')
Create channel groups
This method returns a local PubNubChannelGroup
entity.
pubnub.channel_group(String)
Parameter | Description |
---|---|
channel_group *Type: String | The name of the channel group to create a subscription of. |
Sample code
pubnub.channel_group("channelGroupName")
Create channel metadata
This method returns a local PubNubChannelMetadata
entity.
pubnub.channel_metadata(String)
Parameter | Description |
---|---|
channel_metadata *Type: String | The String identifier of the channel metadata object to create a subscription of. |
Sample code
pubnub.channel_metadata("channelMetadata")
Create user metadata
This method returns a local PubNubUserMetadata
entity.
pubnub.user_metadata(String)
Parameter | Description |
---|---|
user_metadata *Type: String | The String identifier of the user metadata object to create a subscription of. |
Sample code
pubnub.userMetadata("user_metadata")
Event listeners
Messages and events are received in your app using a listener. This listener allows a single point to receive all messages, signals, and events.
You can attach listeners to the instances of Subscription
, SubscriptionSet
, and, in the case of the connection status, the PubNub client.
Add listeners
You can implement multiple listeners or register an event-specific listener that receives only a selected type, like message
or file
.
Method(s)
# Add event-specific listeners
# using closure for reusable listener
def on_message(listener):
def message_callback(message):
print(f"\033[94mMessage received on: {listener}: \n{message.message}\033[0m\n")
return message_callback
# without closure
def on_message_action(message_action):
print(f"\033[5mMessageAction received: \n{message_action.value}\033[0m\n")
def on_presence(listener):
def presence_callback(presence):
print(f"\033[0;32mPresence received on: {listener}: \t{presence.uuid} {presence.event}s "
show all 77 linesSample code
subscription = pubnub.channel(f'{channel1}').subscription()
def on_message(listener):
def message_callback(message):
print(f"\033[94mMessage received on: {listener}: \n{message.message}\033[0m\n")
return message_callback
def on_message_action(message_action):
print(f"\033[5mMessageAction received: \n{message_action.value}\033[0m\n")
subscription.on_message = on_message('message_listener')
subscription.on_message_action = on_message_action
subscription.subscribe()
show all 20 linesAdd connection status listener
The PubNub client has a listener dedicated to handling connection status updates.
Client scope
This listener is only available on the PubNub object.
Method(s)
pubnub.add_listener()
Sample code
class PrintListener(SubscribeListener):
def status(self, pubnub, status):
print(f'Status:\n{status.__dict__}')
def message(self, pubnub, message):
pass
def presence(self, pubnub, presence):
pass
listener = PrintListener()
pubnub.add_listener(listener)
Returns
The subscription status. For information about available statuses, refer to SDK statuses.
Unsubscribe
Stop receiving real-time updates from a Subscription
or a SubscriptionSet
.
Method(s)
subscription.unsubscribe()
subscription_set.unsubscribe()
Sample code
channel = pubnub.channel(f'{channel}')
t1_subscription = channel.subscription()
t1_subscription.subscribe()
subscription_set1 = pubnub.subscription_set(channels=['channel1', 'channel2'])
subscription_set.subscribe()
t1_subscription1.unsubscribe()
subscription_set.unsubscribe()
Returns
None
Unsubscribe all
Stop receiving real-time updates from all data streams and remove the entities associated with them.
Client scope
This method is only available on the PubNub object.
Method(s)
pubnub.unsubscribe_all()
Sample code
channel = pubnub.channel(f'{channel}')
t1_subscription = channel.subscription()
t1_subscription.subscribe()
subscription_set1 = pubnub.subscription_set(channels=['channel1', 'channel2'])
subscription_set.subscribe()
t1_subscription1.unsubscribe()
subscription_set.unsubscribe()
pubnub.unsubscribe_all()
Returns
None
Subscribe (old)
Not recommended
The use of this method is discouraged. Use Subscribe instead.
Receive messages
Your app receives messages and events via event listeners. The event listener is a single point through which your app receives all the messages, signals, and events that are sent in any channel you are subscribed to.
For more information about adding a listener, refer to the Event Listeners section.
Description
This function causes the client to create an open TCP socket to the PubNub Real-Time Network and begin listening for messages on a specified channel
ID. To subscribe to a channel
ID the client must send the appropriate subscribe_key
at initialization.
By default a newly subscribed client will only receive messages published to the channel after the subscribe()
call completes.
If a client gets disconnected from a channel, it can automatically attempt to reconnect to that channel
ID and retrieve any available messages that were missed during that period. This can be achieved by setting setReconnectionPolicy
to PNReconnectionPolicy.LINEAR
, when initializing the client.
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 channel(s). Unsubscribing from all channels resets the last-received timetoken
and thus, there could be some gaps in the subscription that may lead to message loss.
Method(s)
To Subscribe to a channel
you can use the following method(s) in the Python SDK:
pubnub.subscribe() \
.channels(String|List|Tuple) \
.channel_groups(String|List|Tuple) \
.with_timetoken(Int) \
.with_presence() \
.execute()
Parameter | Description |
---|---|
channels Type: String | List | Tuple | Subscribe to channels , Either channel ID or channel_group is required. |
channel_groups Type: String | List | Tuple | Subscribe to channel_groups , Either channel ID or channel_group is required. |
timetoken Type: Int | Pass a timetoken . |
with_presence Type: Command | Also subscribe to related presence information. |
Sample code
Subscribe to a channel:
pubnub.subscribe() \
.channels('my_channel') \
.execute()
Event listeners
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.
Returns
PNMessageResult
PNMessageResult
is returned in the Listeners
The subscribe()
operation returns a PNStatus
for messages which contains the following fields:
Field | Type | Description |
---|---|---|
category | PNStatusCategory | See the Python SDK listener categories. |
is_error | Boolean | This is True if an error occurred in the execution of the operation. |
error_data | PNErrorData | Error data of the exception (if Error is True ). |
status_code | int | Status code of the execution. |
The subscribe()
operation returns a PNMessageResult
for messages which contains the following fields:
Field | Type | Description |
---|---|---|
message | Object | The message sent on the channel ID. |
subscription | String | The channel group or wildcard subscription match (if exists). |
channel | String | The channel ID for which the message belongs. |
timetoken | Int | Timetoken for the message. |
user_metadata | Dictionary | User metadata . |
The subscribe()
operation returns a PNPresenceEventResult
from presence which contains the following operations:
Field | Type | Description |
---|---|---|
event | String | Events like join , leave , timeout , state-change . |
uuid | String | uuid for event. |
timestamp | Int | timestamp for event. |
occupancy | Int | Current occupancy . |
subscription | String | The channel group or wildcard subscription match (if exists). |
channel | String | The channel ID for which the message belongs. |
timetoken | Int | timetoken of the message. |
user_metadata | Dictionary | User metadata . |
The subscribe()
operation returns a PNSignalResult
for signals which contains the following operations:
Field | Type | Description |
---|---|---|
timetoken | Int | An int representation of the timetoken when Signal was sent. |
channel | String | The channel ID on which Signal occurred. |
publisher | String | ID of the sender. |
message | Object | The payload. |
Other examples
Basic subscribe with logging
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'
pubnub = PubNub(pnconfig)
show all 17 linesLogging setup
For information on how to properly enable logging at the package level and the correct function call syntax, see the Logging documentyarn.
Subscribing to multiple channels
It's possible to subscribe to more than one channel using the Multiplexing feature. The example shows how to do that using an array to specify the channel names.
Alternative subscription methods
You can also use Wildcard Subscribe and Channel Groups to subscribe to multiple channels at a time. To use these features, the Stream Controller add-on must be enabled on your keyset in the Admin Portal.
pubnub.subscribe() \
.channels(["my_channel1", "my_channel2"]) \
.execute()
Subscribing to a Presence channel
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.
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
.
pubnub.subscribe()\
.channels("my_channel")\
.with_presence()\
.execute()
Sample Responses
Join event
if envelope.event == 'join':
envelope.uuid # 175c2c67-b2a9-470d-8f4b-1db94f90e39e
envelope.timestamp # 1345546797
envelope.occupancy # 2
Leave event
{
"action" : "leave",
"timestamp" : 1345549797,
"uuid" : "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
"occupancy" : 1
}
Timeout event
if envelope.event == 'timeout':
envelope.uuid # 175c2c67-b2a9-470d-8f4b-1db94f90e39e
envelope.timestamp # 1345546797
envelope.occupancy # 0
State change event
if envelope.event == 'state-change':
envelope.uuid # 76c2c571-9a2b-d074-b4f8-e93e09f49bd
envelope.timestamp # 1345546797
envelope.user_metadata # {'is_typing': True}
Interval event
{
"action":"interval",
"timestamp":1474396578,
"occupancy":2
}
When a channel is in interval mode with presence_deltas
pnconfig
flag enabled, the interval message may also include the following fields which contain an array of changed UUIDs since the last interval message.
- joined
- left
- timedout
For example, this interval message indicates there were 2 new UUIDs that joined and 1 timed out UUID since the last interval:
{
"action" : "interval",
"occupancy" : <# users in channel>,
"timestamp" : <unix timestamp>,
"joined" : ["uuid2", "uuid3"],
"timedout" : ["uuid1"]
}
If the full interval message is greater than 30KB
(since the max publish payload is ∼32KB
), none of the extra fields will be present. Instead there will be a here_now_refresh
boolean field set to True
. This indicates to the user that they should do a hereNow
request to get the complete list of users present in the channel.
{
"action" : "interval",
"occupancy" : <# users in channel>,
"timestamp" : <unix timestamp>,
"here_now_refresh" : True
}
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 (with Enable Wildcard Subscribe checked). Read the support page on enabling add-on features on your keys.
Wildcard subscribes allow the client to subscribe to multiple channels using wildcard. For example, if you subscribe to a.*
you will get all messages for a.b
, a.c
, a.x
. The wildcarded *
portion refers to any portion of the channel string name after the dot (.)
.
pubnub.subscribe() \
.channels("foo.*") \
.execute()
Wildcard grants and revokes
Only one level (a.*
) of wildcarding is supported. If you grant on *
or a.b.*
, the grant will treat *
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
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.
Required User ID
Always set the user_id
to uniquely identify the user or device that connects to PubNub. This user_id
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the user_id
, you won't be able to connect to PubNub.
from pubnub.enums import PNStatusCategory
from pubnub.pubnub import SubscribeListener, PubNub
class MySubscribeListener(SubscribeListener):
def __init__(self):
if status.category == PNStatusCategory.PNConnectedCategory:
state = {
'field_a': 'awesome',
'field_b': 10
}
envelope = pubnub.set_state().channels('my_channel').\
channel_groups('awesome_channel_groups').state(state).sync()
else:
show all 32 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. Read the support page on enabling add-on features on your keys.
pubnub.subscribe() \
.channel_groups("awesome_channel_group") \
.execute()
Subscribe to the Presence channel of a channel group
Requires Stream Controller and Presence add-ons
This method requires both the Stream Controller and Presence add-ons are enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
pubnub.subscribe() \
.channel_groups("awesome_channel_group") \
.with_presence() \
.execute()
Event listeners
You can be notified of connectivity status, message and presence notifications via the listeners.
Listeners should be added before calling the method.
Add listeners
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)
show all 104 linesRemove listeners
my_listener = MySubscribeCallback()
pubnub.add_listener(my_listener)
# some time later
pubnub.remove_listener(my_listener)
Handling disconnects
from pubnub.callbacks import SubscribeCallback
from pubnub.enums import PNStatusCategory
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):
show all 26 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. This may be due to many reasons, such as: the machine or device isn't connected to the internet; the internet connection has been lost; your internet service provider is having trouble; or, perhaps the SDK is behind a proxy. |
PNReconnectedCategory | The SDK was able to reconnect to PubNub. |
PNConnectedCategory | SDK subscribed with a new mix of channels. This is fired every time the channel ID or channel group mix changes. |
PNUnexpectedDisconnectCategory | Previously started subscribe loop did fail and at this moment client disconnected from real-time data channels. |
PNUnknownCategory | Returned when the subscriber gets a non-200 HTTP response code from the server. |
SubscribeListener
should not be used with high-performance sections of your app.
Unsubscribe (old)
Not recommended
The use of this method is discouraged. Use Unsubscribe instead.
When subscribed to a single channel, this function causes the client to issue a leave
from the channel
and close any open socket to the PubNub Network. For multiplexed channels, the specified channel
(s) will be removed and the socket remains open until there are no more channels remaining 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 channel(s). Unsubscribing from all channels resets the last-received timetoken
and thus, there could be some gaps in the subscription that may lead to message loss.
Method(s)
To Unsubscribe from a channel
you can use the following method(s) in the Python SDK:
pubnub.unsubscribe() \
.channels(String|List|Tuple) \
.channel_groups(String|List|Tuple) \
.execute()
Parameter | Description |
---|---|
channels Type: String | List | Tuple | Subscribe to channels , Either channel ID or channel_group is required. |
channel_groups Type: String | List | Tuple | Subscribe to channel_groups , Either channel ID or channel_group is required |
Sample code
Unsubscribe from a channel:
pubnub.unsubscribe() \
.channels("my_channel") \
.execute()
Event listeners
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.
Response
The output below demonstrates the response to a successful call:
if envelope.event == 'leave':
envelope.uuid # 175c2c67-b2a9-470d-8f4b-1db94f90e39e
envelope.timestamp # 1345546797
envelope.occupancy # 2
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. Read the support page on enabling add-on features on your keys.
pubnub.unsubscribe() \
.channels(["my_channel1", "my_channel2"]) \
.execute()
Example response
{
"action" : "leave"
}
Unsubscribe from a channel group
pubnub.unsubscribe() \
.channels_groups(["my_group1", "my_group2") \
.execute()
{
"action": "leave"
}
Unsubscribe all (old)
Not recommended
The use of this method is discouraged. Use Unsubscribe All instead.
Unsubscribe from all channels and all channel groups.
Method(s)
pubnub.unsubscribe_all()
Sample code
pubnub.unsubscribe_all()
Returns
None