twitch

package
v3.35.0 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2024 License: Apache-2.0 Imports: 21 Imported by: 0

Documentation

Overview

Package twitch implements a client for the Twitch APIs

Index

Constants

View Source
const (
	BadgeBroadcaster = "broadcaster"
	BadgeFounder     = "founder"
	BadgeModerator   = "moderator"
	BadgeSubscriber  = "subscriber"
	BadgeVIP         = "vip"
)

Collection of known badges

View Source
const (
	EventSubEventTypeChannelAdBreakBegin                   = "channel.ad_break.begin"
	EventSubEventTypeChannelFollow                         = "channel.follow"
	EventSubEventTypeChannelPointCustomRewardRedemptionAdd = "channel.channel_points_custom_reward_redemption.add"
	EventSubEventTypeChannelHypetrainBegin                 = "channel.hype_train.begin"
	EventSubEventTypeChannelHypetrainProgress              = "channel.hype_train.progress"
	EventSubEventTypeChannelHypetrainEnd                   = "channel.hype_train.end"
	EventSubEventTypeChannelRaid                           = "channel.raid"
	EventSubEventTypeChannelShoutoutCreate                 = "channel.shoutout.create"
	EventSubEventTypeChannelShoutoutReceive                = "channel.shoutout.receive"
	EventSubEventTypeChannelUpdate                         = "channel.update"
	EventSubEventTypeChannelPollBegin                      = "channel.poll.begin"
	EventSubEventTypeChannelPollEnd                        = "channel.poll.end"
	EventSubEventTypeChannelPollProgress                   = "channel.poll.progress"
	EventSubEventTypeChannelSuspiciousUserMessage          = "channel.suspicious_user.message"
	EventSubEventTypeChannelSuspiciousUserUpdate           = "channel.suspicious_user.update"
	EventSubEventTypeStreamOffline                         = "stream.offline"
	EventSubEventTypeStreamOnline                          = "stream.online"
	EventSubEventTypeUserAuthorizationRevoke               = "user.authorization.revoke"
)

Collection of known EventSub event-types

View Source
const (
	EventSubTopicVersion1    = "1"
	EventSubTopicVersion2    = "2"
	EventSubTopicVersionBeta = "beta"
)

Collection of topic versions known to the API

View Source
const (
	// API Scopes
	ScopeChannelBot                   = "channel:bot"
	ScopeChannelEditCommercial        = "channel:edit:commercial"
	ScopeChannelManageAds             = "channel:manage:ads"
	ScopeChannelManageBroadcast       = "channel:manage:broadcast"
	ScopeChannelManageModerators      = "channel:manage:moderators"
	ScopeChannelManagePolls           = "channel:manage:polls"
	ScopeChannelManagePredictions     = "channel:manage:predictions"
	ScopeChannelManageRaids           = "channel:manage:raids"
	ScopeChannelManageRedemptions     = "channel:manage:redemptions"
	ScopeChannelManageVIPS            = "channel:manage:vips"
	ScopeChannelManageWhispers        = "user:manage:whispers"
	ScopeChannelReadAds               = "channel:read:ads"
	ScopeChannelReadHypetrain         = "channel:read:hype_train"
	ScopeChannelReadPolls             = "channel:read:polls"
	ScopeChannelReadRedemptions       = "channel:read:redemptions"
	ScopeChannelReadSubscriptions     = "channel:read:subscriptions"
	ScopeClipsEdit                    = "clips:edit"
	ScopeModeratorManageAnnoucements  = "moderator:manage:announcements"
	ScopeModeratorManageBannedUsers   = "moderator:manage:banned_users"
	ScopeModeratorManageChatMessages  = "moderator:manage:chat_messages"
	ScopeModeratorManageChatSettings  = "moderator:manage:chat_settings"
	ScopeModeratorManageShieldMode    = "moderator:manage:shield_mode"
	ScopeModeratorManageShoutouts     = "moderator:manage:shoutouts"
	ScopeModeratorReadFollowers       = "moderator:read:followers"
	ScopeModeratorReadShoutouts       = "moderator:read:shoutouts"
	ScopeModeratorReadSuspiciousUsers = "moderator:read:suspicious_users"
	ScopeUserBot                      = "user:bot"
	ScopeUserManageChatColor          = "user:manage:chat_color"
	ScopeUserManageWhispers           = "user:manage:whispers"
	ScopeUserReadChat                 = "user:read:chat"

	// Deprecated v5 scope but used in chat
	ScopeV5ChannelEditor = "channel_editor"

	// Chat Scopes
	ScopeChatEdit    = "chat:edit"     // Send live stream chat and rooms messages.
	ScopeChatRead    = "chat:read"     // View live stream chat and rooms messages.
	ScopeWhisperRead = "whispers:read" // View your whisper messages.
)

Collection of known API scopes

Variables

View Source
var ErrAnyHTTPError = newHTTPError(0, nil, nil)

ErrAnyHTTPError can be used in errors.Is() to match an HTTPError with any status code

View Source
var ErrNoStreamsFound = errors.New("no streams found")

