Гайд YouTube Stream Chat API

  • 702
  • 2
  • 237
Нам понадобится нугет пакеты
1. Google.Apis.YouTube.v3.Data
2. YouTube.Base.Clients

Теперь создадим приложение в консоли гугла
1. Заходим на Google Console
2. Создаем проект
3. В APIs & Services нажимаем Library
4. Ищет там YouTube Data API v3
5. Нажимаем Manage
6. Нажимаем CREDENTIALS
7. Создаём OAuth client ID
1660641158030.png

7.1 Application Type = Desktop APP
7.2 Сохраняем Your Client ID и Your Client Secret
7.3 Используем Your Client ID и Your Client Secret в примере ниже

Код прослушивателя чата:
internal class Program
{
    public static string clientID = "";
    public static string clientSecret = "";

    private static SemaphoreSlim fileLock = new SemaphoreSlim(1);

    public static readonly List<OAuthClientScopeEnum> scopes = new List<OAuthClientScopeEnum>()
    {
        OAuthClientScopeEnum.ChannelMemberships,
        OAuthClientScopeEnum.ManageAccount,
        OAuthClientScopeEnum.ManageData,
        OAuthClientScopeEnum.ManagePartner,
        OAuthClientScopeEnum.ManagePartnerAudit,
        OAuthClientScopeEnum.ManageVideos,
        OAuthClientScopeEnum.ReadOnlyAccount,
        OAuthClientScopeEnum.ViewAnalytics,
        OAuthClientScopeEnum.ViewMonetaryAnalytics
    };
    private static Channel channel;
    private static LiveBroadcast broadcast;
    private static ChatClient client;
    private static void Main(string[] args)
    {
        Task.Run(async () =>
        {
            try
            {
                System.Console.WriteLine("Initializing connection");

                YouTubeConnection connection = await YouTubeConnection.ConnectViaLocalhostOAuthBrowser(clientID, clientSecret, scopes);

                if (connection != null)
                {
                    channel = await connection.Channels.GetMyChannel();

                    //Channel channel = await connection.Channels.GetChannelByID("");

                    if (channel != null)
                    {
                        System.Console.WriteLine("Connection successful. Logged in as: " + channel.Snippet.Title);

                        broadcast = await connection.LiveBroadcasts.GetMyActiveBroadcast();

                        System.Console.WriteLine("Connecting chat client!");

                        client = new ChatClient(connection);
                        client.OnMessagesReceived += Client_OnMessagesReceived;

                        if (await client.Connect(broadcast))
                        {
                            System.Console.WriteLine("Live chat connection successful!");

                            if (await connection.LiveBroadcasts.GetMyActiveBroadcast() != null)
                            {
                                await client.SendMessage("Hello World!");
                            }
                            else
                            {
                                System.Console.WriteLine("Broadcast not enable!");
                            }

                            while (true) { }
                        }
                        else
                        {
                            System.Console.WriteLine("Failed to connect to live chat");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.ToString());
            }
        });

        System.Console.ReadLine();
    }

    private static void Client_OnMessagesReceived(object sender, IEnumerable<LiveChatMessage> messages)
    {
        foreach (LiveChatMessage message in messages)
        {
            try
            {
                if (message.Snippet.HasDisplayContent.GetValueOrDefault())
                {
                    
                    System.Console.WriteLine(string.Format("{0}: {1}", message.AuthorDetails.DisplayName, message.Snippet.DisplayMessage));
                }


            }
            catch (Exception ex)
            {
                
            }
        }
    }
}
 
Сверху Снизу