pubsub

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 28, 2021 License: MIT Imports: 16 Imported by: 0

README

Twitch PubSub Golang Library

Go Reference

Twitch PubSub enables you to subscribe to a topic for updates (e.g. when a user cheers in a channel). This Go library will establish a WebSocket connection to Twitch's servers, listen on topics you care about, and get messages on those topics in real time.

This library implements the connection management requirements as described in the official docs, including handling of PING/PONGs and RECONNECT messages.

go get github.com/tracy-and-matt/go-twitch-pubsub@latest 

Usage

A quick usage example. Also check out a fully working example which listens for whisper messages.

import (
  "github.com/tracy-and-matt/go-twitch-pubsub"
  "github.com/tracy-and-matt/go-twitch-pubsub/messages"
)

c, err := pubsub.NewClient()

c.OnConnect = func() {
  // Called every time a connection is established.
  // Fetch authtoken and refresh it if necessary.
  c.Listen("authtoken", "topic.userid)
}

c.OnMessage = func(topic string, message pubsub.Message, raw io.Reader, err error) {
  if err != nil {
    return // do something with error
  }

  switch m := message.(type) {
    case *messages.Whispers:
      fmt.Println(m)
  }
}

c.Connect(ctx)

OnConnect should fetch the latest OAuth token from whatever your source is and refresh it if necessary.

Message Decoders

This library ships with default message decoders for the currently known Twitch message types, see messages. Unfortunately the Twitch docs are sometimes outdated. RegisterMessageDecoder enables you to register custom message decoders to quickly update decoders to adapt to Twitch PubSub message type changes. Please contribute changes back to this library so everyone can benefit.

Alternatives

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNoConnection     = fmt.Errorf("no connection")
	ErrNoNonce          = fmt.Errorf("command responded with unknown nonce")
	ErrNoMessageDecoder = fmt.Errorf("no decoder for message")
)
View Source
var (
	ErrMalformedTopic = fmt.Errorf("malformed topic")
)

Functions

func DebugMessage

func DebugMessage(topic string, message interface{}, raw io.Reader, err error)

DebugMessage can be used for client.OnMessage to debug Twitch messages

func DiscardMessage

func DiscardMessage(topic string, message interface{}, raw io.Reader, err error)

DiscardMessage can be used for client.OnMessage to just discard messages.

func RegisterMessageDecoder

func RegisterMessageDecoder(topic string, d MessageDecoderFunc)

RegisterMessageDecoder registers a new MessageDecoderFunc. It will overwrite any existing decoder for the given topic name.

func Topic

func Topic(topic string) (string, error)

Topic returns topic name without channel ids or user ids. It returns ErrMalformedTopic if the topic name can't be parsed.

func UnregisterMessageDecoder

func UnregisterMessageDecoder(topic string)

UnregisterMessageDecoder unregisters a MessageDecoderFunc

Types

type Client

type Client struct {
	// WebsocketURL specifies the Twitch Websocket URL,
	// leave blank to use the default URL. If you change it,
	// do it before calling Connect(ctx) for the first time to avoid race conditions.
	WebsocketURL string

	// OnConnect is called every time a connection is successfully established
	OnConnect OnConnectFunc

	// OnDisconnect is called every time a connection is lost
	OnDisconnect OnDisconnectFunc

	// OnMessage is called for every message
	OnMessage OnMessageFunc

	// OnUnknownMessage is called for every unknown message. Use it for debugging.
	OnUnknownMessage OnUnknownMessageFunc
	// contains filtered or unexported fields
}

Cient is a Twitch PubSub Client

func NewClient

func NewClient() (*Client, error)

NewClient initializes a new Twitch PubSub client.

func (*Client) Connect

func (c *Client) Connect(ctx context.Context)

Connect will connect to Twitch's PubSub websocket server. It will automatically re-connect if the connection is lost and the given context hasn't been cancelled. To disconnect, cancel the given context.

To manually re-connect, cancel the context and call Connect with a new context. Calling Connect with a new or the same context while the initially given context hasn't been cancelled yet, is a no-op.

Connect is non-blocking and will return immediately.

func (*Client) Listen

func (c *Client) Listen(authToken string, topics ...string) error

Listen on Twitch PubSub topics. Read more about available topics here: https://dev.twitch.tv/docs/pubsub#topics

If the websocket connection is lost, the subscribed topic details are lost as well. It is recommended to call Listen in the OnConnect hook to ensure you subscribe to all necessary topics every time we establish a new connection.

Listen will return an error if called when no connection is established.

func (*Client) Unlisten

func (c *Client) Unlisten(topics ...string) error

Unlisten stops listening for previously subscribed topics. See Listen for more information.

Unlisten will return an error if called when no connection is established.

type MessageDecoderFunc

type MessageDecoderFunc = func(body []byte) (interface{}, error)

MessageDecoderFunc receives the raw body message and decodes it into a structured Message

type OnConnectFunc

type OnConnectFunc func()

OnConnectFunc is called every time a websocket connection has been successfully established. It's recommended to call Listen inside the OnConnectFunc. It's called synchronously and will block until it returns.

type OnDisconnectFunc

type OnDisconnectFunc func()

OnDiscconnectFunc is called every time a websocket connection is lost. It's called synchronously and will block until it returns.

type OnMessageFunc

type OnMessageFunc func(topic string, message interface{}, raw io.Reader, err error)

OnMessageFunc is called for every message Twitch sends. The raw io.Reader argument always has the raw message, and the topic is set on a best-effort basis, even if an error is given.

OnMessageFunc is called synchronously and will block processing other messages until it returns. Read more about this design choice here: https://github.com/golang/go/wiki/CodeReviewComments#synchronous-functions

type OnUnknownMessageFunc

type OnUnknownMessageFunc func(body []byte)

OnUnknownMessageFunc is called for unknown Twitch messages. It's meant for debugging purposes. It's called synchronously and will block until it returns.

type TwitchError

type TwitchError struct {
	// ErrorCode is a Twitch error, for example:
	// ERR_BADMESSAGE, ERR_BADAUTH, ERR_SERVER, ERR_BADTOPIC
	// see https://dev.twitch.tv/docs/pubsub#topics under Responses
	ErrorCode string
}

func (*TwitchError) Error

func (m *TwitchError) Error() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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