ErrNoStreamsFound allows to differntiate between an HTTP error and the fact there just is no stream found

View Source
var ErrUserDoesNotFollow = errors.New("no follow-relation found")

ErrUserDoesNotFollow states the user does not follow the given channel

KnownBadges contains a list of all known badges

Functions

func ValidateStatus added in v3.15.0

func ValidateStatus(opts ClientRequestOpts, resp *http.Response) error

ValidateStatus is the default validation function used when no ValidateFunc is given in the ClientRequestOpts and checks for the returned HTTP status is equal to the OKStatus.

When the status is http.StatusTooManyRequests the function will return an error terminating any retries as retrying would not make sense (the error returned from Request will still be an HTTPError with status 429).

When wrapping this function the body should not have been read before in order to have the response body available in the returned HTTPError

Types

type APICache

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

APICache is used to cache API responses in order not to ask the API over and over again for information seldom changing

func (*APICache) Get

func (t *APICache) Get(key []string) interface{}

Get returns the stored data or nil for the given cache-key

func (*APICache) Set

func (t *APICache) Set(key []string, valid time.Duration, data interface{})

Set sets the stored data for the given cache-key

type AuthType added in v3.14.0

type AuthType uint8

AuthType is a collection of available authorization types in the Twitch API

const (
	AuthTypeUnauthorized AuthType = iota
	AuthTypeAppAccessToken
	AuthTypeBearerToken
)

Definitions of possible / understood auth types

type BadgeCollection

type BadgeCollection map[string]*int

BadgeCollection represents a collection of badges the user has set

func ParseBadgeLevels

func ParseBadgeLevels(m *irc.Message) BadgeCollection

ParseBadgeLevels takes the badges from the irc.Message and returns a BadgeCollection containing all badges the user has set

func (BadgeCollection) Add

func (b BadgeCollection) Add(badge string, level int)

Add sets the given badge to the given level

func (BadgeCollection) Get

func (b BadgeCollection) Get(badge string) int

Get returns the level of the given badge. If the badge is not set its level will be 0.

func (BadgeCollection) Has

func (b BadgeCollection) Has(badge string) bool

Has checks whether the collection contains the given badge at any level

type Category

type Category struct {
	BoxArtURL string `json:"box_art_url"`
	ID        string `json:"id"`
	Name      string `json:"name"`
}

Category represents information about a category

type ChannelStreamSchedule added in v3.15.0

type ChannelStreamSchedule struct {
	Segments         []ChannelStreamScheduleSegment `json:"segments"`
	BroadcasterID    string                         `json:"broadcaster_id"`
	BroadcasterName  string                         `json:"broadcaster_name"`
	BroadcasterLogin string                         `json:"broadcaster_login"`
	Vacation         struct {
		StartTime time.Time `json:"start_time"`
		EndTime   time.Time `json:"end_time"`
	} `json:"vacation"`
}

ChannelStreamSchedule represents the schedule of a channels with its segments represening single planned streams

type ChannelStreamScheduleSegment added in v3.20.0

type ChannelStreamScheduleSegment struct {
	ID            string     `json:"id"`
	StartTime     time.Time  `json:"start_time"`
	EndTime       time.Time  `json:"end_time"`
	Title         string     `json:"title"`
	CanceledUntil *time.Time `json:"canceled_until"`
	Category      struct {
		ID   string `json:"id"`
		Name string `json:"name"`
	} `json:"category"`
	IsRecurring bool `json:"is_recurring"`
}

ChannelStreamScheduleSegment represents a single stream inside the ChannelStreamSchedule

type Client

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

Client bundles the API access methods into a Client

func New

func New(clientID, clientSecret, accessToken, refreshToken string) *Client

New creates a new Client with the given credentials

func (*Client) APICache

func (c *Client) APICache() *APICache

APICache returns the internal APICache used by the Client

func (*Client) AddChannelVIP added in v3.2.0

func (c *Client) AddChannelVIP(ctx context.Context, channel, userName string) error

AddChannelVIP adds the given user as a VIP in the given channel

func (*Client) BanUser

func (c *Client) BanUser(ctx context.Context, channel, username string, duration time.Duration, reason string) error

BanUser bans or timeouts a user in the given channel. Setting the duration to 0 will result in a ban, setting if greater than 0 will result in a timeout. The timeout is automatically converted to full seconds. The timeout duration must be less than 1209600s.

func (*Client) CreateClip added in v3.16.0

func (c *Client) CreateClip(ctx context.Context, channel string, addDelay bool) (ccr CreateClipResponse, err error)

CreateClip triggers the creation of a clip in the given channel. If addDelay is true an artificial delay will be added (for broadcasters who trigger this function already knowing something will happen but not yet visible in stream).

func (*Client) CreateStreamMarker added in v3.34.0

func (c *Client) CreateStreamMarker(ctx context.Context, description string) (marker StreamMarkerInfo, err error)

CreateStreamMarker creates a marker for the currently running stream. The stream must be live, no VoD, no upload and no re-run. The description may be up to 140 chars and can be omitted.

