twitchwh

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 24, 2025 License: GPL-3.0 Imports: 14 Imported by: 0

README

TwitchWH

TwitchWH is a Twitch Webhook EventSub library for Go.

Full documentation: https://pkg.go.dev/github.com/LinneB/twitchwh

Table of contents:

Installation

go get github.com/LinneB/twitchwh

Basic Usage

This is a basic example of how to use TwitchWH. It creates a new client, adds an event listener, and subscribes to an event.

For the full documentation, see pkg.go.dev.

package main

import (
	"log"
	"net/http"

	"github.com/LinneB/twitchwh"
)

func main() {
	// Create a new Client
	client, err := twitchwh.New(twitchwh.ClientConfig{
		ClientID:      "client id",
		ClientSecret:  "super secret client secret",
		WebhookSecret: "random string between 10 and 100 characters",
		// This example assumes you have a domain that points to this app on port 8080
		WebhookURL:    "https://yourdomain.com/eventsub",
		// Enable log output
		Debug: true,
	})
	if err != nil {
		log.Panic(err)
	}

	// Set up an event handler
	client.On("stream.online", func(event json.RawMessage) {
		var eventBody struct {
			BroadcasterUserLogin string `json:"broadcaster_user_login"`
		}
		json.Unmarshal(event, &eventBody)
		log.Printf("%s went live!", eventBody.BroadcasterUserLogin)
	})

	// Setup the HTTP event handler
	// This needs to be done before you subscribe to any events, since AddSubscription will wait until Twitch sends the challenge request
	http.HandleFunc("/eventsub", client.Handler)
	go http.ListenAndServe(":8080", nil)

	// Add a subscription for LinneB going live
	// Note that this will throw an error if the subscription already exists
	err = client.AddSubscription("stream.online", "1", twitchwh.Condition{
		BroadcasterUserID: "215185844",
	})
	if err != nil {
		log.Panic(err)
	}

	// Wait forever
	select {}
}

Contributing

Contributions are welcome. If you find any issues or have any suggestions, please open an issue or a pull request.

Questions and feature requests are also welcome, just open an issue.

Supported Events

TwitchWH should theoretically support all current and future EventSub events, as long as the Condition struct has the required fields. If you find an event that is not supported, don't hesitate to open an issue.

Documentation

Overview

Package twitchwh is a library for interacting with Twitch EventSub over the Webhook transport. It allows you to assign event handlers to specific events.

To get started, create a new client using the New function. Then, assign an event handler using the On<EventType> fields. Finally, setup the HTTP handler for your application using the Handler function.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {

	// Fired whenever a subscription is revoked.
	// Check Subscription.Status for the reason.
	OnRevocation func(Subscription)
	// contains filtered or unexported fields
}

func New

func New(config ClientConfig) (*Client, error)

Creates a new client

func (*Client) AddSubscription

func (c *Client) AddSubscription(Type string, version string, condition Condition) error

AddSubscription attemps to create a new subscription based on the type, version, and condition. You can find all subscription types, versions, and conditions at: EventSub subscription types. It will block until Twitch sends the verification request, or timeout after 10 seconds.

!! AddSubscription should only be called AFTER twitchwh.Client.Handler is set up accordingly. !!

// Setup the HTTP event handler
http.HandleFunc("/eventsub", client.Handler)
go http.ListenAndServe(":8080", nil)

_ := client.AddSubscription("stream.online", "1", twitchwh.Condition{
	BroadcasterUserID: "215185844",
})

func (*Client) GetSubscriptions

func (c *Client) GetSubscriptions() (subscriptions []Subscription, err error)

GetSubscriptions retrieves all subscriptions, including revoked ones. Automatically handles pagination.

Returns subscriptions and an error (if any).

func (*Client) GetSubscriptionsByStatus

func (c *Client) GetSubscriptionsByStatus(status string) (subscriptions []Subscription, err error)

Get all subscriptions with the provided status. For a list of all status types see: https://dev.twitch.tv/docs/api/reference/#get-eventsub-subscriptions . Automatically handles pagination.

Returns subscriptions and an error (if any).

func (*Client) GetSubscriptionsByType

func (c *Client) GetSubscriptionsByType(Type string) (subscriptions []Subscription, err error)

Get all subscriptions that match the provided type (eg. "stream.online"). Automatically handles pagination.

Returns subscriptions and an error (if any).

func (*Client) Handler

func (c *Client) Handler(w http.ResponseWriter, r *http.Request)

Handler is the HTTP handler for requests from Twitch. It is up to you to assign this handler to the correct path according to your setup

client, _ := twitchwh.New(twitchwh.ClientConfig{
	// ...
	WebhookURL:    "https://mydomain.com/eventsub",
})
http.HandleFunc("/eventsub", client.Handler)
http.ListenAndServe(":443", nil)

This example assumes https://mydomain.com is pointing to the Go app.

