Language: EN

twitchlib

How to make a bot for Twitch in C# with TwitchLib

Today we are going to see how to make a bot that connects and interacts with a Twitch channel, developed in a .NET 6 application in C#.

This is a fairly common project today, because it is common for any developer who does live streams on Twitch to want to have their own channel bot, and give it a more professional and personalized look.

This type of development is more common in languages like JavaScript or Python, than in languages like C#. Fortunately, making a bot for Twitch in .NET is very simple thanks to the TwitchLib library.

TwitchLib is a library with a high degree of maturity. In fact, the first versions are more than 5 years old, although it is actively updated. It is compatible with chat services, whispers, API v5, and the new Helix API.

It is developed in .NET Standard 2.0, so it is compatible with .NET Framework 4.6.1 to 4.8, .NET Core 2.x, 3.x, .NET 5.0 and 6.0, Mono, Xamarin, UWP. So it is compatible with Windows, Linux and MacOS, Android and Unity.

The entire TwitchLib library is Open Source and the code is available on the project page https://github.com/TwitchLib/TwitchLib. I recommend taking a look because, after the latest refactorings, the code has become very organized and interesting.

How to use TwitchLib

TwitchLib is available as a NuGet package, so adding it to our project is very simple. We just have to do,

Install-Package TwitchLib

TwitchLib is divided into various modules, each of which allows you to connect to one of the Twitch services. modules

  • TwitchLib.Client
  • TwitchLib.Api
  • TwitchLib.PubSub
  • TwitchLib.Unity
  • TwitchLib.Extension
  • TwitchLib.Webhook

Each of these modules / services allows you to perform a series of actions. Likewise, they have different authentication requirements.

These differences are well documented on the project’s website. But, in summary,

  • Client, allows you to perform most actions associated with chat. Read and write messages, ban users, change chat mode, detect subscriptions, hosting, and raid.
  • API, allows you to perform more advanced actions, such as badges, bits, blocks, followers, hype train.

And the other modules are for more advanced and less frequent functionalities.

Bot Authentication on Twitch

In order to connect our bot to Twitch we will need to create its own account. This is a requirement according to the terms of service and, in addition, it avoids us the concern that by a fault we end up with our main account banned.

Once we have our bot’s account registered, we must obtain the parameters to authorize the connection by OAuth2.

To do this you have to register your application in the developer console https://dev.twitch.tv/console. By registering our App we will get a ClientId and a Secret.

Next, you have to choose one of the authentication methods, as explained in https://dev.twitch.tv/docs/authentication/. There are different authentication flows, recommended for each of the cases.

The “Authorization code grant flow” flow is sufficient for our case. Therefore, we must make a request to a URL, using the ClientId and the Secret that we obtained when registering our App.

Alternatively, in the case that we are only using the Client functionalities, we can alternatively use a third-party service such as https://twitchapps.com/tmi/. This collects the most common functions in a Twitch bot, and simplifies the authentication process a lot.

Using a third-party application always gives a certain concern from a security point of view. But TwitchApp is well known and therefore has some reliability.

Example of using TwitchLib

Finally, we are going to see a couple of simple examples of TwitchLib Client and API. These are based on the examples provided by the project’s own website.

Example of Twichlib.Client

To use Twichlib.Client we will need the bot’s UserName, and the OAuth key that we have obtained either through the request indicated in the Twitch documentation, or through a third-party App (it has the form oauth).

Console.WriteLine("Twitchlib Client demo");

var bot = new BotTwitch();
bot.Start();

Console.ReadLine();

public class BotTwitch
{
    TwitchClient? client;

    public BotTwitch()
    {           
    }

    private void Init()
    {
        var clientOptions = new ClientOptions
        {
            MessagesAllowedInPeriod = 750,
            ThrottlingPeriod = TimeSpan.FromSeconds(30)
        };

        WebSocketClient customClient = new WebSocketClient(clientOptions);
        client = new TwitchClient(customClient);

        ConnectionCredentials credentials = new ConnectionCredentials(Resources.username, Resources.oauth);
        client.Initialize(credentials);
    }

    public void Start()
    {
        if (client == null) Init();

        client.OnLog += Client_OnLog;
        client.OnConnected += Client_OnConnected;            
        client.OnJoinedChannel += Client_OnJoinedChannel;
        client.OnMessageReceived += Client_OnMessageReceived;
        client.OnChatCommandReceived += Client_OnChatCommandReceived;
        client.OnWhisperReceived += Client_OnWhisperReceived;
        client.OnNewSubscriber += Client_OnNewSubscriber;

        client.Connect();

        string channel_to_join = "luisllamas_es";
        client.JoinChannel(channel_to_join);
    }

    public void Stop()
    {
        client?.Disconnect();
        client = null;
    }

    private void Client_OnLog(object sender, OnLogArgs e)
    {
        //Console.WriteLine($"{e.DateTime.ToString()}: {e.BotUsername} - {e.Data}");
    }

    private void Client_OnConnected(object sender, OnConnectedArgs e)
    {
        Console.WriteLine($"Connected");
    }

    private void Client_OnJoinedChannel(object sender, OnJoinedChannelArgs e)
    {
        Console.WriteLine($"Joined to {e.Channel}");
        client?.SendMessage(e.Channel, "Hey guys! I am a bot connected via TwitchLib!");
    }

    private void Client_OnMessageReceived(object sender, OnMessageReceivedArgs e)
    {
        Console.WriteLine($"Message received: {e.ChatMessage.Message}");
    }

    private void Client_OnChatCommandReceived(object sender, OnChatCommandReceivedArgs e)
    {
        Console.WriteLine($"Command received: {e.Command.CommandText}");
    }

    private void Client_OnWhisperReceived(object sender, OnWhisperReceivedArgs e)
    {
        Console.WriteLine($"Whisper received: {e.WhisperMessage.Message}");
    }
    
    private void Client_OnNewSubscriber(object sender, OnNewSubscriberArgs e)
    {
        Console.WriteLine($"Suscribed: {e.Subscriber.DisplayName}");
    }
}

Example of Twichlib.API

To use Twichlib.API we will necessarily need the ClientId and the Secret that we have obtained when registering our App. With these values we will generate a connection Token in order to use the API.

Console.WriteLine("Twitchlib API demo");

TwitchLib.Api.TwitchAPI api = new TwitchLib.Api.TwitchAPI();
api.Settings.ClientId = Resources.client_id;
api.Settings.Secret = Resources.secret;

var token = await api.Auth.GetAccessTokenAsync();
api.Settings.AccessToken = token;

string channel_name = "luisllamas_es";
ExtFollowerService service = new ExtFollowerService(api);
var followersCount = await service.GetFollowersCountAsync(channel_name);

Console.Write(followersCount);
Console.ReadLine();

Download the code

All the code from this post is available for download on Github. github-full