Create custom events
Learn how Unreal Chat SDK handles events before creating your own custom chat events.
Event handling
PubNub events
With a standard PubNub SDK like the Unreal SDK, building a chat app requires additional steps:
- Subscribe to channels to receive messages
- Add event listeners to handle messages, signals, and events
Unreal Chat SDK handles this automatically. All listener methods return a function to stop receiving events and unsubscribe from the channel.
| 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). |
Unreal 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).
Unreal Chat SDK automatically emits these event types when a user:
- Reports a message (
reportevent type for messages) - 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 the PubNub Pub/Sub API with Publish() or Signal() methods.
Listen to events with:
ListenForEvents()- for current events emitted viaSignal()orPublish()GetEventsHistory()- for historical events emitted viaPublish()
History retrieval
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_ADMIN_CHANNEL - Trigger:
Report()method on theMessageobject - Listener:
ListenForEvents()(current) orGetEventsHistory()(historical) on theChatobject - Sample use case: Message moderation. You might want to create a UI for an operational dashboard to monitor and manage all reported messages.
- Payload:
1payload: {
2 // content of the flagged message
3 text: string;
4 // reason for flagging the message
5 reason: string;
6 // channel where message was flagged
7 reportedMessageChannelId: string;
8 // timetoken of the flagged message
9 reportedMessageTimetoken: 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:
1payload: {
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:
1payload: {
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:
1payload: {
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: The same channel where messages are published.
- 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:
1payload: {
2 // type of a channel to which a user was invited (direct or group)
3 channelType: this.type || "unknown",
4 // ID of the channel to which a user was invited
5 channelId: this.id,
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 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:
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:
1payload: {
2 // ID of the channel on which the user's moderation restrictions were set or lifted
3 channelId: `PUBNUB_INTERNAL_MODERATION.String`
4 // ID of the channel on which the user's moderation restrictions were set or lifted preceded by the PUBNUB_INTERNAL_MODERATION. prefix",
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:
EmitChatEvent()- create and send custom eventsListenForEvents()- listen for incoming eventsGetEventsHistory()- retrieve historical events
Create and send events
EmitChatEvent() constructs and sends events with your custom payload, similar to SendText() for messages.
Method signature
This method takes the following parameters:
- Blueprint
- C++ / Input parameters
1Chat->EmitChatEvent(
2 EPubnubChatEventType ChatEventType,
3 FString ChannelID,
4 FString Payload
5);
| Parameter | Description |
|---|---|
ChatEventType *Type: EPubnubChatEventTypeDefault: n/a | Type of events: PCET_TYPING, PCET_REPORT, PCET_RECEIPT, PCET_MENTION, PCET_INVITE, PCET_CUSTOM, PCET_MODERATION. Use PCET_CUSTOM for full control over event payload and emitting method. |
ChannelIDType: FStringDefault: n/a | Channel where you want to send the events. |
Payload *Type: FStringDefault: 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
This method doesn't return any value.
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#include "Kismet/GameplayStatics.h"
2#include "PubnubChatSubsystem.h"
3#include "JsonObjectConverter.h" // Assumed include for JSON conversion utilities.
4
5UGameInstance* GameInstance = UGameplayStatics::GetGameInstance(this);
6UPubnubChatSubsystem* PubnubChatSubsystem = GameInstance->GetSubsystem<UPubnubChatSubsystem>();
7
8// Initialize the chat.
9UPubnubChat* Chat = PubnubChatSubsystem->InitChat("demo", "demo", "my_user");
10UPubnubChannel* Channel = Chat->GetChannel("support");
11
12// Prepare the JSON payload.
13TSharedPtr<FJsonObject> JsonPayload = MakeShareable(new FJsonObject);
14JsonPayload->SetStringField("chatID", "chat1234");
15JsonPayload->SetStringField("timestamp", "2022-04-30T10:30:00Z");
show all 28 linesReceive current events
ListenForEvents() watches a channel for new custom events and handles them via a callback, similar to Connect() for messages.
Method signature
- Blueprint
- C++ / Input parameters
1Chat->ListenForEvents(
2 FString ChannelID,
3 EPubnubChatEventType ChatEventType,
4 FOnPubnubEventReceived EventCallback
5);
| Parameter | Description |
|---|---|
ChannelIDType: FStringDefault: n/a | Channel you want to listen to for events. |
ChatEventType *Type: EPubnubChatEventTypeDefault: n/a | Type of events: PCET_TYPING, PCET_REPORT, PCET_RECEIPT, PCET_MENTION, PCET_INVITE, PCET_CUSTOM, PCET_MODERATION. |
EventCallback *Type: FOnPubnubEventReceivedDefault: 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
This method doesn't return any value.
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#include "Kismet/GameplayStatics.h"
2#include "PubnubChatSubsystem.h"
3
4UGameInstance* GameInstance = UGameplayStatics::GetGameInstance(this);
5UPubnubChatSubsystem* PubnubChatSubsystem = GameInstance->GetSubsystem<UPubnubChatSubsystem>();
6
7UPubnubChat* Chat = PubnubChatSubsystem ->InitChat("demo", "demo", "my_user");
8
9// Create a pubnub response delegate
10// you MUST implement your own callback function to handle the response
11FOnPubnubEventReceived EventCallback;
12EventCallback.BindDynamic(this, &AMyActor::OnMPubnubEventResponseReceived);
13
14Chat->ListenForEvents(
15 FString("CUSTOMER-SATISFACTION-CREW"),
show all 18 lines1void AMyActor::OnPubnubEventResponseReceived(const FString& ChannelID, const FString& Payload)
2{
3 // Parse the JSON payload
4 TSharedPtr<FJsonObject> JsonObject;
5 TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(Payload);
6
7 if (FJsonSerializer::Deserialize(Reader, JsonObject) && JsonObject.IsValid())
8 {
9 FString TriggerWord;
10 if (JsonObject->TryGetStringField("triggerWord", TriggerWord))
11 {
12 if (TriggerWord.Equals("frustrated", ESearchCase::IgnoreCase))
13 {
14 UE_LOG(LogTemp, Log, "Frustrated customer event detected!");
15 // Handle the frustrated customer event
show all 25 linesGet 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.
Method signature
- Blueprint
- C++ / Input parameters
1Chat->GetEventsHistory(
2 FString ChannelID,
3 FString StartTimetoken,
4 FString EndTimetoken,
5 int Count = 100
6);
| Parameter | Description |
|---|---|
ChannelID *Type: FStringDefault: n/a | Channel from which you want to pull historical messages. |
StartTimetokenType: FStringDefault: n/a | Timetoken delimiting the start of a time slice (exclusive) to pull events from. For details, refer to the Fetch History section. |
EndTimetokenType: FStringDefault: n/a | Timetoken delimiting the end of a time slice (inclusive) to pull events from. For details, refer to the Fetch History section. |
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
| Parameter | Description |
|---|---|
FPubnubEventsHistoryWrapperType: struct | Returned object containing two fields: events and isMore. |
→ EventsType: TArray<FPubnubEvent> | Array listing the requested number of historical events objects. |
→ IsMoreType: bool | Info whether there are more historical events to pull. |
FPubnubEvent
| Parameter | Description |
|---|---|
TimetokenType: FString | Timetoken of the event. |
ChannelIDType: FString | Channel the event occured on. |
User IDType: FString | User ID associated with the event. |
PayloadType: FString | Event payload. |
TypeType: EPubnubChatEventType | Type of the event. |
EPubnubChatEventType
| Value | Description |
|---|---|
PCET_TYPING | Indicates a user is typing a message. Displayed as Typing. |
PCET_REPORT | Represents an event where a message has been flagged or reported for offensive content. Displayed as Report. |
PCET_RECEIPT | Confirms receipt of a message or event. Displayed as Receipt. |
PCET_MENTION | Indicates that a user has been mentioned in a message. Displayed as Mention. |
PCET_INVITE | Represents an invitation event typically sent to a specific user. Displayed as Invite. |
PCET_CUSTOM | Custom event type for specialized behavior or use cases. Displayed as Custom. |
PCET_MODERATION | Represents an event related to content moderation actions. Displayed as Moderation. |
Sample code
Fetch the last 10 historical events from the CUSTOMER-SATISFACTION-CREW channel.
1#include "Kismet/GameplayStatics.h"
2#include "PubnubChatSubsystem.h"
3
4UGameInstance* GameInstance = UGameplayStatics::GetGameInstance(this);
5UPubnubChatSubsystem* PubnubChatSubsystem = GameInstance->GetSubsystem<UPubnubChatSubsystem>();
6
7UPubnubChat* Chat = PubnubChatSubsystem ->InitChat("demo", "demo", "my_user");
8
9FPubnubEventsHistoryWrapper EventsHistory = Chat->GetEventsHistory("CUSTOMER-SATISFACTION-CREW", "", "", 10);