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 JavaScript 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.
| Entity | Method | Events 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 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 (
reportevent type) - Starts/Stops typing a message on a channel (
typingevent type) - Mentions someone else in the message (
mentionevent type) - Reads a message published on a channel (
receiptevent type) - Invites another user to join a channel (
inviteevent type) - Mutes a user, bans them, or removes these restrictions (
moderationevent 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 thepublish()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 thesignal()orpublish()method.getEventsHistory()to get historical events that were emitted with thepublish()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 theMessageobject - Listener:
streamMessageReports()(current) andgetMessageReportsHistory(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()andstopTyping()methods on theChannelobject - Listener:
getTyping()on theChannelobject - 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
Userobject, 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 thecurrentUsermethod on theChatobject. - Trigger:
sendText()method on theChannelobject - Listener:
listenForEvents()(current) orgetEventsHistory()(historical) on theChatobject - 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 theMembershipobject) is used for all events related to message read receipts. - Target: The same channel where messages are published.
- Trigger:
markAllMessagesAsRead()method on theChatobject, thesetLastReadMessageTimetoken()method on theMembershipobject, and thesetLastReadMessage()method on theMembershipobject - Listener:
streamReadReceipts()(current) on theChatobject - 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()andinviteMultiplemethods on theChannelobject - Listener:
listenForEvents()(current) orgetEventsHistory()(historical) on theChatobject - 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, whereuser_idis the ID of the moderated user. - Trigger:
setRestrictions()methods on theChannel,Chat, andUserobjects - Listener:
listenForEvents()(current) orgetEventsHistory()(historical) on theChatobject - 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
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:
1chat.emitEvent({
2 // in case of "mention" events
3 user: string;
4 // for every other type of event
5 channel: string;
6 type: "typing" | "report" | "receipt" | "mention" | "invite" | "moderation" | "custom";
7 // only respected for "custom" events
8 method?: "signal" | "publish";
9 payload: EventPayloads["type"] | any;
10}): Promise<PubNub.SignalResponse> | Promise<PubNub.PublishResponse>
Input
| Parameter | Description |
|---|---|
userType: stringDefault: n/a | User for which the mention is emitted. |
channelType: stringDefault: n/a | Channel where you want to send the events. |
type *Type: stringDefault: n/a | Type of events. Use custom for full control over event payload and emitting method. |
methodType: stringDefault: n/a | PubNub method you want to use to send your events. You can choose between the signal() method for small-sized and short-lived events or publish() method for events with larger payload that you want to store in history (Chat SDK enables history for events on the publish() method by default). Read PubNub docs for differences between messages and signals. |
payload *Type: EventPayloads[type] or anyDefault: 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 struture for other types of events. |
Output
| Type | Description |
|---|---|
Promise<PubNub.SignalResponse> or Promise<PubNub.PublishResponse> | 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.
1chat.emitEvent({
2 channel: "CUSTOMER-SATISFACTION-CREW";
3 type: "custom";
4 method: "publish"
5 payload: {
6 "chatID": "chat1234",
7 "timestamp": "2022-04-30T10:30:00Z",
8 "customerID": "customer5678",
9 "triggerWord": "frustrated"
10 };
11}): any
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:
1chat.listenForEvents<"type">({
2 // in case of "mention" events
3 user: string;
4 // for every other type of event
5 channel: string;
6 type: "typing" | "report" | "receipt" | "mention" | "invite" | "moderation" | "custom";
7 // only respected for "custom" events
8 method?: "signal" | "publish";
9 callback: (event: Event<"type">) => unknown;
10}): () => void
Input
| Parameter | Description |
|---|---|
userType: stringDefault: n/a | User whose mention events you want to listen for. |
channelType: stringDefault: n/a | Channel you want to listen to for events. |
type *Type: stringDefault: n/a | Type of events to listen for. |
methodType: stringDefault: n/a | PubNub method used to send events you listen for. |
callback *Type: (event: Event<"type">) => unknownDefault: n/a | Callback function passed as a parameter. It defines the custom behavior to be executed whenever an event is detected on the specified channel. |
Output
| Type | Description |
|---|---|
() => 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// simulated event data received
2const eventData = {
3 "chatID": "chat1234",
4 "timestamp": "2022-04-30T10:30:00Z",
5 "customerID": "customer5678",
6 "triggerWord": "frustrated"
7};
8
9// example function to handle the "frustrated" event and satisfy the customer
10function handleFrustratedEvent(eventData) {
11 // extract relevant information from the event data
12 const customerID = eventData.customerID;
13 const timestamp = eventData.timestamp;
14 const triggerWord = eventData.triggerWord;
15
show all 37 linesGet 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:
1chat.getEventsHistory({
2 channel: string;
3 startTimetoken?: string;
4 endTimetoken?: string;
5 count?: number;
6}): Promise<{
7 events: Event[];
8 isMore: boolean;
9}>
Input
| Parameter | Description |
|---|---|
channel *Type: stringDefault: n/a | Channel from which you want to pull historical messages. |
startTimetokenType: stringDefault: n/a | Timetoken delimiting the start of a time slice (exclusive) to pull events from. For details, refer to the Fetch History section. |
endTimetokenType: stringDefault: n/a | Timetoken delimiting the end of a time slice (inclusive) to pull events from. For details, refer to the Fetch History section. |
countType: numberDefault: 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
| Parameter | Description |
|---|---|
Promise<>Type: object | Returned object containing two fields: events and isMore. |
→ eventsType: Event[] | Array listing the requested number of historical events objects. |
→ isMoreType: 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 theUserobject - Listener:
listenForEvents()(current) orgetEventsHistory()(historical) on theChatobject - 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}