- Notifications
You must be signed in to change notification settings - Fork2
Fast and reliable Twitch libraries written for >= .NET 8.0
License
occluder/MiniTwitch
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
MiniTwitch is a collection of Twitch libraries for NET Core 6.0+ with the goal of providing convenient asynchronous APIs for Twitch services and care for performance and memory.
Only the IRC and PubSub components are curently implemented, other components for remaining Twitch services are still in development (Helix, EventSub). 🛠
MiniTwitch.Irc is the component responsible for Twitch chat services. The usage of this package revolves around theIrcClient
class which handles connection, communication and channel management
- Package code is fully documented with XML comments
- Full coverage of chatroom messages and events with convenient APIs
- Built with performance and memory in mind.Nanosecond speeds, with low memory allocation
- Exposes events as
ValueTask
, making for efficient & concurrent usage - Automatically reconnects upon disconnection & automatically rejoins channels
- Simple & customizable ratelimiting of sending messages and joining channels
- Allows for connecting anonymously - No need for authorization if you don't plan to send anything!
- Understand what happens behind the scenes by supplying an
ILogger
. Allows you to use any logging library which implementslogging abstractions
here is an example usage of theIrcClient
class:
usingMiniTwitch.Irc;usingMiniTwitch.Irc.Models;namespaceMiniTwitchExample;publicclassProgram{staticasyncTaskMain(){Botbot=new("myusername","mytoken");awaitbot.Client.ConnectAsync();awaitbot.Client.JoinChannel("occluder");_=Console.ReadLine();}}publicclassBot{publicIrcClientClient{get;init;}publicBot(stringusername,stringtoken){Client=newIrcClient(options=>{options.Username=username;options.OAuth=token;});Client.OnChannelJoin+=ChannelJoinEvent;Client.OnMessage+=MessageEvent;}privateValueTaskChannelJoinEvent(IrcChannelchannel){returnClient.SendMessage(channel.Name,"Hello from MiniTwitch!");}privateasyncValueTaskMessageEvent(Privmsgmessage){if(message.Content=="penis123"){awaitmessage.ReplyWith("That's my password!!");}elseif(message.Content=="Wait a minute!"){awaitTask.Delay(TimeSpan.FromMinutes(1));awaitmessage.ReplyWith("I waited. Now what?");}}}
MiniTwitch.PubSub is the component responsible for interaction with the Twitch PubSub service. The usage of this package revolves around thePubSubClient
class and theTopics
static class.
- Package code is fully documented with XML comments
- Exposes documented & undocumented PubSub topics
- Uses
System.Text.Json
under the hood; Fast, efficient and without unnecessary dependencies - Exposes events with
Func<T1, .., ValueTask>
delegates, making asynchronous handling very easy - Automatically reconnects upon disconnection & automatically re-listens to topics
- Simplistic; Events have clear descriptions on what they do and how to get them invoked
- Multi-token support; You're not limited to 1 auth token per
PubSubClient
- Comes with a built-in logger, which can be disabled or replaced easily
- Events return the topic parameters as
ChannelId
orUserId
, making them easily distinguishable
here is an example usage of thePubSubClient
class:
usingMiniTwitch.PubSub;usingMiniTwitch.PubSub.Interfaces;usingMiniTwitch.PubSub.Models;usingMiniTwitch.PubSub.Payloads;namespaceMiniTwitchExample;publicclassProgram{staticasyncTaskMain(){PubSubClientclient=new("my token");awaitclient.ConnectAsync();varplaybackResponse=awaitclient.ListenTo(Topics.VideoPlayback(36175310));if(playbackResponse.IsSuccess)Console.WriteLine($"Listened to{playbackResponse.TopicKey} successfully!");varresponses=awaitclient.ListenTo(Topics.Following(783267696)|Topics.ChatroomsUser(754250938,"a different token"));foreach(varresponseinresponses){if(!response.IsSuccess)Console.WriteLine($"Failed to listen to{response.TopicKey}! Error:{response.Error}");}client.OnStreamUp+=OnStreamUp;client.OnFollow+=OnFollow;client.OnTimedOut+=OnTimedOut;_=Console.ReadLine();}privatestaticValueTaskOnStreamUp(ChannelIdchannelId,IStreamUpstream){Console.WriteLine($"Channel ID{channelId} just went live! (Stream delay:{stream.PlayDelay})");returnValueTask.CompletedTask;}privatestaticValueTaskOnFollow(ChannelIdchannelId,Followerfollower){Console.WriteLine($"{follower.Name} just followed you!");returnValueTask.CompletedTask;}privatestaticValueTaskOnTimedOut(UserIduserId,ITimeOutDatatimeout){Console.WriteLine($"Your other account (ID:{userId}) has been timed out for{timeout.ExpiresInMs}ms in channel ID{timeout.ChannelId}");returnValueTask.CompletedTask;}}
MiniTwitch.Helix conveniently wraps the Twitch Helix API and exposes them through theHelixWrapper
class.
Contains all generally available and beta Helix API endpoints
Virtually no dependencies
Returns meaningful information about responses with
HelixResult
:- HelixResult.Success: Whether the request was successful
- HelixResult.StatusCode: Status code of the response
- HelixResult.Message: Contains the error message for the request, if not successful
- HelixResult.Elapsed: The amount of time the request took to get a response
- HelixResult.RateLimit.Limit: Maximum amount of requests that can be made in a period
- HelixResult.RateLimit.Remaining: The amount of requests that can be made before the ratelimit resets
- HelixResult.RateLimit.ResetsIn: The amount of time before the ratelimit resets
Validates access tokens & warns before their expiry
Easy pagination API for
HelixResult<T>
:- HelixResult.CanPaginate: Determines whether the next page of content can be requested
- HelixResult.Paginate(): Fetches the next page of content
This example demonstrates the usage ofHelixWrapper
and pagination throughHelixResult<T>
usingMiniTwitch.Helix;usingMiniTwitch.Helix.Models;usingMiniTwitch.Helix.Responses;namespaceMiniTwitchExample;publicclassProgram{publicstaticHelixWrapperHelix{get;set;}staticasyncTaskMain(){Helix=newHelixWrapper("wjm4xzd5fxp4ilaykzmmwc3dett9vm",783267696);varemotes=awaitGetAllMyEmotes();}privatestaticasyncTask<List<string>>GetAllMyEmotes(){HelixResult<UserEmotes>emotesResult=awaitHelix.GetUserEmotes();if(!emotesResult.Success){return[];}List<string>emoteList=[];foreach(varemoteinemotesResult.Value.Data){emoteList.Add(emote.Name);}// Fetch the next pages of content.// The code inside will not run if there are no more pages.awaitforeach(varnextEmotesResultinemotesResult.EnumeratePages()){foreach(varemoteinnextEmotesResult.Value.Data){emoteList.Add(emote.Name);}}returnemoteList;}}
All events use either theFunc<T, ValueTask>
,Func<T1, T2, ValueTask>
orFunc<ValueTask>
delegates. Meaning that subscribing methods must have the return typeValueTask
and account for theT
parameters when present (seeclient.OnStreamUp
in the PubSub example above), the parameter name you set does not matter.
If the method doesn't have any asynchronous code, it is recommended to not mark it asasync
and returnValueTask.CompletedTask
,default
or someValueTask
object instead.
Subscribing can be done either by declaring methods:
Client.OnMessage+=MessageEvent;privateasyncValueTaskMessageEvent(Privmsgmessage){ ...}
or with anonymous functions:
Client.OnMessage+=async message=>{ ...};
Note that you cannot unsubscribe from anonymous functions.
Read more about event subscriptionshere
You can add the packages to your project by searching for them with the package manager, or by using the NuGet cli tool:
Install-Package MiniTwitch.IrcInstall-Package MiniTwitch.PubSubInstall-Package MiniTwitch.Helix
MiniTwitch.Common:
MiniTwitch.Irc:
MiniTwitch.PubSub:
MiniTwitch.Helix:
About
Fast and reliable Twitch libraries written for >= .NET 8.0