twitch

package module
Version: v2.8.1 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2021 License: MIT Imports: 13 Imported by: 54

README

go-twitch-irc Coverage Status

This is an irc client for connecting to twitch. It handles the annoying stuff like irc tag parsing. I highly recommend reading the documentation below, but this readme gives a basic overview of the functionality.

Documentation: https://pkg.go.dev/github.com/gempir/go-twitch-irc/v2?tab=doc

Getting Started

package main

import (
	"fmt"

	"github.com/gempir/go-twitch-irc/v2"
)

func main() {
	// or client := twitch.NewAnonymousClient() for an anonymous user (no write capabilities)
	client := twitch.NewClient("yourtwitchusername", "oauth:123123123")

	client.OnPrivateMessage(func(message twitch.PrivateMessage) {
		fmt.Println(message.Message)
	})

	client.Join("gempir")

	err := client.Connect()
	if err != nil {
		panic(err)
	}
}
Available Data

The twitch.User and MessageType structs reflect the data Twitch provides, minus any fields that have been marked as deprecated:

type User struct {
	ID          string
	Name        string
	DisplayName string
	Color       string
	Badges      map[string]int
}

type WhisperMessage struct {
	User User

	Raw       string
	Type      MessageType
	RawType   string
	Tags      map[string]string
	Message   string
	Target    string
	MessageID string
	ThreadID  string
	Emotes    []*Emote
	Action    bool
}

type PrivateMessage struct {
	User User

	Raw     string
	Type    MessageType
	RawType string
	Tags    map[string]string
	Message string
	Channel string
	RoomID  string
	ID      string
	Time    time.Time
	Emotes  []*Emote
	Bits    int
	Action  bool
}

type ClearChatMessage struct {
	Raw            string
	Type           MessageType
	RawType        string
	Tags           map[string]string
	Message        string
	Channel        string
	RoomID         string
	Time           time.Time
	BanDuration    int
	TargetUserID   string
	TargetUsername string
}

type ClearMessage struct {
	Raw         string
	Type        MessageType
	RawType     string
	Tags        map[string]string
	Message     string
	Channel     string
	Login       string
	TargetMsgID string
}

type RoomStateMessage struct {
	Raw     string
	Type    MessageType
	RawType string
	Tags    map[string]string
	Message string
	Channel string
	RoomID  string
	State   map[string]int
}

type UserNoticeMessage struct {
	User User

	Raw       string
	Type      MessageType
	RawType   string
	Tags      map[string]string
	Message   string
	Channel   string
	RoomID    string
	ID        string
	Time      time.Time
	Emotes    []*Emote
	MsgID     string
	MsgParams map[string]string
	SystemMsg string
}

type UserStateMessage struct {
	User User

	Raw       string
	Type      MessageType
	RawType   string
	Tags      map[string]string
	Message   string
	Channel   string
	EmoteSets []string
}

type GlobalUserStateMessage struct {
	User User

	Raw       string
	Type      MessageType
	RawType   string
	Tags      map[string]string
	EmoteSets []string
}

type NoticeMessage struct {
	Raw     string
	Type    MessageType
	RawType string
	Tags    map[string]string
	Message string
	Channel string
	MsgID   string
}

type UserJoinMessage struct {
	// Channel name
	Channel string

	// User name
	User string
}

type UserPartMessage struct {
	// Channel name
	Channel string

	// User name
	User string
}

For unsupported message types, we return RawMessage:

type RawMessage struct {
	Raw     string
	Type    MessageType
	RawType string
	Tags    map[string]string
	Message string
}
Available Methods

ParseMessage parses a raw Twitch IRC message into a User and a message object. User can be nil.

func ParseMessage(line string) (*User, interface{})
Client Methods

These are the available methods of the client so you can get your bot going:

func (c *Client) Say(channel, text string)
func (c *Client) Whisper(username, text string)
func (c *Client) Join(channel string)
func (c *Client) Depart(channel string)
func (c *Client) Userlist(channel string) ([]string, error)
func (c *Client) Connect() error
func (c *Client) Disconnect() error
Options

