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.

EntityMethod(s)Events handled
ChannelOnChannelUpdate and AddListenerToChannelsUpdate()(Un)Subscribe the current user to/from a channel and start/stop getting all objects events of type channel.
UserOnUserUpdated and AddListenerToUsersUpdate()(Un)Subscribe the current user to/from a channel and start/stop getting all objects events of type uuid.
MessageOnMessageUpdated and AddListenerToMessagesUpdate()(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.
MembershipOnMembershipUpdated and AddListenerToMembershipsUpdate()(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.
ChannelOnUsersTyping(Un)Subscribe the current user to/from a channel and start/stop getting all Signal events of type typing.
ChannelOnPresenceUpdate(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 (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 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 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 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:

  • StartListeningFor{Type}Events() methods for the current events that are emitted with the Signal() or Publish() method.

    The {Type} stands for a given type of emitted events: StartListeningForReportEvents(), StartListeningForCustomEvents(), StartListeningForMentionEvents(), StartListeningForInviteEvents(), StartListeningForModerationEvents().

  • 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: StartListeningForReportEvents() (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:
{
"text": "string // content of the flagged message (optional)",
"reason": "string // reason for flagging the message",
"reportedMessageTimetoken": "string // timetoken of the flagged message (optional)",
"reportedMessageChannelId": "string // channel where message was flagged (optional)",
"reportedUserId": "string // author of the flagged message (optional)"
}

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: Handler of the OnUsersTyping events
  • 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:
{
"value": "boolean // value showing whether someone is typing or not"
}

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 TryGetCurrentUser() method on the Chat object.
  • Trigger: SendText() method on the Channel object
  • Listener: StartListeningForMentionEvents() (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:
{
"messageTimetoken": "string // timetoken of the message where someone is mentioned",
"channel": "string // channel on which the message with mention was sent"
}

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:
{
"messageTimetoken": "string // timetoken of the read message"
}

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: StartListeningForInviteEvents() (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:
{
"channelType": "ChannelType || \"unknown\" // type of a channel to which a user was invited (direct or group)",
"channelId": "string // ID of the channel to which a user was invited"
}

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).
  • Trigger: SetRestrictions() methods on the Channel, Chat, and User objects
  • Listener: StartListeningForModerationEvents() (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:
{
"channelId": "string // ID of the channel on which the user's moderation restrictions were set or lifted",
"restriction": "\"muted\" | \"banned\" | \"lifted\" // type of restriction: whether a user was muted, banned, or at least one of these restrictions was removed",
"reason": "string // reason for muting or banning the user (optional)"
}

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 StartListeningForCustomEvents() 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(
PubnubChatEventType type,
string channelId,
string jsonPayload
)
Input
ParameterTypeRequiredDefaultDescription
typePubnubChatEventTypeYesn/aType of events (Typing, Report, Receipt, Mention, Invite, Custom, Moderation). Use Custom for full control over event payload and emitting method.
channelIdstringYes (all non-Mention events)n/aChannel where you want to send the events.
jsonPayloadstringYesn/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 struture for other types of events.
Output

This method doesn't return any data.

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.

chat.EmitEvent(
type: PubnubChatEventType.Custom,
channelId: "CUSTOMER-SATISFACTION-CREW",
jsonPayload:
"{\"chatID\": \"chat1234\"," +
"\"timestamp\": \"2022-04-30T10:30:00Z\"," +
"\"customerID\": \"customer5678\"," +
"\"triggerWord\": \"frustrated\"}"
);

Receive current events

StartListeningForCustomEvents() 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:

// start listening
chat.StartListeningForCustomEvents(string channelId)

// triggered custom event
public event Action<CustomEvent> OnCustomEvent;
// needs a corresponding event handler
void EventHandler(CustomEvent event)
Input
ParameterTypeRequiredDefaultDescription
channelIdstringYesn/aChannel you want to listen to for events.
Output

This method doesn't return any data.

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.

// simulated event data received
string eventData =
"\"chatID\":\"chat1234\"," +
"\"timestamp\":\"2022-04-30T10:30:00Z\"," +
"\"customerID\":\"customer5678\"," +
"\"triggerWord\":\"frustrated\"";

// example function to handle the "frustrated" event and satisfy the customer
void HandleFrustratedEvent(string eventData) {
//example basic JSON parsing using Newtonsoft JSON.NET
var data = JsonConvert.DeserializeObject<Dictionary<string,string>>(eventData);

// extract relevant information from the event data
string customerID = data["customerID"];
string timestamp = data["timestamp"];
show all 35 lines

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:

chat.GetEventsHistory(
string channelId,
string startTimeToken,
string endTimeToken,
int count
)

Input

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

TypeDescription
EventsHistoryWrapperAn object containing the filtered, sorted, and paginated list of historical events.

Basic usage

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

// define the required parameters
string channelId = "CUSTOMER-SATISFACTION-CREW";
int count = 10;

// fetch the last 10 historical events
EventsHistoryWrapper history = chat.GetEventsHistory(channelId, "", "", count);

// process the returned historical events
foreach (var eventItem in history.Events)
{
Console.WriteLine($"Timestamp: {eventItem.TimeToken}, Event type: {eventItem.Type}");
}
Last updated on