twitchlib

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

  • 5 min

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

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

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

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

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 applications. Therefore, it is compatible with Windows, Linux and MacOS, Android and Unity.

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 several modules, each of which allows connection to one of Twitch’s services.

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

Each of these modules/services allows performing 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 performing most actions associated with chat. Reading and writing messages, banning users, changing chat mode, detecting subscriptions, host, and raid.
  • API, allows performing 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

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, furthermore, it saves us the worry that a failure might get our main account banned.

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

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

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

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

Alternatively, if we are only using the Client functionalities, we can alternatively use a third-party service like https://twitchapps.com/tmi/. This covers the most common functions in a Twitch bot and greatly simplifies the authentication process.

Using a third-party application always raises security concerns. But TwitchApp is well-known and therefore has some reliability.

TwitchLib Usage Example

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

TwitchLib.Client Example

To use TwitchLib.Client we will need the bot’s UserName, and the OAuth key we obtained either through the request indicated in Twitch’s 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}");
    }
}
Copied!

TwitchLib.API Example

To use TwitchLib.API we will necessarily need the ClientId and Secret we obtained when registering our App. With these values we will generate a connection Token to be able 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();
Copied!

Download the Code

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