Manage chat rooms for sessions and parties
Overview
In this guide, you will learn how to use the Chat service to send and receive messages between players, from within a session or party chat room. Because parties are managed by the Session service, the process is similar for both.
Throughout this guide, you will see the term topic referred to. It is interchangeable with chat rooms for the purposes of this guide. Both are a representation of a channel that chat messages can be sent through.
Players are automatically subscribed to the chat room when they join the session, and removed when they leave.
Goals
After you complete this guide, you should have an understanding of how to:
- Configure a session template to support chat
- Create a new session with a chat room
- Send messages through the session chat room
Prerequisites
Before you begin this guide, you should have an understanding of the following:
- You are familiar with our Lobby, Session and Chat services.
- You have installed the appropriate SDK for your game.
- You have access to your game Namespace in the Admin Portal.
Enabling Chat Rooms for Sessions
Chat rooms are managed at the session level, and can be enabled as part of the session template. To configure a session template to be chat enabled, you will need to do so through the API Docs for your environment, by following these instructions:
Open the Swagger page for your environment. For example, AccelByte Demo Environment.
Either choose to POST to create a new session template, or PUT to update an existing template. For either option, be sure to set the appropriate values for the request body.
Make sure you have targeted your game namespace, and add your request body with
textChat
set to true.Execute the request and verify the output indicates it ran successfully.
Sample request Body:
{
"name": "default",
"deployment": "default",
"inactiveTimeout": 60,
"inviteTimeout": 60,
"joinability": "OPEN",
"maxPlayers": 5,
"minPlayers": 1,
"type": "P2P",
“textChat”: “true”
}
Connecting to the Chat Service
Before a player is able to send or receive chat messages, they first need to be authenticated by the AccelByte Identity service. This will automatically connect them to the Chat service with their user account.
If you are using our OSS plugin, you will need to enable the following config value in the DefaultEngine.ini, so that users can automatically be connected to the Chat service after logging in.
[OnlineSubsystemAccelByte]
bAutoChatConnectAfterLoginSuccess=true
Creating a Session Chat Room
In general, there are no additional steps necessary to create a chat room for a session, if it is created using a template that is chat enabled. When using our services, you will find there are three ways to create a session with a chat room:
Through Matchmaking, when a match is found a game session will be created based on a session template. If the template is chat enabled, then the session chat room will automatically be created.
Creating a session manually using a session template. As long as the template is chat enabled, the session chat room will automatically be created.
Creating a session without a session template. This will require you to pass in the required session settings, including setting chat as true.
If you need to create a session without a template, then you can use this code sample to see how to define the session settings prior to calling CreateSession
with chat enabled.
- Unreal Engine
- OSS
- Unity
// This example illustrates how to manually create a party session with a chat room / topic.
FAccelByteModelsV2PartyCreateRequest CreatePartyRequest;
// Set text chat as true or the session.
CreatePartyRequest.TextChat = true;
// Bind this delegate to listen for the player being added to the session chat room / topic.
ApiClient->Chat.SetAddToTopicNotifDelegate(
Api::Chat::FAddToTopicNotif::CreateLambda([](const FAccelByteModelsChatUpdateUserTopicNotif& Result)
{
UE_LOG(LogTemp, Log, TEXT("Added to topic [%s] by user [%s]"), *Result.TopicId, *Result.SenderId);
})
);
// Create the new session with a chat room / topic.
ApiClient->Session.CreateParty(CreatePartyRequest,
THandler<FAccelByteModelsV2PartySession>::CreateLambda(
[](const FAccelByteModelsV2PartySession& Result)
{
UE_LOG(LogTemp, Log, TEXT("Party created"));
}),
FErrorHandler::CreateLambda([](int32 ErrorCode, FString ErrorMessage)
{
UE_LOG(LogTemp, Error, TEXT("Error code: %d\nError message:%s"), ErrorCode, *ErrorMessage);
})
);
// The OSS uses the Session Interface to create and manage parties and sessions.
// Define the session settings for the session you will be creating.
FOnlineSessionSettings NewSessionSettings;
NewSessionSettings.NumPrivateConnections = 4;
NewSessionSettings.Set(SETTING_SESSION_JOIN_TYPE, TEXT("INVITE_ONLY"));
NewSessionSettings.Set(SETTING_SESSION_TYPE, SETTING_SESSION_TYPE_PARTY_SESSION);
NewSessionSettings.Set(SETTING_SESSION_TEMPLATE_NAME, ConfigurationTemplateName);
// Set text chat as true in the session settings.
NewSessionSettings.Set(SETTING_SESSION_TEXTCHAT, true);
// Bind the delegate to listen for the successful creation of the new session.
FName SessionNameResponse = FName(TEXT(""));
auto OnCreateSessionCompleteDelegate = SessionInterface->AddOnCreateSessionCompleteDelegate_Handle(
FOnCreateSessionCompleteDelegate::CreateLambda([&SessionNameResponse](FName SessionName, bool bWasSuccessful)
{
SessionNameResponse = SessionName;
}));
// Bind this delegate to listen for the player being added to the session chat room / topic to acquire information about the room.
FString InTopicId;
auto TopicAddedHandle = ChatInterface->AddOnTopicAddedDelegate_Handle(
FOnTopicAddedDelegate::CreateLambda([&InTopicId](FString ChatTopicName, FString TopicId, FString SenderId)
{
InTopicId = TopicId;
}));
// Create the new session with a chat room / topic.
SessionInterface->CreateSession(LocalUserId.ToSharedRef().Get(), NAME_Session, NewSessionSettings);
// This example illustrates how to manually create a party session with a chat room / topic.
ApiClient apiClient = MultiRegistry.GetApiClient();
// Bind this delegate to listen for the player being added to the session chat room / topic.
apiClient.GetChat().AddedToTopic += topic =>
{
Debug.Log("Added to topic" + topic.topicId);
};
var createPartyRequest = new SessionV2PartySessionCreateRequest
{
configurationName = configurationTemplateName,
textChat = true // set text chat to true for this session.
};
// Create the new session with a chat room.
Result<SessionV2PartySession> createPartySessionResult = null;
apiClient.GetSession().CreateParty(createPartyRequest, result =>
{
if (!result.IsError)
{
Debug.Log("Party creation success");
}
});
The returned ID (RoomId
/ TopicId
) will have a prefix based on the type of session created:
s.
corresponds to a V2 game session chat room / topicp.
corresponds to V2 party session chat room / topic
Joining a Session Chat Room
When a player joins a session, they will automatically be subscribed to its chat room as a member without additional work.
You can register the appropriate delegate to listen for when other players are added to a chat room.
- Unreal Engine
- OSS
- Unity
// Bind this delegate to listen for the player being added to a session chat room / topic.
ApiClient->Chat.SetAddToTopicNotifDelegate(
Api::Chat::FAddRemoveFromTopicNotif::CreateLambda([](const FAccelByteModelsChatUpdateUserTopicNotif& Result)
{
UE_LOG(LogTemp, Log, TEXT("Added to topic [%s] by user [%s]"), *Result.TopicId, *Result.SenderId);
})
);
FString SessionV2RoomId;
// Bind this delegate to listen for the player being added to a session chat room / topic.
ChatInterface->AddOnChatRoomMemberJoinDelegate_Handle(
FOnChatRoomMemberJoinDelegate::CreateLambda([&SessionV2RoomId](const FUniqueNetId& UserId, const FChatRoomId& RoomId, const FUniqueNetId& MemberId)
{
// The user is automatically added to room / topic on creation or joining a session
const auto RoomType = FOnlineChatAccelByte::GetChatRoomType(RoomId);
if (RoomType == EAccelByteChatRoomType::PARTY_V2)
{
// this is session v2 room
SessionV2RoomId = RoomId;
}
// note: this is triggered for all users
if (UserId == MemberId)
{
// current user has joined the chat room
}
else
{
// another user has joined the chat room
}
}));
// Bind this delegate to listen for the player being added to a session chat room / topic.
apiClient.GetChat().AddedToTopic += topic =>
{
Debug.Log("Added to topic" + topic.topicId);
};
Leaving a Session Chat Room
When a player leaves a session, the Session service will manage removing them as a member of the chat room, including players who are kicked out of a session.
You can register the appropriate delegate to listen for when a player is removed from a chat room.
- Unreal Engine
- OSS
- Unity
// Bind this delegate to listen for the player being removed to a session chat room / topic.
ApiClient->Chat.SetRemoveFromTopicNotifDelegate(
Api::Chat::FAddRemoveFromTopicNotif::CreateLambda([](const FAccelByteModelsChatUpdateUserTopicNotif& Result)
{
UE_LOG(LogTemp, Log, TEXT("Removed from topic [%s] by user [%s]"), *Result.TopicId, *Result.SenderId);
})
);
// Bind this delegate to listen for the player being removed to a session chat room / topic.
FUniqueNetIdPtr ExitMemberId;
auto MemberExitRoomEventHandle = ChatInterface->AddOnChatRoomMemberExitDelegate_Handle(
FOnChatRoomMemberExitDelegate::CreateLambda([&ExitMemberId](const
FUniqueNetId& UserId, const FChatRoomId& RoomId, const FUniqueNetId& MemberId)
{
ExitMemberId = MemberId.AsShared();
}));
// Bind this delegate to listen for the player being removed to a session chat room / topic.
apiClient.GetChat().RemovedFromTopic += topic =>
{
Debug.Log("Removed from topic " + topic.topicId);
};
Sending a Chat Message in a Session
Once a player is in a chat room, they can start sending messages to the room for other players to receive. Because players can be subscribed to multiple chat rooms, you need to provide the appropriate room ID / topic ID with the message when requesting to send it to ensure it is delivered to the correct session chat room.
- Unreal Engine
- OSS
- Unity
FApiClientPtr ApiClient = FMultiRegistry::GetApiClient(TEXT("0"));
// Call SendChat from the Chat Interface to send the message.
// You will need to have acquired and stored the ID when the player joins the session chat room / topic.
ApiClient->Chat.SendChat(TEXT("topic_id"), TEXT("message to send"), Api::Chat::FSendChatResponse::CreateLambda(
[](const FAccelByteModelsChatSendChatResponse& Result)
{
UE_LOG(LogTemp, Log, TEXT("Send message to topic success."));
}),
FErrorHandler::CreateLambda([](int32 ErrorCode, FString ErrorMessage)
{
UE_LOG(LogTemp, Error, TEXT("Error code: %d\nError message:%s"), ErrorCode, *ErrorMessage);
})
);
// Bind this delegate to listen if the chat message was successfully sent through the service.
auto ChatRoomMessageSentHandle = ChatInterface->AddOnSendChatCompleteDelegate_Handle(
FOnSendChatCompleteDelegate::CreateLambda([](FString UserId, FString MsgBody, FString RoomId, bool bWasSuccessful)
{
// handle success or failure here
}));
TSharedPtr<const FUniqueNetId> LocalUserId;
// Call SendRoomChat from the Chat Interface to send the message.
// You will need to have acquired the RoomID when the player joins the session chat room, or by calling FOnlineChatAccelByte::GetJoinedRooms to get all joined rooms.
ChatInterface->SendRoomChat(LocalUserId.ToSharedRef().Get(), RoomId, TestRoomMessage);
// Call SendChatMessage after already in a Chat Room / Topic and have the Id stored.
// You will need to have acquired and stored the TopicId when the player joins the session topic.
apiClient.GetChat().SendChatMessage("topicId", "this is chat message", result =>
{
if (!result.IsError)
{
Debug.Log(("Success sending chat message"));
}
});
Receiving a Chat Message in a Session
To listen for chat messages from other players, register the appropriate delegate. It will be called when new messages are available along with the associated room ID / topic ID the message was sent to.
- Unreal SDK
- Online Subsystem
- Unity SDK
// Bind this delegate to listen for new messages sent from other players.
ApiClient->Chat.SetChatNotifDelegate(
Api::Chat::FChatNotif::CreateLambda([](const FAccelByteModelsChatNotif& Result)
{
UE_LOG(LogTemp, Log, TEXT("Receive chat! From[%s] content: [%s]"), *Result.From, *Result.Message);
})
);
FString ReceivedChatRoomMessage = TEXT("");
// Listen to chat room message received notification
auto ChatRoomMessageReceivedHandle = ChatInterface->AddOnChatRoomMessageReceivedDelegate_Handle(
FOnChatRoomMessageReceivedDelegate::CreateLambda(
[&ReceivedChatRoomMessage](const FUniqueNetId& UserId, const FChatRoomId& RoomId, const TSharedRef<FChatMessage> ChatMessage)
{
ReceivedChatRoomMessage = ChatMessage->GetBody();
}));
FString ReceivedPrivateMessage = TEXT("");
// Listen to private message received notification
auto ChatRoomMessageReceivedHandle =
ChatInterface->AddOnChatPrivateMessageReceivedDelegate_Handle(
FOnChatPrivateMessageReceivedDelegate::CreateLambda(
[&ReceivedPrivateMessage](const FUniqueNetId& UserId, const TSharedRef<FChatMessage>& ChatMessage)
{
ReceivedPrivateMessage = ChatMessage->GetBody();
}));
// Bind this delegate to listen for new messages sent from other players.
apiClient.GetChat().NewChatMessage += chat =>
{
Debug.Log("Receive new chat " + chat.message + " from user id " + chat.from);
};