On your client you can configure multiple options:

client.IrcAddress = "127.0.0.1:3030" // for custom irc server
client.TLS = false // enabled by default, will connect to non TLS server of twitch when off or the given client.IrcAddress
client.SetupCmd = "LOGIN custom_command_here" // Send a custom command on successful IRC connection, before authentication.
client.Capabilities = []string{twitch.TagsCapability, twitch.CommandsCapability} // Customize which capabilities are sent
client.SetRateLimiter(twitch.CreateVerifiedRateLimiter()) // If you have a verified bot or other needs use this to set a custom rate limiter

Option modifications must be done before calling Connect on the client.

Capabilities

By default, the client sends along all 3 Twitch capabilities (Tags, Commands, Membership).

Callbacks

These callbacks are available to pass to the client:

client.OnConnect(func() {})
client.OnPrivateMessage(func(message PrivateMessage) {})
client.OnWhisperMessage(func(message WhisperMessage) {})
client.OnClearChatMessage(func(message ClearChatMessage) {})
client.OnClearMessage(func(message ClearMessage) {})
client.OnRoomStateMessage(func(message RoomStateMessage) {})
client.OnUserNoticeMessage(func(message UserNoticeMessage) {})
client.OnUserStateMessage(func(message UserStateMessage) {})
client.OnGlobalUserStateMessage(func(message GlobalUserStateMessage) {})
client.OnNoticeMessage(func(message NoticeMessage) {})
client.OnUserJoinMessage(func(message UserJoinMessage) {})
client.OnUserPartMessage(func(message UserPartMessage) {})
Message Types

If you ever need more than basic PRIVMSG, this might be for you. These are the message types currently supported:

WHISPER
PRIVMSG
CLEARCHAT
CLEARMSG
ROOMSTATE
USERNOTICE
USERSTATE
GLOBALUSERSTATE
NOTICE
JOIN
PART

Documentation

Index

Constants

View Source
const (

	// TagsCapability for Twitch's Tags capabilities, see https://dev.twitch.tv/docs/irc/tags
	TagsCapability = "twitch.tv/tags"

	// CommandsCapability for Twitch's Commands capabilities, see https://dev.twitch.tv/docs/irc/commands
	CommandsCapability = "twitch.tv/commands"

	// MembershipCapability for Twitch's Membership capabilities, see https://dev.twitch.tv/docs/irc/membership
	MembershipCapability = "twitch.tv/membership"
)
View Source
const Unlimited = -1

Variables

View Source
var (
	// ErrClientDisconnected returned from Connect() when a Disconnect() was called
	ErrClientDisconnected = errors.New("client called Disconnect()")

	// ErrLoginAuthenticationFailed returned from Connect() when either the wrong or a malformed oauth token is used
	ErrLoginAuthenticationFailed = errors.New("login authentication failed")

	// ErrConnectionIsNotOpen is returned by Disconnect in case you call it without being connected
	ErrConnectionIsNotOpen = errors.New("connection is not open")

	// WriteBufferSize can be modified to change the write channel buffer size.
	// Must be configured before NewClient is called to take effect
	WriteBufferSize = 512

	// ReadBufferSize can be modified to change the read channel buffer size.
	// Must be configured before NewClient is called to take effect
	ReadBufferSize = 64

	// DefaultCapabilities is the default caps when creating a new Client
	DefaultCapabilities = []string{TagsCapability, CommandsCapability, MembershipCapability}
)

Functions

This section is empty.

Types

type ClearChatMessage

type ClearChatMessage struct {
	Raw            string
	Type           MessageType
	RawType        string
	Tags           map[string]string
	Message        string
	Channel        string
	RoomID         string
	Time           time.Time
	BanDuration    int
	TargetUserID   string
	TargetUsername string
}

ClearChatMessage data you receive from CLEARCHAT message type

func (*ClearChatMessage) GetType

