Create custom events
Before creating your own custom chat events, learn how Unity Chat SDK handles PubNub and chat-specific events.
Event handling
PubNub events
Add corresponding event listeners for your app to receive and handle all messages, signals, and events sent to the channel(s) you are subscribed to.
Follow the links to method descriptions for details and examples.
| Entity | Method(s) | Events handled |
|---|---|---|
Channel | OnChannelUpdate and AddListenerToChannelsUpdate() | (Un)Subscribe the current user to/from a channel and start/stop getting all objects events of type channel. |
User | OnUserUpdated and AddListenerToUsersUpdate() | (Un)Subscribe the current user to/from a channel and start/stop getting all objects events of type uuid. |
Message | OnMessageUpdated and AddListenerToMessagesUpdate() | (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 | OnMembershipUpdated and AddListenerToMembershipsUpdate() | (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 | OnUsersTyping | (Un)Subscribe the current user to/from a channel and start/stop getting all Signal events of type typing. |
Channel | OnPresenceUpdate | (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 events
Events, just like messages, are separate entities in the Unity 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, the Typing Indicator feature relies on events - based on whether a user is typing or not, the typing indicator starts or stops.
Unity 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 Unity 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 Unity 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, Unity Chat SDK uses different methods:
-
SetListeningFor{Type}Events()methods for the current events that are emitted with theSignal()orPublish()method.The
{Type}stands for a given type of emitted events:SetListeningForReportEvents(),SetListeningForCustomEvents(),SetListeningForMentionEvents(),SetListeningForInviteEvents(),SetListeningForModerationEvents(). -
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:
SetListeningForReportEvents()(current) - 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{
2 "text": "string // content of the flagged message (optional)",
3 "reason": "string // reason for flagging the message",
4 "reportedMessageTimetoken": "string // timetoken of the flagged message (optional)",
5 "reportedMessageChannelId": "string // channel where message was flagged (optional)",
6 "reportedUserId": "string // author of the flagged message (optional)"
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()andstopTyping()methods on theChannelobject - Listener: Handler of the
OnUsersTypingevents - 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{
2 "value": "boolean // value showing whether someone is typing or not"
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
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 theGetCurrentUser()method on theChatobject. - Trigger:
SendText()method on theChannelobject - Listener:
SetListeningForMentionEvents()(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:
1{
2 "messageTimetoken": "string // timetoken of the message where someone is mentioned",
3 "channel": "string // channel on which the message with mention was sent"
4}
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:
SetListeningForReadReceiptsEvents()(current) on theChannelobject - 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{
2 "messageTimetoken": "string // timetoken of the read message"
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()andInviteMultiplemethods on theChannelobject - Listener:
SetListeningForInviteEvents()(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:
1{
2 "channelType": "ChannelType || \"unknown\" // type of a channel to which a user was invited (direct or group)",
3 "channelId": "string // ID of the channel to which a user was invited"
4}
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 ID of the moderated user (user channel with the name same as the user ID) preceded by the
PUBNUB_INTERNAL_MODERATION.prefix, likePUBNUB_INTERNAL_MODERATION.[UserId]. - Trigger:
SetRestrictions()methods on theChannel,Chat, andUserobjects - Listener:
SetListeningForModerationEvents()(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:
1{
2 "channelId": "PUBNUB_INTERNAL_MODERATION.String // ID of the channel on which the user's moderation restrictions were set or lifted preceded by the PUBNUB_INTERNAL_MODERATION. prefix",
3 "restriction": "\"muted\" | \"banned\" | \"lifted\" // type of restriction: whether a user was muted, banned, or at least one of these restrictions was removed",
4 "reason": "string // reason for muting or banning the user (optional)"
5}
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
SetListeningForCustomEvents()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 PubnubChatEventType type,
3 string channelId,
4 string jsonPayload
5)
Input
| Parameter | Description |
|---|---|
type *Type: PubnubChatEventTypeDefault: n/a | Type of events (Typing, Report, Receipt, Mention, Invite, Custom, Moderation). Use Custom for full control over event payload and emitting method. |
channelIdType: stringDefault: n/a | Channel where you want to send the events. |
jsonPayload *Type: stringDefault: 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
An awaitable Task<ChatOperationResult>.
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
Receive current events
SetListeningForCustomEvents() 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:
1// start listening
2channel.SetListeningForCustomEvents(bool listen)
3
4// triggered custom event
5public event Action<CustomEvent> OnCustomEvent;
6// needs a corresponding event handler
7void EventHandler(CustomEvent event)
Input
| Parameter | Description |
|---|---|
listen *Type: boolDefault: n/a | Channel you want to listen to for events. |
Output
This method doesn't return anything.
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
Get historical events
GetEventsHistory() lets you get historical events from a selected channel.
In its logic, you can compare this method to the FetchHistory() 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 string channelId,
3 string startTimeToken,
4 string endTimeToken,
5 int count
6)
Input
| Parameter | Description |
|---|---|
channelId *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. |
countType: intDefault: 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
| Type | Description |
|---|---|
Task<ChatOperationResult<EventsHistoryWrapper>> | An awaitable Task with the object containing the filtered, sorted, and paginated list of historical events. |
Sample code
Fetch the last 10 historical events from the CUSTOMER-SATISFACTION-CREW channel.
1