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 like the Swift 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 actions 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)

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()
Limitation

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:
1public class Report: EventContent {
2 public let text: String?
3 public let reason: String
4 public let reportedMessageTimetoken: Timetoken?
5 public let reportedMessageChannelId: String?
6 public let reportedUserId: String?
7}

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:
1public class Typing: EventContent {
2 public let value: Bool
3}

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:
1public class Mention: EventContent {
2 public let messageTimetoken: Timetoken
3 public let channel: String
4 public let parentChannel: String?
5}

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:
1public class Receipt: EventContent {
2 public let messageTimetoken: Timetoken
3}

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:
1public class Invite: EventContent {
2 public let channelType: ChannelType
3 public let channelId: String
4}

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:

1chat.emitEvent<T : EventContent>(
2 channelId: String,
3 payload: T,
4 mergePayloadWith otherPayload: [String: JSONCodable]? = nil
5) async throws -> Timetoken
Input
* required
ParameterDescription
channelId
Type: String
Default:
n/a
Channel where you want to send the events.
payload *
Type: T
Default:
n/a
Type of events. Use custom for full control over event payload and emitting method.
mergePayloadWith *
Type: [String: JSONCodable]
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
ParameterDescription
Timetoken
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.

1// Define a custom payload that conforms to EventContent
2class CustomEventPayload: EventContent, JSONCodable {
3 let chatID: String
4 let timestamp: String
5 let customerID: String
6 let triggerWord: String
7
8 init(chatID: String, timestamp: String, customerID: String, triggerWord: String) {
9 self.chatID = chatID
10 self.timestamp = timestamp
11 self.customerID = customerID
12 self.triggerWord = triggerWord
13 }
14}
15
show all 32 lines

Receive current events

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

Method signature

This method takes the following parameters:

1chat.listenForEvents<T: EventContent>(
2 type: T.Type,
3 channelId: String,
4 customMethod: EmitEventMethod = .publish
5 ) -> AsyncStream<EventWrapper<T>>
Input
* required
ParameterDescription
type *
Type: T.Type
Default:
n/a
Type parameter allowing access to type information at runtime.
channelId *
Type: String
Default:
n/a
Channel to listen for new events.
customMethod
Type: EmitEventMethod
Default:
n/a
An optional custom method for emitting events. If not provided, defaults to .publish. Available values: .publish and .signal.
Output
ParameterDescription
AsyncStream<EventWrapper<T>>
An asynchronous stream that produces a value each time a new event of the specified type is emitted.

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// Define a custom payload that conforms to EventContent
2class CustomEventPayload: EventContent, JSONCodable {
3 let chatID: String
4 let timestamp: String
5 let customerID: String
6 let triggerWord: String
7
8 init(chatID: String, timestamp: String, customerID: String, triggerWord: String) {
9 self.chatID = chatID
10 self.timestamp = timestamp
11 self.customerID = customerID
12 self.triggerWord = triggerWord
13 }
14}
15
show all 64 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: Timetoken? = nil,
4 endTimetoken: Timetoken? = nil,
5 count: Int = 100
6) async throws -> (events: [EventWrapper<EventContent>], isMore: Bool)

Input

* required
ParameterDescription
channelId *
Type: String
Default:
n/a
Channel from which you want to pull historical messages.
startTimetoken
Type: Timetoken
Default:
n/a
Timetoken delimiting the start of a time slice (exclusive) to pull events from. For details, refer to the Fetch History section.
endTimetoken
Type: Timetoken
Default:
n/a
Timetoken delimiting the end of a time slice (inclusive) to pull events from. For details, refer to the Fetch History section.
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
(events: [EventWrapper<EventContent>], isMore: Bool)
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: Bool
Info whether there are more historical events to pull.

Sample code

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

1// Define the custom payload type conforming to EventContent
2class CustomEventContent: EventContent, JSONCodable {
3 let chatID: String
4 let timestamp: String
5 let customerID: String
6 let triggerWord: String
7
8 init(chatID: String, timestamp: String, customerID: String, triggerWord: String) {
9 self.chatID = chatID
10 self.timestamp = timestamp
11 self.customerID = customerID
12 self.triggerWord = triggerWord
13 }
14}
15
show all 29 lines
Last updated on