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 JavaScript 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
onUpdated() or onDeleted() (streamUpdates() deprecated; streamUpdatesOn() remains supported)
(Un)Subscribe the current user to/from a channel and start/stop getting all objects events of type channel.
User
onUpdated() or onDeleted() (streamUpdates() deprecated; streamUpdatesOn() remains supported)
(Un)Subscribe the current user to/from a channel and start/stop getting all objects events of type uuid.
Message
onUpdated() (streamUpdates() deprecated; streamUpdatesOn() remains supported)
(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
onUpdated() or onDeleted()
(Un)Subscribe the current user to/from a channel and start/stop getting all objects events of type membership.
Channel
onMessageReceived()
(Un)Subscribe the current user to/from a channel and start/stop getting all message events of type text.
Channel
onTypingChanged()
(Un)Subscribe the current user to/from a channel and start/stop getting all signal events of type typing.
Channel
onPresenceChanged()
(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).
Channel
onCustomEvent()
(Un)Subscribe the current user to/from a channel and start/stop getting all custom message events.

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

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: onMessageReported() (current), streamMessageReports() (deprecated), 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:
1type ReportEventPayload = {
2 // content of the flagged message
3 text?: string
4 // reason for flagging the message
5 reason: string
6 // timetoken of the flagged message
7 reportedMessageTimetoken?: string
8 // channel where message was flagged
9 reportedMessageChannelId?: string
10 // author of the flagged message
11 reportedUserId?: string
12}

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:
1type TypingEventPayload = {
2 // value showing whether someone is typing or not
3 value: boolean
4}

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:
1type MentionEventPayload = {
2 // timetoken of the message where someone is mentioned
3 messageTimetoken: string
4 // channel on which the message with mention was sent
5 channel: string
6}

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: onReadReceiptReceived() (current) on the Channel object, streamReadReceipts() (deprecated)
  • 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:
1type ReceiptEventPayload = {
2 // timetoken of the read message
3 messageTimetoken: string
4}

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:
1type InviteEventPayload = {
2 // type of a channel to which a user was invited (direct or group)
3 channelType: ChannelType || "unknown"
4 // ID of the channel to which a user was invited
5 channelId: string
6}

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:
1type ModerationEventPayload = {
2 // ID of the channel on which the user's moderation restrictions were set or lifted
3 channelId: PUBNUB_INTERNAL_MODERATION.[string]
4 // type of restriction: whether a user was muted, banned, or at least one of these restrictions was removed
5 restriction: "muted" | "banned" | "lifted"
6 // reason for muting or banning the user
7 reason?: string
8}

Custom events

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

  • channel.emitCustomEvent() - create and send custom events on a channel
  • channel.onCustomEvent() - listen for incoming custom events on a channel
  • getEventsHistory() - retrieve historical events

The CustomEventData type has the following shape:

1type CustomEventData = {
2 timetoken: string
3 userId: string
4 payload: any
5 type?: string
6}

Create and send events

channel.emitCustomEvent() constructs and sends a custom event on the channel, similar to sendText() for messages.

icon

Under the hood

Method signature

This method takes the following parameters:

1channel.emitCustomEvent(
2 payload: any,
3 options?: {
4 messageType?: string
5 storeInHistory?: boolean
6 }
7): Promise<PublishResponse>
Input
* required
ParameterDescription
payload *
Type: any
Default:
n/a
Metadata in the form of key-value pairs you want to pass as a custom event from your chat app.
options
Type: object
Default:
n/a
Optional configuration for the event.
 → messageType
Type: string
Default:
n/a
Optional type label to attach to the event payload for filtering on the receiving side.
 → storeInHistory
Type: boolean
Default:
true
If true, the event is stored in Message Persistence.
Output
TypeDescription
Promise<PublishResponse>
Result of the PubNub Publish 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// reference the target channel
2const satisfactionChannel = await chat.getChannel("CUSTOMER-SATISFACTION-CREW")
3
4await satisfactionChannel.emitCustomEvent(
5 {
6 chatID: "chat1234",
7 timestamp: "2022-04-30T10:30:00Z",
8 customerID: "customer5678",
9 triggerWord: "frustrated"
10 },
11 { messageType: "frustration-alert" }
12)

Deprecated method

Deprecated

chat.emitEvent() is deprecated. Use channel.emitCustomEvent() instead.

1chat.emitEvent({
2 channel: string;
3 type: "typing" | "report" | "receipt" | "mention" | "invite" | "moderation" | "custom";
4 method?: "signal" | "publish";
5 payload: EventPayloads["type"] | any;
6}): Promise<PubNub.SignalResponse> | Promise<PubNub.PublishResponse>

Receive current events

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

icon

Under the hood

Method signature

This method takes the following parameters:

1channel.onCustomEvent(
2 callback: (event: CustomEventData) => void,
3 options?: {
4 messageType?: string
5 }
6): () => void
Input
* required
ParameterDescription
callback *
Type: (event: CustomEventData) => void
Default:
n/a
Callback function invoked whenever a custom event is received on the channel.
options
Type: object
Default:
n/a
Optional configuration for filtering events.
 → messageType
Type: string
Default:
n/a
When provided, only events with a matching type field are passed to the callback.
Output
TypeDescription
() => void
Function you can call to disconnect (unsubscribe) from the channel and stop receiving events.

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// reference the channel to monitor
2const satisfactionChannel = await chat.getChannel("CUSTOMER-SATISFACTION-CREW")
3
4// example function to handle the "frustrated" event and satisfy the customer
5function handleFrustratedEvent(eventData: CustomEventData) {
6 const { customerID, timestamp, triggerWord } = eventData.payload
7
8 const response = `Thank you for reaching out. We're sorry to hear that you're ${triggerWord}. Our team is here to help and will work to resolve your concerns as quickly as possible. Your satisfaction is important to us.`
9
10 sendResponseToCustomerChat(customerID, timestamp, response)
11}
12
13// listen for custom events of type "frustration-alert"
14const stopListening = satisfactionChannel.onCustomEvent(
15 (event) => {
show all 24 lines

Deprecated method

Deprecated

chat.listenForEvents() is deprecated. Use entity-level methods instead: channel.onTypingChanged(), channel.onMessageReported(), channel.onReadReceiptReceived(), channel.onCustomEvent(), user.onMentioned(), user.onInvited(), user.onRestrictionChanged().

1chat.listenForEvents<"type">({
2 channel: string;
3 type: "typing" | "report" | "receipt" | "mention" | "invite" | "moderation" | "custom";
4 method?: "signal" | "publish";
5 callback: (event: Event<"type">) => unknown;
6}): () => void

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.

icon

Under the hood

Method signature

This method takes the following parameters:

1chat.getEventsHistory({
2 channel: string;
3 startTimetoken?: string;
4 endTimetoken?: string;
5 count?: number;
6}): Promise<{
7 events: Event[];
8 isMore: boolean;
9}>

Input

* required
ParameterDescription
channel *
Type: string
Default:
n/a
Channel from which you want to pull historical messages.
startTimetoken
Type: string
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: string
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: number
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
Promise<>
Type: object
Returned object containing two fields: events and isMore.
 → events
Type: Event[]
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 {
3 channel: "CUSTOMER-SATISFACTION-CREW"
4 count: 10
5 }
6)

Events for reported users (deprecated)

  • Type: report
  • PubNub method: PubNub method used to send events you listen for. publish() (with history) is used for all events related to user reporting.
  • Target: PUBNUB_INTERNAL_ADMIN_CHANNEL
  • Trigger: DEPRECATED_report() method on the User object
  • Listener: listenForEvents() (current) or getEventsHistory() (historical) on the Chat object
  • Sample use case: User moderation. You might want to create a UI for an operational dashboard to monitor and manage all reported users.
  • Payload:
1payload: {
2 // reason for flagging the user
3 reason: string;
4 // flagged user
5 reportedUserId: string;
6}
Last updated on