twitchws

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Jan 8, 2025 License: Apache-2.0 Imports: 11 Imported by: 0

README

lint tests Go Reference Go Report Card GitHub go.mod Go version GitHub Release

Twitch WebSocket EventSub Client


This repo contains of two packages:

  • twitchws: Twitch WebSocket EventSub client
  • eventsub: EventSub messages declared by Twitch

Package twitchws

Implements Twitch WebSocket EventSub protocol requirements described here. The client is able to handle:

  • EventSub notifications
  • keep-alive messages
  • reconnection requests
  • revocation requests

Usage example with Twitch CLI:

package main

import (
	"fmt"
	
	"github.com/vpetrigo/go-twitch-ws"
)

const websocketTwitchTestServer = "ws://127.0.0.1:8080/ws"

func main() {
	messageHandler := func(m *twitchws.Metadata, p *twitchws.Payload) {
		fmt.Printf("Metadata: %+v\n", m)
		fmt.Printf("Payload: %+v\n", p)
	}
	stateHandler := func(state string) func() {
		return func() {
			fmt.Printf("Event: %s\n", state)
		}
	}

	c := twitchws.NewClient(
		websocketTwitchTestServer,
		twitchws.WithOnWelcome(messageHandler),
		twitchws.WithOnNotification(messageHandler),
		twitchws.WithOnConnect(stateHandler("Connect")),
		twitchws.WithOnDisconnect(stateHandler("Disconnect")),
		twitchws.WithOnRevocation(messageHandler))

	err := c.Connect()

	if err != nil {
		fmt.Println(err)
	}

	err = c.Wait()

	if err != nil {
		fmt.Println(err)
	}

	err = c.Close()

	if err != nil {
		fmt.Println(err)
	}
}

Package eventsub

It is an attempt to automatically parse Twitch official API reference in order to generate respective types. There are some issues that have to be resolved before all types will be properly parsed.

Examples

All examples are available in the examples directory

Contribution

Contributions are always welcome! If you have an idea, it's best to float it by me before working on it to ensure no effort is wasted. If there's already an open issue for it, knock yourself out. See the contributing section for additional details

Design

Documentation

Overview

Package twitchws provides a client library for interacting with Twitch's EventSub WebSocket API. This package manages WebSocket connections, handles reconnections, processes different message types, and exposes an interface to listen for events and notifications from Twitch EventSub.

Features

• Establish and manage a WebSocket connection to the Twitch EventSub service.

• Support for reconnection with automatic handling of session re-establishment.

• Handlers for various Twitch EventSub message types, including session updates, notifications, keepalives, and more.

• Customizable message and event handling through callback functions.

• Context-driven lifecycle management, ensuring clean connection termination and resource cleanup.

• Built-in support for message caching and TTL-based handling of message metadata.

Usage Example

Below is an example of using the `twitchws` package to connect to the Twitch EventSub WebSocket and listen to event notifications.

package main

import (
	"context"
	"fmt"

	"github.com/vpetrigo/go-twitch-ws"
)

const websocketTwitchTestServer = "ws://127.0.0.1:8080/ws"

func main() {
	messageHandler := func(m *twitchws.Metadata, p *twitchws.Payload) {
		fmt.Printf("Metadata: %+v\n", m)
		fmt.Printf("Payload: %+v\n", p)
	}
	stateHandler := func(state string) func() {
		return func() {
			fmt.Printf("Event: %s\n", state)
		}
	}
	c := twitchws.NewClient(
		websocketTwitchTestServer,
		twitchws.WithOnWelcome(messageHandler),
		twitchws.WithOnNotification(messageHandler),
		twitchws.WithOnConnect(stateHandler("Connect")),
		twitchws.WithOnDisconnect(stateHandler("Disconnect")),
		twitchws.WithOnRevocation(messageHandler))
	// Start the WebSocket connection.
	err := c.Connect()

	if err != nil {
		fmt.Println(err)
	}
	// Wait or run other application logic here.
	err = c.Wait()

	if err != nil {
		fmt.Println(err)
	}
	// Properly stop the client when shutting down.
	err = c.Close()

	if err != nil {
		fmt.Println(err)
	}
}

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrAlreadyInUse     = errors.New("client already in use")      // WebSocket client is already in use.
	ErrNotConnected     = errors.New("client is not connected")    // WebSocket client is not connected
	ErrConnectionFailed = errors.New("failed to setup connection") // Failed to set up WebSocket connection
)

Functions

This section is empty.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

func NewClient

func NewClient(url string, opts ...Option) *Client

NewClient creates and returns a new Client instance configured with the provided WebSocket URL and optional settings.