func (msg *ClearChatMessage) GetType() MessageType

GetType implements the Message interface, and returns this message's type

type ClearMessage added in v2.1.0

type ClearMessage struct {
	Raw         string
	Type        MessageType
	RawType     string
	Tags        map[string]string
	Message     string
	Channel     string
	Login       string
	TargetMsgID string
}

ClearMessage data you receive from CLEARMSG message type

func (*ClearMessage) GetType added in v2.1.0

func (msg *ClearMessage) GetType() MessageType

GetType implements the Message interface, and returns this message's type

type Client

type Client struct {
	IrcAddress string

	TLS bool

	// Option whether to send pings every `IdlePingInterval`. The IdlePingInterval is interrupted every time a message is received from the irc server
	// The variable may only be modified before calling Connect
	SendPings bool

	// IdlePingInterval is the interval at which to send a ping to the irc server to ensure the connection is alive.
	// The variable may only be modified before calling Connect
	IdlePingInterval time.Duration

	// PongTimeout is the time go-twitch-irc waits after sending a ping before issuing a reconnect
	// The variable may only be modified before calling Connect
	PongTimeout time.Duration

	// SetupCmd is the command that is ran on successful connection to Twitch. Useful if you are proxying or something to run a custom command on connect.
	// The variable must be modified before calling Connect or the command will not run.
	SetupCmd string

	// Capabilities is the list of capabilities that should be sent as part of the connection setup
	// By default, this is all caps (Tags, Commands, Membership)
	// If this is an empty list or nil, no CAP REQ message is sent at all
	Capabilities []string
	// contains filtered or unexported fields
}

Client client to control your connection and attach callbacks

func NewAnonymousClient added in v2.3.0

func NewAnonymousClient() *Client

NewAnonymousClient to create a new client without login requirements (anonymous user) Do note that the Say and Whisper functions will be ineffectual when using this constructor

func NewClient

func NewClient(username, oauth string) *Client

NewClient to create a new client

func (*Client) Connect

func (c *Client) Connect() error

Connect connect the client to the irc server

func (*Client) Depart

func (c *Client) Depart(channel string)

Depart leave a twitch channel

func (*Client) Disconnect

func (c *Client) Disconnect() error

Disconnect close current connection

func (*Client) FollowersOff added in v2.5.0

func (c *Client) FollowersOff(channel string)

FollowersOn run twitch command `/followersoff` with the given channel in argument

func (*Client) FollowersOn added in v2.5.0

func (c *Client) FollowersOn(channel, duration string)

FollowersOn run twitch command `/followers` with the given channel and duration in argument

func (*Client) Join

func (c *Client) Join(channels ...string)

Join enter a twitch channel to read more messages. It will respect the given ratelimits. This is not a blocking operation.

func (*Client) OnClearChatMessage

func (c *Client) OnClearChatMessage(callback func(message ClearChatMessage))

OnClearChatMessage attach callback to new messages such as timeouts

func (*Client) OnClearMessage added in v2.1.0

func (c *Client) OnClearMessage(callback func(message ClearMessage))

OnClearMessage attach callback when a single message is deleted

func (*Client) OnConnect

func (c *Client) OnConnect(callback func())

OnConnect attach callback to when a connection has been established

func (*Client) OnGlobalUserStateMessage added in v2.4.0

func (c *Client) OnGlobalUserStateMessage(callback func(message GlobalUserStateMessage))

OnGlobalUserStateMessage attach callback to new global user state

func (*Client) OnNamesMessage

func (c *Client) OnNamesMessage(callback func(message NamesMessage))

OnNamesMessage attaches callback to /names response

func (*Client) OnNoticeMessage

func (c *Client) OnNoticeMessage(callback func(message NoticeMessage))

OnNoticeMessage attach callback to new notice message such as hosts

func (*Client) OnPingMessage

func (c *Client) OnPingMessage(callback func(message PingMessage))

OnPingMessage attaches callback to PING message

func (*Client) OnPingSent