func (*Client) DeleteMessage

func (c *Client) DeleteMessage(ctx context.Context, channel, messageID string) error

DeleteMessage deletes one or all messages from the specified chat. If no messageID is given all messages are deleted. If a message ID is given the message must be no older than 6 hours and it must not be posted by broadcaster or moderator.

func (*Client) GetAuthorizedUser

func (c *Client) GetAuthorizedUser(ctx context.Context) (userID string, userName string, err error)

GetAuthorizedUser returns the userID / userName of the user the client is authorized for

func (*Client) GetBroadcasterSubscriptionCount added in v3.9.0

func (c *Client) GetBroadcasterSubscriptionCount(ctx context.Context, broadcasterName string) (subCount, subPoints int64, err error)

GetBroadcasterSubscriptionCount gets a list of users that subscribe to the specified broadcaster.

func (*Client) GetChannelStreamSchedule added in v3.15.0

func (c *Client) GetChannelStreamSchedule(ctx context.Context, channel string) (*ChannelStreamSchedule, error)

GetChannelStreamSchedule gets the broadcaster’s streaming schedule

func (*Client) GetClipByID added in v3.8.0

func (c *Client) GetClipByID(ctx context.Context, clipID string) (ClipInfo, error)

GetClipByID gets a video clip that were captured from streams by its ID (slug in the URL)

func (*Client) GetCurrentStreamInfo

func (c *Client) GetCurrentStreamInfo(ctx context.Context, username string) (*StreamInfo, error)

GetCurrentStreamInfo returns the StreamInfo of the currently running stream of the given username

func (*Client) GetDisplayNameForUser

func (c *Client) GetDisplayNameForUser(ctx context.Context, username string) (string, error)

GetDisplayNameForUser returns the display name for a login name set by the user themselves

func (*Client) GetFollowDate

func (c *Client) GetFollowDate(ctx context.Context, from, to string) (time.Time, error)

GetFollowDate returns the point-in-time the {from} followed the {to} or an ErrUserDoesNotFollow in case they do not follow

func (*Client) GetIDForUsername

func (c *Client) GetIDForUsername(ctx context.Context, username string) (string, error)

GetIDForUsername takes a login name and returns the userID for that username

func (*Client) GetLatestPoll added in v3.11.0

func (c *Client) GetLatestPoll(ctx context.Context, channel string) (*PollInfo, error)

GetLatestPoll returns the lastest (active or past) poll inside the given channel

func (*Client) GetRecentStreamInfo

func (c *Client) GetRecentStreamInfo(ctx context.Context, username string) (category string, title string, err error)

GetRecentStreamInfo returns the category and the title the given username has configured for their recent (or next) stream

func (*Client) GetToken

func (c *Client) GetToken(ctx context.Context) (string, error)

GetToken returns the access-token for the configured credentials after validating and - if required - renewing the token

func (*Client) GetTokenInfo added in v3.20.0

func (c *Client) GetTokenInfo(ctx context.Context) (user string, scopes []string, expiresAt time.Time, err error)

GetTokenInfo requests a validation for the token set within the client and returns the authorized user, their granted scopes on this token and an error in case something went wrong.

func (*Client) GetTwitchAppAccessToken added in v3.19.0

func (c *Client) GetTwitchAppAccessToken(ctx context.Context) (string, error)

GetTwitchAppAccessToken uses client-id and -secret to generate a new app-access-token in case none is present or returns the cached token.

func (*Client) GetUserInformation

func (c *Client) GetUserInformation(ctx context.Context, user string) (*User, error)

GetUserInformation takes an userID or an userName and returns the User information for them

func (*Client) GetUsernameForID added in v3.18.0

func (c *Client) GetUsernameForID(ctx context.Context, id string) (string, error)

GetUsernameForID retrieves the login name (not the display name) for the given user ID

func (*Client) GetVideos added in v3.34.0

func (c *Client) GetVideos(ctx context.Context, opts GetVideoOpts) (videos []Video, err error)

GetVideos fetches information about one or more published videos

func (*Client) HasLiveStream

func (c *Client) HasLiveStream(ctx context.Context, username string) (bool, error)

HasLiveStream checks whether the given user is currently streaming

func (*Client) ModifyChannelInformation

func (c *Client) ModifyChannelInformation(ctx context.Context, channel string, category, title *string) error

ModifyChannelInformation adjusts category and title for the given channel

func (*Client) RefreshToken

func (c *Client) RefreshToken(ctx context.Context) error

RefreshToken takes the configured refresh-token and renews the corresponding access-token

func (*Client) RemoveChannelVIP added in v3.2.0

func (c *Client) RemoveChannelVIP(ctx context.Context, channel, userName string) error

RemoveChannelVIP removes the given user as a VIP in the given channel

func (*Client) Request added in v3.14.0

func (c *Client) Request(ctx context.Context, opts ClientRequestOpts) error

Request executes the request towards the Twitch API defined by the ClientRequestOpts and takes care of token management and response checking

func (*Client) RunCommercial added in v3.7.0

