Godot Engine (C#)
The Godot plugin is a GDExtension. It works with Godot 4.5 or newer. To use it from C#, you need the .NET edition of Godot. This guide covers C#; if you use GDScript, see the Godot GDScript Guide.
Installing the plugin
- Unzip the downloaded
TwitchSDK-Godot-2.1.zip(see Overview for the download) and copy itsaddonsfolder into your project, so that you haveres://addons/twitchsdk/twitchsdk.gdextension. - Restart the editor. Godot loads GDExtensions automatically, so there’s nothing to enable under Project Settings > Plugins.
- Build your project (for example with Build in the editor, or
dotnet build).
You should now see a Twitch dock (at the top right, next to Scene and Import) and a Twitch section in Project Settings.
The addon contains:
| Path | Contents |
|---|---|
twitchsdk.gdextension |
Tells Godot which library to load for each platform. |
bin/ |
The native libraries: template_debug for the editor and debug exports, template_release for release exports. |
csharp/ |
The C# wrappers. Godot doesn’t generate C# bindings for GDExtension classes, so the addon ships typed wrappers in the TwitchSDK namespace. Godot compiles them as part of your project. |
The download contains the libraries for Windows (x64). The plugin’s source also builds for Linux and macOS; see Exporting.
Setting up the plugin
Navigate to the Developer Console and register an application with the OAuth Redirect URL http://localhost and the Client Type Public, or use an existing application’s Client ID. Then enter the Client ID in the Twitch dock. The dock checks it against Twitch as you type, and shows Client ID is valid! once it’s correct.
The plugin logs users in with the device code flow, which only needs the Client ID. Don’t put a client secret in your project; it isn’t used, and it must never ship in a game build.
The dock edits these project settings, which you can also change under Project Settings > Twitch:
| Setting | Meaning |
|---|---|
twitch/auth/client_id |
Your application’s Client ID. |
twitch/debug/use_eventsub_proxy |
Connect to a local EventSub test proxy instead of Twitch. It takes effect the next time the game starts. Never enable this in releases. |
The dock also shows the installed plugin and core library versions.
The plugin starts automatically when the game starts, as long as it has a Client ID. If the project setting is empty (for example because players enter their own Client ID), it waits until you set Twitch.ClientId. Until then, calls fail with an error that explains this.
How calls work
Everything goes through the static Twitch class in the TwitchSDK namespace. Almost every call returns a TwitchTask or TwitchTask<T>, the counterpart of the Unity plugin’s GameTask. You can either await it, or check it every frame:
- Awaiting it returns the result, or throws a
TwitchExceptionif the call failed. IsCompletedtells you whether the call has finished.MaybeResultis the result once the call has finished successfully, andnull(or the default value) until then. It never throws.Exceptionis theTwitchExceptionif the call failed, andnullotherwise.
// Awaiting, from an async method:
try
{
var user = await Twitch.GetMyUserInfo();
GD.Print(user.DisplayName);
}
catch (TwitchException e)
{
GD.PushError(e.Message);
}
// Checking it every frame:
private TwitchTask<TwitchUserInfo> _userTask;
public override void _Ready()
{
_userTask = Twitch.GetMyUserInfo();
}
public override void _Process(double delta)
{
if (_userTask == null || !_userTask.IsCompleted)
return;
if (_userTask.Exception != null)
GD.PushError(_userTask.Exception.Message);
else
GD.Print(_userTask.MaybeResult.DisplayName);
_userTask = null;
}
Tasks always complete from the frame loop, on the main thread, never from inside the call that created them.
If a call fails and nobody awaits it or checks its error, the plugin prints a warning when the task is freed.
Calls that need a logged-in user wait until the user has logged in, so a call made before the login completes finishes after it.
Requests and results are plain C# classes with the same names as the plugin’s GDScript classes, such as TwitchPollDefinition, TwitchPollInfo and TwitchUserInfo, and PascalCase properties. Results are snapshots: changing them doesn’t change anything in the plugin. Enums such as AuthStatus and PollStatus are in the TwitchSDK namespace too.
See the Godot Reference for the complete API.
Authentication
Most functionality requires the user to log in with their Twitch account and grant your game the OAuth scopes it needs.
Twitch.GetAuthenticationInfo(scopes) starts the login. Its result is a TwitchAuthenticationInfo with a Uri and a UserCode: show both to the user, or open the URI in a browser for them with OS.ShellOpen(). They log in there and enter the code. If the user is already logged in, the result is null.
Twitch.GetAuthState() completes immediately with a TwitchAuthState. Its Status is one of:
AuthStatus.LoggedOut: nobody is logged in.AuthStatus.Loading: the state is being determined, for example while a saved login is loaded.AuthStatus.WaitingForCode: the login has started, and the user still needs to enter the code.AuthStatus.LoggedIn: the user is logged in.Scopeslists the scopes they granted.
The login is saved in user://twitch-twitchsdk-authorization.json, so the user stays logged in when they restart your game. Twitch.LogOut() logs them out.
List of Scopes
| Scope | Scope string | Type of Access |
|---|---|---|
OAuthScope.BitsRead |
bits:read |
View Bits information for a channel. Needed for cheer events and the Bits leaderboard. |
OAuthScope.ChannelManageBroadcast |
channel:manage:broadcast |
Manage a channel’s broadcast configuration, including updating channel information, tags and stream markers. |
OAuthScope.ChannelManagePolls |
channel:manage:polls |
Manage a channel’s polls. |
OAuthScope.ChannelManagePredictions |
channel:manage:predictions |
Manage a channel’s Channel Points Predictions. |
OAuthScope.ChannelManageRedemptions |
channel:manage:redemptions |
Manage Channel Points custom rewards and their redemptions on a channel. |
OAuthScope.ChannelReadHypeTrain |
channel:read:hype_train |
View Hype Train information for a channel. |
OAuthScope.ClipsEdit |
clips:edit |
Manage Clips for a channel. |
OAuthScope.UserReadSubscriptions |
user:read:subscriptions |
View if an authorized user is subscribed to specific channels. |
Some functionality needs a scope that isn’t in OAuthScope. Pass its scope string in the second argument of GetAuthenticationInfo(scopes, customScopes):
moderator:read:followersfor follow events.channel:read:subscriptionsfor subscription events.user:read:emailto receive the user’s email address inTwitchUserInfo.
Request only the scopes you need. Please refer to Scopes to learn more about which scopes you should select.
Example of an Authentication Manager class
This class starts the login when LogIn() is called (for example from a login button), shows the code to the user, and welcomes them once they’re logged in.
using Godot;
using TwitchSDK;
public partial class AuthManager : Node
{
// We suggest you only request the scopes you actively need.
private static readonly OAuthScope[] Scopes =
{
OAuthScope.ChannelManagePolls,
OAuthScope.ChannelManagePredictions,
OAuthScope.ChannelManageRedemptions,
};
private static readonly string[] CustomScopes = { "moderator:read:followers" };
// Triggered by something external, like a login button on an options menu screen.
public async void LogIn()
{
try
{
var info = await Twitch.GetAuthenticationInfo(Scopes, CustomScopes);
if (info != null)
{
GD.Print($"Please log in at {info.Uri} with the code {info.UserCode}");
OS.ShellOpen(info.Uri);
}
else
{
GD.Print("The user is already logged in.");
}
// GetMyUserInfo() waits for the login to complete.
var user = await Twitch.GetMyUserInfo();
GD.Print($"We are logged in as {user.DisplayName} - welcome!");
}
catch (TwitchException e)
{
GD.PushError($"Login failed: {e.Message}");
}
}
public bool IsLoggedIn()
{
var state = Twitch.GetAuthState().MaybeResult;
return state != null && state.Status == AuthStatus.LoggedIn;
}
public async void LogOut()
{
await Twitch.LogOut();
}
}
Polls
Creating a poll requires the user to be logged in with the channel:manage:polls scope.
To create a poll, pass a TwitchPollDefinition to Twitch.NewPoll(). Its result is a TwitchPoll that keeps itself up to date until the poll ends:
- Its
Infoproperty is the latestTwitchPollInfo, with the poll’sStatusand itsChoices(each aTwitchPollChoiceInfowith itsVotes). - It raises
Updatedon every update, andEndedonce the poll is over. ThePollEndedtask completes then, too. FinishPoll()ends the poll early and shows the results to viewers.DeletePoll()ends it without showing results.Dispose()stops tracking the poll.
Twitch allows titles of up to 60 characters, 2 to 5 choices of up to 25 characters each, and durations from 15 to 1800 seconds.
Example of a Poll Manager class
using System.Linq;
using Godot;
using TwitchSDK;
public partial class TwitchPollManager : Node
{
private TwitchPoll _poll;
// Called by some external class.
public async void StartPoll(string pollTitle, string[] pollChoices)
{
// We already started a poll, so we don't do anything.
if (_poll != null)
return;
try
{
_poll = await Twitch.NewPoll(new TwitchPollDefinition
{
Title = pollTitle,
Choices = pollChoices,
Duration = 60, // in seconds
});
}
catch (TwitchException e)
{
GD.PushError($"Creating the poll failed: {e.Message}");
return;
}
_poll.Updated += OnPollUpdated;
_poll.Ended += OnPollEnded;
}
private void OnPollUpdated(TwitchPollInfo info)
{
foreach (var choice in info.Choices)
GD.Print($"{choice.Title}: {choice.Votes} votes");
}
private void OnPollEnded(TwitchPollInfo info)
{
_poll = null;
// The poll was ended early or removed by someone, so we don't take the results.
if (info.Status != PollStatus.Completed)
return;
// Now we can tally the results and do something.
var winner = info.Choices.OrderByDescending(c => c.Votes).First();
GD.Print($"The community chose {winner.Title} with {winner.Votes} votes!");
}
}
Predictions
Predictions work much like polls, but viewers bet Channel Points on the outcome, and your game decides which outcome won. Creating a prediction requires the user to be logged in with the channel:manage:predictions scope.
To create a prediction, pass a TwitchPredictionDefinition to Twitch.NewPrediction(). Its result is a TwitchPrediction that keeps itself up to date until the prediction is resolved or canceled:
- Its
Infoproperty is the latestTwitchPredictionInfo, with the prediction’sStatus, itsOutcomes(each aTwitchPredictionOutcomewith its number ofUsersandChannelPoints) and, once resolved, itsWinningOutcomeId. - It raises
Updatedon every update,Lockedonce voting has closed, andEndedonce the prediction is resolved or canceled. Resolve(outcome)picks the winning outcome. It’s allowed even before the prediction is locked.Cancel()refunds everyone, andLock()closes voting early.
Example of a Predictions Manager class
using Godot;
using TwitchSDK;
public partial class TwitchPredictionManager : Node
{
private TwitchPrediction _prediction;
public async void CreatePrediction(string predictionTitle, string[] predictionOutcomes)
{
// We already started a prediction, so we don't do anything.
if (_prediction != null)
return;
try
{
_prediction = await Twitch.NewPrediction(new TwitchPredictionDefinition
{
Title = predictionTitle,
Outcomes = predictionOutcomes, // for example { "Yes", "No" }
Duration = 120, // in seconds, from 1 to 1800
});
}
catch (TwitchException e)
{
GD.PushError($"Creating the prediction failed: {e.Message}");
return;
}
_prediction.Locked += _ => GD.Print("Voting has closed.");
_prediction.Ended += _ => _prediction = null;
}
// Called once the game knows the result, with the index of the outcome that happened.
public async void EndPrediction(int winningOutcome)
{
if (_prediction == null)
return;
try
{
await _prediction.Resolve(_prediction.Info.Outcomes[winningOutcome]);
}
catch (TwitchException e)
{
GD.PushError($"Resolving the prediction failed: {e.Message}");
}
}
// Called if the game can't determine a result. Viewers get their Channel Points back.
public async void CancelPrediction()
{
if (_prediction != null)
await _prediction.Cancel();
}
}
Channel Point Rewards
Channel Point rewards allow you to create dynamic in-game events based on redemptions made by users on a given stream. This is the most open-ended of all supported functions and, as such, any functionality implemented will be highly dependent on your game’s design.
This requires the user to be logged in with the channel:manage:redemptions scope.
Twitch.ReplaceCustomRewards() sets the complete list of rewards your game has on the channel: rewards you pass that don’t exist yet are created, and rewards your game created earlier that aren’t in the list are removed. Each reward needs at least a Title and a Cost; see TwitchCustomRewardDefinition in the reference for the other options.
Clear your rewards when the game ends by passing an empty array, or by awaiting Twitch.PrepareShutdown() before quitting (see Shutting down). Removing a reward sets its pending redemptions to Fulfilled.
The example below uses Channel Points to provide a list of colors which could be used in various ways in-game.
using System;
using Godot;
using TwitchSDK;
public partial class TwitchChannelPointManager : Node
{
public async void SetSampleRewards()
{
try
{
await Twitch.ReplaceCustomRewards(new[]
{
new TwitchCustomRewardDefinition { Title = "Red!", Cost = 10 },
new TwitchCustomRewardDefinition { Title = "Blue!", Cost = 25 },
new TwitchCustomRewardDefinition { Title = "Octarine!", Cost = 750 },
});
}
catch (TwitchException e)
{
GD.PushError($"Creating the rewards failed: {e.Message}");
}
}
public async void ClearRewards()
{
// An empty list removes all rewards the game has created.
await Twitch.ReplaceCustomRewards(Array.Empty<TwitchCustomRewardDefinition>());
}
}
Once you have created custom Channel Point rewards, subscribe to their redemptions as described under Subscribe to Events. Each redemption starts out Unfulfilled. Use Twitch.ResolveCustomReward(rewardEvent, CustomRewardRedemptionState.Fulfilled) once your game has acted on it, or CustomRewardRedemptionState.Canceled to refund the viewer’s Channel Points.
User Info
To retrieve information about the logged-in user, such as DisplayName, LoginName or BroadcasterType, call Twitch.GetMyUserInfo(). Its result is a TwitchUserInfo. If the user isn’t logged in yet, the task waits until they are.
GetUserInfoById() and GetUserInfoByLoginName() return the same information for other users. If no such user exists, the result’s fields are empty.
If you wish to retrieve the user’s email address, you must request the user:read:email scope at authentication.
public async void ShowUserInformation()
{
var user = await Twitch.GetMyUserInfo();
GD.Print($"Login Name: {user.LoginName}");
GD.Print($"Display Name: {user.DisplayName}");
GD.Print($"Broadcaster Type: {user.BroadcasterType}");
GD.Print($"User Type: {user.UserType}");
}
Stream Info
To retrieve information about the logged-in user’s stream, such as ViewerCount, Language or GameName, call Twitch.GetMyStreamInfo(). Its result is a TwitchStreamInfo. If the user isn’t live, its Id is empty.
GetStreamInfoById() returns the same information for another channel (or null if that channel isn’t live), and QueryStreams() searches for live streams.
public async void ShowStreamInformation()
{
var stream = await Twitch.GetMyStreamInfo();
if (stream == null || string.IsNullOrEmpty(stream.Id))
{
GD.Print("The user isn't live right now.");
return;
}
GD.Print($"Game Name: {stream.GameName}");
GD.Print($"Mature: {stream.IsMature}");
GD.Print($"Language: {stream.Language}");
GD.Print($"Title: {stream.Title}");
GD.Print($"Viewers: {stream.ViewerCount}");
}
Subscribe to Events
Events such as new followers, subscribers, cheers, raids, Hype Trains and Channel Point redemptions arrive through EventSub. Each SubscribeTo...Events() call returns a TwitchTask<EventStream<T>>, where T is the event type:
| Method | Event type | Required scope |
|---|---|---|
SubscribeToChannelFollowEvents() |
TwitchChannelFollowEvent |
moderator:read:followers |
SubscribeToChannelSubscribeEvents() |
TwitchChannelSubscribeEvent |
channel:read:subscriptions |
SubscribeToChannelCheerEvents() |
TwitchChannelCheerEvent |
bits:read |
SubscribeToChannelRaidEvents() |
TwitchChannelRaidEvent |
none |
SubscribeToHypeTrainEvents() |
TwitchHypeTrainEvent |
channel:read:hype_train |
SubscribeToCustomRewardEvents() |
TwitchCustomRewardEvent |
channel:manage:redemptions |
If the user didn’t grant the required scope, Twitch refuses the subscription. The plugin logs a warning and no events of that type arrive.
When working with an EventStream<T>, you have a choice to either use WaitForEvent() or TryGetNextEvent(out T).
We recommend that you only use one of them for the same stream. If you check for events every frame, such as in _Process, use TryGetNextEvent: it returns true and puts the next event in its out parameter if one has arrived, and returns false otherwise.
Events that arrive while you aren’t reading them are buffered (up to 512 per stream), so keep reading them, and call Dispose() on the stream when you no longer want events.
Follows
using Godot;
using TwitchSDK;
public partial class FollowEvents : Node
{
private EventStream<TwitchChannelFollowEvent> _follows;
public override async void _Ready()
{
_follows = await Twitch.SubscribeToChannelFollowEvents();
}
public override void _Process(double delta)
{
if (_follows != null && _follows.TryGetNextEvent(out var followEvent))
{
// Do something
GD.Print($"{followEvent.UserDisplayName} is now following!");
}
}
public override void _ExitTree()
{
_follows?.Dispose();
}
}
The remaining examples await WaitForEvent() in a loop instead. They keep the stream in a field, so it can be disposed when the node leaves the tree. Disposing the stream makes the pending WaitForEvent() throw a TwitchException, which ends the loop.
Subscribers
using Godot;
using TwitchSDK;
public partial class SubscriberEvents : Node
{
private EventStream<TwitchChannelSubscribeEvent> _subscribers;
public override async void _Ready()
{
try
{
_subscribers = await Twitch.SubscribeToChannelSubscribeEvents();
while (!_subscribers.IsClosed)
{
var subscribeEvent = await _subscribers.WaitForEvent();
// Do something
if (subscribeEvent.IsGift)
GD.Print($"{subscribeEvent.UserDisplayName} received a gifted subscription!");
else
GD.Print($"{subscribeEvent.UserDisplayName} has subscribed!");
}
}
catch (TwitchException e)
{
// Also happens when the stream is disposed.
GD.Print($"Stopped listening for subscribers: {e.Message}");
}
}
public override void _ExitTree()
{
_subscribers?.Dispose();
}
}
The other event types work the same way. The following examples show only the loop; put it in a class like the one above.
Cheers
_cheers = await Twitch.SubscribeToChannelCheerEvents();
while (!_cheers.IsClosed)
{
var cheerEvent = await _cheers.WaitForEvent();
// Do something
var name = cheerEvent.IsAnonymous ? "An anonymous viewer" : cheerEvent.UserDisplayName;
GD.Print($"{name} cheered {cheerEvent.Bits} Bits!");
}
Channel Point Rewards
_redemptions = await Twitch.SubscribeToCustomRewardEvents();
while (!_redemptions.IsClosed)
{
var rewardEvent = await _redemptions.WaitForEvent();
// Updates to redemptions (fulfilled or canceled) arrive here too.
if (rewardEvent.Status != CustomRewardRedemptionState.Unfulfilled)
continue;
// Do something
GD.Print($"{rewardEvent.RedeemerName} has bought {rewardEvent.CustomRewardTitle} for {rewardEvent.CustomRewardCost}!");
await Twitch.ResolveCustomReward(rewardEvent, CustomRewardRedemptionState.Fulfilled);
}
Hype Train
Hype Train events arrive when a Hype Train starts, makes progress, and ends. EndedAt is empty until the Hype Train is over.
_hypeTrains = await Twitch.SubscribeToHypeTrainEvents();
while (!_hypeTrains.IsClosed)
{
var hypeTrainEvent = await _hypeTrains.WaitForEvent();
// Do something
if (string.IsNullOrEmpty(hypeTrainEvent.EndedAt))
GD.Print($"The Hype Train is at level {hypeTrainEvent.Level}: {hypeTrainEvent.Progress} / {hypeTrainEvent.Goal} points!");
else
GD.Print($"The Hype Train ended at level {hypeTrainEvent.Level}.");
}
Raids
_raids = await Twitch.SubscribeToChannelRaidEvents();
while (!_raids.IsClosed)
{
var raidEvent = await _raids.WaitForEvent();
// Do something
GD.Print($"{raidEvent.FromBroadcasterName} has raided {raidEvent.ToBroadcasterName} with {raidEvent.Viewers} viewers!");
}
Drops
The plugin supports the “offline inventory” model of Twitch Drops: your game asks Twitch which Drops the logged-in user has claimed, grants the matching items, and then marks the Drops as fulfilled. The plugin can only read and fulfill the logged-in user’s own Drops, and there are no Drop events, so check when the player asks for it (for example with a “Check for Drops” button) or at an interval. No extra scope is needed.
Your Drops campaign must be set up for your game’s category, by a developer organization that the owner of your Client ID belongs to.
using System.Collections.Generic;
using Godot;
using TwitchSDK;
public partial class DropsManager : Node
{
// Call this from your "Check for Drops" button.
public async void CheckForDrops()
{
try
{
// By default, only the Drops the user has claimed but not received yet.
var list = await Twitch.GetDropEntitlements();
var granted = new List<TwitchDropEntitlement>();
foreach (var entitlement in list.Entitlements)
{
// BenefitId tells you which reward this is.
if (GrantItem(entitlement.BenefitId))
granted.Add(entitlement);
}
if (granted.Count > 0)
await Twitch.FulfillDropEntitlements(granted.ToArray());
}
catch (TwitchException e)
{
GD.PushError($"Checking for Drops failed: {e.Message}");
}
}
// Your own inventory logic. Return true only if the item was actually granted.
private bool GrantItem(string benefitId)
{
return true;
}
}
Log messages
The plugin’s log messages are printed to Godot’s output (debug messages only when Godot runs with --verbose). They are also raised as the Twitch.LogMessage event, for example to show them in an in-game console:
public override void _Ready()
{
Twitch.LogMessage += OnTwitchLog;
}
public override void _ExitTree()
{
Twitch.LogMessage -= OnTwitchLog;
}
private void OnTwitchLog(LogLevel level, string message)
{
if (level >= LogLevel.Warning)
GD.Print($"Twitch: {message}");
}
Shutting down
The plugin shuts down automatically when the game exits. If your game created Channel Point rewards, await Twitch.PrepareShutdown() before quitting, so that they’re removed from the channel:
using Godot;
using TwitchSDK;
public partial class QuitHandler : Node
{
public override void _Ready()
{
// Let us clean up before the window closes.
GetTree().AutoAcceptQuit = false;
}
public override void _Notification(int what)
{
if (what == NotificationWMCloseRequest)
Quit();
}
private async void Quit()
{
await Twitch.PrepareShutdown();
GetTree().Quit();
}
}
Exporting
Exported games load the template_release (release export) or template_debug (debug export) library listed in twitchsdk.gdextension, so make sure both are in addons/twitchsdk/bin for every platform you export to.
The download contains the Windows (x64) libraries. Libraries for Linux (x64 and arm64) and macOS are built from the plugin’s source on those systems; the source is available upon request (see Overview).
Samples
The plugin comes with two sample projects that show all of its functionality: one written in C#, and one in GDScript. They have the same pages as the Unity and Unreal samples: authorization, polls, predictions, Drops, and a general page with user and stream info, channel settings, Channel Point rewards and live events.