如果 master 沒有您想要的功能,請在進行 PR 之前檢查「Dev」版本。
TwitchLib 是一個功能強大的 C# 函式庫,可與各種 Twitch 服務進行互動。目前支援的服務有:聊天和耳語、API(v5(已棄用)、helix、未記錄和第三方)、PubSub 事件系統和 Twitch 擴充。以下是構成 TwitchLib 的核心元件的描述。
在 Discord 上直接與我們交談。 https://discord.gg/8NXaEyV
有關完整的庫文檔,請在此處查看 doxygen 文檔。
以下是如何利用 TwitchLib 每個核心元件的基本範例。這些是 C# 範例。注意:Twitchlib.API 目前不支援 Visual Basic。更新:PR 的 Visual Basic 修復,但需要由使用它的人進行測試。
using System ;
using TwitchLib . Client ;
using TwitchLib . Client . Enums ;
using TwitchLib . Client . Events ;
using TwitchLib . Client . Extensions ;
using TwitchLib . Client . Models ;
using TwitchLib . Communication . Clients ;
using TwitchLib . Communication . Models ;
namespace TestConsole
{
class Program
{
static void Main ( string [ ] args )
{
Bot bot = new Bot ( ) ;
Console . ReadLine ( ) ;
}
}
class Bot
{
TwitchClient client ;
public Bot ( )
{
ConnectionCredentials credentials = new ConnectionCredentials ( " twitch_username " , " access_token " ) ;
var clientOptions = new ClientOptions
{
MessagesAllowedInPeriod = 750 ,
ThrottlingPeriod = TimeSpan . FromSeconds ( 30 )
} ;
WebSocketClient customClient = new WebSocketClient ( clientOptions ) ;
client = new TwitchClient ( customClient ) ;
client . Initialize ( credentials , " channel " ) ;
client . OnLog += Client_OnLog ;
client . OnJoinedChannel += Client_OnJoinedChannel ;
client . OnMessageReceived += Client_OnMessageReceived ;
client . OnWhisperReceived += Client_OnWhisperReceived ;
client . OnNewSubscriber += Client_OnNewSubscriber ;
client . OnConnected += Client_OnConnected ;
client . Connect ( ) ;
}
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 to { e . AutoJoinChannel } " ) ;
}
private void Client_OnJoinedChannel ( object sender , OnJoinedChannelArgs e )
{
Console . WriteLine ( " Hey guys! I am a bot connected via TwitchLib! " ) ;
client . SendMessage ( e . Channel , " Hey guys! I am a bot connected via TwitchLib! " ) ;
}
private void Client_OnMessageReceived ( object sender , OnMessageReceivedArgs e )
{
if ( e . ChatMessage . Message . Contains ( " badword " ) )
client . TimeoutUser ( e . ChatMessage . Channel , e . ChatMessage . Username , TimeSpan . FromMinutes ( 30 ) , " Bad word! 30 minute timeout! " ) ;
}
private void Client_OnWhisperReceived ( object sender , OnWhisperReceivedArgs e )
{
if ( e . WhisperMessage . Username == " my_friend " )
client . SendWhisper ( e . WhisperMessage . Username , " Hey! Whispers are so cool!! " ) ;
}
private void Client_OnNewSubscriber ( object sender , OnNewSubscriberArgs e )
{
if ( e . Subscriber . SubscriptionPlan == SubscriptionPlan . Prime )
client . SendMessage ( e . Channel , $" Welcome { e . Subscriber . DisplayName } to the substers! You just earned 500 points! So kind of you to use your Twitch Prime on this channel! " ) ;
else
client . SendMessage ( e . Channel , $" Welcome { e . Subscriber . DisplayName } to the substers! You just earned 500 points! " ) ;
}
}
}
Imports System
Imports TwitchLib.Client
Imports TwitchLib.Client.Enums
Imports TwitchLib.Client.Events
Imports TwitchLib.Client.Extensions
Imports TwitchLib.Client.Models
Module Module1
Sub Main()
Dim bot As New Bot()
Console.ReadLine()
End Sub
Friend Class Bot
Private client As TwitchClient
Public Sub New ()
Dim credentials As New ConnectionCredentials( "twitch_username" , "Token" )
client = New TwitchClient()
client.Initialize(credentials, "Channel" )
AddHandler client.OnJoinedChannel, AddressOf onJoinedChannel
AddHandler client.OnMessageReceived, AddressOf onMessageReceived
AddHandler client.OnWhisperReceived, AddressOf onWhisperReceived
AddHandler client.OnNewSubscriber, AddressOf onNewSubscriber
AddHandler client.OnConnected, AddressOf Client_OnConnected
client.Connect()
End Sub
Private Sub Client_OnConnected( ByVal sender As Object , ByVal e As OnConnectedArgs)
Console.WriteLine( $ "Connected to {e.AutoJoinChannel}" )
End Sub
Private Sub onJoinedChannel( ByVal sender As Object , ByVal e As OnJoinedChannelArgs)
Console.WriteLine( "Hey guys! I am a bot connected via TwitchLib!" )
client.SendMessage(e.Channel, "Hey guys! I am a bot connected via TwitchLib!" )
End Sub
Private Sub onMessageReceived( ByVal sender As Object , ByVal e As OnMessageReceivedArgs)
If e.ChatMessage.Message.Contains( "badword" ) Then
client.TimeoutUser(e.ChatMessage.Channel, e.ChatMessage.Username, TimeSpan.FromMinutes( 30 ), "Bad word! 30 minute timeout!" )
End If
End Sub
Private Sub onWhisperReceived( ByVal sender As Object , ByVal e As OnWhisperReceivedArgs)
If e.WhisperMessage.Username = "my_friend" Then
client.SendWhisper(e.WhisperMessage.Username, "Hey! Whispers are so cool!!" )
End If
End Sub
Private Sub onNewSubscriber( ByVal sender As Object , ByVal e As OnNewSubscriberArgs)
If e.Subscriber.SubscriptionPlan = SubscriptionPlan.Prime Then
client.SendMessage(e.Channel, $ "Welcome {e.Subscriber.DisplayName} to the substers! You just earned 500 points! So kind of you to use your Twitch Prime on this channel!" )
Else
client.SendMessage(e.Channel, $ "Welcome {e.Subscriber.DisplayName} to the substers! You just earned 500 points!" )
End If
End Sub
End Class
End Module
有關 TwitchClient 事件和呼叫的完整列表,請按一下此處
注意:TwitchAPI 現在是一個單例類,需要使用可選的 clientid 和身份驗證令牌進行實例化。請注意,如果無法提供至少一個客戶端 ID,有時甚至無法提供存取令牌,將會導致異常。 v5(已棄用)和 Helix 幾乎完全在 Twitch 用戶 ID 上運行。所有 Twitch api 版本中都有方法來取得對應的使用者名稱/使用者 ID。
using System . Collections . Generic ;
using System . Threading . Tasks ;
using TwitchLib . Api ;
using TwitchLib . Api . Helix . Models . Users ;
using TwitchLib . Api . V5 . Models . Subscriptions ; //v5 Deprecated
namespace Example
{
class Program
{
private static TwitchAPI api ;
private void Main ( )
{
api = new TwitchAPI ( ) ;
api . Settings . ClientId = " client_id " ;
api . Settings . AccessToken = " access_token " ; // App Secret is not an Accesstoken
}
private async Task ExampleCallsAsync ( )
{
//Gets a list of all the subscritions of the specified channel.
var allSubscriptions = await api . Helix . Subscriptions . GetBroadcasterSubscriptionsAsync ( " broadcasterID " , null , 100 , " accesstoken " )
//Get channels a specified user follows.
var userFollows = await api . Helix . Users . GetUsersFollowsAsync ( " user_id " ) ;
//Get Specified Channel Follows
var channelFollowers = await api . Helix . Users . GetUsersFollowsAsync ( fromId : " channel_id " ) ;
//Returns a stream object if online, if channel is offline it will be null/empty.
var streams = await api . Helix . Streams . GetStreamsAsync ( userIds : userIdsList ) ; // Alternative: userLogins: userLoginsList
//Update Channel Title/Game/Language/Delay - Only require 1 option here.
var request = new ModifyChannelInformationRequest ( ) { GameId = " New_Game_Id " , Title = " New stream title " , BroadcasterLanguage = " New_Language " , Delay = New_Delay } ;
await api . Helix . Channels . ModifyChannelInformationAsync ( " broadcaster_Id " , request , " AccessToken " ) ;
}
}
}
Imports System.Collections.Generic
Imports System.Threading.Tasks
Imports TwitchLib.Api
Imports TwitchLib.Api.Models.Helix.Users.GetUsersFollows
Imports TwitchLib.Api.Models.Helix.Users.GetUsers
Imports TwitchLib.Api.Models.v5.Subscriptions // V5 deprecated
Module Module1
Public api As TwitchAPI
Sub Main()
api = New TwitchAPI()
api.Settings.ClientId = "Client_id"
api.Settings.AccessToken = "access_token" // App Secret is not an Accesstoken
streaming().Wait()
getchanfollows().Wait()
getusersubs().Wait()
getnumberofsubs().Wait()
getsubstochannel().Wait()
Console.ReadLine()
End Sub
Private Async Function getusersubs() As Task
'Checks subscription for a specific user and the channel specified.
Dim subscription As Subscription = Await api.Channels.v5.CheckChannelSubscriptionByUserAsync( "channel_id" , "user_id" )
Console.WriteLine( "User subed: " + subscription.User.Name.ToString)
End Function
Private Async Function streaming() As Task
'shows if the channel is streaming or not (true/false)
Dim isStreaming As Boolean = Await api.Streams.v5.BroadcasterOnlineAsync( "channel_id" )
If isStreaming = True Then
Console.WriteLine( "Streaming" )
Else
Console.WriteLine( "Not Streaming" )
End If
End Function
Private Async Function chanupdate() As Task
'Update Channel Title/Game
'not used this yet
Await api.Channels.v5.UpdateChannelAsync( "channel_id" , "New stream title" , "Stronghold Crusader" )
End Function
Private Async Function getchanfollows() As Task
'Get Specified Channel Follows
Dim channelFollowers = Await api.Channels.v5.GetChannelFollowersAsync( "channel_id" )
Console.WriteLine(channelFollowers.Total.ToString)
End Function
Private Async Function getchanuserfollow() As Task
'Get channels a specified user follows.
Dim userFollows As GetUsersFollowsResponse = Await api.Users.helix.GetUsersFollowsAsync( "user_id" )
Console.WriteLine(userFollows.TotalFollows.ToString)
End Function
Private Async Function getnumberofsubs() As Task
'Get the number of subs to your channel
Dim numberofsubs = Await api.Channels.v5.GetChannelSubscribersAsync( "channel_id" )
Console.WriteLine(numberofsubs.Total.ToString)
End Function
Private Async Function getsubstochannel() As Task
'Gets a list of all the subscritions of the specified channel.
Dim allSubscriptions As List( Of Subscription) = Await api.Channels.v5.GetAllSubscribersAsync( "channel_id" )
Dim num As Integer
For num = 0 To allSubscriptions.Count - 1
Console.WriteLine(allSubscriptions.Item(num).User.Name.ToString)
Next num
End Function
End Module
有關 TwitchAPI 呼叫的完整列表,請按一下此處
using System ;
using TwitchLib . PubSub ;
using TwitchLib . PubSub . Events ;
namespace TwitchLibPubSubExample
{
class Program
{
private TwitchPubSub client ;
static void Main ( string [ ] args )
{
new Program ( ) . Run ( ) ;
}
private void Run ( )
{
client = new TwitchPubSub ( ) ;
client . OnPubSubServiceConnected += onPubSubServiceConnected ;
client . OnListenResponse += onListenResponse ;
client . OnStreamUp += onStreamUp ;
client . OnStreamDown += onStreamDown ;
client . ListenToVideoPlayback ( " channelUsername " ) ;
client . ListenToBitsEvents ( " channelTwitchID " ) ;
client . Connect ( ) ;
Console . ReadLine ( ) ; // Quick fix to keep program from closing right away. ReadKey could also be used.
}
private void onPubSubServiceConnected ( object sender , EventArgs e )
{
// SendTopics accepts an oauth optionally, which is necessary for some topics
client . SendTopics ( ) ;
}
private void onListenResponse ( object sender , OnListenResponseArgs e )
{
if ( ! e . Successful )
throw new Exception ( $" Failed to listen! Response: { e . Response } " ) ;
}
private void onStreamUp ( object sender , OnStreamUpArgs e )
{
Console . WriteLine ( $" Stream just went up! Play delay: { e . PlayDelay } , server time: { e . ServerTime } " ) ;
}
private void onStreamDown ( object sender , OnStreamDownArgs e )
{
Console . WriteLine ( $" Stream just went down! Server time: { e . ServerTime } " ) ;
}
}
}
有關 TwitchPubSub 功能的完整列表,請按一下此處
請參閱此處的擴充自述文件。
注意:使用這些項目作為參考,不保證它們是最新的。
如果您在使用這些範例時遇到任何問題,請指出您在問題或 Discord 中引用的範例。
若要透過 NuGet 控制台透過 NuGet 安裝此程式庫,請使用:
Install-Package TwitchLib