func (c *Client) RunCommercial(ctx context.Context, channel string, duration int64) error

RunCommercial starts a commercial on the specified channel

func (*Client) SearchCategories

func (c *Client) SearchCategories(ctx context.Context, name string) ([]Category, error)

SearchCategories returns a list of categories matching the given search. The result is not exact but contains Twitchs fuzzy-results.

func (*Client) SendChatAnnouncement

func (c *Client) SendChatAnnouncement(ctx context.Context, channel, color, message string) error

SendChatAnnouncement sends an announcement in the specified channel with the given message. Colors must be blue, green, orange, purple or primary (empty color = primary)

func (*Client) SendShoutout added in v3.4.0

func (c *Client) SendShoutout(ctx context.Context, channel, user string) error

SendShoutout creates a Twitch-native shoutout in the given channel for the given user. This equals `/shoutout <user>` in the channel.

func (*Client) SendWhisper

func (c *Client) SendWhisper(ctx context.Context, toUser, message string) error

SendWhisper sends a whisper from the bot to the specified user.

For details about message limits see the official documentation: https://dev.twitch.tv/docs/api/reference#send-whisper

func (*Client) SetTokenUpdateHook

func (c *Client) SetTokenUpdateHook(f func(string, string) error)

SetTokenUpdateHook registers a function to listen for token changes after renewing the internal token. It is presented with an access- and a refresh-token if those changes.

func (*Client) UnbanUser

func (c *Client) UnbanUser(ctx context.Context, channel, username string) error

UnbanUser removes a timeout or ban given to the user in the channel

func (*Client) UpdateShieldMode added in v3.5.0

func (c *Client) UpdateShieldMode(ctx context.Context, channel string, enable bool) error

UpdateShieldMode activates or deactivates the Shield Mode in the given channel

func (*Client) UpdateToken

func (c *Client) UpdateToken(accessToken, refreshToken string)

UpdateToken overwrites the configured access- and refresh-tokens

func (*Client) ValidateToken

func (c *Client) ValidateToken(ctx context.Context, force bool) error

ValidateToken executes a request against the Twitch API to validate the token is still valid. If the expiry is known and the force parameter is not supplied, the request is omitted.

type ClientRequestOpts added in v3.14.0

type ClientRequestOpts struct {
	AuthType        AuthType
	Body            io.Reader
	Method          string
	NoRetry         bool
	NoValidateToken bool
	OKStatus        int
	Out             interface{}
	URL             string
	ValidateFunc    func(ClientRequestOpts, *http.Response) error
}

ClientRequestOpts contains the options to create a request to the Twitch APIs

type ClipInfo added in v3.8.0

type ClipInfo struct {
	ID              string    `json:"id"`
	URL             string    `json:"url"`
	EmbedURL        string    `json:"embed_url"`
	BroadcasterID   string    `json:"broadcaster_id"`
	BroadcasterName string    `json:"broadcaster_name"`
	CreatorID       string    `json:"creator_id"`
	CreatorName     string    `json:"creator_name"`
	VideoID         string    `json:"video_id"`
	GameID          string    `json:"game_id"`
	Language        string    `json:"language"`
	Title           string    `json:"title"`
	ViewCount       int64     `json:"view_count"`
	CreatedAt       time.Time `json:"created_at"`
	ThumbnailURL    string    `json:"thumbnail_url"`
	Duration        float64   `json:"duration"`
	VodOffset       int64     `json:"vod_offset"`
}

ClipInfo contains the information about a clip

type CreateClipResponse added in v3.16.0

type CreateClipResponse struct {
	ID      string `json:"id"`
	EditURL string `json:"edit_url"`
}

CreateClipResponse contains the API response to a create clip call

type ErrorResponse added in v3.15.0

type ErrorResponse struct {
	Error   string `json:"error"`
	Status  int    `json:"status"`
	Message string `json:"message"`
}

ErrorResponse is a response sent by Twitch API in case there is an error

type EventSubCondition

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

EventSubCondition defines the condition the subscription should listen on - all fields are optional and those defined in the EventSub documentation for the given topic should be set

func (EventSubCondition) Hash

func (e EventSubCondition) Hash() (string, error)

Hash generates a hashstructure hash for the condition for comparison

type EventSubEventAdBreakBegin added in v3.19.0

type EventSubEventAdBreakBegin struct {
	Duration             int64     `json:"duration_seconds"`
	StartedAt            time.Time `json:"started_at"`
	IsAutomatic          bool      `json:"is_automatic"`
	BroadcasterUserID    string    `json:"broadcaster_user_id"`
	BroadcasterUserLogin string    `json:"broadcaster_user_login"`
	BroadcasterUserName  string    `json:"broadcaster_user_name"`
	RequesterUserID      string    `json:"requester_user_id"`
	RequesterUserLogin   string    `json:"requester_user_login"`
	RequesterUserName    string    `json:"requester_user_name"`
}

EventSubEventAdBreakBegin contains the payload for an AdBreak event

type EventSubEventChannelPointCustomRewardRedemptionAdd

