On this page

Create custom events

Learn how Chat SDK handles events before creating your own custom chat events.

Event handling

PubNub events

With a standard PubNub SDK, building a chat app requires additional steps:

  • Subscribe to channels to receive messages
  • Add event listeners to handle messages, signals, and events

Chat SDK handles this automatically. All listener methods return a function to stop receiving events and unsubscribe from the channel.

EntityMethodEvents handled
Channel
streamUpdates() or streamUpdatesOn()
(Un)Subscribe the current user to/from a channel and start/stop getting all objects events of type channel.
User
streamUpdates() or streamUpdatesOn()
(Un)Subscribe the current user to/from a channel and start/stop getting all objects events of type uuid.
Message
streamUpdates() or streamUpdatesOn()
(Un)Subscribe the current user to/from a channel and start/stop getting all messageAction events (for message and message reactions changes) of type added or removed.
Membership
streamUpdates() or streamUpdatesOn()
(Un)Subscribe the current user to/from a channel and start/stop getting all objects events of type membership.
Channel
connect()
(Un)Subscribe the current user to/from a channel and start/stop getting all message events of type text.
Channel
getTyping()
(Un)Subscribe the current user to/from a channel and start/stop getting all signal events of type typing.
Channel
streamPresence()
(Un)Subscribe the current user to/from a channel and start/stop getting all presence events of type action (responsible for monitoring when users join, leave the channels, or when their channel connection times out and they get disconnected).

Chat SDK wraps server responses into entities like Channel, Message, and User with methods and properties for building your app's UI.

Chat events

Events are separate entities that carry data payloads and can trigger business logic (for example, the Typing Indicator starts or stops based on typing events).

Chat SDK automatically emits these event types when a user:

  • Reports a message (report event type)
  • Starts/Stops typing a message on a channel (typing event type)
  • Mentions someone else in the message (mention event type)
  • Reads a message published on a channel (receipt event type)
  • Invites another user to join a channel (invite event type)
  • Mutes a user, bans them, or removes these restrictions (moderation event type)

All event types use the PubNub Pub/Sub API with one of these methods:

  • publish() - for events requiring history (always enabled in Chat SDK)
  • signal() - for short-lived events without history (for example, typing indicators)

Listen to events with:

  • listenForEvents() - for current events emitted via signal() or publish()
  • getEventsHistory() - for historical events emitted via publish()
History limitations

getEventsHistory() cannot filter by event type. It returns all events emitted via publish() on the channel within the specified timeframe.

Each event type has a fixed payload structure documented below.

Events for reported messages

  • Type: report
  • PubNub method: PubNub method used to send events you listen for. publish() (with history) is used for all events related to message reporting.
  • Target: PUBNUB_INTERNAL_MODERATION_{channel_id}
  • Trigger: report() method on the Message object
  • Listener: streamMessageReports() (current) and getMessageReportsHistory (historical)
  • Sample use case: Message moderation. You might want to create a UI for an operational dashboard to monitor and manage all reported messages.
  • Payload:
1@SerialName("report")
2 class Report(
3 // content of the flagged message
4 val text: String? = null,
5 // reason for flagging the message
6 val reason: String,
7 // timetoken of the flagged message
8 val reportedMessageTimetoken: Long? = null,
9 // channel where message was flagged
10 val reportedMessageChannelId: String? = null,
11 // author of the flagged message
12 val reportedUserId: String?,
13 ) : EventContent()

Events for typing indicator

  • Type: typing
  • PubNub method: PubNub method used to send events you listen for. signal() (without history) is used for all events related to typing.
  • Target: The same channel where messages are published.
  • Trigger: startTyping() and stopTyping() methods on the Channel object
  • Listener: getTyping() on the Channel object
  • Sample use case: Typing indicator. You might want to show graphically on the channel that another channel member is typing or has stopped typing a message.
  • Payload:
1@SerialName("typing")
2 class Typing(
3 // value showing whether someone is typing or not
4 val value: Boolean
5 ) : EventContent()

Events for mentions

  • Type: mention
  • PubNub method: PubNub method used to send events you listen for. publish() (with history) is used for all events related to mentions.
  • Target: Unlike in other event types, a target for mention events is equal to a user ID. This ID is treated as a user-specific channel and is used to send system notifications about changes concerning a User object, such as creating, updating, or deleting that user. The channel name is equal to the ID (id) of the user and you can retrieve it by calling the currentUser method on the Chat object.
  • Trigger: sendText() method on the Channel object
  • Listener: listenForEvents() (current) or getEventsHistory() (historical) on the Chat object
  • Sample use case: User mentions. You might want to receive notifications for all events emitted when you are mentioned in a parent or thread channel.
  • Payload:
