Message Persistence API for Ruby SDK
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)
Batch history
Requires Message Persistence
This method requires that Message Persistence is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
This function fetches historical messages from multiple channels. The include_message_actions flag also allows you to fetch message actions along with the messages for a single channel.
fetch_messages() vs history()
Use fetch_messages() for retrieving messages from multiple channels simultaneously (up to 500 channels). For single-channel message retrieval with additional options like reverse or include_token, use the history() method instead.
It's possible to control how messages are returned and in what order. For example, you can:
- Search for messages starting on the newest end of the timeline.
- Search for messages from the oldest end of the timeline.
- Page through results by providing a
startORendtimetoken. - Retrieve a slice of the time line by providing both a
startANDendtimetoken. - Retrieve a specific (maximum) number of messages using the
maxparameter.
Batch history returns up to 100 messages on a single channel, or 25 per channel on a maximum of 500 channels. Use the start and end timestamps to page through the next batch of messages.
Start & End parameter usage clarity
If you specify only the start parameter (without end), you will receive messages that are older than the start timetoken.
If you specify only the end parameter (without start), you will receive messages from that end timetoken and newer.
Specify values for both start and end parameters to retrieve messages between those timetokens (inclusive of the end value).
Keep in mind that you will still receive a maximum of 100 messages (or 25, for multiple channels) even if there are more messages that meet the timetoken values. Iterative calls to history adjusting the start timetoken are necessary to page through the full set of results if more messages meet the timetoken values.
Method(s)
Use the following method(s) in the Ruby SDK:
1fetch_messages(
2 channel: channel,
3 channels: channels,
4 max: max,
5 start: start,
6 end: end,
7 include_meta: include_meta,
8 include_message_actions: include_message_actions,
9 include_uuid: include_uuid,
10 include_message_type: include_message_type,
11 include_custom_message_type: include_custom_message_type,
12 encode_channels: encode_channels,
13 cipher_key: cipher_key,
14 random_iv: random_iv,
15 http_sync: http_sync,
show all 17 lines| Parameter | Description |
|---|---|
channelType: String | A single channel to fetch messages from. You can use the include_message_actions flag to get message actions history for this channel. |
channelsType: Array | Array of channels to fetch messages from. Maximum of 500 channels. Can't be used with include_message_actions as you can only get the message actions history for a single channel. |
maxType: Integer | Maximum number of messages to return per channel. Default is 25 for multiple channels or 100 for a single channel. |
startType: Integer | timetoken delimiting the start of time slice (exclusive) to pull messages from. |
endType: Integer | timetoken delimiting the end of time slice (inclusive) to pull messages from. |
include_metaType: Boolean | Include message metadata in the response. Default is false. |
include_message_actionsType: Boolean | Include message actions in the response. Only works with single channel. Default is false. |
include_uuidType: Boolean | Include UUID of the publisher in the response. Default is true. |
include_message_typeType: Boolean | Whether to include the PubNub message type in the response. Default is true. |
include_custom_message_typeType: Boolean | Whether to include the custom message type in the response. Default is false. |
encode_channelsType: Boolean | Whether to encode channel names for URL safety. Default is true. Set to false when not using include_message_actions. |
cipher_keyType: String | Custom cipher key for message decryption. If provided, overrides the default crypto configuration. |
random_ivType: Boolean | Whether to use random initialization vector for encryption. Default is true. Only used when cipher_key is provided. |
http_syncType: Boolean | Default false. The method is executed asynchronously and returns a future. To retrieve the value, call the value method on the Envelope object. If set to true, method returns an array of envelopes (even if there's only one Envelope). |
callbackType: Lambda accepting one parameter | Callback that is called for each Envelope. For async methods, a future is returned. To retrieve the value, call the value method on the Envelope object. The thread is locked until the value is returned. |
Sample code
Reference code
Retrieve the last 25 messages on multiple channels:
1require 'pubnub'
2
3def fetch_messages(pubnub)
4 pubnub.fetch_messages(
5 channels: ['demo', 'example'],
6 max: 25
7 ) do |envelope|
8 if envelope.status[:error]
9 puts "Error fetching messages: #{envelope.status[:error]}"
10 else
11 puts "Messages fetched successfully:"
12 envelope.result[:data][:channels].each do |channel, messages|
13 puts "Channel: #{channel}"
14 messages.each do |message|
15 puts "Message: #{message['message']}, Timetoken: #{message['timetoken']}"
show all 36 linesResponse
The Ruby SDK returns false on fail. An array is returned on success.
The fetch_messages() function returns a list of messages for each channel. The output below demonstrates the format for a fetch_messages() response:
1 @result = {
2 :data => {
3 :channels => {
4 'channel1' => [
5 { 'message' => 'Message1', 'timetoken' => 15010808292416521 },
6 { 'message' => 'Message2', 'timetoken' => 15010808292416522 }
7 ],
8 'channel2' => [
9 { 'message' => 'Message3', 'timetoken' => 15010808292416523 },
10 { 'message' => 'Message4', 'timetoken' => 15010808292416524 }
11 ]
12 }
13 }
14 },
15 @status = {
show all 18 linesOther examples
Fetch messages with metadata
1pubnub.fetch_messages(
2 channels: ['channel1', 'channel2'],
3 include_meta: true
4) do |envelope|
5 puts envelope.result[:data][:channels]
6end
Fetch messages with message actions
1pubnub.fetch_messages(
2 channel: 'channel1',
3 include_message_actions: true
4) do |envelope|
5 puts envelope.result[:data][:channels]
6end
Fetch messages with custom encryption
1pubnub.fetch_messages(
2 channels: ['channel1', 'channel2'],
3 cipher_key: 'my_custom_cipher_key',
4 random_iv: true
5) do |envelope|
6 puts envelope.result[:data][:channels]
7end
History
Requires Message Persistence
This method requires that Message Persistence is enabled for your key in the Admin Portal.
This function fetches historical messages of a channel.
It is possible to control how messages are returned and in what order, for example you can:
- Search for messages starting on the newest end of the timeline (default behavior -
reverse=false) - Search for messages from the oldest end of the timeline by setting
reversetotrue. - Page through results by providing a
startORendtimetoken. - Retrieve a slice of the time line by providing both a
startANDendtimetoken. - Limit the number of messages to a specific quantity using the
countparameter.
Start & End parameter usage clarity
If only the start parameter is specified (without end), you will receive messages that are older than and up to that start timetoken value. If only the end parameter is specified (without start) you will receive messages that match that end timetoken value and newer. Specifying values for both start and end parameters will return messages between those timetoken values (inclusive on the end value). Keep in mind that you will still receive a maximum of 100 messages even if there are more messages that meet the timetoken values. Iterative calls to history adjusting the start timetoken is necessary to page through the full set of results if more than 100 messages meet the timetoken values.
Method(s)
Use the following method(s) in the Ruby SDK:
1history(
2 channels: channels,
3 count: count,
4 start: start,
5 end: end,
6 reverse: reverse,
7 include_token: include_token,
8 include_meta: include_meta,
9 http_sync: http_sync,
10 callback: callback
11)
| Parameter | Description |
|---|---|
channels *Type: String, Symbol | Specify channels to return history messages from. |
countType: Integer | Specifies the number of historical messages to return. Default/maximum is 100. |
startType: Integer | timetoken delimiting the start of time slice (exclusive) to pull messages from. |
endType: Integer | timetoken delimiting the end of time slice (inclusive) to pull messages from. |
reverseType: Boolean | Setting to true will traverse the time line in reverse starting with the oldest message first.Default is false. If both start and end arguments are provided, reverse is ignored and messages are returned starting with the newest message. |
http_syncType: Boolean | Default false. Method will be executed asynchronously and will return future, to get its value you can use value method. If set to true, method will return array of envelopes (even if there's only one envelope). For sync methods Envelope object will be returned. |
include_tokenType: Boolean | With include_token parameter set to true each envelope will contain timetoken specific for message that it holds. Default: false |
include_metaType: Boolean | When set to true, the history response will include the meta information associated with each message if it was set during publishing. Default: false. |
callbackType: Lambda accepting one parameter | Callback that will be called for each envelope. For async methods future will be returned, to retrieve value Envelope object you have to call value method (thread will be locked until the value is returned). |
tip
reverse parameterMessages are always returned sorted in ascending time direction from history regardless of reverse. The reverse direction matters when you have more than 100 (or count, if it's set) messages in the time interval, in which case reverse determines the end of the time interval from which it should start retrieving the messages.
Sample code
Retrieve the last 100 messages on a channel:
1pubnub.history(
2 channel: 'history_channel',
3 count: 100
4) do |envelope|
5 puts envelope.result[:data][:messages]
6end
Response
The Ruby SDK returns false on fail. An array is returned on success.
The history() function returns a list of up to 100 messages, the timetoken of the first (oldest) message and the timetoken of the last (newest) message in the resulting set of messages. The output below demonstrates the format for a history() response:
1#<Pubnub::Envelope:0x007fd384da4ad0
2 @result = {
3 :data => {
4 :messages => ["Pub1", "Pub2", "Pub3", "Pub4", "Pub5", "Pub6", "Pub7", "Pub8", "Pub9", "Pub10"],
5 :end => 15010808292416521,
6 :start => 15010808287349573
7 }
8 },
9 @status = {
10 :code => 200
11 }
12>
Other examples
Use history() to retrieve the three oldest messages by retrieving from the time line in reverse
1pubnub.history(
2 channel: :history,
3 count: 3,
4 reverse: true,
5 http_sync: true
6)
Response
1#<Pubnub::Envelope:0x007fd3858e34c8
2 @result = {
3 :data => {
4 :messages => ["Pub1", "Pub2", "Pub3"],
5 :end => 15010808288498250,
6 :start => 15010808287349573
7 }
8 },
9 @status = {
10 :code => 200
11 }
12>
Use history() to retrieve messages newer than a given timetoken by paging from oldest message to newest message starting at a single point in time (exclusive)
1pubnub.history(
2 channel: :history,
3 start: 15010808287700000,
4 reverse: true,
5 http_sync: true
6)
Response
1#<Pubnub::Envelope:0x007fd38523ced0
2 @result = {
3 :data => {
4 :messages => ["Pub1"],
5 :end => 15010808287349573,
6 :start => 15010808287349573
7 }
8 }
9 @status = {
10 :code => 200
11 }
12>
Use history() to retrieve messages until a given timetoken by paging from newest message to oldest message until a specific end point in time (inclusive)
1pubnub.history(
2 channel: :history,
3 end: 15010808287700000,
4 http_sync: true
5)
Response
1#<Pubnub::Envelope:0x007fd3860dbce8
2 @result = {
3 :data => {
4 :messages => ["Pub2", "Pub3", "Pub4", "Pub5", "Pub6", "Pub7", "Pub8", "Pub9", "Pub10"],
5 :end => 15010808292416521,
6 :start => 15010808287951883
7 }
8 }
9 @status = {
10 :code => 200
11 }
12>
History paging example
Usage
You can call the method by passing 0 or a valid timetoken as the argument.
1pubnub.paged_history(channel: :messages, limit: 10, page: 20) do |envelope|
2 puts envelope.result[:data][:messages]
3end
Include timetoken in history response
1# ASYNC
2# Call history with include_token: true
3future_envelope = pubnub.history(channel: :demo, include_token: true)
4# Get timetoken of first retrieved message
5future_envelope.value.result[:data][:messages].first['timetoken']
6
7# SYNC
8# Call history with include_token: true
9envelope = pubnub.history(channel: :demo, include_token: true, http_sync: true)
10# Get timetoken of first retrieved message
11envelope.result[:data][:messages].first['timetoken']
12
13# Example response in result[:data][:messages]
14# [
15# {"message"=>"Whatever", "timetoken"=>14865606002747651},
show all 18 linesDelete messages from history
Requires Message Persistence
This method requires that Message Persistence is enabled for your key in the Admin Portal.
Removes the messages from the history of a specific channel.
Required setting
There is a setting to accept delete from history requests for a key, which you must enable by checking the Enable Delete-From-History checkbox in the key settings for your key in the Admin Portal.
Requires Initialization with secret key.
Method(s)
To Delete Messages from History you can use the following method(s) in the Ruby SDK.
1delete_messages(
2 channels: channels,
3 start: start,
4 end: end,
5 http_sync: http_sync,
6 callback: callback
7)
| Parameter | Description |
|---|---|
channels *Type: String, Symbol | Channels from which messages will be deleted. |
startType: String, Integer | Timestamp since when messages should be deleted. |
endType: String, Integer | Timestamp until when messages should be deleted. |
http_syncType: Boolean | Default false. Method will be executed asynchronously and will return future, to get its value you can use value method. If set to true, method will return array of envelopes (even if there's only one envelope). For sync methods Envelope object will be returned. |
callbackType: Lambda accepting one parameter | Callback that will be called for each envelope. For async methods future will be returned, to retrieve value Envelope object you have to call value method (thread will be locked until the value is returned). |
Sample code
1pubnub.delete_messages(channel: 'my-channel', start: 1508284800, end: 1508935781, callback: check_response_status)
Response
1#<Pubnub::Envelope
2 @status = {
3 :code => 200,
4 :operation => :delete,
5 :category => :ack,
6 :error => false,
7 # [...]
8 },
9 # [...]
10>
Other examples
Delete specific message from history
To delete a specific message, pass the publish timetoken (received from a successful publish) in the end parameter and timetoken +/- 1 in the start parameter. For example, if 15526611838554310 is the publish timetoken, pass 15526611838554309 in start and 15526611838554310 in end parameters respectively as shown in the following code snippet.
1pubnub.delete_messages(channel: 'my-channel', start: 15526611838554309, end: 15526611838554310, callback: check_response_status)
Message counts
Requires Message Persistence
This method requires that Message Persistence is enabled for your key in the Admin Portal.
Returns the number of messages published on one or more channels since a given time. The count returned is the number of messages in history with a timetoken value greater than or equal to than the passed value in the channel_timetokensparameter.
Unlimited message retention
For keys with unlimited message retention enabled, this method considers only messages published in the last 30 days.
Method(s)
You can use the following method(s) in the Ruby SDK:
1pubnub.message_counts(
2 channels: array_of_channels,
3 channel_timetokens: array_of_timetokens
4)
| Parameter | Description |
|---|---|
channel *Type: String, Symbol Default: n/a | Either array of channels, string with single channel or string with comma separated channels |
channel_timetokens *Type: Array Default: null | Array of timetokens, in order of the channels list. Specify a single timetoken to apply it to all channels. Otherwise, the list of timetokens must be the same length as the list of channels, or the function returns a PNStatus with an error flag. |
http_syncType: Boolean Default: n/a | Default false. Method will be executed asynchronously and will return future, to get its value you can use value method. If set to true, method will return array of envelopes (even if there's only one envelope). For sync methods Envelope object will be returned. |
Sample code
1envelope = pubnub.message_counts(channel:['a', 'b', 'c', 'd'], channel_timetokens: 12123).value
2 p envelope.result[:data]
Returns
Channels count
Channels without messages have a count of 0. Channels with 10,000 messages or more have a count of 10000.
Returns Concurrent::Future object if PubNub is configured with http_sync: false (default behavior) or envelope if it's set to sync mode
1#<Pubnub::Envelope
2 @result=
3 {
4 :data=>
5 {
6 "channels"=>{"a"=>2, "c"=>0, "b"=>0, "d"=>0}
7 }
8 @status=
9 {
10 :code=>200
11 }
12>
Other examples
Retrieve count of messages using different timetokens for each channel
1envelope = pubnub.message_counts(channel:['a', 'b', 'c', 'd'], channel_timetokens: [123135129, 123135124, 12312312, 123135125]).value
2 p envelope.result[:data]