func (c *Client) OnPingSent(callback func())

OnPingSent attaches callback that's called whenever the client sends out a ping message

func (*Client) OnPongMessage

func (c *Client) OnPongMessage(callback func(message PongMessage))

OnPongMessage attaches callback to PONG message

func (*Client) OnPrivateMessage

func (c *Client) OnPrivateMessage(callback func(message PrivateMessage))

OnPrivateMessage attach callback to new standard chat messages

func (*Client) OnReconnectMessage

func (c *Client) OnReconnectMessage(callback func(message ReconnectMessage))

OnReconnectMessage attaches callback that is triggered whenever the twitch servers tell us to reconnect

func (*Client) OnRoomStateMessage

func (c *Client) OnRoomStateMessage(callback func(message RoomStateMessage))

OnRoomStateMessage attach callback to new messages such as submode enabled

func (*Client) OnUnsetMessage

func (c *Client) OnUnsetMessage(callback func(message RawMessage))

OnUnsetMessage attaches callback to message types we currently don't support

func (*Client) OnUserJoinMessage

func (c *Client) OnUserJoinMessage(callback func(message UserJoinMessage))

OnUserJoinMessage attaches callback to user joins

func (*Client) OnUserNoticeMessage

func (c *Client) OnUserNoticeMessage(callback func(message UserNoticeMessage))

OnUserNoticeMessage attach callback to new usernotice message such as sub, resub, and raids

func (*Client) OnUserPartMessage

func (c *Client) OnUserPartMessage(callback func(message UserPartMessage))

OnUserPartMessage attaches callback to user parts

func (*Client) OnUserStateMessage

func (c *Client) OnUserStateMessage(callback func(message UserStateMessage))

OnUserStateMessage attach callback to new userstate

func (*Client) OnWhisperMessage

func (c *Client) OnWhisperMessage(callback func(message WhisperMessage))

OnWhisperMessage attach callback to new whisper

func (*Client) Say

func (c *Client) Say(channel, text string)

Say write something in a chat

func (*Client) SetIRCToken

func (c *Client) SetIRCToken(ircToken string)

SetIRCToken updates the oauth token for this client used for authentication This will not cause a reconnect, but is meant more for "on next connect, use this new token" in case the old token has expired

func (*Client) SetRateLimiter added in v2.7.0

func (c *Client) SetRateLimiter(rateLimiter *RateLimiter)

SetRateLimiter will set the rate limits for the client. Use the factory methods CreateDefaultRateLimiter, CreateVerifiedRateLimiter or CreateUnlimitedRateLimiter to create the rate limits Creating your own RateLimiter without the factory methods is not recommended, as we will likely break the API in the future

func (*Client) Userlist

func (c *Client) Userlist(channel string) ([]string, error)

Userlist returns the userlist for a given channel

func (*Client) Whisper

func (c *Client) Whisper(username, text string)

Whisper write something in private to someone on twitch whispers are heavily spam protected so your message might get blocked because of this verify your bot to prevent this

type Emote

type Emote struct {
	Name      string
	ID        string
	Count     int
	Positions []EmotePosition
}

Emote twitch emotes

type EmotePosition added in v2.6.0

type EmotePosition struct {
	Start int
	End   int
}

EmotePosition is a single position of an emote to be used for text replacement.

type GlobalUserStateMessage added in v2.4.0

type GlobalUserStateMessage struct {
	User User

	Raw       string
	Type      MessageType
	RawType   string
	Tags      map[string]string
	EmoteSets []string
}

GlobalUserStateMessage On successful login, provides data about the current logged-in user through IRC tags See https://dev.twitch.tv/docs/irc/tags/#globaluserstate-twitch-tags

func (*GlobalUserStateMessage) GetType added in v2.4.0

func (msg *GlobalUserStateMessage) GetType() MessageType

GetType implements the Message interface, and returns this message's type

type Message

type Message interface {
	GetType() MessageType
}

Message interface that all messages implement

func ParseMessage