type EventSubEventChannelPointCustomRewardRedemptionAdd struct {
	ID                   string `json:"id"`
	BroadcasterUserID    string `json:"broadcaster_user_id"`
	BroadcasterUserLogin string `json:"broadcaster_user_login"`
	BroadcasterUserName  string `json:"broadcaster_user_name"`
	UserID               string `json:"user_id"`
	UserLogin            string `json:"user_login"`
	UserName             string `json:"user_name"`
	UserInput            string `json:"user_input"`
	Status               string `json:"status"`
	Reward               struct {
		ID     string `json:"id"`
		Title  string `json:"title"`
		Cost   int64  `json:"cost"`
		Prompt string `json:"prompt"`
	} `json:"reward"`
	RedeemedAt time.Time `json:"redeemed_at"`
}

EventSubEventChannelPointCustomRewardRedemptionAdd contains the payload for an channel-point redeem event

type EventSubEventChannelUpdate

type EventSubEventChannelUpdate struct {
	BroadcasterUserID           string   `json:"broadcaster_user_id"`
	BroadcasterUserLogin        string   `json:"broadcaster_user_login"`
	BroadcasterUserName         string   `json:"broadcaster_user_name"`
	Title                       string   `json:"title"`
	Language                    string   `json:"language"`
	CategoryID                  string   `json:"category_id"`
	CategoryName                string   `json:"category_name"`
	ContentClassificationLabels []string `json:"content_classification_labels"`
}

EventSubEventChannelUpdate contains the payload for a channel update event

type EventSubEventFollow

type EventSubEventFollow struct {
	UserID               string    `json:"user_id"`
	UserLogin            string    `json:"user_login"`
	UserName             string    `json:"user_name"`
	BroadcasterUserID    string    `json:"broadcaster_user_id"`
	BroadcasterUserLogin string    `json:"broadcaster_user_login"`
	BroadcasterUserName  string    `json:"broadcaster_user_name"`
	FollowedAt           time.Time `json:"followed_at"`
}

EventSubEventFollow contains the payload for a follow event

type EventSubEventHypetrain added in v3.26.0

type EventSubEventHypetrain struct {
	ID                   string `json:"id"`
	BroadcasterUserID    string `json:"broadcaster_user_id"`
	BroadcasterUserLogin string `json:"broadcaster_user_login"`
	BroadcasterUserName  string `json:"broadcaster_user_name"`
	Level                int64  `json:"level"`
	Total                int64  `json:"total"`
	Progress             int64  `json:"progress"` // Only Beginn, Progress
	Goal                 int64  `json:"goal"`     // Only Beginn, Progress
	TopContributions     []struct {
		UserID    string `json:"user_id"`
		UserLogin string `json:"user_login"`
		UserName  string `json:"user_name"`
		Type      string `json:"type"`
		Total     int64  `json:"total"`
	} `json:"top_contributions"`
	LastContribution *struct {
		UserID    string `json:"user_id"`
		UserLogin string `json:"user_login"`
		UserName  string `json:"user_name"`
		Type      string `json:"type"`
		Total     int64  `json:"total"`
	} `json:"last_contribution,omitempty"`
	StartedAt      time.Time  `json:"started_at"`
	ExpiresAt      *time.Time `json:"expires_at,omitempty"`       // Only Begin, Progress
	EndedAt        *time.Time `json:"ended_at,omitempty"`         // Only End
	CooldownEndsAt *time.Time `json:"cooldown_ends_at,omitempty"` // Only End
}

EventSubEventHypetrain contains the payload for all three (begin, progress and end) hypetrain events. Certain fields are not available at all event types

type EventSubEventPoll added in v3.11.0

type EventSubEventPoll struct {
	ID                   string `json:"id"`
	BroadcasterUserID    string `json:"broadcaster_user_id"`
	BroadcasterUserLogin string `json:"broadcaster_user_login"`
	BroadcasterUserName  string `json:"broadcaster_user_name"`
	Title                string `json:"title"`
	Choices              []struct {
		ID                 string `json:"id"`
		Title              string `json:"title"`
		ChannelPointsVotes int    `json:"channel_points_votes"`
		Votes              int    `json:"votes"`
	} `json:"choices"`
	ChannelPointsVoting struct {
		IsEnabled     bool `json:"is_enabled"`
		AmountPerVote int  `json:"amount_per_vote"`
	} `json:"channel_points_voting"`

	StartedAt time.Time `json:"started_at"`         // begin, progress, end
	EndsAt    time.Time `json:"ends_at,omitempty"`  // begin, progress
	Status    string    `json:"status,omitempty"`   // end -- enum(completed, archived, terminated)
	EndedAt   time.Time `json:"ended_at,omitempty"` // end
}

EventSubEventPoll contains the payload for a poll change event (not all fields are present in all poll events, see docs!)

type EventSubEventRaid