1@SerialName("mention")
2 class Mention(
3 // timetoken of the message where someone is mentioned
4 val messageTimetoken: Long,
5 // channel on which the message with mention was sent
6 val channel: String,
7 // parent channel on which the message with mention was sent
8 val parentChannel: String? = null
9 ) : EventContent()

Events for read receipts

  • Type: receipt
  • PubNub method: PubNub method used to send events you listen for. signal() (with history persisted as the last read message on the Membership object) is used for all events related to message read receipts.
  • Target: The same channel where messages are published.
  • Trigger: markAllMessagesAsRead() method on the Chat object, the setLastReadMessageTimetoken() method on the Membership object, and the setLastReadMessage() method on the Membership object
  • Listener: streamReadReceipts() (current) on the Chat object
  • Sample use case: Read receipts. You might want to indicate on a channel - through avatars or some other indicator - that a message was read by another user/other users.
  • Payload:
1@SerialName("receipt")
2 class Receipt(
3 // timetoken of the read message
4 val messageTimetoken: Long
5 ) : EventContent()

Events for channel initations

  • Type: invite
  • PubNub method: PubNub method used to send events you listen for. publish() (with history) is used for all events related to channel invitations.
  • Target: An event is sent to the ID of the invited user (user channel with the name same as the user ID).
  • Trigger: invite() and inviteMultiple methods on the Channel object
  • Listener: listenForEvents() (current) or getEventsHistory() (historical) on the Chat object
  • Sample use case: Channel invitations. You might want to notify users that they were invited to join a channel.
  • Payload:
1@SerialName("invite")
2 class Invite(
3 // type of a channel to which a user was invited (direct or group)
4 val channelType: ChannelType,
5 // ID of the channel to which a user was invited
6 val channelId: String
7 ) : EventContent()

Events for user moderation

  • Type: moderation
  • PubNub method: PubNub method used to send events you listen for. publish() (with history) is used for all events related to user restrictions.
  • Target: An event is sent to the PUBNUB_INTERNAL_MODERATION.[user_id] channel, where user_id is the ID of the moderated user.
  • Trigger: setRestrictions() methods on the Channel, Chat, and User objects
  • Listener: listenForEvents() (current) or getEventsHistory() (historical) on the Chat object
  • Sample use case: User moderation. You might want to notify users when they were muted, banned, or when you remove these restrictions from them.
  • Payload:
1@SerialName("moderation")
2 class Moderation(
3 // ID of the channel on which the user's moderation restrictions were set or lifted
4 val channelId: PUBNUB_INTERNAL_MODERATION.[string],
5 // type of restriction: whether a user was muted, banned, or at least one of these restrictions was removed ("lifted")
6 val restriction: RestrictionType,
7 // reason for muting or banning the user
8 val reason: String? = null
9 ) : EventContent()

Custom events

The custom event type carries custom payloads for additional business logic. Methods:

  • emitEvent() - create and send custom events
  • listenForEvents() - listen for incoming events
  • getEventsHistory() - retrieve historical events

Create and send events

emitEvent() constructs and sends events with your custom payload, similar to sendText() for messages.

Method signature

This method takes the following parameters:

1fun <T : EventContent> emitEvent(
2 channelId: String,
3 payload: T,
4 mergePayloadWith: Map<String, Any>? = null,
5 ): PNFuture<PNPublishResult>
Input
* required
ParameterDescription
channelId
Type: String
Default:
n/a
Channel where you want to send the events.
payload *
Type: T
Default:
n/a
The payload of the emitted event. Use one of [EventContent] subclasses, for example: [EventContent.Mention], [EventContent.TextMessageContent] or [EventContent.Custom] for sending arbitrary data.
mergePayloadWith *
Type: Map<String, Any>
Default:
n/a
Metadata in the form of key-value pairs you want to pass as events from your chat app. Can contain anything in case of custom events, but has a predefined structure for other types of events.
Output
TypeDescription
PNFuture<PNPublishResult>
Result of the PubNub Publish or Signal call.

Sample code