func ParseMessage(line string) Message

ParseMessage parse a raw Twitch IRC message

type MessageType

type MessageType int

MessageType different message types possible to receive via IRC

const (
	// UNSET is for message types we currently don't support
	UNSET MessageType = -1
	// WHISPER private messages
	WHISPER MessageType = 0
	// PRIVMSG standard chat message
	PRIVMSG MessageType = 1
	// CLEARCHAT timeout messages
	CLEARCHAT MessageType = 2
	// ROOMSTATE changes like sub mode
	ROOMSTATE MessageType = 3
	// USERNOTICE messages like subs, resubs, raids, etc
	USERNOTICE MessageType = 4
	// USERSTATE messages
	USERSTATE MessageType = 5
	// NOTICE messages like sub mode, host on
	NOTICE MessageType = 6
	// JOIN whenever a user joins a channel
	JOIN MessageType = 7
	// PART whenever a user parts from a channel
	PART MessageType = 8
	// RECONNECT is sent from Twitch when they request the client to reconnect (i.e. for an irc server restart)
	// https://dev.twitch.tv/docs/irc/commands/#reconnect-twitch-commands
	RECONNECT MessageType = 9
	// NAMES (or 353 https://www.alien.net.au/irc/irc2numerics.html#353) is the response sent from the server when
	// the client requests a list of names for a channel
	NAMES MessageType = 10
	// PING is a message that can be sent from the IRC server. go-twitch-irc responds to PINGs automatically
	PING MessageType = 11
	// PONG is a message that should be sent from the IRC server as a response to us sending a PING message.
	PONG MessageType = 12
	// CLEARMSG whenever a single message is deleted
	CLEARMSG MessageType = 13
	// GLOBALUSERSTATE On successful login, provides data about the current logged-in user through IRC tags
	GLOBALUSERSTATE MessageType = 14
)

type NamesMessage

type NamesMessage struct {
	Raw     string
	Type    MessageType
	RawType string

	// Channel name
	Channel string

	// List of user names
	Users []string
}

NamesMessage describes the data posted in response to a /names command See https://www.alien.net.au/irc/irc2numerics.html#353

func (*NamesMessage) GetType

func (msg *NamesMessage) GetType() MessageType

GetType implements the Message interface, and returns this message's type

type NoticeMessage

type NoticeMessage struct {
	Raw     string
	Type    MessageType
	RawType string
	Tags    map[string]string
	Message string
	Channel string
	MsgID   string
}

NoticeMessage data you receive from the NOTICE message type

func (*NoticeMessage) GetType

func (msg *NoticeMessage) GetType() MessageType

GetType implements the Message interface, and returns this message's type

type PingMessage

type PingMessage struct {
	Raw     string
	Type    MessageType
	RawType string

	Message string
}

PingMessage describes an IRC PING message

func (*PingMessage) GetType

func (msg *PingMessage) GetType() MessageType

GetType implements the Message interface, and returns this message's type

type PongMessage

type PongMessage struct {
	Raw     string
	Type    MessageType
	RawType string

	Message string
}

PongMessage describes an IRC PONG message

func (*PongMessage) GetType

func (msg *PongMessage) GetType() MessageType

GetType implements the Message interface, and returns this message's type

type PrivateMessage

type PrivateMessage struct {
	User User

	Raw          string
	Type         MessageType
	RawType      string
	Tags         map[string]string
	Message      string
	Channel      string
	RoomID       string
	ID           string
	Time         time.Time
	Emotes       []*Emote
	Bits         int
	Action       bool
	FirstMessage bool
}

PrivateMessage data you receive from PRIVMSG message type

func (*PrivateMessage) GetType

func (msg *PrivateMessage) GetType() MessageType

GetType implements the Message interface, and returns this message's type

type RateLimiter added in v2.7.0

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

func CreateDefaultRateLimiter added in v2.7.0

func CreateDefaultRateLimiter() *RateLimiter

func CreateUnlimitedRateLimiter added in v2.7.0