type EventSubEventRaid struct {
	FromBroadcasterUserID    string `json:"from_broadcaster_user_id"`
	FromBroadcasterUserLogin string `json:"from_broadcaster_user_login"`
	FromBroadcasterUserName  string `json:"from_broadcaster_user_name"`
	ToBroadcasterUserID      string `json:"to_broadcaster_user_id"`
	ToBroadcasterUserLogin   string `json:"to_broadcaster_user_login"`
	ToBroadcasterUserName    string `json:"to_broadcaster_user_name"`
	Viewers                  int64  `json:"viewers"`
}

EventSubEventRaid contains the payload for a raid event

type EventSubEventShoutoutCreated added in v3.7.0

type EventSubEventShoutoutCreated struct {
	BroadcasterUserID      string    `json:"broadcaster_user_id"`
	BroadcasterUserLogin   string    `json:"broadcaster_user_login"`
	BroadcasterUserName    string    `json:"broadcaster_user_name"`
	ModeratorUserID        string    `json:"moderator_user_id"`
	ModeratorUserLogin     string    `json:"moderator_user_login"`
	ModeratorUserName      string    `json:"moderator_user_name"`
	ToBroadcasterUserID    string    `json:"to_broadcaster_user_id"`
	ToBroadcasterUserLogin string    `json:"to_broadcaster_user_login"`
	ToBroadcasterUserName  string    `json:"to_broadcaster_user_name"`
	ViewerCount            int64     `json:"viewer_count"`
	StartedAt              time.Time `json:"started_at"`
	CooldownEndsAt         time.Time `json:"cooldown_ends_at"`
	TargetCooldownEndsAt   time.Time `json:"target_cooldown_ends_at"`
}

EventSubEventShoutoutCreated contains the payload for a shoutout created event

type EventSubEventShoutoutReceived added in v3.6.0

type EventSubEventShoutoutReceived struct {
	BroadcasterUserID        string    `json:"broadcaster_user_id"`
	BroadcasterUserLogin     string    `json:"broadcaster_user_login"`
	BroadcasterUserName      string    `json:"broadcaster_user_name"`
	FromBroadcasterUserID    string    `json:"from_broadcaster_user_id"`
	FromBroadcasterUserLogin string    `json:"from_broadcaster_user_login"`
	FromBroadcasterUserName  string    `json:"from_broadcaster_user_name"`
	ViewerCount              int64     `json:"viewer_count"`
	StartedAt                time.Time `json:"started_at"`
}

EventSubEventShoutoutReceived contains the payload for a shoutout received event

type EventSubEventStreamOffline

type EventSubEventStreamOffline struct {
	BroadcasterUserID    string `json:"broadcaster_user_id"`
	BroadcasterUserLogin string `json:"broadcaster_user_login"`
	BroadcasterUserName  string `json:"broadcaster_user_name"`
}

EventSubEventStreamOffline contains the payload for a stream offline event

type EventSubEventStreamOnline

type EventSubEventStreamOnline struct {
	ID                   string    `json:"id"`
	BroadcasterUserID    string    `json:"broadcaster_user_id"`
	BroadcasterUserLogin string    `json:"broadcaster_user_login"`
	BroadcasterUserName  string    `json:"broadcaster_user_name"`
	Type                 string    `json:"type"`
	StartedAt            time.Time `json:"started_at"`
}

EventSubEventStreamOnline contains the payload for a stream online event

type EventSubEventSuspiciousUserMessage added in v3.29.0

type EventSubEventSuspiciousUserMessage struct {
	BroadcasterUserID    string   `json:"broadcaster_user_id"`
	BroadcasterUserName  string   `json:"broadcaster_user_name"`
	BroadcasterUserLogin string   `json:"broadcaster_user_login"`
	UserID               string   `json:"user_id"`
	UserName             string   `json:"user_name"`
	UserLogin            string   `json:"user_login"`
	LowTrustStatus       string   `json:"low_trust_status"` // Can be the following: "none", "active_monitoring", or "restricted"
	SharedBanChannelIDs  []string `json:"shared_ban_channel_ids"`
	Types                []string `json:"types"`                  // can be "manual", "ban_evader_detector", or "shared_channel_ban"
	BanEvasionEvaluation string   `json:"ban_evasion_evaluation"` // can be "unknown", "possible", or "likely"
	Message              struct {
		MessageID string `json:"message_id"`
		Text      string `json:"text"`
		Fragments []struct {
			Type      string `json:"type"`
			Text      string `json:"text"`
			Cheermote struct {
				Prefix string `json:"prefix"`
				Bits   int    `json:"bits"`
				Tier   int    `json:"tier"`
			} `json:"Cheermote"`
			Emote struct {
				ID         string `json:"id"`
				EmoteSetID string `json:"emote_set_id"`
			} `json:"emote"`
		} `json:"fragments"`
	} `json:"message"`
}

EventSubEventSuspiciousUserMessage contains the payload for a channel.suspicious_user.message

type EventSubEventSuspiciousUserUpdated added in v3.29.0

