Created
January 19, 2024 16:46
-
-
Save recursivecodes/15cee808a55970ba5bedb247d3de72c1 to your computer and use it in GitHub Desktop.
A script to integrate Amazon IVS chat into a Unity game.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using System.Threading.Tasks; | |
using UnityEngine; | |
using UnityEngine.UI; | |
using UnityEngine.Networking; | |
using NativeWebSocket; | |
using TMPro; | |
[System.Serializable] | |
public class ChatAttributes | |
{ | |
public string username; | |
public static ChatAttributes CreateFromJSON(string jsonString) | |
{ | |
return JsonUtility.FromJson<ChatAttributes>(jsonString); | |
} | |
} | |
[System.Serializable] | |
public class ChatSender | |
{ | |
public string UserId; | |
public ChatAttributes Attributes; | |
public static ChatSender CreateFromJSON(string jsonString) | |
{ | |
return JsonUtility.FromJson<ChatSender>(jsonString); | |
} | |
} | |
[System.Serializable] | |
public class ChatMessage | |
{ | |
public string Type; | |
public string Id; | |
public string RequestId; | |
public string Content; | |
public ChatSender Sender; | |
public static ChatMessage CreateFromJSON(string jsonString) | |
{ | |
return JsonUtility.FromJson<ChatMessage>(jsonString); | |
} | |
} | |
[System.Serializable] | |
public class ChatToken | |
{ | |
public System.DateTime sessionExpirationTime; | |
public string token; | |
public System.DateTime tokenExpirationTime; | |
public static ChatToken CreateFromJSON(string jsonString) | |
{ | |
return JsonUtility.FromJson<ChatToken>(jsonString); | |
} | |
} | |
[System.Serializable] | |
public class ChatTokenRequest | |
{ | |
public string chatArn; | |
public string username; | |
public string userId; | |
public ChatTokenRequest(string chatArn, string username, string userId) | |
{ | |
this.chatArn = chatArn; | |
this.username = username; | |
this.userId = userId; | |
} | |
} | |
public class IVSChat : MonoBehaviour | |
{ | |
TMP_Text chatContainer; | |
ScrollRect scrollRect; | |
WebSocket websocket; | |
async Task<ChatToken> GetChatToken() | |
{ | |
using UnityWebRequest www = new UnityWebRequest("http://localhost:3000/chat-token"); | |
ChatTokenRequest tokenRequest = new ChatTokenRequest( | |
"arn:aws:ivschat:us-east-1:639934345351:room/0wgOPVl4ZRdu", | |
"IVS HUD Chat Demo User", | |
System.Guid.NewGuid().ToString() | |
); | |
www.uploadHandler = new UploadHandlerRaw(System.Text.Encoding.ASCII.GetBytes(JsonUtility.ToJson(tokenRequest))); | |
www.downloadHandler = new DownloadHandlerBuffer(); | |
www.method = UnityWebRequest.kHttpVerbPOST; | |
www.SetRequestHeader("Content-Type", "application/json"); | |
var request = www.SendWebRequest(); | |
while (!request.isDone) | |
{ | |
await Task.Yield(); | |
}; | |
var response = www.downloadHandler.text; | |
if (www.result != UnityWebRequest.Result.Success) | |
{ | |
Debug.Log(www.error); | |
return default; | |
} | |
else | |
{ | |
return ChatToken.CreateFromJSON(www.downloadHandler.text); | |
} | |
} | |
async Task<WebSocket> ConnectChat() | |
{ | |
var chatToken = await GetChatToken(); | |
websocket = new WebSocket("wss://edge.ivschat.us-east-1.amazonaws.com", chatToken.token); | |
websocket.OnOpen += () => | |
{ | |
Debug.Log("Chat Connection: Open"); | |
}; | |
websocket.OnError += (e) => | |
{ | |
Debug.Log("Chat Connection: Error " + e); | |
}; | |
websocket.OnClose += (e) => | |
{ | |
Debug.Log("Chat Connection: Closed"); | |
}; | |
websocket.OnMessage += (bytes) => | |
{ | |
var msgString = System.Text.Encoding.UTF8.GetString(bytes); | |
Debug.Log("Chat Message Received! " + msgString); | |
ChatMessage chatMsg = ChatMessage.CreateFromJSON(msgString); | |
Debug.Log(chatMsg); | |
if (chatMsg.Type == "MESSAGE") | |
{ | |
chatContainer.text += "<b>" + chatMsg.Sender.Attributes?.username + "</b>: " + chatMsg.Content + "\n"; | |
scrollRect.verticalNormalizedPosition = 0; | |
} | |
}; | |
return websocket; | |
} | |
async void Start() | |
{ | |
chatContainer = GetComponent<TMP_Text>(); | |
scrollRect = chatContainer.transform.parent.parent.parent.GetComponent<ScrollRect>(); | |
await ConnectChat(); | |
await websocket.Connect(); | |
} | |
void Update() | |
{ | |
#if !UNITY_WEBGL || UNITY_EDITOR | |
websocket?.DispatchMessageQueue(); | |
#endif | |
} | |
async void OnDestroy() | |
{ | |
Debug.Log("OnDestroy"); | |
if (websocket != null) await websocket.Close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment