PubNub Logo Docs
Support Contact Sales Login Try Our APIs

›MESSAGES

Collapse all
Dark mode

Back to Home

Overview

  • In-App Chat

Chat Components

  • Overview
  • REACT

    • React Components

    ANDROID

    • Getting Started
    • UI Components
    • Data Components
    • Chat Provider

    IOS

    • Getting Started
    • UI Components
    • Data Components
    • Chat Provider

SDKs

  • Overview
  • USERS

    • Setup
    • Metadata
    • Permissions
    • Presence
    • Mentions

    CHANNELS

    • Types and Names
    • Metadata
    • Subscriptions
    • Memberships

    MESSAGES

    • Sending Messages
    • Message Storage
    • Unread Counts
    • File Upload
    • Typing Indicators
    • Read Receipts
    • Emoji Reactions
    • Update Messages
    • Delete Messages
    • Message Webhooks

    PUSH NOTIFICATIONS

    • Overview

    MODERATION

    • Profanity Filters
    • Flag Messages
    • Ban Users
    • Mute Users
    • Spam Prevention

    INTEGRATIONS

    • Overview
    • Content Moderation
    • Image Moderation
    • Language Translation
    • Chatbots
    • GIFs
    • Stickers

Moderation Dashboard

  • Overview
  • Getting Started
  • FEATURES

    • Automatic Text Moderation
    • Automatic Image Moderation
    • Manual Message Moderation
    • Manual User Moderation
    • User Management
    • Channel Management
  • Required Configuration

Debug Console
Network Status

Sending messages

Messages are the actual packages of data that get published to a channel. Messages can be chat messages, typing on/off events, location updates, emojis, or anything that your application publishes.

The message doesn't have to be formatted as JSON, but it's usually the best choice. Most developers use the JSON format and most PubNub SDKs automatically stringify JSON objects before publishing. Here is an example of a JSON message:

{
  "from": "user123",
  "message": "Hello, how are you?"
}

Refer to Message Specifications for more information about messages.

Sending a message

Use the publish method to publish messages in a channel. You can publish a message as a string, or send any data (JSON data, or an object), as long as the data size is below 32 KiB.

JavaScript
Swift
Java
Unity

Go to SDK

pubnub.publish({
message: 'Hello World!',
channel: 'ch-1',
}, (status, response) => {
// handle status, response
});

Go to SDK

pubnub.publish(
channel: "ch-1",
message: ["text": "Hello World!"]
) { result in
switch result {
case let .success(response):
print("Successful Publish Response: \(response)")
case let .failure(error):
print("Failed Publish Response: \(error.localizedDescription)")
}
}

Go to SDK

pubNub.publish()
.message("Hello World!")
.channel("ch-1")
.async(new PNCallback<PNPublishResult>() {
@Override
public void onResponse(PNPublishResult result, PNStatus status) {
if (!status.isError()) {
// message is sent
Long timetoken = result.getTimetoken(); // message timetoken
}
}
});

Go to SDK

pubnub.Publish()
.Channel("ch-1")
.Message("Hello World")
.Async((result, status) => {
if (!status.Error) {
Debug.Log(result.Timetoken);
} else {
Debug.Log(status.Error);
Debug.Log(status.ErrorData.Info);
}
});

For more details on working with messages, refer to Publishing a Message.

Receive messages

If users are subscribed to a channel, listener events are triggered in the SDK when a new message is received in that channel. The message includes the publish payload, the sender's UUID and the timetoken of when the message was published. Refer to Adding a Listener for details on how to add a listener.

The subscribe listener returns an envelope containing a 17-digit precision Unix time (UTC). To convert the timestamp to a UNIX epoch time (in seconds), divide it by 10,000,000. Or, you can use it directly from 17-digit precision time without converting. The format of localeDateTime is something similar to 7/5/2019, 3:58:43 PM.

Tip

You only receive messages on channels to which you are subscribed. To avoid missing messages, add the message listener before calling subscribe().

JavaScript
Swift
Java
Unity

Go to SDK

pubnub.addListener({
message: (message) => {
// handle message
const channelName = message.channel;
const channelGroup = message.subscription;
const publishTimetoken = message.timetoken;
const msg = message.message;
const publisher = message.publisher;

//show time
const unixTimestamp = message.timetoken / 10000000;
const gmtDate = new Date(unixTimestamp * 1000);
const localeDateTime = gmtDate.toLocaleString();
}
});

Go to SDK

listener.didReceiveMessage = { message in
print("Message Received: \(message)")

let messageDate = message.timetoken.timetokenDate
print("The message was sent at \(messageDate)")
}

Go to SDK

pubNub.addListener(new SubscribeCallback() {
@Override
public void message(PubNub pubnub, PNMessageResult message) {
String channel = message.getChannel(); // the channel for which the message belongs
String channelGroup = message.getSubscription(); // the channel group or wildcard subscription match (if exists)
Long publishTimetoken = message.getTimetoken(); // publish timetoken
JsonElement messagePayload = message.getMessage(); // the message payload
String publisher = message.getPublisher(); // the publisher

//show message time
long timetoken = message.getTimetoken() / 10_000L;
SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy HH:mm:ss");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timetoken);
String localDateTime = sdf.format(calendar.getTimeInMillis());
Log.d("localDateTime", localDateTime);
}
});

Go to SDK

pubnub.SubscribeCallback += (sender, e) => {
SubscribeEventEventArgs mea = e as SubscribeEventEventArgs;
if (mea.MessageResult != null) {
Debug.Log("Channel" + mea.MessageResult.Channel); // the channel to which the message belongs
Debug.Log("Payload" + mea.MessageResult.Payload); // the message payload
Debug.Log("Publisher Id: " + mea.MessageResult.IssuingClientId); // the publisher
Debug.Log("Subscription" + mea.MessageResult.Subscription); // the channel group or wildcard subscription match (if exists)
Debug.Log("Timetoken" + mea.MessageResult.Timetoken); // publish timetoken

//show message time
Debug.Log("Channel: " + mea.MessageResult.Channel); // the channel to which the message belongs
Debug.Log("Payload: " + mea.MessageResult.Payload); // the message payload
Debug.Log("Publisher Id: " + mea.MessageResult.IssuingClientId); // the publisher
Debug.Log("Subscription: " + mea.MessageResult.Subscription); // the channel group or wildcard subscription match (if exists)
Debug.Log("Timetoken: " + mea.MessageResult.Timetoken); // publish timetoken
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime dt = epoch.AddSeconds(mea.MessageResult.Timetoken/10000000);
DateTime convertedDate = dt.ToLocalTime();
Debug.Log(convertedDate);
}
};

Message Events

The following events are generated when messages are received on channels or channel groups that are subscribed by the clients.

{
    "actualChannel": null,
    "channel": "my_channel_1",
    "message": "Hello World!",
    "publisher": "pn-58e1a647-3e8a-4c7f-bfa4-e007ea4b2073",
    "subscribedChannel": "my_channel_1",
    "subscription": null,
    "timetoken": "14966804541029440"
}
←MembershipsMessage Storage→
  • Sending a message
  • Receive messages
  • Message Events
© PubNub Inc. - Privacy Policy