type EventSubEventSuspiciousUserUpdated struct {
	BroadcasterUserID    string `json:"broadcaster_user_id"`
	BroadcasterUserName  string `json:"broadcaster_user_name"`
	BroadcasterUserLogin string `json:"broadcaster_user_login"`
	ModeratorUserID      string `json:"moderator_user_id"`
	ModeratorUserName    string `json:"moderator_user_name"`
	ModeratorUserLogin   string `json:"moderator_user_login"`
	UserID               string `json:"user_id"`
	UserName             string `json:"user_name"`
	UserLogin            string `json:"user_login"`
	LowTrustStatus       string `json:"low_trust_status"` // Can be the following: "none", "active_monitoring", or "restricted"
}

EventSubEventSuspiciousUserUpdated contains the payload for a channel.suspicious_user.update

type EventSubEventUserAuthorizationRevoke

type EventSubEventUserAuthorizationRevoke struct {
	ClientID  string `json:"client_id"`
	UserID    string `json:"user_id"`
	UserLogin string `json:"user_login"`
	UserName  string `json:"user_name"`
}

EventSubEventUserAuthorizationRevoke contains the payload for an authorization revoke event

type EventSubSocketClient added in v3.10.0

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

EventSubSocketClient manages a WebSocket transport for the Twitch EventSub API

func NewEventSubSocketClient added in v3.10.0

func NewEventSubSocketClient(opts ...EventSubSocketClientOpt) (*EventSubSocketClient, error)

NewEventSubSocketClient creates a new EventSubSocketClient and applies the given EventSubSocketClientOpts

func (*EventSubSocketClient) Close added in v3.10.0

func (e *EventSubSocketClient) Close()

Close cancels the contained context and brings the EventSubSocketClient to a halt

func (*EventSubSocketClient) Run added in v3.10.0

func (e *EventSubSocketClient) Run() error

Run starts the main communcation loop for the EventSubSocketClient

type EventSubSocketClientOpt added in v3.10.0

type EventSubSocketClientOpt func(*EventSubSocketClient)

EventSubSocketClientOpt is a setter function to apply changes to the EventSubSocketClient on create

func WithLogger added in v3.10.0

func WithLogger(logger *logrus.Entry) EventSubSocketClientOpt

WithLogger configures the logger within the EventSubSocketClient

func WithMustSubscribe added in v3.22.0

func WithMustSubscribe(event, version string, condition EventSubCondition, callback func(json.RawMessage) error) EventSubSocketClientOpt

WithMustSubscribe adds a topic to the subscriptions to be done on connect

func WithRetryBackgroundSubscribe added in v3.22.0

func WithRetryBackgroundSubscribe(event, version string, condition EventSubCondition, callback func(json.RawMessage) error) EventSubSocketClientOpt

WithRetryBackgroundSubscribe adds a topic to the subscriptions to be done on connect async

func WithSocketURL added in v3.10.0

func WithSocketURL(url string) EventSubSocketClientOpt

WithSocketURL overwrites the socket URL to connect to

func WithTwitchClient added in v3.10.0

func WithTwitchClient(c *Client) EventSubSocketClientOpt

WithTwitchClient overwrites the Client to be used

type GetVideoOpts added in v3.34.0

type GetVideoOpts struct {
	ID       string             // Required: Exactly one of ID, UserID, GameID
	UserID   string             // Required: Exactly one of ID, UserID, GameID
	GameID   string             // Required: Exactly one of ID, UserID, GameID
	Language string             // Optional: Use only with GameID
	Period   GetVideoOptsPeriod // Optional: Use only with GameID or UserID
	Sort     GetVideoOptsSort   // Optional: Use only with GameID or UserID
	Type     GetVideoOptsType   // Optional: Use only with GameID or UserID
	First    int64              // Optional: Use only with GameID or UserID
	After    string             // Optional: Use only with UserID
	Before   string             // Optional: Use only with UserID
}

GetVideoOpts contain the query parameter for the GetVideos query

See https://dev.twitch.tv/docs/api/reference/#get-videos for details

type GetVideoOptsPeriod added in v3.34.0

type GetVideoOptsPeriod string

GetVideoOptsPeriod represents a filter used to filter the list of videos by when they were published

const (
	GetVideoOptsPeriodAll   GetVideoOptsPeriod = "all"
	GetVideoOptsPeriodDay   GetVideoOptsPeriod = "day"
	GetVideoOptsPeriodMonth GetVideoOptsPeriod = "month"
	GetVideoOptsPeriodWeek  GetVideoOptsPeriod = "week"
)

List of filters for GetVideoOpts.Period

type GetVideoOptsSort added in v3.34.0

type GetVideoOptsSort string

GetVideoOptsSort represents the order to sort the returned videos in

const (
	GetVideoOptsSortTime     GetVideoOptsSort = "time"
	GetVideoOptsSortTrending GetVideoOptsSort = "trending"
	GetVideoOptsSortViews    GetVideoOptsSort = "views"
)

List of sort options for GetVideoOpts.Sort

type GetVideoOptsType added in v3.34.0

type GetVideoOptsType string

GetVideoOptsType represents a filter used to filter the list of videos by the video's type

