# Godot Getting Started GDScript

Integrating Twitch into a Godot game using GDScript

Source: https://dev.twitch.tv/docs/game-engine-plugins/godot-guide-gdscript/

# Godot Engine (GDScript)

The Godot plugin is a GDExtension. It works with Godot 4.5 or newer, in both the standard and the .NET edition. This guide covers GDScript; if you use C#, see the [Godot C# Guide](https://dev.twitch.tv/docs/game-engine-plugins/godot-guide-csharp.md).

## Installing the plugin

1. Unzip the downloaded `TwitchSDK-Godot-2.1.zip` (see [Overview](https://dev.twitch.tv/docs/game-engine-plugins.md) for the download) and copy its `addons` folder into your project, so that you have `res://addons/twitchsdk/twitchsdk.gdextension`.
2. Restart the editor. Godot loads GDExtensions automatically, so there's nothing to enable under Project Settings > Plugins.

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. GDScript-only projects can delete this folder. |

The download contains the libraries for Windows (x64). The plugin's source also builds for Linux and macOS; see [Exporting](#exporting).

## Setting up the plugin

Navigate to the [Developer Console](https://dev.twitch.tv/console/apps) 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 call `Twitch.set_client_id()`. Until then, calls fail with an error that explains this.

## How calls work

Everything goes through the `Twitch` singleton. Almost every call returns a `TwitchTask`, which you can either **await** or **check** every frame:

```gdscript
# Await the task's completed signal. It passes the result (null if the call failed).
var task := Twitch.get_my_user_info()
var user: TwitchUserInfo = await task.completed
if task.has_error():
	push_error(task.error)
else:
	print(user.display_name)
```

```gdscript
# Or check it from _process.
var user_task: TwitchTask

func _ready() -> void:
	user_task = Twitch.get_my_user_info()

func _process(_delta: float) -> void:
	if user_task and user_task.is_completed():
		if user_task.has_error():
			push_error(user_task.error)
		else:
			print(user_task.result.display_name)
		user_task = null
```

The `completed` signal is always emitted from the frame loop, never from inside the call that created the task, so `await Twitch.something().completed` is always safe. To await a task that may already have finished a while ago, use `await task.wait()` instead. All results arrive on the main thread.

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 typed classes such as `TwitchPollDefinition`, `TwitchPollInfo` and `TwitchUserInfo`. They are `Resource`s, so you can also create them in the inspector and save them as `.tres` files, which is handy for Channel Point reward definitions. Enums are constants on the singleton, for example `Twitch.AUTH_STATUS_LOGGED_IN` or `Twitch.OAUTH_SCOPE_CHANNEL_MANAGE_POLLS`.

Every class is documented in the editor: press F1 and search for *Twitch*. See the [Godot Reference](https://dev.twitch.tv/docs/game-engine-plugins/godot-reference.md) 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.get_authentication_info(scopes)` starts the login. Its result is a `TwitchAuthenticationInfo` with a `uri` and a `user_code`: show both to the user, or open the URI in a browser for them with `OS.shell_open()`. They log in there and enter the code. If the user is already logged in, the result is `null`.

`Twitch.get_auth_state()` completes immediately with a `TwitchAuthState`. Its `status` is one of:

- `Twitch.AUTH_STATUS_LOGGED_OUT`: nobody is logged in.
- `Twitch.AUTH_STATUS_LOADING`: the state is being determined, for example while a saved login is loaded.
- `Twitch.AUTH_STATUS_WAITING_FOR_CODE`: the login has started, and the user still needs to enter the code.
- `Twitch.AUTH_STATUS_LOGGED_IN`: the user is logged in. `scopes` lists 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.log_out()` logs them out.

### List of Scopes

Pass scopes to `get_authentication_info` as an array. It can contain `Twitch.OAUTH_SCOPE_*` constants and scope strings.

| Constant | Scope string | Type of Access |
| --- | --- | --- |
| `Twitch.OAUTH_SCOPE_BITS_READ` | `bits:read` | View Bits information for a channel. Needed for cheer events and the Bits leaderboard. |
| `Twitch.OAUTH_SCOPE_CHANNEL_MANAGE_BROADCAST` | `channel:manage:broadcast` | Manage a channel's broadcast configuration, including updating channel information, tags and stream markers. |
| `Twitch.OAUTH_SCOPE_CHANNEL_MANAGE_POLLS` | `channel:manage:polls` | Manage a channel's polls. |
| `Twitch.OAUTH_SCOPE_CHANNEL_MANAGE_PREDICTIONS` | `channel:manage:predictions` | Manage a channel's Channel Points Predictions. |
| `Twitch.OAUTH_SCOPE_CHANNEL_MANAGE_REDEMPTIONS` | `channel:manage:redemptions` | Manage Channel Points custom rewards and their redemptions on a channel. |
| `Twitch.OAUTH_SCOPE_CHANNEL_READ_HYPE_TRAIN` | `channel:read:hype_train` | View Hype Train information for a channel. |
| `Twitch.OAUTH_SCOPE_CLIPS_EDIT` | `clips:edit` | Manage Clips for a channel. |
| `Twitch.OAUTH_SCOPE_USER_READ_SUBSCRIPTIONS` | `user:read:subscriptions` | View if an authorized user is subscribed to specific channels. |

Some functionality needs a scope that doesn't have a constant. Pass its scope string instead:

- `"moderator:read:followers"` for follow events.
- `"channel:read:subscriptions"` for subscription events.
- `"user:read:email"` to receive the user's email address in `TwitchUserInfo`.

Request only the scopes you need. Please refer to [Scopes](https://dev.twitch.tv/docs/authentication/scopes.md) to learn more about which scopes you should select.

### Example of an authentication script

This script starts the login when `log_in()` is called (for example from a login button), shows the code to the user, and welcomes them once they're logged in.

```gdscript
extends Node

# We suggest you only request the scopes you actively need.
const SCOPES := [
	Twitch.OAUTH_SCOPE_CHANNEL_MANAGE_POLLS,
	Twitch.OAUTH_SCOPE_CHANNEL_MANAGE_PREDICTIONS,
	Twitch.OAUTH_SCOPE_CHANNEL_MANAGE_REDEMPTIONS,
	"moderator:read:followers",
]

func log_in() -> void:
	var task := Twitch.get_authentication_info(SCOPES)
	var info: TwitchAuthenticationInfo = await task.completed
	if task.has_error():
		push_error("Login failed: " + task.error)
		return
	if info:
		print("Please log in at %s with the code %s" % [info.uri, info.user_code])
		OS.shell_open(info.uri)
	else:
		print("The user is already logged in.")

	# get_my_user_info() waits for the login to complete.
	var user: TwitchUserInfo = await Twitch.get_my_user_info().completed
	if user:
		print("We are logged in as %s - welcome!" % user.display_name)

func is_logged_in() -> bool:
	var state: TwitchAuthState = Twitch.get_auth_state().result
	return state != null and state.status == Twitch.AUTH_STATUS_LOGGED_IN

func log_out() -> void:
	await Twitch.log_out().completed
```

## Polls

Creating a poll requires the user to be logged in with the `channel:manage:polls` scope.

To create a poll, fill in a `TwitchPollDefinition` and pass it to `Twitch.new_poll()`. The task's result is a `TwitchPoll` that keeps itself up to date until the poll ends:

- Its `info` property is the latest `TwitchPollInfo`, with the poll's `status` and its `choices` (each a `TwitchPollChoiceInfo` with its `votes`).
- It emits `updated(info)` on every update, and `ended(info)` once the poll is over.
- `finish_poll()` ends the poll early and shows the results to viewers. `delete_poll()` ends it without showing results.

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 script

```gdscript
extends Node

var poll: TwitchPoll

# Called by some external script.
func start_poll(title: String, choices: PackedStringArray) -> void:
	# We already started a poll, so we don't do anything.
	if poll:
		return
	var definition := TwitchPollDefinition.new()
	definition.title = title
	definition.choices = choices
	definition.duration = 60 # in seconds

	var task := Twitch.new_poll(definition)
	poll = await task.completed
	if task.has_error():
		push_error("Creating the poll failed: " + task.error)
		return
	poll.updated.connect(_on_poll_updated)
	poll.ended.connect(_on_poll_ended)

func _on_poll_updated(info: TwitchPollInfo) -> void:
	for choice in info.choices:
		print("%s: %d votes" % [choice.title, choice.votes])

func _on_poll_ended(info: TwitchPollInfo) -> void:
	poll = null
	# The poll was ended early or removed by someone, so we don't take the results.
	if info.status != Twitch.POLL_STATUS_COMPLETED:
		return
	# Now we can tally the results and do something.
	var winner: TwitchPollChoiceInfo = info.choices[0]
	for choice in info.choices:
		if choice.votes > winner.votes:
			winner = choice
	print("The community chose %s with %d votes!" % [winner.title, winner.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, fill in a `TwitchPredictionDefinition` and pass it to `Twitch.new_prediction()`. The task's result is a `TwitchPrediction` that keeps itself up to date until the prediction is resolved or canceled:

- Its `info` property is the latest `TwitchPredictionInfo`, with the prediction's `status`, its `outcomes` (each a `TwitchPredictionOutcome` with its number of `users` and `channel_points`) and, once resolved, its `winning_outcome_id`.
- It emits `updated(info)` on every update, `locked(info)` once voting has closed, and `ended(info)` once the prediction is resolved or canceled.
- `resolve(outcome)` picks the winning outcome. It's allowed even before the prediction is locked. `cancel()` refunds everyone, and `lock()` closes voting early.

### Example of a prediction script

```gdscript
extends Node

var prediction: TwitchPrediction

func create_prediction(title: String, outcomes: PackedStringArray) -> void:
	# We already started a prediction, so we don't do anything.
	if prediction:
		return
	var definition := TwitchPredictionDefinition.new()
	definition.title = title
	definition.outcomes = outcomes # for example ["Yes", "No"]
	definition.duration = 120 # in seconds, from 1 to 1800

	var task := Twitch.new_prediction(definition)
	prediction = await task.completed
	if task.has_error():
		push_error("Creating the prediction failed: " + task.error)
		return
	prediction.locked.connect(func(_info: TwitchPredictionInfo): print("Voting has closed."))
	prediction.ended.connect(func(_info: TwitchPredictionInfo): prediction = null)

# Called once the game knows the result, with the index of the outcome that happened.
func end_prediction(winning_outcome: int) -> void:
	if not prediction:
		return
	var task := prediction.resolve(prediction.info.outcomes[winning_outcome])
	await task.completed
	if task.has_error():
		push_error("Resolving the prediction failed: " + task.error)

# Called if the game can't determine a result. Viewers get their Channel Points back.
func cancel_prediction() -> void:
	if prediction:
		await prediction.cancel().completed
```

## 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.replace_custom_rewards()` 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. It takes a typed `Array[TwitchCustomRewardDefinition]`. 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.prepare_shutdown()` before quitting (see [Shutting down](#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.

```gdscript
extends Node

func set_sample_rewards() -> void:
	var rewards: Array[TwitchCustomRewardDefinition] = [
		_reward("Red!", 10),
		_reward("Blue!", 25),
		_reward("Octarine!", 750),
	]
	var task := Twitch.replace_custom_rewards(rewards)
	await task.completed
	if task.has_error():
		push_error("Creating the rewards failed: " + task.error)

func clear_rewards() -> void:
	# An empty list removes all rewards the game has created.
	var none: Array[TwitchCustomRewardDefinition] = []
	await Twitch.replace_custom_rewards(none).completed

func _reward(title: String, cost: int) -> TwitchCustomRewardDefinition:
	var reward := TwitchCustomRewardDefinition.new()
	reward.title = title
	reward.cost = cost
	return reward
```

Once you have created custom Channel Point rewards, subscribe to their redemptions as described under [Subscribe to Events](#subscribe-to-events). Each redemption starts out unfulfilled. Use `Twitch.resolve_custom_reward_event(event, Twitch.CUSTOM_REWARD_REDEMPTION_STATE_FULFILLED)` once your game has acted on it, or `Twitch.CUSTOM_REWARD_REDEMPTION_STATE_CANCELED` to refund the viewer's Channel Points.

## User Info

To retrieve information about the logged-in user, such as `display_name`, `login_name` or `broadcaster_type`, call `Twitch.get_my_user_info()`. Its result is a `TwitchUserInfo`. If the user isn't logged in yet, the task waits until they are.
`get_user_info_by_id()` and `get_user_info_by_login_name()` 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.

```gdscript
func show_user_information() -> void:
	var task := Twitch.get_my_user_info()
	var user: TwitchUserInfo = await task.completed
	if task.has_error():
		push_error(task.error)
		return
	print("Login Name: ", user.login_name)
	print("Display Name: ", user.display_name)
	print("Broadcaster Type: ", user.broadcaster_type)
	print("User Type: ", user.user_type)
```

## Stream Info

To retrieve information about the logged-in user's stream, such as `viewer_count`, `language` or `game_name`, call `Twitch.get_my_stream_info()`. Its result is a `TwitchStreamInfo`. If the user isn't live, its `id` is empty.
`get_stream_info_by_id()` returns the same information for another channel (or `null` if that channel isn't live), and `query_streams()` searches for live streams.

```gdscript
func show_stream_information() -> void:
	var task := Twitch.get_my_stream_info()
	var stream: TwitchStreamInfo = await task.completed
	if task.has_error():
		push_error(task.error)
		return
	if stream == null or stream.id.is_empty():
		print("The user isn't live right now.")
		return
	print("Game Name: ", stream.game_name)
	print("Mature: ", stream.is_mature)
	print("Language: ", stream.language)
	print("Title: ", stream.title)
	print("Viewers: ", stream.viewer_count)
```

## Subscribe to Events

Events such as new followers, subscribers, cheers, raids, Hype Trains and Channel Point redemptions arrive through EventSub. Each `subscribe_to_*_events()` call returns a task whose result is a `TwitchEventStream`:

| Method | Event type | Required scope |
| --- | --- | --- |
| `subscribe_to_channel_follow_events()` | `TwitchChannelFollowEvent` | `moderator:read:followers` |
| `subscribe_to_channel_subscribe_events()` | `TwitchChannelSubscribeEvent` | `channel:read:subscriptions` |
| `subscribe_to_channel_cheer_events()` | `TwitchChannelCheerEvent` | `bits:read` |
| `subscribe_to_channel_raid_events()` | `TwitchChannelRaidEvent` | none |
| `subscribe_to_hype_train_events()` | `TwitchHypeTrainEvent` | `channel:read:hype_train` |
| `subscribe_to_custom_reward_events()` | `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 a `TwitchEventStream`, you have a choice to either use `wait_for_event()` or `try_get_next_event()`.
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 `try_get_next_event()`: it returns the next event if one has arrived, and `null` otherwise. `wait_for_event()` returns a task that completes with the next event.

Events that arrive while you aren't reading them are buffered (up to 512 per stream), so keep reading them, and call `close()` on the stream when you no longer want events. Freeing the stream closes it too.

### Follows

```gdscript
extends Node

var follows: TwitchEventStream

func _ready() -> void:
	follows = await Twitch.subscribe_to_channel_follow_events().completed

func _process(_delta: float) -> void:
	if not follows:
		return
	var event: TwitchChannelFollowEvent = follows.try_get_next_event()
	if event:
		# Do something
		print(event.user_display_name, " is now following!")

func _exit_tree() -> void:
	if follows:
		follows.close()
```

The remaining examples use `wait_for_event()` in a loop instead. Each one runs until the stream is closed.

### Subscribers

```gdscript
func listen_for_subscribers() -> void:
	var stream: TwitchEventStream = await Twitch.subscribe_to_channel_subscribe_events().completed
	while stream and not stream.is_closed():
		var wait := stream.wait_for_event()
		var event: TwitchChannelSubscribeEvent = await wait.completed
		if wait.has_error():
			break
		# Do something
		if event.is_gift:
			print(event.user_display_name, " received a gifted subscription!")
		else:
			print(event.user_display_name, " has subscribed!")
```

### Cheers

```gdscript
func listen_for_cheers() -> void:
	var stream: TwitchEventStream = await Twitch.subscribe_to_channel_cheer_events().completed
	while stream and not stream.is_closed():
		var wait := stream.wait_for_event()
		var event: TwitchChannelCheerEvent = await wait.completed
		if wait.has_error():
			break
		# Do something
		var who := "An anonymous viewer" if event.is_anonymous else event.user_display_name
		print("%s cheered %d Bits!" % [who, event.bits])
```

### Channel Point Rewards

```gdscript
func listen_for_redemptions() -> void:
	var stream: TwitchEventStream = await Twitch.subscribe_to_custom_reward_events().completed
	while stream and not stream.is_closed():
		var wait := stream.wait_for_event()
		var event: TwitchCustomRewardEvent = await wait.completed
		if wait.has_error():
			break
		# Updates to redemptions (fulfilled or canceled) arrive here too.
		if event.status != Twitch.CUSTOM_REWARD_REDEMPTION_STATE_UNFULFILLED:
			continue
		# Do something
		print("%s has bought %s for %d!" % [event.redeemer_name, event.custom_reward_title, event.custom_reward_cost])
		Twitch.resolve_custom_reward_event(event, Twitch.CUSTOM_REWARD_REDEMPTION_STATE_FULFILLED)
```

### Hype Train

Hype Train events arrive when a Hype Train starts, makes progress, and ends. `ended_at` is empty until the Hype Train is over.

```gdscript
func listen_for_hype_trains() -> void:
	var stream: TwitchEventStream = await Twitch.subscribe_to_hype_train_events().completed
	while stream and not stream.is_closed():
		var wait := stream.wait_for_event()
		var event: TwitchHypeTrainEvent = await wait.completed
		if wait.has_error():
			break
		# Do something
		if event.ended_at.is_empty():
			print("The Hype Train is at level %d: %d / %d points!" % [event.level, event.progress, event.goal])
		else:
			print("The Hype Train ended at level %d." % event.level)
```

### Raids

```gdscript
func listen_for_raids() -> void:
	var stream: TwitchEventStream = await Twitch.subscribe_to_channel_raid_events().completed
	while stream and not stream.is_closed():
		var wait := stream.wait_for_event()
		var event: TwitchChannelRaidEvent = await wait.completed
		if wait.has_error():
			break
		# Do something
		print("%s has raided %s with %d viewers!" % [event.from_broadcaster_name, event.to_broadcaster_name, event.viewers])
```

## Drops

The plugin supports the "offline inventory" model of [Twitch Drops](https://dev.twitch.tv/docs/drops.md): 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.

```gdscript
func check_for_drops() -> void:
	# By default, only the Drops the user has claimed but not received yet.
	var task := Twitch.get_drop_entitlements()
	var result: TwitchDropEntitlementList = await task.completed
	if task.has_error():
		push_error("Checking for Drops failed: " + task.error)
		return

	# Grant each reward in-game. Only fulfill the ones you actually granted.
	var granted: Array[TwitchDropEntitlement] = []
	for entitlement in result.entitlements:
		# benefit_id tells you which reward this is.
		if grant_item(entitlement.benefit_id):
			granted.append(entitlement)

	if not granted.is_empty():
		var fulfill := Twitch.fulfill_drop_entitlement_list(granted)
		await fulfill.completed
		if fulfill.has_error():
			push_error("Marking the Drops fulfilled failed: " + fulfill.error)

# Your own inventory logic. Return true only if the item was actually granted.
func grant_item(benefit_id: String) -> bool:
	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 emitted as the `Twitch.log_message(level, message)` signal, for example to show them in an in-game console:

```gdscript
func _ready() -> void:
	Twitch.log_message.connect(_on_twitch_log)

func _on_twitch_log(level: int, message: String) -> void:
	if level >= Twitch.LOG_LEVEL_WARNING:
		print("Twitch: ", message)
```

## Shutting down

The plugin shuts down automatically when the game exits. If your game created Channel Point rewards, await `Twitch.prepare_shutdown()` before quitting, so that they're removed from the channel:

```gdscript
extends Node

func _ready() -> void:
	# Let us clean up before the window closes.
	get_tree().set_auto_accept_quit(false)

func _notification(what: int) -> void:
	if what == NOTIFICATION_WM_CLOSE_REQUEST:
		_quit()

func _quit() -> void:
	await Twitch.prepare_shutdown().completed
	get_tree().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](https://dev.twitch.tv/docs/game-engine-plugins.md)).

## Samples

The plugin comes with two sample projects that show all of its functionality: one written in GDScript, and one in C#. 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.
