Skip to content

Instantly share code, notes, and snippets.

@kwea123
Created October 25, 2021 12:57
Show Gist options
  • Save kwea123/66a7eb25c3d9d2190c0cbba6bb488848 to your computer and use it in GitHub Desktop.
Save kwea123/66a7eb25c3d9d2190c0cbba6bb488848 to your computer and use it in GitHub Desktop.
Youtube API that fetches live stream chat room in Unity.
using System.Collections;
using System.Collections.Generic;
using System;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using SimpleJSON;
public class YoutubeAPI : MonoBehaviour
{
public string videoId;
public bool isActive = false;
public float pullEveryXSeconds;
private const string youtubeAPIURL = "https://www.googleapis.com/youtube/v3";
private string apiKey;
private HashSet<string> viewedETags;
public Queue<Tuple<string, string, string>> history;
IEnumerator Start()
{
StreamReader reader = new StreamReader("Assets/Resources/youtubeapikey.txt");
apiKey = reader.ReadToEnd();
if (videoId != "") // videoId must be provided at the beginning!!
{
viewedETags = new HashSet<string>();
history = new Queue<Tuple<string, string, string>>();
// get chatId from videoId
var chatIDURL = $"{youtubeAPIURL}/videos?id={videoId}&key={apiKey}&part=liveStreamingDetails";
var req = UnityWebRequest.Get(chatIDURL);
yield return req.SendWebRequest();
var json = JSON.Parse (req.downloadHandler.text);
var liveChatId = json["items"][0]["liveStreamingDetails"]["activeLiveChatId"].ToString();
// form chatURL
var chatURL = $"{youtubeAPIURL}/liveChat/messages?liveChatId={liveChatId}&part=snippet,authorDetails&key={apiKey}";
// pulling chats ...
while(true)
{
if (!isActive)
yield return new WaitForSeconds(1);
else
{
req = UnityWebRequest.Get(chatURL);
yield return req.SendWebRequest();
json = JSON.Parse (req.downloadHandler.text);
var chats = json["items"];
foreach (var chat in chats)
{
var etag = chat.Value["etag"];
if (viewedETags.Contains(etag))
continue;
var snip = chat.Value["snippet"];
var author = chat.Value["authorDetails"];
// other useful keys:
// snippet:
// "publishedAt": "2021-10-14T06:41:08.539641+00:00", (UTC time)
// authorDetails:
// "profileImageUrl": "https://yt3.ggpht.com/ytc/AKedOLQjdwY5hM1Olj3PdpNs-f8eARuZfqxn6eKo36WaDA=s88-c-k-c0x00ffffff-no-rj",
// "isVerified": false,
// "isChatOwner": true,
// "isChatSponsor": false,
// "isChatModerator": false
Debug.Log ($"from {videoId}, "+author["displayName"].ToString() +
" 說: " + snip["displayMessage"].ToString());
var tuple = new Tuple<string, string, string>
(author["displayName"].ToString(),
snip["displayMessage"].ToString(),
snip["publishedAt"].ToString());
history.Enqueue(tuple);
viewedETags.Add(etag);
}
// wait a little before next query.
// yield return new WaitForSeconds(json["pollingIntervalMillis"].AsFloat/1000);
yield return new WaitForSeconds(pullEveryXSeconds);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment