Create custom events

Before creating your own custom chat events, learn how Chat SDK handles PubNub and chat-specific events.

Event handling

PubNub events

If you were to use a standard PubNub SDK, such as the Swift SDK, to build a chat app, you would have to perform additional steps as part of your PubNub initialization:

  • Explicitly subscribe to the chosen channel(s) to receive messages.
  • Add event listeners for your app to receive and handle all messages, signals, and events sent to the channel(s) you are subscribed to.

Luckily, the Chat SDK does this work automatically for you as part of other methods you will run on various entities to build and work with your chat app.

All these methods also return a function you can invoke to stop receiving events of a given type and unsubscribe from the channel. Follow the links to method descriptions for details and examples.

EntityMethodEvents handled
ChannelstreamUpdates() or streamUpdatesOn()(Un)Subscribe the current user to/from a channel and start/stop getting all objects events of type channel.
UserstreamUpdates() or streamUpdatesOn()(Un)Subscribe the current user to/from a channel and start/stop getting all objects events of type uuid.
MessagestreamUpdates() 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.
MembershipstreamUpdates() or streamUpdatesOn()(Un)Subscribe the current user to/from a channel and start/stop getting all objects events of type membership.
Channelconnect()(Un)Subscribe the current user to/from a channel and start/stop getting all message events of type text.
ChannelgetTyping()(Un)Subscribe the current user to/from a channel and start/stop getting all signal events of type Typing.
ChannelstreamPresence()(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 all events returned as HTTP responses from the server into meaningful and handy entities, like Channel, Message, User. These objects contain methods you can invoke to build your chat app and parameters you can display on your app's UI.

Chat events

Events, just like messages, are separate entities in the Chat SDK that carry data as a payload. Contrary to messages, however, events are not merely data transmitters but can trigger additional business logic. For example, in the Chat SDK, the Typing Indicator feature relies on events - based on whether a user is typing or not, the typing indicator starts or stops.

Chat SDK handles a few intrinsic types of such events that get emitted automatically 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 underneath the PubNub Pub/Sub API and one of these methods:

  • publish() - if event history is required, like for storing reported messages. For the purpose of the Chat SDK, history is always enabled when emitting an event with the publish() method.
  • signal() - if no event history is required, like in the case of the typing indicator that relies on short-lived signals.

Different Chat SDK methods emit (handle) different chat event types. For example, the sendText() method called on the Channel object emits Mention events because the IDs of the mentioned users are always passed as part of published messages.

To listen to those events, Chat SDK uses two methods:

  • listenForEvents() for the current events that are emitted with the signal() or publish() method.
  • getEventsHistory() to get historical events that were emitted with the publish() method.
Events history limitations

The getEventsHistory() method uses PubNub Message Persistence API which has limitations - you cannot filter the results by type. Calling this method would return all event types that happened on a given channel in a given timeframe as long as they were emitted with the publish() method that stores history. Check custom events for an example showing this method.

The payload structure of the chat events is fixed and depends on the event type.

Read the subsections to get a better overview of each event type - check how they work and get some ideas on using them in your chat app to trigger additional business logic.

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

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

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

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

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

Custom events

Chat SDK provides an additional type of events called custom. As the type name suggests, they are meant to let you carry your custom payloads and use them to perform additional business logic in your chat app.

With Chat SDK, you can:

  • Trigger such custom events using the emitEvent() method.
  • Listen to them with the listenForEvents() method.
  • Get all historical events using the getEventsHistory() method.

Create and send events

emitEvent() handles (constructs and sends) events with your custom payload.

In its logic, you can compare this method to the sendText() method used for sending new messages.

Method signature

This method takes the following parameters:

chat.emitEvent<T : EventContent>(
channelId: String,
payload: T,
mergePayloadWith otherPayload: [String: JSONCodable]? = nil,
completion: ((Swift.Result<Timetoken, Error>) -> Void)? = nil
)
Input
ParameterTypeRequiredDefaultDescription
channelIdStringYes (all non-Mention events)n/aChannel where you want to send the events.
payloadTYesn/aType of events. Use custom for full control over event payload and emitting method.
mergePayloadWith[String: JSONCodable]Yesn/aMetadata 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
((Swift.Result<Timetoken, Error>) -> Void)Result of the PubNub Publish or Signal call.

Basic usage

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.

// Define a custom payload that conforms to EventContent
class CustomEventPayload: EventContent, JSONCodable {
let chatID: String
let timestamp: String
let customerID: String
let triggerWord: String

init(chatID: String, timestamp: String, customerID: String, triggerWord: String) {
self.chatID = chatID
self.timestamp = timestamp
self.customerID = customerID
self.triggerWord = triggerWord
}
}

show all 36 lines

Receive current events

listenForEvents() lets you watch a selected channel for any new custom events emitted by your chat app. You can decide what to do with the incoming custom events and handle them using the callback function.

In its logic, you can compare this method to the connect() method used for receiving new messages.

Method signature

This method takes the following parameters:

chat.listenForEvents<T: EventContent>(
type: T.Type,
channelId: String,
customMethod: EmitEventMethod = .publish,
callback: @escaping ((EventWrapper<T>) -> Void)
) -> AutoCloseable
Input
ParameterTypeRequiredDefaultDescription
typeT.TypeYesn/aType parameter allowing access to type information at runtime.
channelIdStringYesn/aChannel to listen for new events.
customMethodEmitEventMethodNon/aAn optional custom method for emitting events. If not provided, defaults to .publish. Available values: .publish and .signal.
callback@escaping ((EventWrapper<T>) -> Void)Yesn/aA lambda function that is called with an EventWrapper<T> as its parameter. It defines the custom behavior to be executed whenever an event is detected on the specified channel.
Output
TypeDescription
AutoCloseableInterface that lets you stop receiving updates by invoking the close() method.

Basic usage

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.

// Define a custom payload that conforms to EventContent
class CustomEventPayload: EventContent, JSONCodable {
let chatID: String
let timestamp: String
let customerID: String
let triggerWord: String

init(chatID: String, timestamp: String, customerID: String, triggerWord: String) {
self.chatID = chatID
self.timestamp = timestamp
self.customerID = customerID
self.triggerWord = triggerWord
}
}

show all 54 lines

Get historical events

getEventsHistory() lets you get historical events from a selected channel.

In its logic, you can compare this method to the getHistory() method used for receiving historical messages. Similarly to this method, you cannot filter the results by type, so you'll get all events emitted with the publish() method that happened on a given channel in a given timeframe (not only Custom events).

Method signature

This method takes the following parameters:

chat.getEventsHistory(
channelId: String,
startTimetoken: Timetoken? = nil,
endTimetoken: Timetoken? = nil,
count: Int = 100,
completion: ((Swift.Result<(events: [EventWrapper<EventContent>], isMore: Bool), Error>) -> Void)? = nil
)

Input

ParameterTypeRequiredDefaultDescription
channelIdStringYesn/aChannel from which you want to pull historical messages.
startTimetokenTimetokenNon/aTimetoken delimiting the start of a time slice (exclusive) to pull events from. For details, refer to the Fetch History section.
endTimetokenTimetokenNon/aTimetoken delimiting the end of a time slice (inclusive) to pull events from. For details, refer to the Fetch History section.
countIntNo100Number 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

ParameterTypeDescription
((Swift.Result<(events: [EventWrapper<EventContent>], isMore: Bool), Error>) -> Void)objectReturned object containing two fields: events and isMore.
 → eventsSet<Event<EventContent>>Array listing the requested number of historical events objects.
 → isMoreBoolInfo whether there are more historical events to pull.

Basic usage

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

// Define the custom payload type conforming to EventContent
class CustomEventContent: EventContent, JSONCodable {
let chatID: String
let timestamp: String
let customerID: String
let triggerWord: String

init(chatID: String, timestamp: String, customerID: String, triggerWord: String) {
self.chatID = chatID
self.timestamp = timestamp
self.customerID = customerID
self.triggerWord = triggerWord
}
}

show all 59 lines
Last updated on