func CreateUnlimitedRateLimiter() *RateLimiter

func CreateVerifiedRateLimiter added in v2.7.0

func CreateVerifiedRateLimiter() *RateLimiter

func (*RateLimiter) Start added in v2.7.0

func (r *RateLimiter) Start()

func (*RateLimiter) Throttle added in v2.7.0

func (r *RateLimiter) Throttle()

type RawMessage

type RawMessage struct {
	Raw     string
	Type    MessageType
	RawType string
	Tags    map[string]string
	Message string
}

RawMessage data you receive from TMI

func (*RawMessage) GetType

func (msg *RawMessage) GetType() MessageType

GetType implements the Message interface, and returns this message's type

type ReconnectMessage

type ReconnectMessage struct {
	Raw     string
	Type    MessageType
	RawType string
}

ReconnectMessage describes the

func (*ReconnectMessage) GetType

func (msg *ReconnectMessage) GetType() MessageType

GetType implements the Message interface, and returns this message's type

type RoomStateMessage

type RoomStateMessage struct {
	Raw     string
	Type    MessageType
	RawType string
	Tags    map[string]string
	Message string
	Channel string
	RoomID  string
	State   map[string]int
}

RoomStateMessage data you receive from ROOMSTATE message type

func (*RoomStateMessage) GetType

func (msg *RoomStateMessage) GetType() MessageType

GetType implements the Message interface, and returns this message's type

type User

type User struct {
	ID          string
	Name        string
	DisplayName string
	Color       string
	Badges      map[string]int
}

User data you receive from TMI

type UserJoinMessage

type UserJoinMessage struct {
	Raw     string
	Type    MessageType
	RawType string

	// Channel name
	Channel string

	// User name
	User string
}

UserJoinMessage desJoines the message that is sent whenever a user joins a channel we're connected to See https://dev.twitch.tv/docs/irc/membership/#join-twitch-membership

func (*UserJoinMessage) GetType

func (msg *UserJoinMessage) GetType() MessageType

GetType implements the Message interface, and returns this message's type

type UserNoticeMessage

type UserNoticeMessage struct {
	User User

	Raw       string
	Type      MessageType
	RawType   string
	Tags      map[string]string
	Message   string
	Channel   string
	RoomID    string
	ID        string
	Time      time.Time
	Emotes    []*Emote
	MsgID     string
	MsgParams map[string]string
	SystemMsg string
}

UserNoticeMessage data you receive from USERNOTICE message type

func (*UserNoticeMessage) GetType

func (msg *UserNoticeMessage) GetType() MessageType

GetType implements the Message interface, and returns this message's type

type UserPartMessage

type UserPartMessage struct {
	Raw     string
	Type    MessageType
	RawType string

	// Channel name
	Channel string

	// User name
	User string
}

UserPartMessage describes the message that is sent whenever a user leaves a channel we're connected to See https://dev.twitch.tv/docs/irc/membership/#part-twitch-membership

func (*UserPartMessage) GetType

func (msg *UserPartMessage) GetType() MessageType

GetType implements the Message interface, and returns this message's type

type UserStateMessage

type UserStateMessage struct {
	User User

	Raw       string
	Type      MessageType
	RawType   string
	Tags      map[string]string
	Message   string
	Channel   string
	EmoteSets []string
}

UserStateMessage data you receive from the USERSTATE message type

func (*UserStateMessage) GetType

func (msg *UserStateMessage) GetType() MessageType

GetType implements the Message interface, and returns this message's type

type WhisperMessage

type WhisperMessage struct {
	User User

	Raw       string
	Type      MessageType
	RawType   string
	Tags      map[string]string
	Message   string
	Target    string
	MessageID string
	ThreadID  string
	Emotes    []*Emote
	Action    bool
}

WhisperMessage data you receive from WHISPER message type

func (*WhisperMessage) GetType

func (msg *WhisperMessage) GetType() MessageType

GetType implements the Message interface, and returns this message's type

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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