PubNub Logo Docs
Support Contact Sales Login Try Our APIs

›First steps

Collapse all
Dark mode

Home

  • Home

First steps

  • Set up your account
  • Get the SDK
  • Initialize PubNub
  • Identify users and devices
  • Send messages
  • Receive messages
  • Retrieve old messages
  • Check user presence
  • Add custom metadata
  • Manage access
  • Add serverless business logic
  • Send push notifications

Setup

  • PubNub account
  • Application
  • Users & devices
  • Connection management
  • Data security
  • Data persistence
  • API limits

Chat

  • In-App Chat

SDKs

  • SDKs

Messages

  • Publish
  • Receive
  • Actions
  • Payload type conventions

Channels

  • Basics
  • Subscription
  • Naming conventions

User presence

  • Basics
  • Events
  • State
  • Webhooks

Metadata

  • Channel
  • User
  • Membership

Message Persistence

  • Message Persistence

File sharing

  • File sharing

Access management

  • Manage access

Push notifications

  • Basics
  • iOS
  • Android
  • Troubleshooting

Best practices

  • Architectural choices
  • Message aggregation
  • Friend list & status feed
  • Troubleshooting
  • Migration guides

Serverless processing

    EVENTS & ACTIONS

    • Basics
    • Configure Events & Actions

    FUNCTIONS

    • Basics
    • Development guidelines
    • Functions API
    • Custom integrations

Debug Console
Network Status

Retrieve old messages

Even though realtime messaging has the obvious benefit of receiving data nearly instantly, it's impossible to keep track of all incoming messages. There are times you might be more interested in messages that have been sent in the past.

PubNub allows you to retain and retrieve historical messages. All you need to know is the channel name the message was sent to and the message's timetoken. Beforehand, however, you must enable the Storage feature in the Admin Portal and configure the amount of time your messages are stored for.

You can retrieve historical messages from one or multiple channels. You can also control the time range and influence the return order. A single request may retrieve up to 100 messages for a single channel or 25 messages for multiple channels (up to 500). If you're not interested in the message content, you may also retrieve the number of messages you missed.

Most use cases require retrieving messages missed since a device or user was last online. To do that, you only provide the end parameter with a timetoken of the last received message. The following code returns the last 100 messages on the chats_guilds.mages_guild channel.

JavaScript
Swift
Objective-C
Android
C#
Python

Go to SDK

pubnub.fetchMessages(
{
channels: ["chats_guilds.mages_guild"],
end: '15343325004275466',
count: 100
},
function(status, response) {
console.log(status, response);
}
);

Go to SDK

pubnub.fetchMessageHistory(
for: ["chats_guilds.mages_guild"],
end: "15343325004275466"
) { result in
switch result {
case let .success(response):
print("Successful History Fetch Response: \(response)")

case let .failure(error):
print("Failed History Fetch Response: \(error.localizedDescription)")
}
}

Go to SDK

self.pubnub.history()
.channels(@[@"chats_guilds.mages_guild"])
.end(15343325004275466).limit(100)
.performWithCompletion(^(PNHistoryResult *result, PNErrorStatus *status) {
// handle returned messages in result
});

Go to SDK

pubNub.fetchMessages()
.channels(Arrays.asList("chats_guilds.mages_guild"))
.async(new PNCallback<PNFetchMessagesResult>() {
@Override
public void onResponse(@Nullable final PNFetchMessagesResult result, @NotNull final PNStatus status) {
if (!status.isError()) {
final Map<String, List<PNFetchMessageItem>> channelToMessageItemsMap = result.getChannels();
final Set<String> channels = channelToMessageItemsMap.keySet();
for (final String channel : channels) {
List<PNFetchMessageItem> pnFetchMessageItems = channelToMessageItemsMap.get(channel);
for (final PNFetchMessageItem fetchMessageItem: pnFetchMessageItems) {
System.out.println(fetchMessageItem.getMessage());
System.out.println(fetchMessageItem.getMeta());
System.out.println(fetchMessageItem.getTimetoken());
}
}
}
else {
System.err.println("Handling error");
}
}
});

Go to SDK

pubnub.FetchHistory()
.Channels(new string[] { "chats_guilds.mages_guild" })
.MaximumPerChannel(100)
.End(15343325004275466)
.Execute(new PNFetchHistoryResultExt((result, status) => {
// handle returned messages in result
}));

Go to SDK

envelope = pubnub.fetch_messages()\
.channels(["chats_guilds.mages_guild"])\
.count(100)\
.end(15343325004275466)\
.sync()

If the messages have any emojis, reactions, or delivery acknowledgements attached, you may retrieve them as well.

Having read how to work with historical messages, let's focus back on the present. As your channels get more traction and users start to subscribe, it's worthwhile to understand how to check who's currently online.

← Receive messagesCheck user presence →
© PubNub Inc. - Privacy Policy