const (
	GetVideoOptsTypeAll       GetVideoOptsType = "all"
	GetVideoOptsTypeArchive   GetVideoOptsType = "archive"
	GetVideoOptsTypeHighlight GetVideoOptsType = "highlight"
	GetVideoOptsTypeUpload    GetVideoOptsType = "upload"
)

List of types for GetVideoOpts.Type

type HTTPError added in v3.15.0

type HTTPError struct {
	Body []byte
	Code int
	Err  error
}

HTTPError represents an HTTP error containing the response body (or the wrapped error occurred while readiny the body) and the status code returned by the server

func (HTTPError) Error added in v3.15.0

func (h HTTPError) Error() string

Error implements the error interface and returns a formatted version of the error including the body, might therefore leak confidential information when included in the response body

func (HTTPError) Is added in v3.15.0

func (h HTTPError) Is(target error) bool

Is checks whether the given error is an HTTPError and the status code matches the given error

func (HTTPError) Unwrap added in v3.15.0

func (h HTTPError) Unwrap() error

Unwrap returns the wrapped error occurred when reading the body

type OAuthTokenResponse

type OAuthTokenResponse struct {
	AccessToken  string   `json:"access_token"`
	RefreshToken string   `json:"refresh_token"`
	ExpiresIn    int      `json:"expires_in"`
	Scope        []string `json:"scope"`
	TokenType    string   `json:"token_type"`
}

OAuthTokenResponse is used when requesting a token

type OAuthTokenValidationResponse

type OAuthTokenValidationResponse struct {
	ClientID  string   `json:"client_id"`
	Login     string   `json:"login"`
	Scopes    []string `json:"scopes"`
	UserID    string   `json:"user_id"`
	ExpiresIn int      `json:"expires_in"`
}

OAuthTokenValidationResponse is used when validating a token

type PollInfo added in v3.11.0

type PollInfo struct {
	ID               string `json:"id"`
	BroadcasterID    string `json:"broadcaster_id"`
	BroadcasterName  string `json:"broadcaster_name"`
	BroadcasterLogin string `json:"broadcaster_login"`
	Title            string `json:"title"`
	Choices          []struct {
		ID                 string `json:"id"`
		Title              string `json:"title"`
		Votes              int    `json:"votes"`
		ChannelPointsVotes int    `json:"channel_points_votes"`
	} `json:"choices"`
	ChannelPointsVotingEnabled bool       `json:"channel_points_voting_enabled"`
	ChannelPointsPerVote       int        `json:"channel_points_per_vote"`
	Status                     string     `json:"status"`
	Duration                   int        `json:"duration"`
	StartedAt                  time.Time  `json:"started_at"`
	EndedAt                    *time.Time `json:"ended_at"`
}

PollInfo contains information about a Twitch poll

type StreamInfo

type StreamInfo struct {
	ID           string    `json:"id"`
	UserID       string    `json:"user_id"`
	UserLogin    string    `json:"user_login"`
	UserName     string    `json:"user_name"`
	GameID       string    `json:"game_id"`
	GameName     string    `json:"game_name"`
	Type         string    `json:"type"`
	Title        string    `json:"title"`
	ViewerCount  int64     `json:"viewer_count"`
	StartedAt    time.Time `json:"started_at"`
	Language     string    `json:"language"`
	ThumbnailURL string    `json:"thumbnail_url"`
	TagIds       []string  `json:"tag_ids"` //revive:disable-line:var-naming // Disabled to prevent breaking change
	IsMature     bool      `json:"is_mature"`
}

StreamInfo contains all the information known about a stream

type StreamMarkerInfo added in v3.34.0

type StreamMarkerInfo struct {
	ID              string    `json:"id"`
	CreatedAt       time.Time `json:"created_at"`
	Description     string    `json:"description"`
	PositionSeconds int64     `json:"position_seconds"`
}

StreamMarkerInfo contains information about a marker on a stream

type User

type User struct {
	DisplayName     string `json:"display_name"`
	ID              string `json:"id"`
	Login           string `json:"login"`
	ProfileImageURL string `json:"profile_image_url"`
}

User represents the data known about an user

type Video added in v3.34.0

type Video struct {
	ID            string    `json:"id"`
	StreamID      *string   `json:"stream_id"`
	UserID        string    `json:"user_id"`
	UserLogin     string    `json:"user_login"`
	UserName      string    `json:"user_name"`
	Title         string    `json:"title"`
	Description   string    `json:"description"`
	CreatedAt     time.Time `json:"created_at"`
	PublishedAt   time.Time `json:"published_at"`
	URL           string    `json:"url"`
	ThumbnailURL  string    `json:"thumbnail_url"`
	Viewable      string    `json:"viewable"`
	ViewCount     int64     `json:"view_count"`
	Language      string    `json:"language"`
	Type          string    `json:"type"`
	Duration      string    `json:"duration"`
	MutedSegments []struct {
		Duration int64 `json:"duration"`
		Offset   int64 `json:"offset"`
	} `json:"muted_segments"`
}

Video contains information about a published video

Jump to

Keyboard shortcuts

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