func NewClientDefault

func NewClientDefault(opts ...Option) *Client

NewClientDefault creates a new Client instance with the default websocketTwitch URL and optional configuration options.

func (*Client) Close

func (c *Client) Close() error

Close gracefully terminates the client's connection, stops the worker, cancels contexts, and waits for cleanup to complete.

func (*Client) Connect

func (c *Client) Connect() error

Connect establishes a connection by initializing contexts, transitioning to the connecting state, and starting the worker. Returns an error if the client is already active.

func (*Client) Wait

func (c *Client) Wait() error

Wait blocks until all client tasks have completed. Returns any error encountered during awaiting.

type EventSubScope added in v0.1.2

type EventSubScope struct {
	Version       string
	MsgType       interface{}
	ConditionType interface{}
}

type EventsubCondition

type EventsubCondition struct {
	BroadcasterUserID     string `json:"broadcaster_user_id,omitempty"`
	ToBroadcasterUserID   string `json:"to_broadcaster_user_id,omitempty"`
	UserID                string `json:"user_id,omitempty"`
	FromBroadcasterUserID string `json:"from_broadcaster_user_id,omitempty"`
	ModeratorUserID       string `json:"moderator_user_id,omitempty"`
	ClientID              string `json:"client_id,omitempty"`
	ExtensionClientID     string `json:"extension_client_id,omitempty"`
	OrganizationID        string `json:"organization_id,omitempty"`
	CategoryID            string `json:"category_id,omitempty"`
	CampaignID            string `json:"campaign_id,omitempty"`
}

type EventsubSubscription

type EventsubSubscription struct {
	ID        string            `json:"id"`
	Status    string            `json:"status"`
	Type      string            `json:"type"`
	Version   string            `json:"version"`
	Condition EventsubCondition `json:"condition"`
	Transport EventsubTransport `json:"transport"`
	CreatedAt string            `json:"created_at"`
	Cost      int64             `json:"cost"`
}

type EventsubTransport

type EventsubTransport struct {
	Method    string `json:"method"`
	Callback  string `json:"callback,omitempty"`
	SessionID string `json:"session_id,omitempty"`
}

type Metadata

type Metadata struct {
	MessageID           string `json:"message_id"`
	MessageType         string `json:"message_type"`
	MessageTimestamp    string `json:"message_timestamp"`
	SubscriptionType    string `json:"subscription_type"`
	SubscriptionVersion string `json:"subscription_version"`
}

type Notification

type Notification struct {
	Subscription EventsubSubscription `json:"subscription"`
	Event        interface{}          `json:"event"`
}

type OnEventFn

type OnEventFn func()

OnEventFn defines a callback function to be executed on specific client events such as connection or disconnection.

type OnMessageEventFn

type OnMessageEventFn func(*Metadata, *Payload)

OnMessageEventFn defines a callback function to process message events, receiving metadata and payload as parameters.

type Option

type Option func(*Client)

Option is a functional option used to configure a Client instance.

func WithOnConnect

func WithOnConnect(fn OnEventFn) Option

WithOnConnect sets the callback function to be executed when the client successfully connects to the WebSocket server.

func WithOnDisconnect

func WithOnDisconnect(fn OnEventFn) Option

WithOnDisconnect sets the callback function to be executed when the client disconnects.

func WithOnKeepalive

func WithOnKeepalive(fn OnMessageEventFn) Option

WithOnKeepalive sets a callback function to handle keepalive messages for the client instance.

func WithOnNotification

func WithOnNotification(fn OnMessageEventFn) Option

WithOnNotification sets the callback function to handle notification messages received by the client.

func WithOnReconnect

func WithOnReconnect(fn OnMessageEventFn) Option

WithOnReconnect configures a callback function to be invoked when a reconnect message is received by the client.

func WithOnRevocation

func WithOnRevocation(fn OnMessageEventFn) Option

WithOnRevocation sets a callback function to handle revocation messages and returns an Option for the Client configuration.

func WithOnWelcome

func WithOnWelcome(fn OnMessageEventFn) Option

WithOnWelcome sets a callback function to handle welcome message events for the client.

type Payload

type Payload struct {
	Payload interface{}
}

type Session

type Session struct {
	ID                      string `json:"id"`
	Status                  string `json:"status"`
	ReconnectURL            string `json:"reconnect_url"`
	ConnectedAt             string `json:"connected_at"`
	KeepaliveTimeoutSeconds int    `json:"keepalive_timeout_seconds"`
}

Directories

Path Synopsis
internal
pkg

Jump to

Keyboard shortcuts

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