You want to monitor a high-priority channel with a keyword spotter that identifies dissatisfaction words like "annoyed," "frustrated," or "angry." Suppose a message sent by any of the customers present on this channel contains any of these words. In that case, you want to resend it (with relevant metadata) to a separate technical channel (CUSTOMER-SATISFACTION-CREW) that's monitored by the team responsible for customer satisfaction.

1val channelId = "CUSTOMER-SATISFACTION-CREW"
2val customPayloads = EventContent.Custom(
3 data = mapOf(
4 "chatID" to "chat1234",
5 "timestamp" to "2022-04-30T10:30:00Z",
6 "customerID" to "customer5678",
7 "triggerWord" to "frustrated"
8 )
9)
10
11chat.emitEvent(channelId = channelId, payload = customPayloads).async { result ->
12 result.onSuccess { pnPublishResult: PNPublishResult ->
13 println("Message successfully emitted having timetoken: ${pnPublishResult.timetoken}")
14 }.onFailure { ex: PubNubException ->
15 println("Failed to emitEvent.")
show all 18 lines

Receive current events

listenForEvents() watches a channel for new custom events and handles them via a callback, similar to connect() for messages.

Method signature

This method takes the following parameters:

1fun <reified T : EventContent> Chat.listenForEvents(
2 channelId: String,
3 customMethod: EmitEventMethod = EmitEventMethod.PUBLISH,
4 noinline callback: (event: Event<T>) -> Unit
5): AutoCloseable
Input
* required
ParameterDescription
T *
Type: reified T : EventContent
Default:
n/a
Reified type parameter bounded by the EventContent interface, allowing access to type information at runtime.
channelId *
Type: String
Default:
n/a
Channel to listen for new events.
customMethod
Type: String
Default:
n/a
An optional method used for emitting events. Used when listening to Custom events. If not provided, defaults to PUBLISH.
callback *
Type: noinline (event: Event<T>) -> Unit
Default:
n/a
A lambda function that is called with an Event<T> as its parameter. It defines the custom behavior to be executed whenever an event is detected on the specified channel.
Output
TypeDescription
AutoCloseable
Interface that lets you stop receiving updates by invoking the close() method.

Sample code

Monitor a channel for frustrated customer events. When such an event occurs, the handleFrustratedEvent function responds with a message acknowledging the customer's frustration and offering assistance.

1// simulated event data received
2val eventData = mapOf(
3 "chatID" to "chat1234",
4 "timestamp" to "2022-04-30T10:30:00Z",
5 "customerID" to "customer5678",
6 "triggerWord" to "frustrated"
7);
8
9// example function to handle the "frustrated" event and satisfy the customer
10fun handleFrustratedEvent(eventData: EventContent.Custom) {
11 // extract relevant information from the event data
12 val customerID = eventData.data["customerID"]
13 val timestamp = eventData.data["timestamp"]
14 val triggerWord = eventData.data["triggerWord"]
15
show all 29 lines

Get historical events

getEventsHistory() retrieves historical events from a channel, similar to getHistory() for messages. Results cannot be filtered by type and include all events emitted via publish() in the specified timeframe.

Method signature

This method takes the following parameters:

1chat.getEventsHistory(
2 channelId: String,
3 startTimetoken: Long? = null,
4 endTimetoken: Long? = null,
5 count: Int?
6
7): PNFuture<GetEventsHistoryResult>

Input

* required
ParameterDescription
channelId *
Type: String
Default:
n/a
Channel from which you want to pull historical messages.
startTimetoken
Type: Long
Default:
n/a
Timetoken delimiting the start of a time slice (exclusive) to pull events from. For details, refer to Message Persistence.
endTimetoken
Type: Long
Default:
n/a
Timetoken delimiting the end of a time slice (inclusive) to pull events from. For details, refer to Message Persistence.
count
Type: Int
Default:
100
Number of historical events to return for the channel in a single call. You can pull a maximum number of 100 events in a single call.

Output

ParameterDescription
PNFuture<GetEventsHistoryResult>
Type: object
Returned object containing two fields: events and isMore.
 → events
Type: Set<Event<EventContent>>
Array listing the requested number of historical events objects.
 → isMore
Type: Boolean
Info whether there are more historical events to pull.

Sample code

Fetch the last 10 historical events from the CUSTOMER-SATISFACTION-CREW channel.

1chat.getEventsHistory(
2 channelId = "CUSTOMER-SATISFACTION-CREW",
3 count = 10
4).async { result ->
5 // ...
6}
Last updated on