func (*Client) On added in v0.1.0

func (c *Client) On(event string, handler func(json.RawMessage))

Assign a handler to a particular event type. The handler takes a json.RawMessage that contains the event body. For a list of event types, see [https://dev.twitch.tv/docs/eventsub/eventsub-subscription-types/].

func (*Client) RemoveSubscription

func (c *Client) RemoveSubscription(id string) error

RemoveSubscription attempts to remove a subscription based on the ID. Returns SubscriptionNotFoundError if the subscription does not exist.

func (*Client) RemoveSubscriptionByType added in v0.0.2

func (c *Client) RemoveSubscriptionByType(Type string, condition Condition) error

RemoveSubscriptionByType attempts to remove a subscription based on the type and condition.

If no subscriptions are found, it will return nil.

Note: This will remove ALL subscriptions that match the provided type and condition.

type ClientConfig

type ClientConfig struct {
	// Client ID of your Twitch application
	ClientID string
	// Client Secret generated for your Twitch application. !! THIS IS NOT YOUR WEBHOOK SECRET !!
	ClientSecret string
	// Webhook secret used to verify events. This should be a random string between 10-100 characters
	WebhookSecret string
	// Full EventSub URL path, eg: https://mydomain.com/eventsub
	WebhookURL string
	// Log output
	Debug bool
}

ClientConfig is used to configure a new Client

type Condition

type Condition struct {
	// broadcaster_user_id
	BroadcasterUserID string `json:"broadcaster_user_id,omitempty"`

	// moderator_user_id
	ModeratorUserID string `json:"moderator_user_id,omitempty"`

	// user_id
	UserID string `json:"user_id,omitempty"`

	// from_broadcaster_id
	FromBroadcasterUserID string `json:"from_broadcaster_user_id,omitempty"`

	// to_broadcaster_id
	ToBroadcasterUserID string `json:"to_broadcaster_user_id,omitempty"`

	// reward_id
	//
	// This should be int/string depending on subscription type
	RewardID any `json:"reward_id,omitempty"`

	// client_id
	ClientID string `json:"client_id,omitempty"`

	// extension_client_id
	ExtensionClientID string `json:"extension_client_id,omitempty"`

	// conduit_id
	ConduitID string `json:"conduit_id,omitempty"`

	// organization_id
	OrganizationID string `json:"organization_id,omitempty"`

	// category_id
	CategoryID string `json:"category_id,omitempty"`

	// campaign_id
	CampaignID string `json:"campaign_id,omitempty"`
}

Condition for subscription. Empty values will be omitted. Fill out the options applicable to your subscription type

type DuplicateSubscriptionError added in v0.0.3

type DuplicateSubscriptionError struct {
	Condition Condition
	Type      string
}

Attempted to add a subscription with a type and condition that already exists.

The Condition and Type fields are included in the error.

func (*DuplicateSubscriptionError) Error added in v0.0.3

type InternalError added in v0.0.3

type InternalError struct {

	// Original error that caused this error, if any.
	OriginalError error
	// contains filtered or unexported fields
}

Returned for misc errors, like network or serialization errors for example.

func (*InternalError) Error added in v0.0.3

func (e *InternalError) Error() string

type Subscription

type Subscription struct {
	ID      string `json:"id"`
	Status  string `json:"status"`
	Type    string `json:"type"`
	Version string `json:"version"`
	Cost    int    `json:"cost"`
	// PLEASE NOTE that this will DEFAULT all unused conditions. Check the Type and get the correct condition for that type.
	Condition Condition `json:"condition"`
	Transport struct {
		Method   string `json:"method"`
		Callback string `json:"callback"`
	} `json:"transport"`
	CreatedAt time.Time `json:"created_at"`
}

type SubscriptionNotFoundError added in v0.0.3

type SubscriptionNotFoundError struct{}

Could not find a subscription with the specified parameters.

func (*SubscriptionNotFoundError) Error added in v0.0.3

func (e *SubscriptionNotFoundError) Error() string

type UnauthorizedError added in v0.0.3

type UnauthorizedError struct{}

Helix returned an authorization error. This usually means the token, Client-ID, or client secret are invalid.

func (*UnauthorizedError) Error added in v0.0.3

func (e *UnauthorizedError) Error() string

type UnhandledStatusError added in v0.0.3

type UnhandledStatusError struct {
	Status int
	Body   []byte
}

Helix returned an unexpected HTTP status code that is not handled by TwitchWH.

func (*UnhandledStatusError) Error added in v0.0.3

func (e *UnhandledStatusError) Error() string

type VerificationTimeoutError added in v0.0.3

type VerificationTimeoutError struct {
	Subscription Subscription
}

Returned whenever AddSubscription times out waiting for verification confirmation.

func (*VerificationTimeoutError) Error added in v0.0.3

func (e *VerificationTimeoutError) Error() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL