Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Fast and reliable Twitch libraries written for >= .NET 8.0

License

NotificationsYou must be signed in to change notification settings

occluder/MiniTwitch

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

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

Features

  • 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 asValueTask, 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 anILogger. Allows you to use any logging library which implementslogging abstractions

Getting Started

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

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.

Features

  • Package code is fully documented with XML comments
  • Exposes documented & undocumented PubSub topics
  • UsesSystem.Text.Json under the hood; Fast, efficient and without unnecessary dependencies
  • Exposes events withFunc<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 perPubSubClient
  • Comes with a built-in logger, which can be disabled or replaced easily
  • Events return the topic parameters asChannelId orUserId, making them easily distinguishable

Getting Started

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 (Pre-release)

MiniTwitch.Helix conveniently wraps the Twitch Helix API and exposes them through theHelixWrapperclass.

Features

  • Contains all generally available and beta Helix API endpoints

  • Virtually no dependencies

  • Returns meaningful information about responses withHelixResult:

    • 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 forHelixResult<T>:

    • HelixResult.CanPaginate: Determines whether the next page of content can be requested
    • HelixResult.Paginate(): Fetches the next page of content

Getting Started

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;}}

Subscribing to events

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


Installation

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

Dependencies

MiniTwitch.Common:

MiniTwitch.Irc:

MiniTwitch.PubSub:

MiniTwitch.Helix:

About

Fast and reliable Twitch libraries written for >= .NET 8.0

Topics

Resources

License

Stars

Watchers

Forks

Languages


[8]ページ先頭

©2009-2025 Movatter.jp