Message Persistence API for Python-Asyncio SDK
fetch_messages(), delete_messages(), and message_counts().
Message Persistence must be enabled on the keyset before you store or read history, and new keysets don't enable it by default.
Each builder method has a keyword argument of the same name, except where a table says otherwise.
A builder sends its request when you await its future(). A request that fails, or fails validation, does not raise an exception. future() resolves with a PubNubAsyncioException whose result is None and whose status holds the error. Call is_error() on the awaited value before you read result.
Message Persistence gives you real-time access to the history of messages published to PubNub. Each message is timestamped to the nearest 10 nanoseconds and stored across multiple availability zones in several geographic locations. You can encrypt stored messages with AES-256 so they are not readable on PubNub’s network. For details, see Message Persistence.
You control how long messages are stored through your account’s retention policy. Options include: 1 day, 7 days, 30 days, 3 months, 6 months, 1 year, or Unlimited.
You can retrieve the following:
- Messages
- Message reactions
- Files (using the File Sharing API)
Fetch history
Message Persistence add-on
This method requires that the Message Persistence add-on is enabled for your key in the Admin Portal.
Requires Message Persistence add-on
This method requires that the Message Persistence add-on is enabled for your key in the Admin Portal. See Enable the features your app calls.
fetch_messages() returns the messages that Message Persistence stores for one or more channels, using a PubNub client for Python-Asyncio.
The start and end timetokens control which messages the call returns and in what order.
-
If you specify only
start, the call returns messages older than that timetoken, becausestartis the newer, exclusive boundary of the query. -
If you specify only
end, the call returns messages with a timetoken equal to or newer thanend, becauseendis the older, inclusive boundary of the query.
How to use the start and end parameters
PubNub retrieves messages by searching backward through time (newest to oldest). Because of this, the parameter names are the reverse of their intuitive meaning:
startis the newer boundary (higher timetoken value) - search begins here, exclusiveendis the older boundary (lower timetoken value) - search stops here, inclusive
When you provide both parameters, start must be a higher timetoken than end.
Results are always returned in oldest-first order.
start to the timetoken of the oldest message in the previous response.The start and end parameters take an int, so convert a timetoken string with int().channelsrequired#- IDs of the channels to fetch messages from, up to 500 channels. Pass a list of channel names or one string. A string is split on commas, so
"ch1,ch2"names two channels. With more than one channel and include_message_actions set to True fails validation with the messageHistory can return message action data for a single channel only. Either pass a single channel or disable the include_message_actions flag. count#- Number of messages to return for each channel. The default is
100for one channel, and25for several channels or withinclude_message_actionsset totrue. The SDK lowers a larger value to that default. The builder also acceptsmaximum_per_channel()as an alias. start#- Timetoken that sets the newer boundary of the query (exclusive). Retrieval begins at this timetoken and moves backward in time. With
end,startmust be a higher timetoken thanend. end#- Timetoken that sets the older boundary of the query (inclusive). Retrieval stops at this timetoken. With
start,endmust be a lower timetoken thanstart. include_meta#- Whether each returned message includes the metadata that its publisher set at publish time, in the
metaproperty. include_message_actions#- Whether the response includes the message actions of each message, which limits the call to one channel and 25 messages.
include_message_type#- Whether each returned message includes its PubNub message type in the
message_typeproperty. include_custom_message_type#- Whether the request asks PubNub to include the custom message type of each message. The SDK sends the flag, but the items of the result do not expose a custom message type. Only the builder form sets it. For the background, see Message Persistence.
include_uuid#- Whether each returned message includes the User ID of its publisher in the
uuidproperty. decrypt#- Whether the SDK decrypts each message with the crypto module of the client. Without it,
messageholds the stored payload. If decryption fails, the item keeps the stored payload and setserror. The keyword argument offetch_messages()isdecrypt_messages, and the builder method isdecrypt_messages().
Sample code
Returns
fetch_messages() resolves with an AsyncioEnvelope whose result is a PNFetchMessagesResult and whose status is a PNStatus.
PNFetchMessagesResult
channels#- Maps each channel name to a list of
PNFetchMessageItemobjects, oldest first. start_timetoken#- The
startvalue of the request, orNonewhen the request set none. end_timetoken#- The
endvalue of the request, orNonewhen the request set none.
PNFetchMessageItem
message#- The message payload.
timetoken#- Timetoken that PubNub assigned to the message.
meta#- Metadata that the publisher set at publish time, or
Nonewhen the message has none. uuid#- User ID of the publisher. Present only when the response holds it, for example with
include_uuid. message_type#- PubNub message type. Present only when the response holds it, for example with
include_message_type. actions#- Message actions on the message, grouped by action type and then by action value. Each action is a dict with
uuidandactionTimetoken. An empty dict when the message has no actions.Nonewithoutinclude_message_actions. error#- Decryption error, or
None. Set only when the SDK fails to decrypt the message, andmessagethen holds the stored payload.
With include_message_actions set to true, PubNub truncates the response when the returned messages hold more than 25000 message actions in total. The Python result has no more property, so it does not report where the truncation stopped. Lower count to fetch fewer messages in each call.
Other examples
Examples for Fetch history
Syntax
1await pubnub.fetch_messages() \
2 .channels(channels: Union[str, List[str]]) \
3 .count(count: int) \
4 .start(start: int) \
5 .end(end: int) \
6 .include_meta(include_meta: bool) \
7 .include_message_actions(include_message_actions: bool) \
8 .include_message_type(include_message_type: bool) \
9 .include_custom_message_type(include_custom_message_type: bool) \
10 .include_uuid(include_uuid: bool) \
11 .decrypt_messages(decrypt: bool) \
12 .future() -> AsyncioEnvelope
Basic usage (Builder Pattern)
1envelope = await pubnub.fetch_messages() \
2 .channels(["my_channel"]) \
3 .maximum_per_channel(1) \
4 .include_message_actions(True) \
5 .include_meta(True) \
6 .include_message_type(True) \
7 .include_uuid(True) \
8 .future()
9if envelope.is_error():
10 print(f"Error: {envelope.status.error_data}")
11else:
12 for message in envelope.result.channels["my_channel"]:
13 print("Message: %s" % message.message)
14 print("Meta: %s" % message.meta)
15 print("Timetoken: %s" % message.timetoken)
show all 18 linesBasic usage (Named Arguments)
1envelope = await pubnub.fetch_messages(channels=["my_channel"], count=1, include_message_actions=True,
2 include_meta=True, include_message_type=True, include_uuid=True).future()
3if envelope.is_error():
4 print(f"Error: {envelope.status.error_data}")
5else:
6 for message in envelope.result.channels["my_channel"]:
7 print(f"Message: {message.message}")
8 print(f"Meta: {message.meta}")
9 print(f"Timetoken: {message.timetoken}")
Fetch messages in a time range
Fetch messages in a time range
1envelope = await pubnub.fetch_messages() \
2 .channels(["my_channel"]) \
3 .start(newer_timetoken) \
4 .end(older_timetoken) \
5 .future()
6if envelope.is_error():
7 print(f"Error: {envelope.status.error_data}")
Fetch messages from several channels
Fetch messages from several channels
1envelope = await pubnub.fetch_messages() \
2 .channels(["ch1", "ch2"]) \
3 .maximum_per_channel(30) \
4 .future()
5if envelope.is_error():
6 print(f"Error: {envelope.status.error_data}")
7else:
8 for channel_name, items in envelope.result.channels.items():
9 print(channel_name, len(items))
Delete messages from history
Message Persistence add-on
This method requires that the Message Persistence add-on is enabled for your key in the Admin Portal.
Requires Message Persistence add-on
This method requires that the Message Persistence add-on is enabled for your key in the Admin Portal. See Enable the features your app calls.
delete_messages() deletes stored messages from channel history, optionally within a time range, using a PubNub client for Python-Asyncio.
Delete-From-History must be enabled for the keyset in the Admin Portal before a delete call succeeds. A call on a keyset where it is off fails with a 403 error.
The start timetoken is always the exclusive boundary and the end timetoken is always the inclusive boundary. The call deletes the message at end but not the message at start, whichever of the two values is larger. For the full walkthrough, see Delete messages from history.
channelrequired#- ID of the channel to delete messages from. An empty value fails validation with the message
Channel missing. start#- Timetoken that sets the exclusive boundary of the range to delete. The call keeps the message at this timetoken.
end#- Timetoken that sets the inclusive boundary of the range to delete. The call deletes the message at this timetoken.
Sample code
Returns
delete_messages() resolves with an AsyncioEnvelope.
Other examples
Delete a single message
To delete one message, pass its publish timetoken, which a successful publish() returns, as end. Pass the next higher or the next lower timetoken as start. For example, if 15526611838554310 is the publish timetoken, pass 15526611838554310 as end and either 15526611838554309 or 15526611838554311 as start. Both pairs delete only the message at 15526611838554310.
Examples for Delete messages from history
Syntax
1await pubnub.delete_messages() \
2 .channel(channel: str) \
3 .start(start: int) \
4 .end(end: int) \
5 .future() -> AsyncioEnvelope
Basic usage (Builder Pattern)
1envelope = await pubnub.delete_messages() \
2 .channel("my_channel") \
3 .start(newer_timetoken) \
4 .end(older_timetoken) \
5 .future()
6if envelope.is_error():
7 print(f"Error: {envelope.status.error_data}")
Basic usage (Named Arguments)
1envelope = await pubnub.delete_messages(channel="my_channel", start=tokens[3], end=tokens[2]).future()
2if envelope.is_error():
3 print(f"Error: {envelope.status.error_data}")
Delete a single message (Builder Pattern)
1envelope = await pubnub.delete_messages() \
2 .channel("my_channel") \
3 .start(publish_timetoken - 1) \
4 .end(publish_timetoken) \
5 .future()
6if envelope.is_error():
7 print(f"Error: {envelope.status.error_data}")
Delete a single message (Named Arguments)
1envelope = await pubnub.delete_messages(channel="my_channel", start=publish_timetoken - 1,
2 end=publish_timetoken).future()
3if envelope.is_error():
4 print(f"Error: {envelope.status.error_data}")
Message counts
Message Persistence add-on
This method requires that the Message Persistence add-on is enabled for your key in the Admin Portal.
Requires Message Persistence add-on
This method requires that the Message Persistence add-on is enabled for your key in the Admin Portal. See Enable the features your app calls.
message_counts() returns the number of messages published to one or more channels since a timetoken, using a PubNub client for Python-Asyncio.
message_counts() considers only messages published in the last 30 days.channelrequired#- IDs of the channels to count messages in. Pass a list of channel names or one string. A string is split on commas, so
"ch1,ch2"names two channels. The keyword argument ofmessage_counts()ischannels. An empty value fails validation with the messageChannel missing. channel_timetokensrequired#- Timetokens from which to count messages, listed in the same order as
channel. The list must hold exactly one timetoken per channel. Each item is an int or a str. The keyword argument ofmessage_counts()ischannels_timetoken. A list whose length differs from the number of channels fails validation with the messageThe number of channels and the number of timetokens do not match..
Sample code
Returns
message_counts() resolves with an AsyncioEnvelope whose result is a PNMessageCountResult and whose status is a PNStatus.
PNMessageCountResult
channels#- Maps each channel name to its message count. A channel without messages has a count of
0. A channel with 10,000 messages or more has a count of10000.
Other examples
Count messages with a different timetoken for each channel
Examples for Message counts
Syntax
1await pubnub.message_counts() \
2 .channel(channel: Union[str, List[str]]) \
3 .channel_timetokens(channel_timetokens: List[Union[int, str]]) \
4 .future() -> AsyncioEnvelope
Basic usage (Builder Pattern)
1envelope = await pubnub.message_counts() \
2 .channel("my_channel") \
3 .channel_timetokens([timetoken]) \
4 .future()
5if envelope.is_error():
6 print(f"Error: {envelope.status.error_data}")
7else:
8 print(envelope.result.channels["my_channel"])
Basic usage (Named Arguments)
1envelope = await pubnub.message_counts(channels="my_channel", channels_timetoken=[tokens[2]]).future()
2if envelope.is_error():
3 print(f"Error: {envelope.status.error_data}")
PNMessageCountResult
1{
2 "channels": {
3 "my_channel": 3
4 }
5}
Count messages with a different timetoken for each channel (Builder Pattern)
1envelope = await pubnub.message_counts() \
2 .channel(["my_channel", "my_channel_2"]) \
3 .channel_timetokens([timetoken, other_timetoken]) \
4 .future()
5if envelope.is_error():
6 print(f"Error: {envelope.status.error_data}")
7else:
8 print(envelope.result.channels)
Count messages with a different timetoken for each channel (Named Arguments)
1envelope = await pubnub.message_counts(channels=["my_channel", "my_channel_2"],
2 channels_timetoken=[tokens[1], other_timetoken]).future()
3if envelope.is_error():
4 print(f"Error: {envelope.status.error_data}")
Not recommended history method
history() is a method of the PubNub Python-Asyncio SDK that fetches the messages of one channel. Its use is not recommended, and fetch_messages() replaces it.
The reference for apps that still call history() is Message Persistence API: history() method that is not recommended for Python-Asyncio SDK. New apps use Fetch history.