helix

package
v1.2.2 Latest Latest
Warning

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

Go to latest
Published: Apr 23, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package helix provides a client for the Twitch Helix API.

Index

Constants

View Source
const (
	// TwitchAuthURL is the base URL for Twitch OAuth endpoints.
	TwitchAuthURL = "https://id.twitch.tv/oauth2"

	// AuthorizeEndpoint is the authorization endpoint.
	AuthorizeEndpoint = TwitchAuthURL + "/authorize"

	// TokenEndpoint is the token endpoint.
	TokenEndpoint = TwitchAuthURL + "/token"

	// ValidateEndpoint is the token validation endpoint.
	ValidateEndpoint = TwitchAuthURL + "/validate"

	// RevokeEndpoint is the token revocation endpoint.
	RevokeEndpoint = TwitchAuthURL + "/revoke"

	// DeviceEndpoint is the device authorization endpoint.
	DeviceEndpoint = TwitchAuthURL + "/device"

	// OpenIDConfigurationEndpoint is the OIDC discovery endpoint.
	OpenIDConfigurationEndpoint = TwitchAuthURL + "/.well-known/openid-configuration"

	// UserInfoEndpoint is the OIDC userinfo endpoint.
	UserInfoEndpoint = TwitchAuthURL + "/userinfo"

	// JWKSEndpoint is the JSON Web Key Set endpoint.
	JWKSEndpoint = TwitchAuthURL + "/keys"
)

Auth URL constants

View Source
const (
	// Analytics scopes
	ScopeAnalyticsReadExtensions = "analytics:read:extensions"
	ScopeAnalyticsReadGames      = "analytics:read:games"

	// Bits scopes
	ScopeBitsRead = "bits:read"

	// Channel scopes
	ScopeChannelBot               = "channel:bot"
	ScopeChannelEditCommercial    = "channel:edit:commercial"
	ScopeChannelManageAds         = "channel:manage:ads"
	ScopeChannelManageBroadcast   = "channel:manage:broadcast"
	ScopeChannelManageClips       = "channel:manage:clips"
	ScopeChannelManageExtensions  = "channel:manage:extensions"
	ScopeChannelManageModerators  = "channel:manage:moderators"
	ScopeChannelManagePolls       = "channel:manage:polls"
	ScopeChannelManagePredictions = "channel:manage:predictions"
	ScopeChannelManageRaids       = "channel:manage:raids"
	ScopeChannelManageRedemptions = "channel:manage:redemptions"
	ScopeChannelManageSchedule    = "channel:manage:schedule"
	ScopeChannelManageVideos      = "channel:manage:videos"
	ScopeChannelManageVIPs        = "channel:manage:vips"
	ScopeChannelManageGuestStar   = "channel:manage:guest_star"
	ScopeChannelModerate          = "channel:moderate"
	ScopeChannelReadAds           = "channel:read:ads"
	ScopeChannelReadCharity       = "channel:read:charity"
	ScopeChannelReadEditors       = "channel:read:editors"
	ScopeChannelReadGoals         = "channel:read:goals"
	ScopeChannelReadGuestStar     = "channel:read:guest_star"
	ScopeChannelReadHypeTrain     = "channel:read:hype_train"
	ScopeChannelReadPolls         = "channel:read:polls"
	ScopeChannelReadPredictions   = "channel:read:predictions"
	ScopeChannelReadRedemptions   = "channel:read:redemptions"
	ScopeChannelReadStreamKey     = "channel:read:stream_key"
	ScopeChannelReadSubscriptions = "channel:read:subscriptions"
	ScopeChannelReadVIPs          = "channel:read:vips"

	// Chat scopes
	ScopeChatEdit = "chat:edit"
	ScopeChatRead = "chat:read"

	// Clips scopes
	ScopeClipsEdit = "clips:edit"

	// Editor scopes
	ScopeEditorManageClips = "editor:manage:clips"

	// Moderation scopes
	ScopeModerationRead                 = "moderation:read"
	ScopeModeratorManageAnnouncements   = "moderator:manage:announcements"
	ScopeModeratorManageAutomod         = "moderator:manage:automod"
	ScopeModeratorManageAutomodSettings = "moderator:manage:automod_settings"
	ScopeModeratorManageBannedUsers     = "moderator:manage:banned_users"
	ScopeModeratorManageBlockedTerms    = "moderator:manage:blocked_terms"
	ScopeModeratorManageChatMessages    = "moderator:manage:chat_messages"
	ScopeModeratorManageChatSettings    = "moderator:manage:chat_settings"
	ScopeModeratorManageGuestStar       = "moderator:manage:guest_star"
	ScopeModeratorManageShieldMode      = "moderator:manage:shield_mode"
	ScopeModeratorManageShoutouts       = "moderator:manage:shoutouts"
	ScopeModeratorManageWarnings        = "moderator:manage:warnings"
	ScopeModeratorManageUnbanRequests   = "moderator:manage:unban_requests"
	ScopeModeratorManageSuspiciousUsers = "moderator:manage:suspicious_users"
	ScopeModeratorReadAutomodSettings   = "moderator:read:automod_settings"
	ScopeModeratorReadBannedUsers       = "moderator:read:banned_users"
	ScopeModeratorReadBlockedTerms      = "moderator:read:blocked_terms"
	ScopeModeratorReadChatMessages      = "moderator:read:chat_messages"
	ScopeModeratorReadChatSettings      = "moderator:read:chat_settings"
	ScopeModeratorReadChatters          = "moderator:read:chatters"
	ScopeModeratorReadFollowers         = "moderator:read:followers"
	ScopeModeratorReadGuestStar         = "moderator:read:guest_star"
	ScopeModeratorReadShieldMode        = "moderator:read:shield_mode"
	ScopeModeratorReadShoutouts         = "moderator:read:shoutouts"
	ScopeModeratorReadSuspiciousUsers   = "moderator:read:suspicious_users"
	ScopeModeratorReadUnbanRequests     = "moderator:read:unban_requests"
	ScopeModeratorReadVIPs              = "moderator:read:vips"
	ScopeModeratorReadWarnings          = "moderator:read:warnings"

	// User scopes
	ScopeUserBot                   = "user:bot"
	ScopeUserEdit                  = "user:edit"
	ScopeUserEditBroadcast         = "user:edit:broadcast"
	ScopeUserManageBlockedUsers    = "user:manage:blocked_users"
	ScopeUserManageChatColor       = "user:manage:chat_color"
	ScopeUserManageWhispers        = "user:manage:whispers"
	ScopeUserReadBlockedUsers      = "user:read:blocked_users"
	ScopeUserReadBroadcast         = "user:read:broadcast"
	ScopeUserReadChat              = "user:read:chat"
	ScopeUserReadEmail             = "user:read:email"
	ScopeUserReadEmotes            = "user:read:emotes"
	ScopeUserReadFollows           = "user:read:follows"
	ScopeUserReadModeratedChannels = "user:read:moderated_channels"
	ScopeUserReadSubscriptions     = "user:read:subscriptions"
	ScopeUserReadWhispers          = "user:read:whispers"
	ScopeUserWriteChat             = "user:write:chat"

	// Whispers scope
	ScopeWhispersRead = "whispers:read"
)

Scope constants for Twitch API permissions.

View Source
const (
	// BadgeBroadcaster is the badge for the channel owner.
	BadgeBroadcaster = "broadcaster"

	// BadgeModerator is the badge for channel moderators.
	// Note: Users with the Lead Moderator role may display either
	// BadgeModerator or BadgeLeadModerator depending on their preference.
	BadgeModerator = "moderator"

	// BadgeLeadModerator is the badge for Lead Moderators.
	// Lead Moderators have additional privileges to help streamers manage
	// their mod teams. They can choose to display either this badge or
	// the regular moderator badge.
	BadgeLeadModerator = "lead_moderator"

	// BadgeVIP is the badge for channel VIPs.
	BadgeVIP = "vip"

	// BadgeSubscriber is the badge for channel subscribers.
	BadgeSubscriber = "subscriber"

	// BadgeFounder is the badge for channel founders (first subscribers).
	BadgeFounder = "founder"

	// BadgeSubGifter is the badge for users who have gifted subscriptions.
	BadgeSubGifter = "sub-gifter"

	// BadgeBitsLeader is the badge for bits leaderboard leaders.
	BadgeBitsLeader = "bits-leader"

	// BadgeBits is the badge showing bits tier.
	BadgeBits = "bits"

	// BadgePremium is the badge for Twitch Prime/Turbo users.
	BadgePremium = "premium"

	// BadgePartner is the badge for Twitch Partners.
	BadgePartner = "partner"

	// BadgeStaff is the badge for Twitch Staff.
	BadgeStaff = "staff"

	// BadgeAdmin is the badge for Twitch Admins.
	BadgeAdmin = "admin"

	// BadgeGlobalMod is the badge for Twitch Global Moderators.
	BadgeGlobalMod = "global_mod"

	// BadgeArtist is the badge for channel artists.
	BadgeArtist = "artist"

	// BadgeNoAudio is the badge indicating the user has no audio.
	BadgeNoAudio = "no_audio"

	// BadgeNoVideo is the badge indicating the user has no video.
	BadgeNoVideo = "no_video"

	// BadgePredictions is the badge for prediction participation.
	BadgePredictions = "predictions"

	// BadgeHypeTrain is the badge for Hype Train participation.
	BadgeHypeTrain = "hype-train"
)

Badge SetID constants for common Twitch chat badges. These constants represent the SetID field in ChatEventBadge and ChatBadge types.

View Source
const (
	// HelixBaseURL is the base URL for the Twitch Helix API.
	HelixBaseURL = "https://api.twitch.tv/helix"

	// DefaultRateLimit is the default rate limit for the API.
	DefaultRateLimit = 800 // requests per minute
)
View Source
const (
	EventSubTypeAutomodMessageHold    = "automod.message.hold"
	EventSubTypeAutomodMessageUpdate  = "automod.message.update"
	EventSubTypeAutomodSettingsUpdate = "automod.settings.update"
	EventSubTypeAutomodTermsUpdate    = "automod.terms.update"
)

EventSub subscription types - Automod

View Source
const (
	EventSubTypeChannelUpdate              = "channel.update"
	EventSubTypeChannelFollow              = "channel.follow"
	EventSubTypeChannelAdBreakBegin        = "channel.ad_break.begin"
	EventSubTypeChannelBitsUse             = "channel.bits.use"
	EventSubTypeChannelSubscribe           = "channel.subscribe"
	EventSubTypeChannelSubscriptionEnd     = "channel.subscription.end"
	EventSubTypeChannelSubscriptionGift    = "channel.subscription.gift"
	EventSubTypeChannelSubscriptionMessage = "channel.subscription.message"
	EventSubTypeChannelCheer               = "channel.cheer"
	EventSubTypeChannelRaid                = "channel.raid"
	EventSubTypeChannelBan                 = "channel.ban"
	EventSubTypeChannelUnban               = "channel.unban"
	EventSubTypeChannelUnbanRequestCreate  = "channel.unban_request.create"
	EventSubTypeChannelUnbanRequestResolve = "channel.unban_request.resolve"
	EventSubTypeChannelModerate            = "channel.moderate"
	EventSubTypeChannelModeratorAdd        = "channel.moderator.add"
	EventSubTypeChannelModeratorRemove     = "channel.moderator.remove"
	EventSubTypeChannelVIPAdd              = "channel.vip.add"
	EventSubTypeChannelVIPRemove           = "channel.vip.remove"
	EventSubTypeChannelWarningSend         = "channel.warning.send"
	EventSubTypeChannelWarningAcknowledge  = "channel.warning.acknowledge"
)

EventSub subscription types - Channel

View Source
const (
	EventSubTypeChannelChatClear             = "channel.chat.clear"
	EventSubTypeChannelChatClearUserMessages = "channel.chat.clear_user_messages"
	EventSubTypeChannelChatMessage           = "channel.chat.message"
	EventSubTypeChannelChatMessageDelete     = "channel.chat.message_delete"
	EventSubTypeChannelChatNotification      = "channel.chat.notification"
	EventSubTypeChannelChatSettingsUpdate    = "channel.chat_settings.update"
	EventSubTypeChannelChatUserMessageHold   = "channel.chat.user_message_hold"
	EventSubTypeChannelChatUserMessageUpdate = "channel.chat.user_message_update"
)

EventSub subscription types - Channel Chat

View Source
const (
	EventSubTypeChannelSharedChatBegin  = "channel.shared_chat.begin"
	EventSubTypeChannelSharedChatUpdate = "channel.shared_chat.update"
	EventSubTypeChannelSharedChatEnd    = "channel.shared_chat.end"
)

EventSub subscription types - Channel Shared Chat

View Source
const (
	EventSubTypeChannelPointsAutomaticRewardRedemptionAdd = "channel.channel_points_automatic_reward_redemption.add"
	EventSubTypeChannelPointsRewardAdd                    = "channel.channel_points_custom_reward.add"
	EventSubTypeChannelPointsRewardUpdate                 = "channel.channel_points_custom_reward.update"
	EventSubTypeChannelPointsRewardRemove                 = "channel.channel_points_custom_reward.remove"
	EventSubTypeChannelPointsRedemptionAdd                = "channel.channel_points_custom_reward_redemption.add"
	EventSubTypeChannelPointsRedemptionUpdate             = "channel.channel_points_custom_reward_redemption.update"
)

EventSub subscription types - Channel Points

View Source
const (
	EventSubTypeChannelPollBegin          = "channel.poll.begin"
	EventSubTypeChannelPollProgress       = "channel.poll.progress"
	EventSubTypeChannelPollEnd            = "channel.poll.end"
	EventSubTypeChannelPredictionBegin    = "channel.prediction.begin"
	EventSubTypeChannelPredictionProgress = "channel.prediction.progress"
	EventSubTypeChannelPredictionLock     = "channel.prediction.lock"
	EventSubTypeChannelPredictionEnd      = "channel.prediction.end"
)

EventSub subscription types - Polls & Predictions

View Source
const (
	EventSubTypeChannelHypeTrainBegin    = "channel.hype_train.begin"
	EventSubTypeChannelHypeTrainProgress = "channel.hype_train.progress"
	EventSubTypeChannelHypeTrainEnd      = "channel.hype_train.end"
)

EventSub subscription types - Hype Train (default v2)

View Source
const (
	// Deprecated: EventSubVersionHypeTrainV1 is deprecated by Twitch. Use EventSubVersionHypeTrainV2.
	EventSubVersionHypeTrainV1 = "1"
	EventSubVersionHypeTrainV2 = "2"
)

EventSub Hype Train version constants.

View Source
const (
	EventSubTypeChannelCharityCampaignDonate   = "channel.charity_campaign.donate"
	EventSubTypeChannelCharityCampaignStart    = "channel.charity_campaign.start"
	EventSubTypeChannelCharityCampaignProgress = "channel.charity_campaign.progress"
	EventSubTypeChannelCharityCampaignStop     = "channel.charity_campaign.stop"
)

EventSub subscription types - Charity

View Source
const (
	EventSubTypeChannelGoalBegin    = "channel.goal.begin"
	EventSubTypeChannelGoalProgress = "channel.goal.progress"
	EventSubTypeChannelGoalEnd      = "channel.goal.end"
)

EventSub subscription types - Goals

View Source
const (
	EventSubTypeChannelShieldModeBegin = "channel.shield_mode.begin"
	EventSubTypeChannelShieldModeEnd   = "channel.shield_mode.end"
)

EventSub subscription types - Shield Mode

View Source
const (
	EventSubTypeChannelShoutoutCreate  = "channel.shoutout.create"
	EventSubTypeChannelShoutoutReceive = "channel.shoutout.receive"
)

EventSub subscription types - Shoutout

View Source
const (
	EventSubTypeChannelSuspiciousUserMessage = "channel.suspicious_user.message"
	EventSubTypeChannelSuspiciousUserUpdate  = "channel.suspicious_user.update"
)

EventSub subscription types - Suspicious User

View Source
const (
	EventSubTypeChannelGuestStarSessionBegin   = "channel.guest_star_session.begin"
	EventSubTypeChannelGuestStarSessionEnd     = "channel.guest_star_session.end"
	EventSubTypeChannelGuestStarGuestUpdate    = "channel.guest_star_guest.update"
	EventSubTypeChannelGuestStarSettingsUpdate = "channel.guest_star_settings.update"
)

EventSub subscription types - Guest Star (Beta)

View Source
const (
	EventSubTypeStreamOnline  = "stream.online"
	EventSubTypeStreamOffline = "stream.offline"
)

EventSub subscription types - Stream

View Source
const (
	EventSubTypeUserAuthorizationGrant  = "user.authorization.grant"
	EventSubTypeUserAuthorizationRevoke = "user.authorization.revoke"
	EventSubTypeUserUpdate              = "user.update"
	EventSubTypeUserWhisperMessage      = "user.whisper.message"
)

EventSub subscription types - User

View Source
const (
	EventSubStatusEnabled                            = "enabled"
	EventSubStatusWebhookCallbackVerificationPending = "webhook_callback_verification_pending"
	EventSubStatusWebhookCallbackVerificationFailed  = "webhook_callback_verification_failed"
	EventSubStatusNotificationFailuresExceeded       = "notification_failures_exceeded"
	EventSubStatusAuthorizationRevoked               = "authorization_revoked"
	EventSubStatusModeratorRemoved                   = "moderator_removed"
	EventSubStatusUserRemoved                        = "user_removed"
	EventSubStatusVersionRemoved                     = "version_removed"
	EventSubStatusBetaMaintenance                    = "beta_maintenance"
	EventSubStatusWebsocketDisconnected              = "websocket_disconnected"
	EventSubStatusWebsocketFailedPingPong            = "websocket_failed_ping_pong"
	EventSubStatusWebsocketReceivedInboundTraffic    = "websocket_received_inbound_traffic"
	EventSubStatusWebsocketConnectionUnused          = "websocket_connection_unused"
	EventSubStatusWebsocketInternalError             = "websocket_internal_error"
	EventSubStatusWebsocketNetworkTimeout            = "websocket_network_timeout"
	EventSubStatusWebsocketNetworkError              = "websocket_network_error"
	EventSubStatusWebsocketFailedToReconnect         = "websocket_failed_to_reconnect"
)

EventSub subscription statuses

View Source
const (
	EventSubTransportWebhook   = "webhook"
	EventSubTransportWebSocket = "websocket"
	EventSubTransportConduit   = "conduit"
)

EventSub transport methods

View Source
const (
	EventSubMessageTypeNotification = "notification"
	EventSubMessageTypeVerification = "webhook_callback_verification"
	EventSubMessageTypeRevocation   = "revocation"
)

EventSub webhook message types

View Source
const (
	EventSubHeaderMessageID           = "Twitch-Eventsub-Message-Id"
	EventSubHeaderMessageTimestamp    = "Twitch-Eventsub-Message-Timestamp"
	EventSubHeaderMessageSignature    = "Twitch-Eventsub-Message-Signature"
	EventSubHeaderMessageType         = "Twitch-Eventsub-Message-Type"
	EventSubHeaderSubscriptionType    = "Twitch-Eventsub-Subscription-Type"
	EventSubHeaderSubscriptionVersion = "Twitch-Eventsub-Subscription-Version"
)

EventSub headers

View Source
const (
	RevocationReasonAuthorizationRevoked = "authorization_revoked"
	RevocationReasonUserRemoved          = "user_removed"
	RevocationReasonNotificationFailures = "notification_failures_exceeded"
	RevocationReasonVersionRemoved       = "version_removed"
	RevocationReasonModeratorsChanged    = "moderator_removed"
)

Common revocation reasons

View Source
const (
	WSMessageTypeWelcome      = "session_welcome"
	WSMessageTypeKeepalive    = "session_keepalive"
	WSMessageTypeNotification = "notification"
	WSMessageTypeReconnect    = "session_reconnect"
	WSMessageTypeRevocation   = "revocation"
)

WebSocket message types

View Source
const (
	WSCloseInternalError         = 4000 // Internal server error
	WSCloseClientSentInbound     = 4001 // Client sent inbound traffic
	WSCloseClientFailedPingPong  = 4002 // Client failed ping-pong
	WSCloseConnectionUnused      = 4003 // Connection unused (no subscriptions within 10s)
	WSCloseReconnectGraceExpired = 4004 // Reconnect grace time expired
	WSCloseNetworkTimeout        = 4005 // Network timeout
	WSCloseNetworkError          = 4006 // Network error
	WSCloseInvalidReconnect      = 4007 // Invalid reconnect
)

WebSocket close codes from Twitch

View Source
const (
	// TwitchIRCWebSocket is the WebSocket URL for Twitch IRC.
	TwitchIRCWebSocket = "wss://irc-ws.chat.twitch.tv:443"

	// TwitchIRCTCP is the TCP address for Twitch IRC.
	TwitchIRCTCP = "irc.chat.twitch.tv:6697"
)
View Source
const (
	UserNoticeTypeSub                 = "sub"
	UserNoticeTypeResub               = "resub"
	UserNoticeTypeSubGift             = "subgift"
	UserNoticeTypeAnonSubGift         = "anonsubgift"
	UserNoticeTypeSubMysteryGift      = "submysterygift"
	UserNoticeTypeGiftPaidUpgrade     = "giftpaidupgrade"
	UserNoticeTypePrimePaidUpgrade    = "primepaidupgrade"
	UserNoticeTypeRaid                = "raid"
	UserNoticeTypeUnraid              = "unraid"
	UserNoticeTypeRitual              = "ritual"
	UserNoticeTypeBitsBadgeTier       = "bitsbadgetier"
	UserNoticeTypeCommunityPayForward = "communitypayforward"
	UserNoticeTypeStandardPayForward  = "standardpayforward"
	UserNoticeTypeAnnouncement        = "announcement"
)

UserNotice types

View Source
const (
	NoticeMsgIDSubsOn              = "subs_on"
	NoticeMsgIDSubsOff             = "subs_off"
	NoticeMsgIDEmoteOnlyOn         = "emote_only_on"
	NoticeMsgIDEmoteOnlyOff        = "emote_only_off"
	NoticeMsgIDSlowOn              = "slow_on"
	NoticeMsgIDSlowOff             = "slow_off"
	NoticeMsgIDFollowersOn         = "followers_on"
	NoticeMsgIDFollowersOff        = "followers_off"
	NoticeMsgIDR9KOn               = "r9k_on"
	NoticeMsgIDR9KOff              = "r9k_off"
	NoticeMsgIDHostOn              = "host_on"
	NoticeMsgIDHostOff             = "host_off"
	NoticeMsgIDMsgChannelSuspended = "msg_channel_suspended"
	NoticeMsgIDMsgBanned           = "msg_banned"
	NoticeMsgIDMsgRateLimit        = "msg_ratelimit"
	NoticeMsgIDMsgDuplicate        = "msg_duplicate"
	NoticeMsgIDMsgFollowersOnly    = "msg_followersonly"
	NoticeMsgIDMsgSubsOnly         = "msg_subsonly"
	NoticeMsgIDMsgEmoteOnly        = "msg_emoteonly"
	NoticeMsgIDMsgSlowMode         = "msg_slowmode"
	NoticeMsgIDMsgR9K              = "msg_r9k"
	NoticeMsgIDNoPermission        = "no_permission"
	NoticeMsgIDUnrecognizedCmd     = "unrecognized_cmd"
)

Common Notice MsgIDs

View Source
const EventSubMaxBodySize = 1 << 20 // 1 MB

EventSubMaxBodySize is the maximum request body size for EventSub webhooks (1 MB). This prevents memory exhaustion from malicious large payloads.

View Source
const (
	EventSubTypeConduitShardDisabled = "conduit.shard.disabled"
)

EventSub subscription types - Conduit

View Source
const (
	EventSubTypeDropEntitlementGrant = "drop.entitlement.grant"
)

EventSub subscription types - Drop

View Source
const (
	EventSubTypeExtensionBitsTransactionCreate = "extension.bits_transaction.create"
)

EventSub subscription types - Extension

View Source
const (
	// EventSubWebSocketURL is the Twitch EventSub WebSocket endpoint.
	EventSubWebSocketURL = "wss://eventsub.wss.twitch.tv/ws"
)
View Source
const (
	// IngestBaseURL is the base URL for the Twitch Ingest API.
	IngestBaseURL = "https://ingest.twitch.tv"
)

Variables

View Source
var (
	ErrInvalidToken         = errors.New("invalid access token")
	ErrTokenExpired         = errors.New("token has expired")
	ErrAuthorizationPending = errors.New("authorization pending")
	ErrInvalidDeviceCode    = errors.New("invalid device code")
	ErrInvalidRefreshToken  = errors.New("invalid refresh token")
	ErrMissingClientID      = errors.New("client ID is required")
	ErrMissingClientSecret  = errors.New("client secret is required")
	ErrMissingRedirectURI   = errors.New("redirect URI is required")
	ErrMissingCode          = errors.New("authorization code is required")
)

Auth errors

View Source
var (
	ErrIRCNotConnected     = errors.New("irc: not connected")
	ErrIRCAlreadyConnected = errors.New("irc: already connected")
	ErrIRCAuthFailed       = errors.New("irc: authentication failed")
	ErrIRCInvalidNick      = errors.New("irc: nick is required")
	ErrIRCInvalidToken     = errors.New("irc: token is required")
)

IRC errors

View Source
var (
	ErrPubSubNotConnected     = errors.New("pubsub: not connected")
	ErrPubSubInvalidTopic     = errors.New("pubsub: invalid topic format")
	ErrPubSubUnsupportedTopic = errors.New("pubsub: topic type not supported")
)

PubSub compatibility errors.

CommonScopes provides commonly used scope combinations.

View Source
var ErrAlreadyConnecting = errors.New("connection already in progress")

ErrAlreadyConnecting is returned when Connect is called while already connecting.

View Source
var EventSubTypeVersion = map[string]string{

	EventSubTypeAutomodMessageHold:    "2",
	EventSubTypeAutomodMessageUpdate:  "2",
	EventSubTypeAutomodSettingsUpdate: "1",
	EventSubTypeAutomodTermsUpdate:    "1",

	EventSubTypeChannelUpdate:              "2",
	EventSubTypeChannelFollow:              "2",
	EventSubTypeChannelAdBreakBegin:        "1",
	EventSubTypeChannelBitsUse:             "1",
	EventSubTypeChannelSubscribe:           "1",
	EventSubTypeChannelSubscriptionEnd:     "1",
	EventSubTypeChannelSubscriptionGift:    "1",
	EventSubTypeChannelSubscriptionMessage: "1",
	EventSubTypeChannelCheer:               "1",
	EventSubTypeChannelRaid:                "1",
	EventSubTypeChannelBan:                 "1",
	EventSubTypeChannelUnban:               "1",
	EventSubTypeChannelUnbanRequestCreate:  "1",
	EventSubTypeChannelUnbanRequestResolve: "1",
	EventSubTypeChannelModerate:            "2",
	EventSubTypeChannelModeratorAdd:        "1",
	EventSubTypeChannelModeratorRemove:     "1",
	EventSubTypeChannelVIPAdd:              "1",
	EventSubTypeChannelVIPRemove:           "1",
	EventSubTypeChannelWarningSend:         "1",
	EventSubTypeChannelWarningAcknowledge:  "1",

	EventSubTypeChannelChatClear:             "1",
	EventSubTypeChannelChatClearUserMessages: "1",
	EventSubTypeChannelChatMessage:           "1",
	EventSubTypeChannelChatMessageDelete:     "1",
	EventSubTypeChannelChatNotification:      "1",
	EventSubTypeChannelChatSettingsUpdate:    "1",
	EventSubTypeChannelChatUserMessageHold:   "1",
	EventSubTypeChannelChatUserMessageUpdate: "1",

	EventSubTypeChannelSharedChatBegin:  "1",
	EventSubTypeChannelSharedChatUpdate: "1",
	EventSubTypeChannelSharedChatEnd:    "1",

	EventSubTypeChannelPointsAutomaticRewardRedemptionAdd: "2",
	EventSubTypeChannelPointsRewardAdd:                    "1",
	EventSubTypeChannelPointsRewardUpdate:                 "1",
	EventSubTypeChannelPointsRewardRemove:                 "1",
	EventSubTypeChannelPointsRedemptionAdd:                "1",
	EventSubTypeChannelPointsRedemptionUpdate:             "1",

	EventSubTypeChannelPollBegin:          "1",
	EventSubTypeChannelPollProgress:       "1",
	EventSubTypeChannelPollEnd:            "1",
	EventSubTypeChannelPredictionBegin:    "1",
	EventSubTypeChannelPredictionProgress: "1",
	EventSubTypeChannelPredictionLock:     "1",
	EventSubTypeChannelPredictionEnd:      "1",

	EventSubTypeChannelHypeTrainBegin:    "2",
	EventSubTypeChannelHypeTrainProgress: "2",
	EventSubTypeChannelHypeTrainEnd:      "2",

	EventSubTypeChannelCharityCampaignDonate:   "1",
	EventSubTypeChannelCharityCampaignStart:    "1",
	EventSubTypeChannelCharityCampaignProgress: "1",
	EventSubTypeChannelCharityCampaignStop:     "1",

	EventSubTypeChannelGoalBegin:    "1",
	EventSubTypeChannelGoalProgress: "1",
	EventSubTypeChannelGoalEnd:      "1",

	EventSubTypeChannelShieldModeBegin: "1",
	EventSubTypeChannelShieldModeEnd:   "1",

	EventSubTypeChannelShoutoutCreate:  "1",
	EventSubTypeChannelShoutoutReceive: "1",

	EventSubTypeChannelSuspiciousUserMessage: "1",
	EventSubTypeChannelSuspiciousUserUpdate:  "1",

	EventSubTypeChannelGuestStarSessionBegin:   "beta",
	EventSubTypeChannelGuestStarSessionEnd:     "beta",
	EventSubTypeChannelGuestStarGuestUpdate:    "beta",
	EventSubTypeChannelGuestStarSettingsUpdate: "beta",

	EventSubTypeConduitShardDisabled: "1",

	EventSubTypeDropEntitlementGrant: "1",

	EventSubTypeExtensionBitsTransactionCreate: "1",

	EventSubTypeStreamOnline:  "1",
	EventSubTypeStreamOffline: "1",

	EventSubTypeUserAuthorizationGrant:  "1",
	EventSubTypeUserAuthorizationRevoke: "1",
	EventSubTypeUserUpdate:              "1",
	EventSubTypeUserWhisperMessage:      "1",
}

EventSubTypeVersion maps subscription types to their latest versions.

Functions

func BroadcasterCondition

func BroadcasterCondition(broadcasterID string) map[string]string

BroadcasterCondition returns a condition with broadcaster_user_id.

func BroadcasterModeratorCondition

func BroadcasterModeratorCondition(broadcasterID, moderatorID string) map[string]string

BroadcasterModeratorCondition returns a condition with broadcaster and moderator IDs.

func BuildTopic added in v1.0.0

func BuildTopic(topicType string, ids ...string) string

BuildTopic constructs a PubSub topic string from components. This is a helper for users migrating from PubSub who need to construct topics.

func CacheKey

func CacheKey(endpoint string, query string) string

CacheKey generates a cache key from a request. Note: This function does not include authentication context. Use CacheKeyWithContext for security-sensitive applications where the same cache might be shared across different tokens.

func CacheKeyWithContext added in v1.0.2

func CacheKeyWithContext(baseURL, endpoint, query, tokenHash string) string

CacheKeyWithContext generates a cache key that includes authentication context. This prevents cache pollution when sharing a cache across different users/tokens. The baseURL ensures environment separation, and tokenHash provides user isolation.

func ClientCondition

func ClientCondition(clientID string) map[string]string

ClientCondition returns a condition with client_id for extension events.

func ConduitCondition

func ConduitCondition(conduitID string) map[string]string

ConduitCondition returns a condition with conduit_id.

func Errors

func Errors(results []BatchResult) []error

Errors returns all errors from batch results.

func EventSubMiddleware

func EventSubMiddleware(secret string, maxAge time.Duration) func(http.Handler) http.Handler

EventSubMiddleware returns middleware that verifies EventSub signatures. Use this with your own http.Handler if you need more control.

func FirstError

func FirstError(results []BatchResult) error

FirstError returns the first error from batch results, or nil if none.

func FromToBroadcasterCondition

func FromToBroadcasterCondition(fromBroadcasterID, toBroadcasterID string) map[string]string

FromToBroadcasterCondition returns a condition for raid events.

func GetEventSubVersion

func GetEventSubVersion(subType string) string

GetEventSubVersion returns the latest version for a subscription type. Returns "1" if the type is not found.

func GetRevocationReason

func GetRevocationReason(subscription EventSubSubscription) string

GetRevocationReason extracts the revocation reason from a subscription status.

func HasErrors

func HasErrors(results []BatchResult) bool

HasErrors returns true if any batch result contains an error.

func IsRateLimitError

func IsRateLimitError(err error) bool

IsRateLimitError returns true if the error is a rate limit error.

func NoCacheContext

func NoCacheContext(ctx context.Context) context.Context

NoCacheContext returns a context that bypasses the cache for a single request.

func ParseEventSubEvent

func ParseEventSubEvent[T any](msg *EventSubWebhookMessage) (*T, error)

ParseEventSubEvent parses the event data from a webhook message into the provided type.

func ParseWSEvent

func ParseWSEvent[T any](eventData json.RawMessage) (*T, error)

ParseWSEvent parses the event JSON into the specified type.

func RewardCondition

func RewardCondition(broadcasterID, rewardID string) map[string]string

RewardCondition returns a condition for channel points reward events.

func SupportedTopics added in v1.0.0

func SupportedTopics() []string

SupportedTopics returns a list of supported PubSub topic patterns.

func TokenHash added in v1.0.2

func TokenHash(token string) string

TokenHash generates a hash of a token for use in cache keys. This avoids storing the actual token in cache keys while still providing isolation between different authenticated users.

func TopicEventSubTypes added in v1.0.0

func TopicEventSubTypes(topic string) []string

TopicEventSubTypes returns the EventSub types that a PubSub topic maps to. Returns nil if the topic is invalid or unsupported.

func UserCondition

func UserCondition(userID string) map[string]string

UserCondition returns a condition with user_id.

func VerifyEventSubSignature

func VerifyEventSubSignature(secret, messageID, timestamp string, body []byte, signature string) bool

VerifyEventSubSignature verifies an EventSub webhook signature. This is useful for custom handler implementations.

func VerifyIDTokenSignature added in v1.0.2

func VerifyIDTokenSignature(idToken string, jwks *JWKS) error

VerifyIDTokenSignature verifies the JWT signature of an ID token using the provided JWKS. This is the recommended way to validate ID tokens for security.

func WithToken added in v1.1.1

func WithToken(ctx context.Context, token *Token) context.Context

WithToken returns a context that overrides the client-level token for a single request. This is useful when making concurrent requests that each require a different user token.

Types

type APIError

type APIError struct {
	StatusCode int
	ErrorType  string
	Message    string
}

APIError represents a Twitch API error.

func (*APIError) Error

func (e *APIError) Error() string

type ActiveExtension

type ActiveExtension struct {
	Active  bool   `json:"active"`
	ID      string `json:"id,omitempty"`
	Version string `json:"version,omitempty"`
	Name    string `json:"name,omitempty"`
	X       int    `json:"x,omitempty"`
	Y       int    `json:"y,omitempty"`
}

ActiveExtension represents an active extension in a slot.

type AdSchedule

type AdSchedule struct {
	NextAdAt        time.Time `json:"next_ad_at,omitempty"`
	LastAdAt        time.Time `json:"last_ad_at,omitempty"`
	Duration        int       `json:"duration"`
	PrerollFreeTime int       `json:"preroll_free_time"`
	SnoozeCount     int       `json:"snooze_count"`
	SnoozeRefreshAt time.Time `json:"snooze_refresh_at,omitempty"`
}

AdSchedule represents the ad schedule for a channel.

type AddBlockedTermParams

type AddBlockedTermParams struct {
	BroadcasterID string `json:"-"`
	ModeratorID   string `json:"-"`
	Text          string `json:"text"`
}

AddBlockedTermParams contains parameters for AddBlockedTerm.

type AddSuspiciousStatusToChatUserParams added in v1.2.0

type AddSuspiciousStatusToChatUserParams struct {
	BroadcasterID string               `json:"-"`
	ModeratorID   string               `json:"-"`
	UserID        string               `json:"user_id"`
	Status        SuspiciousUserStatus `json:"status"`
}

AddSuspiciousStatusToChatUserParams contains parameters for AddSuspiciousStatusToChatUser.

type AuthClient

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

AuthClient is an OAuth client for Twitch authentication.

func NewAuthClient

func NewAuthClient(config AuthConfig) *AuthClient

NewAuthClient creates a new OAuth client with the given configuration.

func (*AuthClient) AutoRefresh

func (c *AuthClient) AutoRefresh(ctx context.Context) (cancel func())

AutoRefresh starts a goroutine that automatically refreshes the token before it expires. If the token has no expiry set (ExpiresAt is zero), it will not attempt automatic refresh until a token with a valid expiry is set.

IMPORTANT: The caller MUST call the returned cancel function to stop the goroutine when it's no longer needed, or ensure the parent context is eventually cancelled. Failure to do so will result in a goroutine leak.

func (*AuthClient) ExchangeCode

func (c *AuthClient) ExchangeCode(ctx context.Context, code string) (*Token, error)

ExchangeCode exchanges an authorization code for an access token.

func (*AuthClient) ExchangeCodeForOIDCToken

func (c *AuthClient) ExchangeCodeForOIDCToken(ctx context.Context, code string) (*OIDCToken, error)

ExchangeCodeForOIDCToken exchanges an authorization code for an OIDC token.

func (*AuthClient) GetAppAccessToken

func (c *AuthClient) GetAppAccessToken(ctx context.Context) (*Token, error)

GetAppAccessToken obtains an app access token using the Client Credentials flow.

func (*AuthClient) GetAuthorizationURL

func (c *AuthClient) GetAuthorizationURL(responseType string) (string, error)

GetAuthorizationURL returns the URL to redirect users to for authorization.

func (*AuthClient) GetCodeAuthURL

func (c *AuthClient) GetCodeAuthURL() (string, error)

GetCodeAuthURL returns the authorization URL for the Authorization Code Grant flow.

func (*AuthClient) GetCurrentOIDCUserInfo

func (c *AuthClient) GetCurrentOIDCUserInfo(ctx context.Context) (*OIDCUserInfo, error)

GetCurrentOIDCUserInfo fetches user information using the current access token.

func (*AuthClient) GetDeviceCode

func (c *AuthClient) GetDeviceCode(ctx context.Context) (*DeviceCodeResponse, error)

GetDeviceCode initiates the Device Code flow.

func (*AuthClient) GetImplicitAuthURL

func (c *AuthClient) GetImplicitAuthURL() (string, error)

GetImplicitAuthURL returns the authorization URL for the Implicit Grant flow.

func (*AuthClient) GetJWKS

func (c *AuthClient) GetJWKS(ctx context.Context) (*JWKS, error)

GetJWKS fetches the JSON Web Key Set for validating ID tokens.

func (*AuthClient) GetOIDCAuthorizationURL

func (c *AuthClient) GetOIDCAuthorizationURL(responseType OIDCResponseType, nonce string, claims map[string]interface{}) (string, error)

GetOIDCAuthorizationURL returns the authorization URL for OIDC flows.

func (*AuthClient) GetOIDCUserInfo

func (c *AuthClient) GetOIDCUserInfo(ctx context.Context, accessToken string) (*OIDCUserInfo, error)

GetOIDCUserInfo fetches user information from the OIDC UserInfo endpoint.

func (*AuthClient) GetOpenIDConfiguration

func (c *AuthClient) GetOpenIDConfiguration(ctx context.Context) (*OpenIDConfiguration, error)

GetOpenIDConfiguration fetches the OIDC discovery document.

func (*AuthClient) GetToken

func (c *AuthClient) GetToken() *Token

GetToken returns the current token.

func (*AuthClient) PollDeviceToken

func (c *AuthClient) PollDeviceToken(ctx context.Context, deviceCode string) (*Token, error)

PollDeviceToken polls for the device token after the user has authorized.

func (*AuthClient) RefreshCurrentToken

func (c *AuthClient) RefreshCurrentToken(ctx context.Context) (*Token, error)

RefreshCurrentToken refreshes the current token if it has a refresh token.

func (*AuthClient) RefreshToken

func (c *AuthClient) RefreshToken(ctx context.Context, refreshToken string) (*Token, error)

RefreshToken refreshes an access token using a refresh token.

func (*AuthClient) RevokeCurrentToken

func (c *AuthClient) RevokeCurrentToken(ctx context.Context) error

RevokeCurrentToken revokes the current token.

func (*AuthClient) RevokeToken

func (c *AuthClient) RevokeToken(ctx context.Context, accessToken string) error

RevokeToken revokes an access token.

func (*AuthClient) SetEndpoints

func (c *AuthClient) SetEndpoints(token, validate, revoke, device, openIDConfig, userInfo, jwks string)

SetEndpoints sets custom endpoints (primarily for testing).

func (*AuthClient) SetHTTPClient

func (c *AuthClient) SetHTTPClient(client *http.Client)

SetHTTPClient sets a custom HTTP client.

func (*AuthClient) SetToken

func (c *AuthClient) SetToken(token *Token)

SetToken sets the current token.

func (*AuthClient) ValidateCurrentToken

func (c *AuthClient) ValidateCurrentToken(ctx context.Context) (*ValidationResponse, error)

ValidateCurrentToken validates the current token.

func (*AuthClient) ValidateIDToken added in v1.0.2

func (c *AuthClient) ValidateIDToken(ctx context.Context, idToken string, nonce string) (*IDTokenClaims, error)

ValidateIDToken performs full validation of an ID token: signature verification, issuer, audience, expiry, and optional nonce check. This is the recommended method for securely validating OIDC ID tokens.

func (*AuthClient) ValidateIDTokenClaims

func (c *AuthClient) ValidateIDTokenClaims(claims *IDTokenClaims, nonce string) error

ValidateIDTokenClaims validates the claims in an ID token. WARNING: This only validates claims, not the JWT signature. For secure validation, use ValidateIDToken instead which verifies the signature first.

func (*AuthClient) ValidateToken

func (c *AuthClient) ValidateToken(ctx context.Context, accessToken string) (*ValidationResponse, error)

ValidateToken validates an access token.

func (*AuthClient) VerifyAndParseIDToken added in v1.0.2

func (c *AuthClient) VerifyAndParseIDToken(ctx context.Context, idToken string) (*IDTokenClaims, error)

VerifyAndParseIDToken verifies the signature and parses an ID token. This is the secure way to validate ID tokens - it fetches the JWKS, verifies the signature, and then parses the claims.

func (*AuthClient) WaitForDeviceToken

func (c *AuthClient) WaitForDeviceToken(ctx context.Context, deviceCode *DeviceCodeResponse) (*Token, error)

WaitForDeviceToken polls for the device token until it's available or the context is cancelled. Returns an error if deviceCode is nil or has an invalid interval.

type AuthConfig

type AuthConfig struct {
	ClientID     string
	ClientSecret string
	RedirectURI  string
	Scopes       []string
	ForceVerify  bool
	State        string
}

AuthConfig holds the configuration for OAuth.

type AuthErrorResponse

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

AuthErrorResponse represents an error response from Twitch auth endpoints.

type AutoModSettings

type AutoModSettings struct {
	BroadcasterID           string `json:"broadcaster_id"`
	ModeratorID             string `json:"moderator_id"`
	OverallLevel            *int   `json:"overall_level"`
	Disability              int    `json:"disability"`
	Aggression              int    `json:"aggression"`
	SexualitySexOrGender    int    `json:"sexuality_sex_or_gender"`
	Misogyny                int    `json:"misogyny"`
	Bullying                int    `json:"bullying"`
	Swearing                int    `json:"swearing"`
	RaceEthnicityOrReligion int    `json:"race_ethnicity_or_religion"`
	SexBasedTerms           int    `json:"sex_based_terms"`
}

AutoModSettings represents AutoMod settings.

type AutoModStatus

type AutoModStatus struct {
	MsgID       string `json:"msg_id"`
	IsPermitted bool   `json:"is_permitted"`
}

AutoModStatus represents the AutoMod status of a message.

type AutoModStatusMessage

type AutoModStatusMessage struct {
	MsgID   string `json:"msg_id"`
	MsgText string `json:"msg_text"`
}

AutoModStatusMessage represents a message to check.

type AutomaticRewardEmote

type AutomaticRewardEmote struct {
	ID    string `json:"id"`
	Begin int    `json:"begin"`
	End   int    `json:"end"`
}

AutomaticRewardEmote represents an emote in an automatic reward message.

type AutomaticRewardMessage

type AutomaticRewardMessage struct {
	Text   string                 `json:"text"`
	Emotes []AutomaticRewardEmote `json:"emotes"`
}

AutomaticRewardMessage represents an automatic reward message.

type AutomaticRewardRedemption

type AutomaticRewardRedemption struct {
	Type          string         `json:"type"` // single_message_bypass_sub_mode, send_highlighted_message, random_sub_emote_unlock, chosen_sub_emote_unlock, chosen_modified_sub_emote_unlock, message_effect, gigantify_an_emote, celebration
	Cost          int            `json:"cost"`
	UnlockedEmote *UnlockedEmote `json:"unlocked_emote,omitempty"`
}

AutomaticRewardRedemption represents an automatic reward.

type AutomodBoundary

type AutomodBoundary struct {
	StartPos int `json:"start_pos"`
	EndPos   int `json:"end_pos"`
}

AutomodBoundary represents text boundaries flagged by automod.

type AutomodCategoryInfo

type AutomodCategoryInfo struct {
	Category   string            `json:"category"`
	Level      int               `json:"level"`
	Boundaries []AutomodBoundary `json:"boundaries"`
}

AutomodCategoryInfo contains automod category information (v2).

type AutomodDetails

type AutomodDetails struct {
	Topics []AutomodTopic `json:"topics"`
}

AutomodDetails contains automod-specific details.

type AutomodFragment

type AutomodFragment struct {
	Type      string              `json:"type"`
	Text      string              `json:"text"`
	Automod   *AutomodDetails     `json:"automod,omitempty"`
	Emote     *ChatEventEmote     `json:"emote,omitempty"`
	Cheermote *ChatEventCheermote `json:"cheermote,omitempty"`
}

AutomodFragment represents a fragment in an automod message.

type AutomodHeldMessage

type AutomodHeldMessage struct {
	Text      string            `json:"text"`
	Fragments []AutomodFragment `json:"fragments"`
}

AutomodHeldMessage represents the message structure in automod events.

type AutomodMessageHoldEvent

type AutomodMessageHoldEvent struct {
	EventSubBroadcaster
	EventSubUser
	MessageID string             `json:"message_id"`
	Message   AutomodHeldMessage `json:"message"`
	HeldAt    time.Time          `json:"held_at"`
	// V2 fields
	Reason      string               `json:"reason,omitempty"` // "automod" or "blocked_term"
	Automod     *AutomodCategoryInfo `json:"automod,omitempty"`
	BlockedTerm *BlockedTermInfo     `json:"blocked_term,omitempty"`
	// V1 fields (deprecated in v2)
	Level     int               `json:"level,omitempty"`
	Category  string            `json:"category,omitempty"`
	Fragments []AutomodFragment `json:"fragments,omitempty"`
}

AutomodMessageHoldEvent is sent when AutoMod holds a message for review. V2 adds reason, automod, and blocked_term fields.

type AutomodMessageUpdateEvent

type AutomodMessageUpdateEvent struct {
	EventSubBroadcaster
	EventSubUser
	EventSubModerator
	MessageID string `json:"message_id"`
	Message   string `json:"message"`
	Status    string `json:"status"` // approved, denied, expired
}

AutomodMessageUpdateEvent is sent when a held message's status is updated.

type AutomodSettingsUpdateEvent

type AutomodSettingsUpdateEvent struct {
	EventSubBroadcaster
	EventSubModerator
	BulliedUsers          int  `json:"bullying"`
	Disability            int  `json:"disability"`
	Misogyny              int  `json:"misogyny"`
	OverallLevel          *int `json:"overall_level"`
	RaceEthnicityReligion int  `json:"race_ethnicity_or_religion"`
	SexBasedTerms         int  `json:"sex_based_terms"`
	SexualitySexGender    int  `json:"sexuality_sex_or_gender"`
	Swearing              int  `json:"swearing"`
}

AutomodSettingsUpdateEvent is sent when automod settings are updated.

type AutomodTermsUpdateEvent

type AutomodTermsUpdateEvent struct {
	EventSubBroadcaster
	EventSubModerator
	Action      string   `json:"action"` // add_permitted, remove_permitted, add_blocked, remove_blocked
	FromAutomod bool     `json:"from_automod"`
	Terms       []string `json:"terms"`
}

AutomodTermsUpdateEvent is sent when automod terms are updated.

type AutomodTopic

type AutomodTopic struct {
	Type  string `json:"type"`
	Score int    `json:"score"`
}

AutomodTopic represents a topic flagged by automod.

type BadgeVersion

type BadgeVersion struct {
	ID          string `json:"id"`
	ImageURL1x  string `json:"image_url_1x"`
	ImageURL2x  string `json:"image_url_2x"`
	ImageURL4x  string `json:"image_url_4x"`
	Title       string `json:"title"`
	Description string `json:"description"`
	ClickAction string `json:"click_action,omitempty"`
	ClickURL    string `json:"click_url,omitempty"`
}

BadgeVersion represents a version of a chat badge.

type BanUserData

type BanUserData struct {
	UserID   string `json:"user_id"`
	Duration int    `json:"duration,omitempty"` // 0 = permanent, 1-1209600 seconds
	Reason   string `json:"reason,omitempty"`
}

BanUserData contains the ban data.

type BanUserParams

type BanUserParams struct {
	BroadcasterID string      `json:"-"`
	ModeratorID   string      `json:"-"`
	Data          BanUserData `json:"data"`
}

BanUserParams contains parameters for BanUser.

type BanUserResponse

type BanUserResponse struct {
	BroadcasterID string    `json:"broadcaster_id"`
	ModeratorID   string    `json:"moderator_id"`
	UserID        string    `json:"user_id"`
	CreatedAt     time.Time `json:"created_at"`
	EndTime       time.Time `json:"end_time,omitempty"`
}

BanUserResponse represents the response from BanUser.

type BannedUser

type BannedUser struct {
	UserID         string    `json:"user_id"`
	UserLogin      string    `json:"user_login"`
	UserName       string    `json:"user_name"`
	ExpiresAt      time.Time `json:"expires_at,omitempty"`
	CreatedAt      time.Time `json:"created_at"`
	Reason         string    `json:"reason"`
	ModeratorID    string    `json:"moderator_id"`
	ModeratorLogin string    `json:"moderator_login"`
	ModeratorName  string    `json:"moderator_name"`
}

BannedUser represents a banned user.

type BatchOptions

type BatchOptions struct {
	// MaxConcurrent limits concurrent requests (0 = unlimited)
	MaxConcurrent int
	// StopOnError stops processing remaining requests on first error
	StopOnError bool
}

BatchOptions configures batch execution behavior.

func DefaultBatchOptions

func DefaultBatchOptions() BatchOptions

DefaultBatchOptions returns default batch options.

type BatchRequest

type BatchRequest struct {
	Request *Request
	Result  interface{}
}

BatchRequest represents a single request in a batch.

type BatchResult

type BatchResult struct {
	Index int
	Error error
}

BatchResult contains the result of a batch request.

type BitsLeaderboard

type BitsLeaderboard struct {
	UserID    string `json:"user_id"`
	UserLogin string `json:"user_login"`
	UserName  string `json:"user_name"`
	Rank      int    `json:"rank"`
	Score     int    `json:"score"`
}

BitsLeaderboard represents a bits leaderboard entry.

type BitsLeaderboardResponse

type BitsLeaderboardResponse struct {
	Data      []BitsLeaderboard `json:"data"`
	DateRange DateRange         `json:"date_range"`
	Total     int               `json:"total"`
}

BitsLeaderboardResponse represents the response from GetBitsLeaderboard.

type BlockUserParams

type BlockUserParams struct {
	TargetUserID  string
	SourceContext string // "chat" or "whisper"
	Reason        string // "spam", "harassment", or "other"
}

BlockUserParams contains parameters for BlockUser.

type BlockedTerm

type BlockedTerm struct {
	BroadcasterID string    `json:"broadcaster_id"`
	ModeratorID   string    `json:"moderator_id"`
	ID            string    `json:"id"`
	Text          string    `json:"text"`
	CreatedAt     time.Time `json:"created_at"`
	UpdatedAt     time.Time `json:"updated_at"`
	ExpiresAt     time.Time `json:"expires_at,omitempty"`
}

BlockedTerm represents a blocked term.

type BlockedTermFound

type BlockedTermFound struct {
	TermID   string          `json:"term_id"`
	Boundary AutomodBoundary `json:"boundary"`
}

BlockedTermFound represents a found blocked term.

type BlockedTermInfo

type BlockedTermInfo struct {
	TermsFound                []BlockedTermFound `json:"terms_found"`
	OwnerBroadcasterUserID    string             `json:"owner_broadcaster_user_id"`
	OwnerBroadcasterUserLogin string             `json:"owner_broadcaster_user_login"`
	OwnerBroadcasterUserName  string             `json:"owner_broadcaster_user_name"`
}

BlockedTermInfo contains blocked term information (v2).

type BlockedUser

type BlockedUser struct {
	UserID      string `json:"user_id"`
	UserLogin   string `json:"user_login"`
	DisplayName string `json:"display_name"`
}

BlockedUser represents a blocked user.

type Cache

type Cache interface {
	// Get retrieves a cached response. Returns nil if not found or expired.
	Get(ctx context.Context, key string) []byte
	// Set stores a response in the cache with the given TTL.
	Set(ctx context.Context, key string, value []byte, ttl time.Duration)
	// Delete removes a cached response.
	Delete(ctx context.Context, key string)
	// Clear removes all cached responses.
	Clear(ctx context.Context)
}

Cache is an interface for caching API responses.

type Category

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

Category represents a category/game.

type Channel

type Channel struct {
	BroadcasterID               string   `json:"broadcaster_id"`
	BroadcasterLogin            string   `json:"broadcaster_login"`
	BroadcasterName             string   `json:"broadcaster_name"`
	BroadcasterLanguage         string   `json:"broadcaster_language"`
	GameID                      string   `json:"game_id"`
	GameName                    string   `json:"game_name"`
	Title                       string   `json:"title"`
	Delay                       int      `json:"delay"`
	Tags                        []string `json:"tags"`
	ContentClassificationLabels []string `json:"content_classification_labels"`
	IsBrandedContent            bool     `json:"is_branded_content"`
}

Channel represents a Twitch channel.

type ChannelAdBreakBeginEvent

type ChannelAdBreakBeginEvent struct {
	DurationSeconds int       `json:"duration_seconds"`
	StartedAt       time.Time `json:"started_at"`
	IsAutomatic     bool      `json:"is_automatic"`
	EventSubBroadcaster
	RequesterUserID    string `json:"requester_user_id"`
	RequesterUserLogin string `json:"requester_user_login"`
	RequesterUserName  string `json:"requester_user_name"`
}

ChannelAdBreakBeginEvent is sent when an ad break begins.

type ChannelBanEvent

type ChannelBanEvent struct {
	EventSubUser
	EventSubBroadcaster
	EventSubModerator
	Reason      string     `json:"reason"`
	BannedAt    time.Time  `json:"banned_at"`
	EndsAt      *time.Time `json:"ends_at,omitempty"` // nil for permanent bans
	IsPermanent bool       `json:"is_permanent"`
}

ChannelBanEvent is sent when a user is banned from a channel.

type ChannelBitsUseEvent

type ChannelBitsUseEvent struct {
	EventSubBroadcaster
	EventSubUser
	BitsUsed int       `json:"bits_used"`
	Type     string    `json:"type"` // cheer, power_up_celebration, power_up_gigantify, power_up_message_effect
	UsedAt   time.Time `json:"used_at"`
	Message  *string   `json:"message,omitempty"`
	PowerUp  *PowerUp  `json:"power_up,omitempty"`
}

ChannelBitsUseEvent is sent when bits are used in a channel.

type ChannelCharityCampaignProgressEvent

type ChannelCharityCampaignProgressEvent = ChannelCharityCampaignStartEvent

ChannelCharityCampaignProgressEvent is sent when charity campaign progress updates.

type ChannelCharityCampaignStartEvent

type ChannelCharityCampaignStartEvent struct {
	ID string `json:"id"`
	EventSubBroadcaster
	CharityName        string        `json:"charity_name"`
	CharityDescription string        `json:"charity_description"`
	CharityWebsite     string        `json:"charity_website"`
	CurrentAmount      CharityAmount `json:"current_amount"`
	TargetAmount       CharityAmount `json:"target_amount"`
	StartedAt          time.Time     `json:"started_at"`
}

ChannelCharityCampaignStartEvent is sent when a charity campaign starts.

type ChannelCharityCampaignStopEvent

type ChannelCharityCampaignStopEvent struct {
	ID string `json:"id"`
	EventSubBroadcaster
	CharityName        string        `json:"charity_name"`
	CharityDescription string        `json:"charity_description"`
	CharityWebsite     string        `json:"charity_website"`
	CurrentAmount      CharityAmount `json:"current_amount"`
	TargetAmount       CharityAmount `json:"target_amount"`
	StoppedAt          time.Time     `json:"stopped_at"`
}

ChannelCharityCampaignStopEvent is sent when a charity campaign stops.

type ChannelCharityDonationEvent

type ChannelCharityDonationEvent struct {
	ID         string `json:"id"`
	CampaignID string `json:"campaign_id"`
	EventSubBroadcaster
	EventSubUser
	CharityName        string        `json:"charity_name"`
	CharityDescription string        `json:"charity_description"`
	CharityWebsite     string        `json:"charity_website"`
	Amount             CharityAmount `json:"amount"`
}

ChannelCharityDonationEvent is sent when a charity donation is made.

type ChannelChatClearEvent

type ChannelChatClearEvent struct {
	EventSubBroadcaster
}

ChannelChatClearEvent is sent when chat is cleared.

type ChannelChatClearUserMessagesEvent

type ChannelChatClearUserMessagesEvent struct {
	EventSubBroadcaster
	TargetUserID    string `json:"target_user_id"`
	TargetUserLogin string `json:"target_user_login"`
	TargetUserName  string `json:"target_user_name"`
	// Shared chat fields
	SourceBroadcasterUserID    *string `json:"source_broadcaster_user_id,omitempty"`
	SourceBroadcasterUserLogin *string `json:"source_broadcaster_user_login,omitempty"`
	SourceBroadcasterUserName  *string `json:"source_broadcaster_user_name,omitempty"`
}

ChannelChatClearUserMessagesEvent is sent when a user's messages are cleared.

type ChannelChatMessageDeleteEvent

type ChannelChatMessageDeleteEvent struct {
	EventSubBroadcaster
	TargetUserID    string `json:"target_user_id"`
	TargetUserLogin string `json:"target_user_login"`
	TargetUserName  string `json:"target_user_name"`
	MessageID       string `json:"message_id"`
	// Shared chat fields
	SourceBroadcasterUserID    *string `json:"source_broadcaster_user_id,omitempty"`
	SourceBroadcasterUserLogin *string `json:"source_broadcaster_user_login,omitempty"`
	SourceBroadcasterUserName  *string `json:"source_broadcaster_user_name,omitempty"`
}

ChannelChatMessageDeleteEvent is sent when a message is deleted.

type ChannelChatMessageEvent

type ChannelChatMessageEvent struct {
	EventSubBroadcaster
	ChatterUserID               string           `json:"chatter_user_id"`
	ChatterUserLogin            string           `json:"chatter_user_login"`
	ChatterUserName             string           `json:"chatter_user_name"`
	MessageID                   string           `json:"message_id"`
	Message                     ChatEventMessage `json:"message"`
	Color                       string           `json:"color"`
	Badges                      []ChatEventBadge `json:"badges"`
	MessageType                 string           `json:"message_type"` // text, channel_points_highlighted, channel_points_sub_only, user_intro, power_ups_message_effect, power_ups_gigantified_emote
	Cheer                       *ChatEventCheer  `json:"cheer,omitempty"`
	Reply                       *ChatEventReply  `json:"reply,omitempty"`
	ChannelPointsCustomRewardID string           `json:"channel_points_custom_reward_id,omitempty"`
	// Shared chat fields (null if not in shared chat or same channel)
	SourceBroadcasterUserID    *string          `json:"source_broadcaster_user_id,omitempty"`
	SourceBroadcasterUserLogin *string          `json:"source_broadcaster_user_login,omitempty"`
	SourceBroadcasterUserName  *string          `json:"source_broadcaster_user_name,omitempty"`
	SourceMessageID            *string          `json:"source_message_id,omitempty"`
	SourceBadges               []ChatEventBadge `json:"source_badges,omitempty"`
}

ChannelChatMessageEvent is sent when a message is sent in chat.

type ChannelChatNotificationEvent

type ChannelChatNotificationEvent struct {
	EventSubBroadcaster
	ChatterUserID              string                            `json:"chatter_user_id"`
	ChatterUserLogin           string                            `json:"chatter_user_login"`
	ChatterUserName            string                            `json:"chatter_user_name"`
	ChatterIsAnonymous         bool                              `json:"chatter_is_anonymous"`
	Color                      string                            `json:"color"`
	Badges                     []ChatEventBadge                  `json:"badges"`
	SystemMessage              string                            `json:"system_message"`
	MessageID                  string                            `json:"message_id"`
	Message                    ChatEventMessage                  `json:"message"`
	NoticeType                 string                            `json:"notice_type"`
	Sub                        *ChatNotificationSub              `json:"sub,omitempty"`
	Resub                      *ChatNotificationResub            `json:"resub,omitempty"`
	SubGift                    *ChatNotificationSubGift          `json:"sub_gift,omitempty"`
	CommunitySubGift           *ChatNotificationCommunitySubGift `json:"community_sub_gift,omitempty"`
	GiftPaidUpgrade            *ChatNotificationGiftPaidUpgrade  `json:"gift_paid_upgrade,omitempty"`
	PrimePaidUpgrade           *ChatNotificationPrimePaidUpgrade `json:"prime_paid_upgrade,omitempty"`
	Raid                       *ChatNotificationRaid             `json:"raid,omitempty"`
	Unraid                     *ChatNotificationUnraid           `json:"unraid,omitempty"`
	PayItForward               *ChatNotificationPayItForward     `json:"pay_it_forward,omitempty"`
	Announcement               *ChatNotificationAnnouncement     `json:"announcement,omitempty"`
	BitsBadgeTier              *ChatNotificationBitsBadgeTier    `json:"bits_badge_tier,omitempty"`
	CharityDonation            *ChatNotificationCharityDonation  `json:"charity_donation,omitempty"`
	SharedChatSub              *ChatNotificationSub              `json:"shared_chat_sub,omitempty"`
	SharedChatResub            *ChatNotificationResub            `json:"shared_chat_resub,omitempty"`
	SharedChatSubGift          *ChatNotificationSubGift          `json:"shared_chat_sub_gift,omitempty"`
	SharedChatCommunitySubGift *ChatNotificationCommunitySubGift `json:"shared_chat_community_sub_gift,omitempty"`
	SharedChatGiftPaidUpgrade  *ChatNotificationGiftPaidUpgrade  `json:"shared_chat_gift_paid_upgrade,omitempty"`
	SharedChatPrimePaidUpgrade *ChatNotificationPrimePaidUpgrade `json:"shared_chat_prime_paid_upgrade,omitempty"`
	SharedChatRaid             *ChatNotificationRaid             `json:"shared_chat_raid,omitempty"`
	SharedChatPayItForward     *ChatNotificationPayItForward     `json:"shared_chat_pay_it_forward,omitempty"`
	SharedChatAnnouncement     *ChatNotificationAnnouncement     `json:"shared_chat_announcement,omitempty"`
	SourceBroadcasterUserID    *string                           `json:"source_broadcaster_user_id,omitempty"`
	SourceBroadcasterUserLogin *string                           `json:"source_broadcaster_user_login,omitempty"`
	SourceBroadcasterUserName  *string                           `json:"source_broadcaster_user_name,omitempty"`
	SourceMessageID            *string                           `json:"source_message_id,omitempty"`
	SourceBadges               []ChatEventBadge                  `json:"source_badges,omitempty"`
}

ChannelChatNotificationEvent is sent for various chat notifications.

type ChannelChatSettingsUpdateEvent

type ChannelChatSettingsUpdateEvent struct {
	EventSubBroadcaster
	EmoteMode                   bool `json:"emote_mode"`
	FollowerMode                bool `json:"follower_mode"`
	FollowerModeDurationMinutes *int `json:"follower_mode_duration_minutes,omitempty"`
	SlowMode                    bool `json:"slow_mode"`
	SlowModeWaitTimeSeconds     int  `json:"slow_mode_wait_time_seconds"`
	SubscriberMode              bool `json:"subscriber_mode"`
	UniqueChatMode              bool `json:"unique_chat_mode"`
}

ChannelChatSettingsUpdateEvent is sent when chat settings are updated.

type ChannelChatUserMessageHoldEvent

type ChannelChatUserMessageHoldEvent struct {
	EventSubBroadcaster
	EventSubUser
	MessageID string              `json:"message_id"`
	Message   ChatUserHoldMessage `json:"message"`
	// Shared chat fields
	SourceBroadcasterUserID    *string `json:"source_broadcaster_user_id,omitempty"`
	SourceBroadcasterUserLogin *string `json:"source_broadcaster_user_login,omitempty"`
	SourceBroadcasterUserName  *string `json:"source_broadcaster_user_name,omitempty"`
}

ChannelChatUserMessageHoldEvent is sent when a user's message is held.

type ChannelChatUserMessageUpdateEvent

type ChannelChatUserMessageUpdateEvent struct {
	EventSubBroadcaster
	EventSubUser
	Status    string              `json:"status"` // approved, denied, invalid
	MessageID string              `json:"message_id"`
	Message   ChatUserHoldMessage `json:"message"`
	// Shared chat fields
	SourceBroadcasterUserID    *string `json:"source_broadcaster_user_id,omitempty"`
	SourceBroadcasterUserLogin *string `json:"source_broadcaster_user_login,omitempty"`
	SourceBroadcasterUserName  *string `json:"source_broadcaster_user_name,omitempty"`
}

ChannelChatUserMessageUpdateEvent is sent when a held message status is updated.

type ChannelCheerEvent

type ChannelCheerEvent struct {
	IsAnonymous bool   `json:"is_anonymous"`
	UserID      string `json:"user_id,omitempty"` // Empty if anonymous
	UserLogin   string `json:"user_login,omitempty"`
	UserName    string `json:"user_name,omitempty"`
	EventSubBroadcaster
	Message string `json:"message"`
	Bits    int    `json:"bits"`
}

ChannelCheerEvent is sent when a user cheers in a channel.

type ChannelEditor

type ChannelEditor struct {
	UserID    string    `json:"user_id"`
	UserName  string    `json:"user_name"`
	CreatedAt time.Time `json:"created_at"`
}

ChannelEditor represents a channel editor.

type ChannelFollowEvent

type ChannelFollowEvent struct {
	EventSubUser
	EventSubBroadcaster
	FollowedAt time.Time `json:"followed_at"`
}

ChannelFollowEvent is sent when a user follows a channel.

type ChannelFollower

type ChannelFollower struct {
	UserID     string    `json:"user_id"`
	UserLogin  string    `json:"user_login"`
	UserName   string    `json:"user_name"`
	FollowedAt time.Time `json:"followed_at"`
}

ChannelFollower represents a user who follows a channel.

type ChannelGoalBeginEvent

type ChannelGoalBeginEvent struct {
	ID string `json:"id"`
	EventSubBroadcaster
	Type          string    `json:"type"` // follower, subscription, subscription_count, new_subscription, new_subscription_count, new_bit, new_cheerer
	Description   string    `json:"description"`
	CurrentAmount int       `json:"current_amount"`
	TargetAmount  int       `json:"target_amount"`
	StartedAt     time.Time `json:"started_at"`
}

ChannelGoalBeginEvent is sent when a goal begins.

type ChannelGoalEndEvent

type ChannelGoalEndEvent struct {
	ID string `json:"id"`
	EventSubBroadcaster
	Type          string    `json:"type"`
	Description   string    `json:"description"`
	CurrentAmount int       `json:"current_amount"`
	TargetAmount  int       `json:"target_amount"`
	StartedAt     time.Time `json:"started_at"`
	EndedAt       time.Time `json:"ended_at"`
	IsAchieved    bool      `json:"is_achieved"`
}

ChannelGoalEndEvent is sent when a goal ends.

type ChannelGoalProgressEvent

type ChannelGoalProgressEvent = ChannelGoalBeginEvent

ChannelGoalProgressEvent is sent when goal progress updates.

type ChannelGuestStarGuestUpdateEvent

type ChannelGuestStarGuestUpdateEvent struct {
	EventSubBroadcaster
	EventSubModerator
	SessionID        string `json:"session_id"`
	GuestUserID      string `json:"guest_user_id"`
	GuestUserLogin   string `json:"guest_user_login"`
	GuestUserName    string `json:"guest_user_name"`
	SlotID           string `json:"slot_id"`
	State            string `json:"state"`
	HostVideoEnabled *bool  `json:"host_video_enabled,omitempty"`
	HostAudioEnabled *bool  `json:"host_audio_enabled,omitempty"`
	HostVolume       *int   `json:"host_volume,omitempty"`
}

ChannelGuestStarGuestUpdateEvent is sent when a guest star guest is updated.

type ChannelGuestStarSessionBeginEvent

type ChannelGuestStarSessionBeginEvent struct {
	EventSubBroadcaster
	SessionID string    `json:"session_id"`
	StartedAt time.Time `json:"started_at"`
}

ChannelGuestStarSessionBeginEvent is sent when a guest star session begins.

type ChannelGuestStarSessionEndEvent

type ChannelGuestStarSessionEndEvent struct {
	EventSubBroadcaster
	SessionID string    `json:"session_id"`
	StartedAt time.Time `json:"started_at"`
	EndedAt   time.Time `json:"ended_at"`
}

ChannelGuestStarSessionEndEvent is sent when a guest star session ends.

type ChannelGuestStarSettingsUpdateEvent

type ChannelGuestStarSettingsUpdateEvent struct {
	EventSubBroadcaster
	IsModeratorSendLiveEnabled  bool   `json:"is_moderator_send_live_enabled"`
	SlotCount                   int    `json:"slot_count"`
	IsBrowserSourceAudioEnabled bool   `json:"is_browser_source_audio_enabled"`
	GroupLayout                 string `json:"group_layout"`
}

ChannelGuestStarSettingsUpdateEvent is sent when guest star settings are updated.

type ChannelHypeTrainBeginEvent

type ChannelHypeTrainBeginEvent struct {
	ID string `json:"id"`
	EventSubBroadcaster
	Total            int                    `json:"total"`
	Progress         int                    `json:"progress"`
	Goal             int                    `json:"goal"`
	TopContributions []EventSubContribution `json:"top_contributions"`
	LastContribution EventSubContribution   `json:"last_contribution"`
	Level            int                    `json:"level"`
	StartedAt        time.Time              `json:"started_at"`
	ExpiresAt        time.Time              `json:"expires_at"`
	// Deprecated: IsGoldenKappaTrain is from v1 which is deprecated. Use Type == HypeTrainTypeGoldenKappa instead.
	// This field is auto-populated from Type during unmarshaling for migration convenience.
	IsGoldenKappaTrain bool `json:"is_golden_kappa_train,omitempty"`
	// V2 fields
	Type                    HypeTrainType          `json:"type,omitempty"`
	IsSharedTrain           bool                   `json:"is_shared_train,omitempty"`
	SharedTrainParticipants []HypeTrainParticipant `json:"shared_train_participants,omitempty"`
	AllTimeHighLevel        int                    `json:"all_time_high_level,omitempty"`
	AllTimeHighTotal        int                    `json:"all_time_high_total,omitempty"`
}

ChannelHypeTrainBeginEvent is sent when a Hype Train begins. Note: Hype Train v1 is deprecated by Twitch. Use v2 fields (Type, IsSharedTrain, etc.).

func (*ChannelHypeTrainBeginEvent) UnmarshalJSON added in v1.0.0

func (e *ChannelHypeTrainBeginEvent) UnmarshalJSON(data []byte) error

UnmarshalJSON implements automatic v1/v2 field conversion for ChannelHypeTrainBeginEvent. When receiving v1 events, it populates Type from IsGoldenKappaTrain. When receiving v2 events, it populates IsGoldenKappaTrain from Type.

type ChannelHypeTrainBeginEventV1 added in v1.0.0

type ChannelHypeTrainBeginEventV1 = ChannelHypeTrainBeginEvent

ChannelHypeTrainBeginEventV1 is the v1 version of the hype train begin event. Deprecated: Use ChannelHypeTrainBeginEvent with v2 subscription instead.

type ChannelHypeTrainEndEvent

type ChannelHypeTrainEndEvent struct {
	ID string `json:"id"`
	EventSubBroadcaster
	Level            int                    `json:"level"`
	Total            int                    `json:"total"`
	TopContributions []EventSubContribution `json:"top_contributions"`
	StartedAt        time.Time              `json:"started_at"`
	EndedAt          time.Time              `json:"ended_at"`
	CooldownEndsAt   time.Time              `json:"cooldown_ends_at"`
	// Deprecated: IsGoldenKappaTrain is from v1 which is deprecated. Use Type == HypeTrainTypeGoldenKappa instead.
	// This field is auto-populated from Type during unmarshaling for migration convenience.
	IsGoldenKappaTrain bool `json:"is_golden_kappa_train,omitempty"`
	// V2 fields
	Type                    HypeTrainType          `json:"type,omitempty"`
	IsSharedTrain           bool                   `json:"is_shared_train,omitempty"`
	SharedTrainParticipants []HypeTrainParticipant `json:"shared_train_participants,omitempty"`
}

ChannelHypeTrainEndEvent is sent when a Hype Train ends. Note: Hype Train v1 is deprecated by Twitch. Use v2 fields (Type, IsSharedTrain, etc.).

func (*ChannelHypeTrainEndEvent) UnmarshalJSON added in v1.0.0

func (e *ChannelHypeTrainEndEvent) UnmarshalJSON(data []byte) error

UnmarshalJSON implements automatic v1/v2 field conversion for ChannelHypeTrainEndEvent. When receiving v1 events, it populates Type from IsGoldenKappaTrain. When receiving v2 events, it populates IsGoldenKappaTrain from Type.

type ChannelHypeTrainEndEventV1 added in v1.0.0

type ChannelHypeTrainEndEventV1 = ChannelHypeTrainEndEvent

ChannelHypeTrainEndEventV1 is the v1 version of the hype train end event. Deprecated: Use ChannelHypeTrainEndEvent with v2 subscription instead.

type ChannelHypeTrainProgressEvent

type ChannelHypeTrainProgressEvent = ChannelHypeTrainBeginEvent

ChannelHypeTrainProgressEvent is sent when a Hype Train progresses.

type ChannelHypeTrainProgressEventV1 added in v1.0.0

type ChannelHypeTrainProgressEventV1 = ChannelHypeTrainProgressEvent

ChannelHypeTrainProgressEventV1 is the v1 version of the hype train progress event. Deprecated: Use ChannelHypeTrainProgressEvent with v2 subscription instead.

type ChannelModerateEvent

type ChannelModerateEvent struct {
	EventSubBroadcaster
	EventSubModerator
	Action            string                     `json:"action"`
	Followers         *ModerateFollowers         `json:"followers,omitempty"`
	Slow              *ModerateSlow              `json:"slow,omitempty"`
	Vip               *ModerateUser              `json:"vip,omitempty"`
	Unvip             *ModerateUser              `json:"unvip,omitempty"`
	Mod               *ModerateUser              `json:"mod,omitempty"`
	Unmod             *ModerateUser              `json:"unmod,omitempty"`
	Ban               *ModerateBan               `json:"ban,omitempty"`
	Unban             *ModerateUser              `json:"unban,omitempty"`
	Timeout           *ModerateTimeout           `json:"timeout,omitempty"`
	Untimeout         *ModerateUser              `json:"untimeout,omitempty"`
	Raid              *ModerateRaid              `json:"raid,omitempty"`
	Unraid            *ModerateRaid              `json:"unraid,omitempty"`
	Delete            *ModerateDelete            `json:"delete,omitempty"`
	AutomodTerms      *ModerateAutomodTerms      `json:"automod_terms,omitempty"`
	UnbanRequest      *ModerateUnbanRequest      `json:"unban_request,omitempty"`
	Warn              *ModerateWarn              `json:"warn,omitempty"`
	SharedChatBan     *ModerateSharedChatBan     `json:"shared_chat_ban,omitempty"`
	SharedChatTimeout *ModerateSharedChatTimeout `json:"shared_chat_timeout,omitempty"`
	SharedChatDelete  *ModerateSharedChatDelete  `json:"shared_chat_delete,omitempty"`
}

ChannelModerateEvent is sent for various moderation actions.

type ChannelModeratorAddEvent

type ChannelModeratorAddEvent struct {
	EventSubUser
	EventSubBroadcaster
}

ChannelModeratorAddEvent is sent when a user is added as a moderator.

type ChannelModeratorRemoveEvent

type ChannelModeratorRemoveEvent struct {
	EventSubUser
	EventSubBroadcaster
}

ChannelModeratorRemoveEvent is sent when a user is removed as a moderator.

type ChannelPointsAutomaticRewardRedemptionAddEvent

type ChannelPointsAutomaticRewardRedemptionAddEvent struct {
	EventSubBroadcaster
	EventSubUser
	ID         string                    `json:"id"`
	Reward     AutomaticRewardRedemption `json:"reward"`
	Message    AutomaticRewardMessage    `json:"message"`
	UserInput  string                    `json:"user_input"`
	RedeemedAt time.Time                 `json:"redeemed_at"`
}

ChannelPointsAutomaticRewardRedemptionAddEvent is sent when an automatic reward is redeemed.

type ChannelPointsRedemptionAddEvent

type ChannelPointsRedemptionAddEvent struct {
	ID string `json:"id"`
	EventSubBroadcaster
	EventSubUser
	UserInput  string         `json:"user_input"`
	Status     string         `json:"status"` // unfulfilled, fulfilled, canceled
	Reward     EventSubReward `json:"reward"`
	RedeemedAt time.Time      `json:"redeemed_at"`
}

ChannelPointsRedemptionAddEvent is sent when a reward is redeemed.

type ChannelPointsRedemptionUpdateEvent

type ChannelPointsRedemptionUpdateEvent = ChannelPointsRedemptionAddEvent

ChannelPointsRedemptionUpdateEvent is sent when a redemption is updated.

type ChannelPointsRewardAddEvent

type ChannelPointsRewardAddEvent struct {
	ID string `json:"id"`
	EventSubBroadcaster
	IsEnabled                        bool                   `json:"is_enabled"`
	IsPaused                         bool                   `json:"is_paused"`
	IsInStock                        bool                   `json:"is_in_stock"`
	Title                            string                 `json:"title"`
	Cost                             int                    `json:"cost"`
	Prompt                           string                 `json:"prompt"`
	IsUserInputRequired              bool                   `json:"is_user_input_required"`
	ShouldRedemptionsSkipQueue       bool                   `json:"should_redemptions_skip_request_queue"`
	MaxPerStream                     EventSubMaxPerStream   `json:"max_per_stream"`
	MaxPerUserPerStream              EventSubMaxPerStream   `json:"max_per_user_per_stream"`
	BackgroundColor                  string                 `json:"background_color"`
	Image                            *EventSubImage         `json:"image"`
	DefaultImage                     EventSubImage          `json:"default_image"`
	GlobalCooldown                   EventSubGlobalCooldown `json:"global_cooldown"`
	CooldownExpiresAt                *time.Time             `json:"cooldown_expires_at"`
	RedemptionsRedeemedCurrentStream *int                   `json:"redemptions_redeemed_current_stream"`
}

ChannelPointsRewardAddEvent is sent when a custom reward is created.

type ChannelPointsRewardRemoveEvent

type ChannelPointsRewardRemoveEvent struct {
	ID string `json:"id"`
	EventSubBroadcaster
	IsEnabled                        bool                   `json:"is_enabled"`
	IsPaused                         bool                   `json:"is_paused"`
	IsInStock                        bool                   `json:"is_in_stock"`
	Title                            string                 `json:"title"`
	Cost                             int                    `json:"cost"`
	Prompt                           string                 `json:"prompt"`
	IsUserInputRequired              bool                   `json:"is_user_input_required"`
	ShouldRedemptionsSkipQueue       bool                   `json:"should_redemptions_skip_request_queue"`
	CooldownExpiresAt                *time.Time             `json:"cooldown_expires_at"`
	RedemptionsRedeemedCurrentStream *int                   `json:"redemptions_redeemed_current_stream"`
	MaxPerStream                     EventSubMaxPerStream   `json:"max_per_stream"`
	MaxPerUserPerStream              EventSubMaxPerStream   `json:"max_per_user_per_stream"`
	GlobalCooldown                   EventSubGlobalCooldown `json:"global_cooldown"`
	BackgroundColor                  string                 `json:"background_color"`
	Image                            *EventSubImage         `json:"image"`
	DefaultImage                     EventSubImage          `json:"default_image"`
}

ChannelPointsRewardRemoveEvent is sent when a custom reward is removed.

type ChannelPointsRewardUpdateEvent

type ChannelPointsRewardUpdateEvent = ChannelPointsRewardAddEvent

ChannelPointsRewardUpdateEvent is sent when a custom reward is updated.

type ChannelPollBeginEvent

type ChannelPollBeginEvent struct {
	ID string `json:"id"`
	EventSubBroadcaster
	Title               string           `json:"title"`
	Choices             []EventSubChoice `json:"choices"`
	BitsVoting          EventSubVoting   `json:"bits_voting"`
	ChannelPointsVoting EventSubVoting   `json:"channel_points_voting"`
	StartedAt           time.Time        `json:"started_at"`
	EndsAt              time.Time        `json:"ends_at"`
}

ChannelPollBeginEvent is sent when a poll begins.

type ChannelPollEndEvent

type ChannelPollEndEvent struct {
	ID string `json:"id"`
	EventSubBroadcaster
	Title               string           `json:"title"`
	Choices             []EventSubChoice `json:"choices"`
	BitsVoting          EventSubVoting   `json:"bits_voting"`
	ChannelPointsVoting EventSubVoting   `json:"channel_points_voting"`
	Status              string           `json:"status"` // completed, archived, terminated
	StartedAt           time.Time        `json:"started_at"`
	EndedAt             time.Time        `json:"ended_at"`
}

ChannelPollEndEvent is sent when a poll ends.

type ChannelPollProgressEvent

type ChannelPollProgressEvent = ChannelPollBeginEvent

ChannelPollProgressEvent is sent when poll results update.

type ChannelPredictionBeginEvent

type ChannelPredictionBeginEvent struct {
	ID string `json:"id"`
	EventSubBroadcaster
	Title     string            `json:"title"`
	Outcomes  []EventSubOutcome `json:"outcomes"`
	StartedAt time.Time         `json:"started_at"`
	LocksAt   time.Time         `json:"locks_at"`
}

ChannelPredictionBeginEvent is sent when a prediction begins.

type ChannelPredictionEndEvent

type ChannelPredictionEndEvent struct {
	ID string `json:"id"`
	EventSubBroadcaster
	Title            string            `json:"title"`
	WinningOutcomeID string            `json:"winning_outcome_id,omitempty"`
	Outcomes         []EventSubOutcome `json:"outcomes"`
	Status           string            `json:"status"` // resolved, canceled
	StartedAt        time.Time         `json:"started_at"`
	EndedAt          time.Time         `json:"ended_at"`
}

ChannelPredictionEndEvent is sent when a prediction ends.

type ChannelPredictionLockEvent

type ChannelPredictionLockEvent = ChannelPredictionBeginEvent

ChannelPredictionLockEvent is sent when a prediction locks.

type ChannelPredictionProgressEvent

type ChannelPredictionProgressEvent = ChannelPredictionBeginEvent

ChannelPredictionProgressEvent is sent when prediction totals update.

type ChannelRaidEvent

type ChannelRaidEvent 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                  int    `json:"viewers"`
}

ChannelRaidEvent is sent when a broadcaster raids another channel.

type ChannelSharedChatBeginEvent

type ChannelSharedChatBeginEvent struct {
	SessionID string `json:"session_id"`
	EventSubBroadcaster
	HostBroadcasterUserID    string                  `json:"host_broadcaster_user_id"`
	HostBroadcasterUserLogin string                  `json:"host_broadcaster_user_login"`
	HostBroadcasterUserName  string                  `json:"host_broadcaster_user_name"`
	Participants             []SharedChatParticipant `json:"participants"`
}

ChannelSharedChatBeginEvent is sent when a shared chat session begins.

type ChannelSharedChatEndEvent

type ChannelSharedChatEndEvent struct {
	SessionID string `json:"session_id"`
	EventSubBroadcaster
	HostBroadcasterUserID    string `json:"host_broadcaster_user_id"`
	HostBroadcasterUserLogin string `json:"host_broadcaster_user_login"`
	HostBroadcasterUserName  string `json:"host_broadcaster_user_name"`
}

ChannelSharedChatEndEvent is sent when a shared chat session ends.

type ChannelSharedChatUpdateEvent

type ChannelSharedChatUpdateEvent = ChannelSharedChatBeginEvent

ChannelSharedChatUpdateEvent is sent when a shared chat session is updated.

type ChannelShieldModeBeginEvent

type ChannelShieldModeBeginEvent struct {
	EventSubBroadcaster
	EventSubModerator
	StartedAt time.Time `json:"started_at"`
}

ChannelShieldModeBeginEvent is sent when shield mode begins.

type ChannelShieldModeEndEvent

type ChannelShieldModeEndEvent struct {
	EventSubBroadcaster
	EventSubModerator
	EndedAt time.Time `json:"ended_at"`
}

ChannelShieldModeEndEvent is sent when shield mode ends.

type ChannelShoutoutCreateEvent

type ChannelShoutoutCreateEvent struct {
	EventSubBroadcaster
	EventSubModerator
	ToBroadcasterUserID    string    `json:"to_broadcaster_user_id"`
	ToBroadcasterUserLogin string    `json:"to_broadcaster_user_login"`
	ToBroadcasterUserName  string    `json:"to_broadcaster_user_name"`
	ViewerCount            int       `json:"viewer_count"`
	StartedAt              time.Time `json:"started_at"`
	CooldownEndsAt         time.Time `json:"cooldown_ends_at"`
	TargetCooldownEndsAt   time.Time `json:"target_cooldown_ends_at"`
}

ChannelShoutoutCreateEvent is sent when a shoutout is created.

type ChannelShoutoutReceiveEvent

type ChannelShoutoutReceiveEvent struct {
	EventSubBroadcaster
	FromBroadcasterUserID    string    `json:"from_broadcaster_user_id"`
	FromBroadcasterUserLogin string    `json:"from_broadcaster_user_login"`
	FromBroadcasterUserName  string    `json:"from_broadcaster_user_name"`
	ViewerCount              int       `json:"viewer_count"`
	StartedAt                time.Time `json:"started_at"`
}

ChannelShoutoutReceiveEvent is sent when a shoutout is received.

type ChannelSubscribeEvent

type ChannelSubscribeEvent struct {
	EventSubUser
	EventSubBroadcaster
	Tier   string `json:"tier"` // 1000, 2000, 3000
	IsGift bool   `json:"is_gift"`
}

ChannelSubscribeEvent is sent when a user subscribes to a channel.

type ChannelSubscriptionEndEvent

type ChannelSubscriptionEndEvent struct {
	EventSubUser
	EventSubBroadcaster
	Tier   string `json:"tier"`
	IsGift bool   `json:"is_gift"`
}

ChannelSubscriptionEndEvent is sent when a subscription ends.

type ChannelSubscriptionGiftEvent

type ChannelSubscriptionGiftEvent struct {
	EventSubUser
	EventSubBroadcaster
	Total           int    `json:"total"`
	Tier            string `json:"tier"`
	CumulativeTotal int    `json:"cumulative_total,omitempty"` // Only if not anonymous
	IsAnonymous     bool   `json:"is_anonymous"`
}

ChannelSubscriptionGiftEvent is sent when a user gifts subscriptions.

type ChannelSubscriptionMessageEvent

type ChannelSubscriptionMessageEvent struct {
	EventSubUser
	EventSubBroadcaster
	Tier             string              `json:"tier"`
	Message          SubscriptionMessage `json:"message"`
	CumulativeMonths int                 `json:"cumulative_months"`
	StreakMonths     int                 `json:"streak_months,omitempty"`
	DurationMonths   int                 `json:"duration_months"`
}

ChannelSubscriptionMessageEvent is sent when a user sends a resubscription message.

type ChannelSuspiciousUserMessageEvent

type ChannelSuspiciousUserMessageEvent struct {
	EventSubBroadcaster
	EventSubUser
	LowTrustStatus       string                `json:"low_trust_status"` // none, active_monitoring, restricted
	SharedBanChannelIDs  []string              `json:"shared_ban_channel_ids,omitempty"`
	Types                []string              `json:"types"`                  // manual, ban_evader_detector, shared_channel_ban
	BanEvasionEvaluation string                `json:"ban_evasion_evaluation"` // unknown, possible, likely
	Message              SuspiciousUserMessage `json:"message"`
}

ChannelSuspiciousUserMessageEvent is sent when a suspicious user sends a message.

type ChannelSuspiciousUserUpdateEvent

type ChannelSuspiciousUserUpdateEvent struct {
	EventSubBroadcaster
	EventSubModerator
	EventSubUser
	LowTrustStatus string `json:"low_trust_status"`
}

ChannelSuspiciousUserUpdateEvent is sent when a suspicious user's status is updated.

type ChannelTeam

type ChannelTeam struct {
	BroadcasterID      string    `json:"broadcaster_id"`
	BroadcasterLogin   string    `json:"broadcaster_login"`
	BroadcasterName    string    `json:"broadcaster_name"`
	BackgroundImageURL string    `json:"background_image_url"`
	Banner             string    `json:"banner"`
	CreatedAt          time.Time `json:"created_at"`
	UpdatedAt          time.Time `json:"updated_at"`
	Info               string    `json:"info"`
	ThumbnailURL       string    `json:"thumbnail_url"`
	TeamName           string    `json:"team_name"`
	TeamDisplayName    string    `json:"team_display_name"`
	ID                 string    `json:"id"`
}

ChannelTeam represents a team that a channel belongs to.

type ChannelUnbanEvent

type ChannelUnbanEvent struct {
	EventSubUser
	EventSubBroadcaster
	EventSubModerator
}

ChannelUnbanEvent is sent when a user is unbanned from a channel.

type ChannelUnbanRequestCreateEvent

type ChannelUnbanRequestCreateEvent struct {
	ID string `json:"id"`
	EventSubBroadcaster
	EventSubUser
	Text      string    `json:"text"`
	CreatedAt time.Time `json:"created_at"`
}

ChannelUnbanRequestCreateEvent is sent when an unban request is created.

type ChannelUnbanRequestResolveEvent

type ChannelUnbanRequestResolveEvent struct {
	ID string `json:"id"`
	EventSubBroadcaster
	EventSubModerator
	EventSubUser
	ResolutionText string `json:"resolution_text,omitempty"`
	Status         string `json:"status"` // approved, canceled, denied
}

ChannelUnbanRequestResolveEvent is sent when an unban request is resolved.

type ChannelUpdateEvent

type ChannelUpdateEvent struct {
	EventSubBroadcaster
	Title                       string   `json:"title"`
	Language                    string   `json:"language"`
	CategoryID                  string   `json:"category_id"`
	CategoryName                string   `json:"category_name"`
	ContentClassificationLabels []string `json:"content_classification_labels"`
}

ChannelUpdateEvent is sent when a broadcaster updates channel properties.

type ChannelVIPAddEvent

type ChannelVIPAddEvent struct {
	EventSubUser
	EventSubBroadcaster
}

ChannelVIPAddEvent is sent when a user is added as a VIP.

type ChannelVIPRemoveEvent

type ChannelVIPRemoveEvent struct {
	EventSubUser
	EventSubBroadcaster
}

ChannelVIPRemoveEvent is sent when a user is removed as a VIP.

type ChannelWarningAcknowledgeEvent

type ChannelWarningAcknowledgeEvent struct {
	EventSubBroadcaster
	EventSubUser
}

ChannelWarningAcknowledgeEvent is sent when a warning is acknowledged.

type ChannelWarningSendEvent

type ChannelWarningSendEvent struct {
	EventSubBroadcaster
	EventSubModerator
	EventSubUser
	Reason         *string  `json:"reason,omitempty"`
	ChatRulesCited []string `json:"chat_rules_cited,omitempty"`
}

ChannelWarningSendEvent is sent when a warning is sent to a user.

type CharityAmount

type CharityAmount struct {
	Value         int    `json:"value"`
	DecimalPlaces int    `json:"decimal_places"`
	Currency      string `json:"currency"`
}

CharityAmount represents a monetary amount for charity.

type CharityCampaign

type CharityCampaign struct {
	ID                 string        `json:"id"`
	BroadcasterID      string        `json:"broadcaster_id"`
	BroadcasterLogin   string        `json:"broadcaster_login"`
	BroadcasterName    string        `json:"broadcaster_name"`
	CharityName        string        `json:"charity_name"`
	CharityDescription string        `json:"charity_description"`
	CharityWebsite     string        `json:"charity_website"`
	CurrentAmount      CharityAmount `json:"current_amount"`
	TargetAmount       CharityAmount `json:"target_amount"`
}

CharityCampaign represents a charity campaign.

type CharityDonation

type CharityDonation struct {
	ID         string        `json:"id"`
	CampaignID string        `json:"campaign_id"`
	UserID     string        `json:"user_id"`
	UserLogin  string        `json:"user_login"`
	UserName   string        `json:"user_name"`
	Amount     CharityAmount `json:"amount"`
}

CharityDonation represents a donation to a charity campaign.

type ChatBadge

type ChatBadge struct {
	SetID    string         `json:"set_id"`
	Versions []BadgeVersion `json:"versions"`
}

ChatBadge represents a chat badge.

type ChatBotClient

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

ChatBotClient provides a high-level interface for Twitch chat bots. It wraps IRCClient with convenience methods and automatic token handling.

func NewChatBotClient

func NewChatBotClient(nick string, authClient *AuthClient, opts ...ChatBotOption) *ChatBotClient

NewChatBotClient creates a new high-level chat bot client. The nick should be the bot's username, and authClient should have a valid user access token.

func (*ChatBotClient) Close

func (c *ChatBotClient) Close() error

Close closes the chat connection.

func (*ChatBotClient) Connect

func (c *ChatBotClient) Connect(ctx context.Context) error

Connect establishes a connection to Twitch chat.

func (*ChatBotClient) GetJoinedChannels

func (c *ChatBotClient) GetJoinedChannels() []string

GetJoinedChannels returns the list of joined channels.

func (*ChatBotClient) IRC

func (c *ChatBotClient) IRC() *IRCClient

IRC returns the underlying IRC client for advanced usage.

func (*ChatBotClient) IsConnected

func (c *ChatBotClient) IsConnected() bool

IsConnected returns whether the client is connected.

func (*ChatBotClient) Join

func (c *ChatBotClient) Join(channels ...string) error

Join joins one or more channels.

func (*ChatBotClient) OnCheer

func (c *ChatBotClient) OnCheer(fn func(*ChatMessage))

OnCheer sets the handler for cheer (bits) messages.

func (*ChatBotClient) OnClearChat

func (c *ChatBotClient) OnClearChat(fn func(*ClearChat))

OnClearChat sets the handler for chat clear/timeout/ban events.

func (*ChatBotClient) OnConnect

func (c *ChatBotClient) OnConnect(fn func())

OnConnect sets the handler for successful connections.

func (*ChatBotClient) OnDisconnect

func (c *ChatBotClient) OnDisconnect(fn func())

OnDisconnect sets the handler for disconnections.

func (*ChatBotClient) OnError

func (c *ChatBotClient) OnError(fn func(error))

OnError sets the handler for errors.

func (*ChatBotClient) OnJoin

func (c *ChatBotClient) OnJoin(fn func(channel, user string))

OnJoin sets the handler for user join events.

func (*ChatBotClient) OnMessage

func (c *ChatBotClient) OnMessage(fn func(*ChatMessage))

OnMessage sets the handler for all chat messages.

func (*ChatBotClient) OnNotice

func (c *ChatBotClient) OnNotice(fn func(*Notice))

OnNotice sets the handler for server notices.

func (*ChatBotClient) OnPart

func (c *ChatBotClient) OnPart(fn func(channel, user string))

OnPart sets the handler for user part events.

func (*ChatBotClient) OnRaid

func (c *ChatBotClient) OnRaid(fn func(*UserNotice))

OnRaid sets the handler for raid events.

func (*ChatBotClient) OnResub

func (c *ChatBotClient) OnResub(fn func(*UserNotice))

OnResub sets the handler for resubscription events.

func (*ChatBotClient) OnRoomState

func (c *ChatBotClient) OnRoomState(fn func(*RoomState))

OnRoomState sets the handler for room state changes.

func (*ChatBotClient) OnSub

func (c *ChatBotClient) OnSub(fn func(*UserNotice))

OnSub sets the handler for new subscription events.

func (*ChatBotClient) OnSubGift

func (c *ChatBotClient) OnSubGift(fn func(*UserNotice))

OnSubGift sets the handler for gift subscription events.

func (*ChatBotClient) OnWhisper

func (c *ChatBotClient) OnWhisper(fn func(*Whisper))

OnWhisper sets the handler for whisper messages.

func (*ChatBotClient) Part

func (c *ChatBotClient) Part(channels ...string) error

Part leaves one or more channels.

func (*ChatBotClient) Reply

func (c *ChatBotClient) Reply(channel, parentMsgID, message string) error

Reply sends a reply to a specific message.

func (*ChatBotClient) Say

func (c *ChatBotClient) Say(channel, message string) error

Say sends a message to a channel.

func (*ChatBotClient) Whisper

func (c *ChatBotClient) Whisper(user, message string) error

Whisper sends a whisper to a user.

type ChatBotOption

type ChatBotOption func(*ChatBotClient)

ChatBotOption configures the ChatBotClient.

func WithChatBotURL added in v1.0.2

func WithChatBotURL(url string) ChatBotOption

WithChatBotURL sets a custom IRC WebSocket URL (for testing).

type ChatEventBadge

type ChatEventBadge struct {
	SetID string `json:"set_id"`
	ID    string `json:"id"`
	Info  string `json:"info"`
}

ChatEventBadge represents a chat badge.

type ChatEventBadges

type ChatEventBadges []ChatEventBadge

ChatEventBadges is a slice of ChatEventBadge with helper methods.

func ToChatEventBadges

func ToChatEventBadges(badges []ChatEventBadge) ChatEventBadges

ToChatEventBadges converts a []ChatEventBadge to ChatEventBadges for use with helper methods.

func (ChatEventBadges) GetBadge

func (badges ChatEventBadges) GetBadge(setID string) *ChatEventBadge

GetBadge returns the badge with the specified SetID, or nil if not found.

func (ChatEventBadges) HasAnyBadge

func (badges ChatEventBadges) HasAnyBadge(setIDs ...string) bool

HasAnyBadge checks if the badges contain any of the specified badge SetIDs.

func (ChatEventBadges) HasBadge

func (badges ChatEventBadges) HasBadge(setID string) bool

HasBadge checks if the badges contain a specific badge SetID.

func (ChatEventBadges) HasBroadcasterPrivileges

func (badges ChatEventBadges) HasBroadcasterPrivileges() bool

HasBroadcasterPrivileges checks if the user is the broadcaster.

func (ChatEventBadges) HasModeratorPrivileges

func (badges ChatEventBadges) HasModeratorPrivileges() bool

HasModeratorPrivileges checks if the user has moderator privileges. This returns true if the user has either the "moderator" or "lead_moderator" badge. Use this method instead of checking only for BadgeModerator to properly support Lead Moderators who may display either badge.

func (ChatEventBadges) HasVIPStatus

func (badges ChatEventBadges) HasVIPStatus() bool

HasVIPStatus checks if the user is a VIP.

func (ChatEventBadges) IsStaff

func (badges ChatEventBadges) IsStaff() bool

IsStaff checks if the user is Twitch staff (staff, admin, or global mod).

func (ChatEventBadges) IsSubscriber

func (badges ChatEventBadges) IsSubscriber() bool

IsSubscriber checks if the user is a subscriber.

type ChatEventCheer

type ChatEventCheer struct {
	Bits int `json:"bits"`
}

ChatEventCheer represents cheer info in a message.

type ChatEventCheermote

type ChatEventCheermote struct {
	Prefix string `json:"prefix"`
	Bits   int    `json:"bits"`
	Tier   int    `json:"tier"`
}

ChatEventCheermote represents a cheermote in a message.

type ChatEventEmote

type ChatEventEmote struct {
	ID         string   `json:"id"`
	EmoteSetID string   `json:"emote_set_id"`
	OwnerID    string   `json:"owner_id"`
	Format     []string `json:"format"` // static, animated
}

ChatEventEmote represents an emote in a message.

type ChatEventFragment

type ChatEventFragment struct {
	Type      string              `json:"type"` // text, cheermote, emote, mention
	Text      string              `json:"text"`
	Cheermote *ChatEventCheermote `json:"cheermote,omitempty"`
	Emote     *ChatEventEmote     `json:"emote,omitempty"`
	Mention   *ChatEventMention   `json:"mention,omitempty"`
}

ChatEventFragment represents a fragment of a chat message.

type ChatEventMention

type ChatEventMention struct {
	UserID    string `json:"user_id"`
	UserLogin string `json:"user_login"`
	UserName  string `json:"user_name"`
}

ChatEventMention represents a mention in a message.

type ChatEventMessage

type ChatEventMessage struct {
	Text      string              `json:"text"`
	Fragments []ChatEventFragment `json:"fragments"`
}

ChatEventMessage represents a chat message structure.

type ChatEventReply

type ChatEventReply struct {
	ParentMessageID   string `json:"parent_message_id"`
	ParentMessageBody string `json:"parent_message_body"`
	ParentUserID      string `json:"parent_user_id"`
	ParentUserLogin   string `json:"parent_user_login"`
	ParentUserName    string `json:"parent_user_name"`
	ThreadMessageID   string `json:"thread_message_id"`
	ThreadUserID      string `json:"thread_user_id"`
	ThreadUserLogin   string `json:"thread_user_login"`
	ThreadUserName    string `json:"thread_user_name"`
}

ChatEventReply represents reply info in a message.

type ChatMessage

type ChatMessage struct {
	ID                     string            // Unique message ID
	Channel                string            // Channel name (without #)
	User                   string            // Username (login)
	UserID                 string            // User's Twitch ID
	Message                string            // Message content
	Emotes                 []IRCEmote        // Emotes used in the message
	Badges                 map[string]string // User badges (badge-name -> version)
	BadgeInfo              map[string]string // Additional badge info (e.g., subscriber months)
	Color                  string            // User's chat color (#RRGGBB)
	DisplayName            string            // User's display name
	IsMod                  bool              // Is channel moderator
	IsVIP                  bool              // Is VIP
	IsSubscriber           bool              // Is subscriber
	IsBroadcaster          bool              // Is the channel broadcaster
	Bits                   int               // Bits cheered (0 if none)
	FirstMessage           bool              // Is this user's first message in channel
	ReturningChatter       bool              // Is a returning chatter
	ReplyParentMsgID       string            // Parent message ID if this is a reply
	ReplyParentUserID      string            // Parent message user ID
	ReplyParentUserLogin   string            // Parent message username
	ReplyParentDisplayName string            // Parent message display name
	ReplyParentMsgBody     string            // Parent message content
	Timestamp              time.Time         // Server timestamp
	Raw                    string            // Raw IRC message
}

ChatMessage represents a PRIVMSG from Twitch IRC.

type ChatNotificationAnnouncement

type ChatNotificationAnnouncement struct {
	Color string `json:"color"`
}

ChatNotificationAnnouncement represents an announcement notification.

type ChatNotificationBitsBadgeTier

type ChatNotificationBitsBadgeTier struct {
	Tier int `json:"tier"`
}

ChatNotificationBitsBadgeTier represents a bits badge tier notification.

type ChatNotificationCharityDonation

type ChatNotificationCharityDonation struct {
	CharityName string        `json:"charity_name"`
	Amount      CharityAmount `json:"amount"`
}

ChatNotificationCharityDonation represents a charity donation notification.

type ChatNotificationCommunitySubGift

type ChatNotificationCommunitySubGift struct {
	ID              string `json:"id"`
	Total           int    `json:"total"`
	SubTier         string `json:"sub_tier"`
	CumulativeTotal *int   `json:"cumulative_total,omitempty"`
}

ChatNotificationCommunitySubGift represents a community sub gift notification.

type ChatNotificationGiftPaidUpgrade

type ChatNotificationGiftPaidUpgrade struct {
	GifterIsAnonymous bool    `json:"gifter_is_anonymous"`
	GifterUserID      *string `json:"gifter_user_id,omitempty"`
	GifterUserLogin   *string `json:"gifter_user_login,omitempty"`
	GifterUserName    *string `json:"gifter_user_name,omitempty"`
}

ChatNotificationGiftPaidUpgrade represents a gift paid upgrade notification.

type ChatNotificationPayItForward

type ChatNotificationPayItForward struct {
	GifterIsAnonymous bool    `json:"gifter_is_anonymous"`
	GifterUserID      *string `json:"gifter_user_id,omitempty"`
	GifterUserLogin   *string `json:"gifter_user_login,omitempty"`
	GifterUserName    *string `json:"gifter_user_name,omitempty"`
}

ChatNotificationPayItForward represents a pay it forward notification.

type ChatNotificationPrimePaidUpgrade

type ChatNotificationPrimePaidUpgrade struct {
	SubTier string `json:"sub_tier"`
}

ChatNotificationPrimePaidUpgrade represents a prime paid upgrade notification.

type ChatNotificationRaid

type ChatNotificationRaid struct {
	UserID          string `json:"user_id"`
	UserLogin       string `json:"user_login"`
	UserName        string `json:"user_name"`
	ViewerCount     int    `json:"viewer_count"`
	ProfileImageURL string `json:"profile_image_url"`
}

ChatNotificationRaid represents a raid notification.

type ChatNotificationResub

type ChatNotificationResub struct {
	CumulativeMonths  int     `json:"cumulative_months"`
	DurationMonths    int     `json:"duration_months"`
	StreakMonths      int     `json:"streak_months"`
	SubTier           string  `json:"sub_tier"`
	IsPrime           bool    `json:"is_prime"`
	IsGift            bool    `json:"is_gift"`
	GifterIsAnonymous bool    `json:"gifter_is_anonymous"`
	GifterUserID      *string `json:"gifter_user_id,omitempty"`
	GifterUserLogin   *string `json:"gifter_user_login,omitempty"`
	GifterUserName    *string `json:"gifter_user_name,omitempty"`
}

ChatNotificationResub represents a resub notification.

type ChatNotificationSub

type ChatNotificationSub struct {
	SubTier        string `json:"sub_tier"`
	IsPrime        bool   `json:"is_prime"`
	DurationMonths int    `json:"duration_months"`
}

ChatNotificationSub represents a sub notification.

type ChatNotificationSubGift

type ChatNotificationSubGift struct {
	DurationMonths     int     `json:"duration_months"`
	CumulativeTotal    *int    `json:"cumulative_total,omitempty"`
	RecipientUserID    string  `json:"recipient_user_id"`
	RecipientUserLogin string  `json:"recipient_user_login"`
	RecipientUserName  string  `json:"recipient_user_name"`
	SubTier            string  `json:"sub_tier"`
	CommunityGiftID    *string `json:"community_gift_id,omitempty"`
}

ChatNotificationSubGift represents a sub gift notification.

type ChatNotificationUnraid

type ChatNotificationUnraid struct{}

ChatNotificationUnraid represents an unraid notification.

type ChatSettings

type ChatSettings struct {
	BroadcasterID                 string `json:"broadcaster_id"`
	SlowMode                      bool   `json:"slow_mode"`
	SlowModeWaitTime              int    `json:"slow_mode_wait_time,omitempty"`
	FollowerMode                  bool   `json:"follower_mode"`
	FollowerModeDuration          int    `json:"follower_mode_duration,omitempty"`
	SubscriberMode                bool   `json:"subscriber_mode"`
	EmoteMode                     bool   `json:"emote_mode"`
	UniqueChatMode                bool   `json:"unique_chat_mode"`
	NonModeratorChatDelay         bool   `json:"non_moderator_chat_delay"`
	NonModeratorChatDelayDuration int    `json:"non_moderator_chat_delay_duration,omitempty"`
}

ChatSettings represents chat room settings.

type ChatUserHoldFragment

type ChatUserHoldFragment struct {
	Type      string              `json:"type"`
	Text      string              `json:"text"`
	Cheermote *ChatEventCheermote `json:"cheermote,omitempty"`
	Emote     *ChatEventEmote     `json:"emote,omitempty"`
}

ChatUserHoldFragment represents a fragment in a held message.

type ChatUserHoldMessage

type ChatUserHoldMessage struct {
	Text      string                 `json:"text"`
	Fragments []ChatUserHoldFragment `json:"fragments"`
}

ChatUserHoldMessage represents a held message.

type Chatter

type Chatter struct {
	UserID    string `json:"user_id"`
	UserLogin string `json:"user_login"`
	UserName  string `json:"user_name"`
}

Chatter represents a user in a channel's chat.

type CheckAutoModStatusParams

type CheckAutoModStatusParams struct {
	BroadcasterID string                 `json:"-"`
	Data          []AutoModStatusMessage `json:"data"`
}

CheckAutoModStatusParams contains parameters for CheckAutoModStatus.

type Cheermote

type Cheermote struct {
	Prefix       string          `json:"prefix"`
	Tiers        []CheermoteTier `json:"tiers"`
	Type         string          `json:"type"`
	Order        int             `json:"order"`
	LastUpdated  time.Time       `json:"last_updated"`
	IsCharitable bool            `json:"is_charitable"`
}

Cheermote represents a cheermote.

type CheermoteImages

type CheermoteImages struct {
	Dark  CheermoteTheme `json:"dark"`
	Light CheermoteTheme `json:"light"`
}

CheermoteImages contains the images for a cheermote tier.

type CheermoteTheme

type CheermoteTheme struct {
	Animated map[string]string `json:"animated"`
	Static   map[string]string `json:"static"`
}

CheermoteTheme contains themed cheermote images.

type CheermoteTier

type CheermoteTier struct {
	MinBits        int             `json:"min_bits"`
	ID             string          `json:"id"`
	Color          string          `json:"color"`
	Images         CheermoteImages `json:"images"`
	CanCheer       bool            `json:"can_cheer"`
	ShowInBitsCard bool            `json:"show_in_bits_card"`
}

CheermoteTier represents a tier of a cheermote.

type ClearChat

type ClearChat struct {
	Channel      string    // Channel name
	User         string    // User being cleared (empty = chat cleared)
	BanDuration  int       // Duration in seconds (0 = permanent ban)
	RoomID       string    // Channel ID
	TargetUserID string    // Banned user's ID
	Timestamp    time.Time // Server timestamp
	Raw          string    // Raw IRC message
}

ClearChat represents a CLEARCHAT message (timeout/ban).

type ClearMessage

type ClearMessage struct {
	Channel     string    // Channel name
	User        string    // Message author
	Message     string    // Deleted message content
	TargetMsgID string    // ID of deleted message
	Timestamp   time.Time // Server timestamp
	Raw         string    // Raw IRC message
}

ClearMessage represents a CLEARMSG message (single message deletion).

type Client

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

Client is a Twitch Helix API client.

func NewClient

func NewClient(clientID string, authClient *AuthClient, opts ...Option) *Client

NewClient creates a new Helix API client.

func NewExtensionClient

func NewExtensionClient(clientID string, jwt *ExtensionJWT, opts ...Option) *Client

NewExtensionClient creates a new Helix client with extension JWT authentication. This client automatically adds the extension JWT to API requests.

func (*Client) AddBlockedTerm

func (c *Client) AddBlockedTerm(ctx context.Context, params *AddBlockedTermParams) (*BlockedTerm, error)

AddBlockedTerm adds a blocked term. Requires: moderator:manage:blocked_terms scope.

func (*Client) AddChannelModerator

func (c *Client) AddChannelModerator(ctx context.Context, broadcasterID, userID string) error

AddChannelModerator adds a moderator to a channel. Requires: channel:manage:moderators scope.

func (*Client) AddChannelVIP

func (c *Client) AddChannelVIP(ctx context.Context, broadcasterID, userID string) error

AddChannelVIP adds a VIP to the channel. Requires: channel:manage:vips scope.

func (*Client) AddSuspiciousStatusToChatUser added in v1.2.0

func (c *Client) AddSuspiciousStatusToChatUser(ctx context.Context, params *AddSuspiciousStatusToChatUserParams) error

AddSuspiciousStatusToChatUser adds a suspicious status to a chat user. The status can be "restricted" or "monitored". Requires: moderator:manage:suspicious_users scope.

func (*Client) AssignGuestStarSlot

func (c *Client) AssignGuestStarSlot(ctx context.Context, broadcasterID, moderatorID, sessionID, guestID, slotID string) error

AssignGuestStarSlot assigns a guest to a slot in a Guest Star session. Requires: channel:manage:guest_star or moderator:manage:guest_star scope. Note: This is a BETA endpoint.

func (*Client) BanUser

func (c *Client) BanUser(ctx context.Context, params *BanUserParams) (*BanUserResponse, error)

BanUser bans a user from a channel. Requires: moderator:manage:banned_users scope.

func (*Client) Batch

func (c *Client) Batch(ctx context.Context, requests []BatchRequest, opts *BatchOptions) []BatchResult

Batch executes multiple requests concurrently with configurable parallelism. Results are returned in the same order as the input requests.

func (*Client) BatchGet

func (c *Client) BatchGet(ctx context.Context, requests []GetRequest, opts *BatchOptions) []BatchResult

BatchGet executes multiple GET requests concurrently.

func (*Client) BatchSequential

func (c *Client) BatchSequential(ctx context.Context, requests []BatchRequest) []BatchResult

BatchSequential executes requests sequentially, useful when order matters or when you want to stop on first error without race conditions.

func (*Client) BatchWithCallback

func (c *Client) BatchWithCallback(ctx context.Context, requests []BatchRequest, opts *BatchOptions, callback func(BatchResult))

BatchWithCallback executes requests and calls the callback for each result. This is useful for processing results as they complete. Note: The callback is serialized with a mutex to prevent concurrent calls. If the callback panics, the panic is recovered and the goroutine continues.

func (*Client) BlockUser

func (c *Client) BlockUser(ctx context.Context, params *BlockUserParams) error

BlockUser blocks a user. Requires: user:manage:blocked_users scope.

func (*Client) CancelRaid

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

CancelRaid cancels a pending raid. Requires: channel:manage:raids scope.

func (*Client) CheckAutoModStatus

func (c *Client) CheckAutoModStatus(ctx context.Context, params *CheckAutoModStatusParams) (*Response[AutoModStatus], error)

CheckAutoModStatus checks if messages meet AutoMod requirements. Requires: moderation:read scope.

func (*Client) CheckUserSubscription

func (c *Client) CheckUserSubscription(ctx context.Context, broadcasterID, userID string) (*UserSubscription, error)

CheckUserSubscription checks if a user is subscribed to a channel. Requires: user:read:subscriptions scope.

func (*Client) ClearCache

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

ClearCache clears all cached responses.

func (*Client) CreateChannelStreamScheduleSegment

func (c *Client) CreateChannelStreamScheduleSegment(ctx context.Context, params *CreateChannelStreamScheduleSegmentParams) (*ScheduleSegment, error)

CreateChannelStreamScheduleSegment creates a new schedule segment. Requires: channel:manage:schedule scope.

func (*Client) CreateClip

func (c *Client) CreateClip(ctx context.Context, params *CreateClipParams) (*CreateClipResponse, error)

CreateClip creates a clip from the broadcaster's stream. Requires: clips:edit scope.

func (*Client) CreateClipFromVOD

func (c *Client) CreateClipFromVOD(ctx context.Context, params *CreateClipFromVODParams) (*CreateClipResponse, error)

CreateClipFromVOD creates a clip from a VOD. Requires: editor:manage:clips or channel:manage:clips scope.

func (*Client) CreateConduit

func (c *Client) CreateConduit(ctx context.Context, shardCount int) (*Conduit, error)

CreateConduit creates a new conduit. Requires: App access token.

func (*Client) CreateCustomReward

func (c *Client) CreateCustomReward(ctx context.Context, params *CreateCustomRewardParams) (*CustomReward, error)

CreateCustomReward creates a custom reward. Requires: channel:manage:redemptions scope.

func (*Client) CreateEventSubSubscription

func (c *Client) CreateEventSubSubscription(ctx context.Context, params *CreateEventSubSubscriptionParams) (*EventSubSubscription, error)

CreateEventSubSubscription creates an EventSub subscription. Requires: App access token.

func (*Client) CreateExtensionSecret

func (c *Client) CreateExtensionSecret(ctx context.Context, extensionID string, delay int) (*Response[ExtensionSecret], error)

CreateExtensionSecret creates a new secret for an extension. Requires: JWT created by extension.

func (*Client) CreateGuestStarSession

func (c *Client) CreateGuestStarSession(ctx context.Context, broadcasterID string) (*GuestStarSession, error)

CreateGuestStarSession creates a Guest Star session. Requires: channel:manage:guest_star scope. Note: This is a BETA endpoint.

func (*Client) CreatePoll

func (c *Client) CreatePoll(ctx context.Context, params *CreatePollParams) (*Poll, error)

CreatePoll creates a poll on a channel. Requires: channel:manage:polls scope.

func (*Client) CreatePrediction

func (c *Client) CreatePrediction(ctx context.Context, params *CreatePredictionParams) (*Prediction, error)

CreatePrediction creates a prediction on a channel. Requires: channel:manage:predictions scope.

func (*Client) CreateStreamMarker

func (c *Client) CreateStreamMarker(ctx context.Context, params *CreateStreamMarkerParams) (*StreamMarker, error)

CreateStreamMarker creates a marker in the stream. Requires: channel:manage:broadcast scope.

func (*Client) DeleteAllSubscriptions

func (c *Client) DeleteAllSubscriptions(ctx context.Context, params *GetEventSubSubscriptionsParams) (int, error)

DeleteAllSubscriptions deletes all EventSub subscriptions matching the filter.

func (*Client) DeleteChannelStreamScheduleSegment

func (c *Client) DeleteChannelStreamScheduleSegment(ctx context.Context, broadcasterID, segmentID string) error

DeleteChannelStreamScheduleSegment deletes a schedule segment. Requires: channel:manage:schedule scope.

func (*Client) DeleteChatMessages

func (c *Client) DeleteChatMessages(ctx context.Context, params *DeleteChatMessagesParams) error

DeleteChatMessages deletes chat messages. Requires: moderator:manage:chat_messages scope.

func (*Client) DeleteConduit

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

DeleteConduit deletes a conduit. Requires: App access token.

func (*Client) DeleteCustomReward

func (c *Client) DeleteCustomReward(ctx context.Context, broadcasterID, rewardID string) error

DeleteCustomReward deletes a custom reward. Requires: channel:manage:redemptions scope.

func (*Client) DeleteEventSubSubscription

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

DeleteEventSubSubscription deletes an EventSub subscription. Requires: App access token.

func (*Client) DeleteGuestStarInvite

func (c *Client) DeleteGuestStarInvite(ctx context.Context, broadcasterID, moderatorID, sessionID, guestID string) error

DeleteGuestStarInvite deletes an invite to a Guest Star session. Requires: channel:manage:guest_star or moderator:manage:guest_star scope. Note: This is a BETA endpoint.

func (*Client) DeleteGuestStarSlot

func (c *Client) DeleteGuestStarSlot(ctx context.Context, broadcasterID, moderatorID, sessionID, guestID, slotID string) error

DeleteGuestStarSlot removes a guest from a slot. Requires: channel:manage:guest_star or moderator:manage:guest_star scope. Note: This is a BETA endpoint.

func (*Client) DeleteVideos

func (c *Client) DeleteVideos(ctx context.Context, videoIDs []string) ([]string, error)

DeleteVideos deletes one or more videos. Requires: channel:manage:videos scope.

func (*Client) Do

func (c *Client) Do(ctx context.Context, req *Request, result interface{}) error

Do executes an API request with automatic retry on rate limit (429).

func (*Client) EndGuestStarSession

func (c *Client) EndGuestStarSession(ctx context.Context, broadcasterID, sessionID string) (*GuestStarSession, error)

EndGuestStarSession ends a Guest Star session. Requires: channel:manage:guest_star scope. Note: This is a BETA endpoint.

func (*Client) EndPoll

func (c *Client) EndPoll(ctx context.Context, params *EndPollParams) (*Poll, error)

EndPoll ends a poll. Requires: channel:manage:polls scope.

func (*Client) EndPrediction

func (c *Client) EndPrediction(ctx context.Context, params *EndPredictionParams) (*Prediction, error)

EndPrediction ends a prediction. Requires: channel:manage:predictions scope.

func (*Client) GetAdSchedule

func (c *Client) GetAdSchedule(ctx context.Context, broadcasterID string) (*AdSchedule, error)

GetAdSchedule gets the ad schedule for a channel. Requires: channel:read:ads scope.

func (*Client) GetAllSubscriptions

func (c *Client) GetAllSubscriptions(ctx context.Context, params *GetEventSubSubscriptionsParams) ([]EventSubSubscription, error)

GetAllSubscriptions returns all EventSub subscriptions, handling pagination automatically.

func (*Client) GetAuthorizationByUser

func (c *Client) GetAuthorizationByUser(ctx context.Context, params *GetAuthorizationByUserParams) (*Response[UserAuthorization], error)

GetAuthorizationByUser gets the authorization scopes that the specified user has granted the application. Requires: App access token.

func (*Client) GetAutoModSettings

func (c *Client) GetAutoModSettings(ctx context.Context, broadcasterID, moderatorID string) (*AutoModSettings, error)

GetAutoModSettings gets the AutoMod settings for a channel. Requires: moderator:read:automod_settings scope.

func (*Client) GetBannedUsers

func (c *Client) GetBannedUsers(ctx context.Context, params *GetBannedUsersParams) (*Response[BannedUser], error)

GetBannedUsers gets the list of banned users for a channel. Requires: moderation:read scope.

func (*Client) GetBitsLeaderboard

func (c *Client) GetBitsLeaderboard(ctx context.Context, params *GetBitsLeaderboardParams) (*BitsLeaderboardResponse, error)

GetBitsLeaderboard gets the bits leaderboard for a channel. Requires: bits:read scope.

func (*Client) GetBlockedTerms

func (c *Client) GetBlockedTerms(ctx context.Context, params *GetBlockedTermsParams) (*Response[BlockedTerm], error)

GetBlockedTerms gets the list of blocked terms for a channel. Requires: moderator:read:blocked_terms scope.

func (*Client) GetBroadcasterSubscriptions

func (c *Client) GetBroadcasterSubscriptions(ctx context.Context, params *GetBroadcasterSubscriptionsParams) (*SubscriptionsResponse, error)

GetBroadcasterSubscriptions gets the list of subscribers for a channel. Requires: channel:read:subscriptions scope.

func (*Client) GetChannelChatBadges

func (c *Client) GetChannelChatBadges(ctx context.Context, broadcasterID string) (*Response[ChatBadge], error)

GetChannelChatBadges gets the chat badges for a channel.

func (*Client) GetChannelEditors

func (c *Client) GetChannelEditors(ctx context.Context, broadcasterID string) (*Response[ChannelEditor], error)

GetChannelEditors gets the list of channel editors. Requires: channel:read:editors scope.

func (*Client) GetChannelEmotes

func (c *Client) GetChannelEmotes(ctx context.Context, broadcasterID string) (*Response[Emote], error)

GetChannelEmotes gets the emotes for a channel.

func (*Client) GetChannelFollowers

func (c *Client) GetChannelFollowers(ctx context.Context, params *GetChannelFollowersParams) (*Response[ChannelFollower], error)

GetChannelFollowers gets the list of users that follow a channel. Requires: moderator:read:followers scope.

func (*Client) GetChannelGuestStarSettings

func (c *Client) GetChannelGuestStarSettings(ctx context.Context, broadcasterID, moderatorID string) (*GuestStarSettings, error)

GetChannelGuestStarSettings gets the Guest Star settings for a channel. Requires: channel:read:guest_star, channel:manage:guest_star, or moderator:read:guest_star scope. Note: This is a BETA endpoint.

func (*Client) GetChannelICalendar

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

GetChannelICalendar gets a channel's stream schedule as iCalendar.

func (*Client) GetChannelInformation

func (c *Client) GetChannelInformation(ctx context.Context, params *GetChannelInformationParams) (*Response[Channel], error)

GetChannelInformation gets channel information for one or more users.

func (*Client) GetChannelStreamSchedule

func (c *Client) GetChannelStreamSchedule(ctx context.Context, params *GetChannelStreamScheduleParams) (*ScheduleResponse, error)

GetChannelStreamSchedule gets a channel's stream schedule.

func (*Client) GetChannelTeams

func (c *Client) GetChannelTeams(ctx context.Context, broadcasterID string) (*Response[ChannelTeam], error)

GetChannelTeams gets the teams a broadcaster belongs to.

func (*Client) GetCharityCampaign

func (c *Client) GetCharityCampaign(ctx context.Context, params *GetCharityCampaignParams) (*Response[CharityCampaign], error)

GetCharityCampaign gets the active charity campaign for a channel. Requires: channel:read:charity scope.

func (*Client) GetCharityCampaignDonations added in v1.2.0

func (c *Client) GetCharityCampaignDonations(ctx context.Context, params *GetCharityCampaignDonationsParams) (*Response[CharityDonation], error)

GetCharityCampaignDonations gets the donations for a charity campaign. Requires: channel:read:charity scope.

func (*Client) GetChatSettings

func (c *Client) GetChatSettings(ctx context.Context, broadcasterID, moderatorID string) (*Response[ChatSettings], error)

GetChatSettings gets the chat settings for a channel.

func (*Client) GetChatters

func (c *Client) GetChatters(ctx context.Context, params *GetChattersParams) (*Response[Chatter], error)

GetChatters gets the list of users in a channel's chat. Requires: moderator:read:chatters scope.

func (*Client) GetCheermotes

func (c *Client) GetCheermotes(ctx context.Context, broadcasterID string) (*Response[Cheermote], error)

GetCheermotes gets the cheermotes available to a broadcaster.

func (*Client) GetClips

func (c *Client) GetClips(ctx context.Context, params *GetClipsParams) (*Response[Clip], error)

GetClips gets clips for a broadcaster or game.

func (*Client) GetClipsDownload

func (c *Client) GetClipsDownload(ctx context.Context, clipIDs []string) (*Response[ClipDownload], error)

GetClipsDownload gets a download URL for clips. Requires: clips:edit scope for clips the user created, or the broadcaster's clips.

func (*Client) GetConduitShards

func (c *Client) GetConduitShards(ctx context.Context, params *GetConduitShardsParams) (*GetConduitShardsResponse, error)

GetConduitShards gets the shards for a conduit. Requires: App access token.

func (*Client) GetConduits

func (c *Client) GetConduits(ctx context.Context) (*Response[Conduit], error)

GetConduits gets the conduits for a client ID. Requires: App access token.

func (*Client) GetContentClassificationLabels

func (c *Client) GetContentClassificationLabels(ctx context.Context, params *GetContentClassificationLabelsParams) (*Response[ContentClassificationLabel], error)

GetContentClassificationLabels gets the list of content classification labels.

func (*Client) GetCreatorGoals

func (c *Client) GetCreatorGoals(ctx context.Context, broadcasterID string) (*Response[CreatorGoal], error)

GetCreatorGoals gets the creator goals for a channel. Requires: channel:read:goals scope.

func (*Client) GetCurrentUser

func (c *Client) GetCurrentUser(ctx context.Context) (*User, error)

GetCurrentUser gets information about the authenticated user.

func (*Client) GetCustomReward added in v1.2.0

func (c *Client) GetCustomReward(ctx context.Context, params *GetCustomRewardParams) (*Response[CustomReward], error)

GetCustomReward gets custom rewards for a channel. Requires: channel:read:redemptions or channel:manage:redemptions scope.

func (*Client) GetCustomRewardRedemption added in v1.2.0

func (c *Client) GetCustomRewardRedemption(ctx context.Context, params *GetCustomRewardRedemptionParams) (*Response[CustomRewardRedemption], error)

GetCustomRewardRedemption gets redemptions for a custom reward. Requires: channel:read:redemptions or channel:manage:redemptions scope.

func (*Client) GetDropsEntitlements

func (c *Client) GetDropsEntitlements(ctx context.Context, params *GetDropsEntitlementsParams) (*Response[DropsEntitlement], error)

GetDropsEntitlements gets drops entitlements. Requires: App access token or user token with viewing:activity:read scope.

func (*Client) GetEmoteSets

func (c *Client) GetEmoteSets(ctx context.Context, emoteSetIDs []string) (*Response[Emote], error)

GetEmoteSets gets emotes from specific emote sets.

func (*Client) GetEventSubSubscriptions

func (c *Client) GetEventSubSubscriptions(ctx context.Context, params *GetEventSubSubscriptionsParams) (*EventSubResponse, error)

GetEventSubSubscriptions gets EventSub subscriptions. Requires: App access token.

func (*Client) GetExtensionAnalytics

func (c *Client) GetExtensionAnalytics(ctx context.Context, params *GetExtensionAnalyticsParams) (*Response[ExtensionAnalytics], error)

GetExtensionAnalytics gets analytics for extensions. Requires: analytics:read:extensions scope.

func (*Client) GetExtensionBitsProducts

func (c *Client) GetExtensionBitsProducts(ctx context.Context, params *GetExtensionBitsProductsParams) (*Response[ExtensionBitsProduct], error)

GetExtensionBitsProducts gets Bits products for an extension. Requires: App access token for the extension.

func (*Client) GetExtensionConfigurationSegment

func (c *Client) GetExtensionConfigurationSegment(ctx context.Context, params *GetExtensionConfigurationSegmentParams) (*Response[ExtensionConfigurationSegment], error)

GetExtensionConfigurationSegment gets extension configuration segment data. Requires: JWT created by extension.

func (*Client) GetExtensionLiveChannels

func (c *Client) GetExtensionLiveChannels(ctx context.Context, params *GetExtensionLiveChannelsParams) (*Response[ExtensionLiveChannel], error)

GetExtensionLiveChannels gets live channels that have an extension installed and activated.

func (*Client) GetExtensionSecrets

func (c *Client) GetExtensionSecrets(ctx context.Context, extensionID string) (*Response[ExtensionSecret], error)

GetExtensionSecrets gets the secrets for an extension. Requires: JWT created by extension.

func (*Client) GetExtensionTransactions

func (c *Client) GetExtensionTransactions(ctx context.Context, params *GetExtensionTransactionsParams) (*Response[ExtensionTransaction], error)

GetExtensionTransactions gets extension transactions. Requires: App access token for the extension.

func (*Client) GetExtensions

func (c *Client) GetExtensions(ctx context.Context, extensionID, extensionVersion string) (*Response[Extension], error)

GetExtensions gets information about extensions. Requires: JWT created by extension.

func (*Client) GetFollowedChannels

func (c *Client) GetFollowedChannels(ctx context.Context, params *GetFollowedChannelsParams) (*Response[FollowedChannel], error)

GetFollowedChannels gets the list of channels that a user follows. Requires: user:read:follows scope.

func (*Client) GetFollowedStreams

func (c *Client) GetFollowedStreams(ctx context.Context, params *GetFollowedStreamsParams) (*Response[Stream], error)

GetFollowedStreams gets streams from channels that the user follows. Requires: user:read:follows scope.

func (*Client) GetGameAnalytics

func (c *Client) GetGameAnalytics(ctx context.Context, params *GetGameAnalyticsParams) (*Response[GameAnalytics], error)

GetGameAnalytics gets analytics for games. Requires: analytics:read:games scope.

func (*Client) GetGames

func (c *Client) GetGames(ctx context.Context, params *GetGamesParams) (*Response[Game], error)

GetGames gets information about one or more games.

func (*Client) GetGlobalChatBadges

func (c *Client) GetGlobalChatBadges(ctx context.Context) (*Response[ChatBadge], error)

GetGlobalChatBadges gets all global chat badges.

func (*Client) GetGlobalEmotes

func (c *Client) GetGlobalEmotes(ctx context.Context) (*Response[Emote], error)

GetGlobalEmotes gets all global emotes.

func (*Client) GetGuestStarInvites

func (c *Client) GetGuestStarInvites(ctx context.Context, broadcasterID, moderatorID, sessionID string) (*Response[GuestStarInvite], error)

GetGuestStarInvites gets the pending invites for a Guest Star session. Requires: channel:read:guest_star, channel:manage:guest_star, or moderator:read:guest_star scope. Note: This is a BETA endpoint.

func (*Client) GetGuestStarSession

func (c *Client) GetGuestStarSession(ctx context.Context, broadcasterID, moderatorID string) (*GuestStarSession, error)

GetGuestStarSession gets the active Guest Star session for a channel. Requires: channel:read:guest_star, channel:manage:guest_star, or moderator:read:guest_star scope. Note: This is a BETA endpoint.

func (*Client) GetHypeTrainEvents

func (c *Client) GetHypeTrainEvents(ctx context.Context, params *GetHypeTrainEventsParams) (*Response[HypeTrainEvent], error)

GetHypeTrainEvents gets hype train events for a channel. Requires: channel:read:hype_train scope. Note: This endpoint is deprecated; use EventSub instead.

func (*Client) GetHypeTrainStatus

func (c *Client) GetHypeTrainStatus(ctx context.Context, broadcasterID string) (*HypeTrainStatus, error)

GetHypeTrainStatus gets the current hype train status for a channel. Requires: channel:read:hype_train scope.

func (*Client) GetIngestServers

func (c *Client) GetIngestServers(ctx context.Context) (*IngestServersResponse, error)

GetIngestServers returns a list of endpoints for ingesting live video into Twitch. This endpoint does not require authentication. Note: This endpoint uses a different base URL (ingest.twitch.tv) than the Helix API.

func (*Client) GetModeratedChannels

func (c *Client) GetModeratedChannels(ctx context.Context, params *GetModeratedChannelsParams) (*Response[ModeratedChannel], error)

GetModeratedChannels gets channels where the user is a moderator. Requires: user:read:moderated_channels scope.

func (*Client) GetModerators

func (c *Client) GetModerators(ctx context.Context, params *GetModeratorsParams) (*Response[Moderator], error)

GetModerators gets the list of moderators for a channel. Requires: moderation:read scope.

func (*Client) GetPolls

func (c *Client) GetPolls(ctx context.Context, params *GetPollsParams) (*Response[Poll], error)

GetPolls gets polls for a channel. Requires: channel:read:polls scope.

func (*Client) GetPredictions

func (c *Client) GetPredictions(ctx context.Context, params *GetPredictionsParams) (*Response[Prediction], error)

GetPredictions gets predictions for a channel. Requires: channel:read:predictions scope.

func (*Client) GetRateLimitInfo

func (c *Client) GetRateLimitInfo() RateLimitInfo

GetRateLimitInfo returns current rate limit information.

func (*Client) GetReleasedExtensions

func (c *Client) GetReleasedExtensions(ctx context.Context, extensionID, extensionVersion string) (*Response[Extension], error)

GetReleasedExtensions gets information about a released extension.

func (*Client) GetSharedChatSession

func (c *Client) GetSharedChatSession(ctx context.Context, broadcasterID string) (*SharedChatSession, error)

GetSharedChatSession gets the active shared chat session for a channel. Requires: No authentication required.

func (*Client) GetShieldModeStatus

func (c *Client) GetShieldModeStatus(ctx context.Context, broadcasterID, moderatorID string) (*ShieldModeStatus, error)

GetShieldModeStatus gets the shield mode status for a channel. Requires: moderator:read:shield_mode scope.

func (*Client) GetStreamKey

func (c *Client) GetStreamKey(ctx context.Context, broadcasterID string) (*StreamKey, error)

GetStreamKey gets the stream key for a broadcaster. Requires: channel:read:stream_key scope.

func (*Client) GetStreamMarkers

func (c *Client) GetStreamMarkers(ctx context.Context, params *GetStreamMarkersParams) (*Response[VideoStreamMarkers], error)

GetStreamMarkers gets stream markers. Requires: user:read:broadcast scope.

func (*Client) GetStreams

func (c *Client) GetStreams(ctx context.Context, params *GetStreamsParams) (*Response[Stream], error)

GetStreams gets active streams.

func (*Client) GetTeams

func (c *Client) GetTeams(ctx context.Context, params *GetTeamsParams) (*Response[Team], error)

GetTeams gets team information.

func (*Client) GetTopGames

func (c *Client) GetTopGames(ctx context.Context, params *GetTopGamesParams) (*Response[Game], error)

GetTopGames gets the top games/categories sorted by number of current viewers.

func (*Client) GetUnbanRequests

func (c *Client) GetUnbanRequests(ctx context.Context, params *GetUnbanRequestsParams) (*Response[UnbanRequest], error)

GetUnbanRequests gets unban requests for a channel. Requires: moderator:read:unban_requests scope.

func (*Client) GetUserActiveExtensions

func (c *Client) GetUserActiveExtensions(ctx context.Context, userID string) (*UserActiveExtensions, error)

GetUserActiveExtensions gets the active extensions for a user. Requires: user:read:broadcast or user:edit:broadcast scope.

func (*Client) GetUserBlockList

func (c *Client) GetUserBlockList(ctx context.Context, params *GetUserBlockListParams) (*Response[BlockedUser], error)

GetUserBlockList gets the authenticated user's block list. Requires: user:read:blocked_users scope.

func (*Client) GetUserChatColor

func (c *Client) GetUserChatColor(ctx context.Context, userIDs []string) (*Response[UserChatColor], error)

GetUserChatColor gets the chat color for one or more users.

func (*Client) GetUserEmotes

func (c *Client) GetUserEmotes(ctx context.Context, params *GetUserEmotesParams) (*UserEmotesResponse, error)

GetUserEmotes gets emotes available to a user. Requires: user:read:emotes scope.

func (*Client) GetUserExtensions

func (c *Client) GetUserExtensions(ctx context.Context) (*Response[UserExtension], error)

GetUserExtensions gets extensions installed by the authenticated user. Requires: user:read:broadcast scope.

func (*Client) GetUsers

func (c *Client) GetUsers(ctx context.Context, params *GetUsersParams) (*Response[User], error)

GetUsers gets information about one or more Twitch users. Requires: No scope for public data, user:read:email for email.

func (*Client) GetVIPs

func (c *Client) GetVIPs(ctx context.Context, params *GetVIPsParams) (*Response[VIP], error)

GetVIPs gets the list of VIPs for a channel. Requires: channel:read:vips scope.

func (*Client) GetVideos

func (c *Client) GetVideos(ctx context.Context, params *GetVideosParams) (*Response[Video], error)

GetVideos gets videos.

func (*Client) InvalidateCache

func (c *Client) InvalidateCache(ctx context.Context, endpoint string, query string)

InvalidateCache removes a specific cached response. Note: This uses a simple cache key without token context. If you're using context-aware caching (different users sharing the same cache), use InvalidateCacheWithContext instead.

func (*Client) InvalidateCacheWithContext added in v1.0.2

func (c *Client) InvalidateCacheWithContext(ctx context.Context, endpoint, query, tokenHash string)

InvalidateCacheWithContext removes a specific cached response using context-aware keys. Use this when sharing a cache across multiple users/tokens. The tokenHash should be generated using TokenHash(token).

func (*Client) ManageHeldAutoModMessages

func (c *Client) ManageHeldAutoModMessages(ctx context.Context, params *ManageHeldAutoModMessageParams) error

ManageHeldAutoModMessages approves or denies a held AutoMod message. Requires: moderator:manage:automod scope.

func (*Client) ModifyChannelInformation

func (c *Client) ModifyChannelInformation(ctx context.Context, params *ModifyChannelInformationParams) error

ModifyChannelInformation modifies channel information. Requires: channel:manage:broadcast scope.

func (*Client) RemoveBlockedTerm

func (c *Client) RemoveBlockedTerm(ctx context.Context, broadcasterID, moderatorID, termID string) error

RemoveBlockedTerm removes a blocked term. Requires: moderator:manage:blocked_terms scope.

func (*Client) RemoveChannelModerator

func (c *Client) RemoveChannelModerator(ctx context.Context, broadcasterID, userID string) error

RemoveChannelModerator removes a moderator from a channel. Requires: channel:manage:moderators scope.

func (*Client) RemoveChannelVIP

func (c *Client) RemoveChannelVIP(ctx context.Context, broadcasterID, userID string) error

RemoveChannelVIP removes a VIP from the channel. Requires: channel:manage:vips scope.

func (*Client) RemoveSuspiciousStatusFromChatUser added in v1.2.0

func (c *Client) RemoveSuspiciousStatusFromChatUser(ctx context.Context, params *RemoveSuspiciousStatusFromChatUserParams) error

RemoveSuspiciousStatusFromChatUser removes a suspicious status from a chat user. Requires: moderator:manage:suspicious_users scope.

func (*Client) ResolveUnbanRequest

func (c *Client) ResolveUnbanRequest(ctx context.Context, params *ResolveUnbanRequestParams) (*UnbanRequest, error)

ResolveUnbanRequest resolves an unban request. Requires: moderator:manage:unban_requests scope.

func (*Client) SearchCategories

func (c *Client) SearchCategories(ctx context.Context, params *SearchCategoriesParams) (*Response[SearchCategory], error)

SearchCategories searches for categories/games.

func (*Client) SearchChannels

func (c *Client) SearchChannels(ctx context.Context, params *SearchChannelsParams) (*Response[SearchChannel], error)

SearchChannels searches for channels.

func (*Client) SendChatAnnouncement

func (c *Client) SendChatAnnouncement(ctx context.Context, params *SendChatAnnouncementParams) error

SendChatAnnouncement sends an announcement to a channel's chat. Requires: moderator:manage:announcements scope.

func (*Client) SendChatMessage

func (c *Client) SendChatMessage(ctx context.Context, params *SendChatMessageParams) (*SendChatMessageResponse, error)

SendChatMessage sends a chat message to a channel. Requires: user:write:chat scope.

func (*Client) SendExtensionChatMessage

func (c *Client) SendExtensionChatMessage(ctx context.Context, params *SendExtensionChatMessageParams) error

SendExtensionChatMessage sends a chat message from an extension. Requires: JWT created by extension.

func (*Client) SendExtensionPubSubMessage

func (c *Client) SendExtensionPubSubMessage(ctx context.Context, params *SendExtensionPubSubMessageParams) error

SendExtensionPubSubMessage sends a PubSub message for an extension. Requires: JWT created by extension.

func (*Client) SendGuestStarInvite

func (c *Client) SendGuestStarInvite(ctx context.Context, broadcasterID, moderatorID, sessionID, guestID string) error

SendGuestStarInvite sends an invite to a Guest Star session. Requires: channel:manage:guest_star or moderator:manage:guest_star scope. Note: This is a BETA endpoint.

func (*Client) SendShoutout

func (c *Client) SendShoutout(ctx context.Context, params *SendShoutoutParams) error

SendShoutout sends a shoutout to another channel. Requires: moderator:manage:shoutouts scope.

func (*Client) SendWhisper

func (c *Client) SendWhisper(ctx context.Context, params *SendWhisperParams) error

SendWhisper sends a whisper message to another user. Requires: user:manage:whispers scope.

func (*Client) SetExtensionConfigurationSegment

func (c *Client) SetExtensionConfigurationSegment(ctx context.Context, params *SetExtensionConfigurationSegmentParams) error

SetExtensionConfigurationSegment sets extension configuration segment data. Requires: JWT created by extension.

func (*Client) SetExtensionJWT

func (c *Client) SetExtensionJWT(jwt *ExtensionJWT)

SetExtensionJWT updates the Client to use extension JWT authentication. This modifies the client to use the provided JWT for all requests.

func (*Client) SetExtensionRequiredConfiguration

func (c *Client) SetExtensionRequiredConfiguration(ctx context.Context, params *SetExtensionRequiredConfigurationParams) error

SetExtensionRequiredConfiguration sets the required configuration for an extension. Requires: JWT created by extension.

func (*Client) SnoozeNextAd

func (c *Client) SnoozeNextAd(ctx context.Context, broadcasterID string) (*SnoozeNextAdResponse, error)

SnoozeNextAd snoozes the next scheduled ad. Requires: channel:manage:ads scope.

func (*Client) StartCommercial

func (c *Client) StartCommercial(ctx context.Context, params *StartCommercialParams) (*Commercial, error)

StartCommercial starts a commercial on a channel. Requires: channel:edit:commercial scope.

func (*Client) StartRaid

func (c *Client) StartRaid(ctx context.Context, params *StartRaidParams) (*Raid, error)

StartRaid starts a raid on another channel. Requires: channel:manage:raids scope.

func (*Client) SubscribeToChannel

func (c *Client) SubscribeToChannel(ctx context.Context, eventType, broadcasterID string, transport CreateEventSubTransport) (*EventSubSubscription, error)

SubscribeToChannel is a helper to subscribe to a channel event using the latest version.

func (*Client) SubscribeToChannelWithModerator

func (c *Client) SubscribeToChannelWithModerator(ctx context.Context, eventType, broadcasterID, moderatorID string, transport CreateEventSubTransport) (*EventSubSubscription, error)

SubscribeToChannelWithModerator is a helper to subscribe to channel events that require moderator.

func (*Client) SubscribeToUser

func (c *Client) SubscribeToUser(ctx context.Context, eventType, userID string, transport CreateEventSubTransport) (*EventSubSubscription, error)

SubscribeToUser is a helper to subscribe to user events using the latest version.

func (*Client) UnbanUser

func (c *Client) UnbanUser(ctx context.Context, broadcasterID, moderatorID, userID string) error

UnbanUser unbans a user from a channel. Requires: moderator:manage:banned_users scope.

func (*Client) UnblockUser

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

UnblockUser unblocks a user. Requires: user:manage:blocked_users scope.

func (*Client) UpdateAutoModSettings

func (c *Client) UpdateAutoModSettings(ctx context.Context, params *UpdateAutoModSettingsParams) (*AutoModSettings, error)

UpdateAutoModSettings updates the AutoMod settings for a channel. Requires: moderator:manage:automod_settings scope.

func (*Client) UpdateChannelGuestStarSettings

func (c *Client) UpdateChannelGuestStarSettings(ctx context.Context, params *UpdateChannelGuestStarSettingsParams) error

UpdateChannelGuestStarSettings updates the Guest Star settings for a channel. Requires: channel:manage:guest_star scope. Note: This is a BETA endpoint.

func (*Client) UpdateChannelStreamSchedule

func (c *Client) UpdateChannelStreamSchedule(ctx context.Context, params *UpdateChannelStreamScheduleParams) error

UpdateChannelStreamSchedule updates a channel's stream schedule settings. Requires: channel:manage:schedule scope.

func (*Client) UpdateChannelStreamScheduleSegment

func (c *Client) UpdateChannelStreamScheduleSegment(ctx context.Context, params *UpdateChannelStreamScheduleSegmentParams) (*ScheduleSegment, error)

UpdateChannelStreamScheduleSegment updates a schedule segment. Requires: channel:manage:schedule scope.

func (*Client) UpdateChatSettings

func (c *Client) UpdateChatSettings(ctx context.Context, params *UpdateChatSettingsParams) (*Response[ChatSettings], error)

UpdateChatSettings updates the chat settings for a channel. Requires: moderator:manage:chat_settings scope.

func (*Client) UpdateConduit

func (c *Client) UpdateConduit(ctx context.Context, params *UpdateConduitParams) (*Conduit, error)

UpdateConduit updates a conduit's shard count. Requires: App access token.

func (*Client) UpdateConduitShards

func (c *Client) UpdateConduitShards(ctx context.Context, params *UpdateConduitShardsParams) (*UpdateConduitShardsResponse, error)

UpdateConduitShards updates shards for a conduit. Requires: App access token.

func (*Client) UpdateCustomReward

func (c *Client) UpdateCustomReward(ctx context.Context, params *UpdateCustomRewardParams) (*CustomReward, error)

UpdateCustomReward updates a custom reward. Requires: channel:manage:redemptions scope.

func (*Client) UpdateDropsEntitlements

func (c *Client) UpdateDropsEntitlements(ctx context.Context, params *UpdateDropsEntitlementsParams) ([]UpdateDropsEntitlementsResponse, error)

UpdateDropsEntitlements updates the fulfillment status of drops entitlements. Requires: App access token or user token.

func (*Client) UpdateExtensionBitsProduct

func (c *Client) UpdateExtensionBitsProduct(ctx context.Context, params *UpdateExtensionBitsProductParams) (*Response[ExtensionBitsProduct], error)

UpdateExtensionBitsProduct updates an extension Bits product. Requires: App access token for the extension.

func (*Client) UpdateGuestStarSlot

func (c *Client) UpdateGuestStarSlot(ctx context.Context, params *UpdateGuestStarSlotParams) error

UpdateGuestStarSlot moves a guest from one slot to another. Requires: channel:manage:guest_star or moderator:manage:guest_star scope. Note: This is a BETA endpoint.

func (*Client) UpdateGuestStarSlotSettings

func (c *Client) UpdateGuestStarSlotSettings(ctx context.Context, params *UpdateGuestStarSlotSettingsParams) error

UpdateGuestStarSlotSettings updates the settings for a Guest Star slot. Requires: channel:manage:guest_star or moderator:manage:guest_star scope. Note: This is a BETA endpoint.

func (*Client) UpdateRedemptionStatus

func (c *Client) UpdateRedemptionStatus(ctx context.Context, params *UpdateRedemptionStatusParams) (*Response[CustomRewardRedemption], error)

UpdateRedemptionStatus updates the status of custom reward redemptions. Requires: channel:manage:redemptions scope.

func (*Client) UpdateShieldModeStatus

func (c *Client) UpdateShieldModeStatus(ctx context.Context, params *UpdateShieldModeStatusParams) (*ShieldModeStatus, error)

UpdateShieldModeStatus updates the shield mode status for a channel. Requires: moderator:manage:shield_mode scope.

func (*Client) UpdateUser

func (c *Client) UpdateUser(ctx context.Context, params *UpdateUserParams) (*User, error)

UpdateUser updates the authenticated user's information. Requires: user:edit scope.

func (*Client) UpdateUserChatColor

func (c *Client) UpdateUserChatColor(ctx context.Context, userID, color string) error

UpdateUserChatColor updates the authenticated user's chat color. Requires: user:manage:chat_color scope.

func (*Client) UpdateUserExtensions

func (c *Client) UpdateUserExtensions(ctx context.Context, params *UpdateUserExtensionsParams) (*UserActiveExtensions, error)

UpdateUserExtensions updates the active extensions for the authenticated user. Requires: user:edit:broadcast scope.

func (*Client) Use

func (c *Client) Use(mw ...Middleware)

Use adds middleware to the client. Middleware is executed in the order added.

func (*Client) WaitForRateLimit

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

WaitForRateLimit blocks until the rate limit resets or context is cancelled. Returns immediately if there are remaining points in the bucket.

func (*Client) WarnChatUser

func (c *Client) WarnChatUser(ctx context.Context, params *WarnChatUserParams) error

WarnChatUser warns a user in chat. Requires: moderator:manage:warnings scope.

type Clip

type Clip 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       int       `json:"view_count"`
	CreatedAt       time.Time `json:"created_at"`
	ThumbnailURL    string    `json:"thumbnail_url"`
	Duration        float64   `json:"duration"`
	VODOffset       int       `json:"vod_offset,omitempty"`
	IsFeatured      bool      `json:"is_featured"`
}

Clip represents a Twitch clip.

type ClipDownload

type ClipDownload struct {
	ID        string `json:"id"`
	URL       string `json:"url"`
	ExpiresAt string `json:"expires_at"`
}

ClipDownload represents a clip download URL.

type Commercial

type Commercial struct {
	Length     int    `json:"length"`
	Message    string `json:"message"`
	RetryAfter int    `json:"retry_after"`
}

Commercial represents a started commercial.

type Conduit

type Conduit struct {
	ID         string `json:"id"`
	ShardCount int    `json:"shard_count"`
}

Conduit represents an EventSub conduit.

type ConduitShard

type ConduitShard struct {
	ID        string                `json:"id"`
	Status    string                `json:"status"`
	Transport ConduitShardTransport `json:"transport"`
}

ConduitShard represents a shard in a conduit.

type ConduitShardDisabledEvent

type ConduitShardDisabledEvent struct {
	ConduitID string                     `json:"conduit_id"`
	ShardID   string                     `json:"shard_id"`
	Status    string                     `json:"status"`
	Transport ConduitShardTransportEvent `json:"transport"`
}

ConduitShardDisabledEvent is sent when a conduit shard is disabled.

type ConduitShardTransport

type ConduitShardTransport struct {
	Method         string `json:"method"`
	Callback       string `json:"callback,omitempty"`
	SessionID      string `json:"session_id,omitempty"`
	ConnectedAt    string `json:"connected_at,omitempty"`
	DisconnectedAt string `json:"disconnected_at,omitempty"`
}

ConduitShardTransport represents the transport for a conduit shard.

type ConduitShardTransportEvent

type ConduitShardTransportEvent struct {
	Method         string `json:"method"`
	SessionID      string `json:"session_id,omitempty"`
	Callback       string `json:"callback,omitempty"`
	ConnectedAt    string `json:"connected_at,omitempty"`
	DisconnectedAt string `json:"disconnected_at,omitempty"`
}

ConduitShardTransportEvent represents transport info in conduit events.

type ContentClassificationLabel

type ContentClassificationLabel struct {
	ID          string `json:"id"`
	Description string `json:"description"`
	Name        string `json:"name"`
}

ContentClassificationLabel represents a content classification label.

type ContentClassificationLabelSetting

type ContentClassificationLabelSetting struct {
	ID        string `json:"id"`
	IsEnabled bool   `json:"is_enabled"`
}

ContentClassificationLabelSetting represents a content classification label setting for modifying a channel.

type CreateChannelStreamScheduleSegmentParams

type CreateChannelStreamScheduleSegmentParams struct {
	BroadcasterID string    `json:"-"`
	StartTime     time.Time `json:"start_time"`
	Timezone      string    `json:"timezone"`
	Duration      int       `json:"duration"` // minutes (30-1380)
	IsRecurring   bool      `json:"is_recurring,omitempty"`
	CategoryID    string    `json:"category_id,omitempty"`
	Title         string    `json:"title,omitempty"`
}

CreateChannelStreamScheduleSegmentParams contains parameters for CreateChannelStreamScheduleSegment.

type CreateClipFromVODParams

type CreateClipFromVODParams struct {
	EditorID      string   `json:"editor_id"`          // Required: User ID of the editor
	BroadcasterID string   `json:"broadcaster_id"`     // Required: User ID of the channel
	VODID         string   `json:"vod_id"`             // Required: ID of the VOD to clip
	VODOffset     int      `json:"vod_offset"`         // Required: Offset in seconds where clip ends
	Title         string   `json:"title"`              // Required: Clip title
	Duration      *float64 `json:"duration,omitempty"` // Optional: Clip length (5-60 seconds, default 30)
}

CreateClipFromVODParams contains parameters for CreateClipFromVOD.

type CreateClipParams

type CreateClipParams struct {
	BroadcasterID string
	HasDelay      bool // Add delay before clip creation (for live streams)
}

CreateClipParams contains parameters for CreateClip.

type CreateClipResponse

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

CreateClipResponse represents the response from CreateClip.

type CreateConduitParams

type CreateConduitParams struct {
	ShardCount int `json:"shard_count"`
}

CreateConduitParams contains parameters for CreateConduit.

type CreateCustomRewardParams

type CreateCustomRewardParams struct {
	BroadcasterID                     string `json:"-"`
	Title                             string `json:"title"`
	Cost                              int    `json:"cost"`
	Prompt                            string `json:"prompt,omitempty"`
	IsEnabled                         *bool  `json:"is_enabled,omitempty"`
	BackgroundColor                   string `json:"background_color,omitempty"`
	IsUserInputRequired               *bool  `json:"is_user_input_required,omitempty"`
	IsMaxPerStreamEnabled             *bool  `json:"is_max_per_stream_enabled,omitempty"`
	MaxPerStream                      *int   `json:"max_per_stream,omitempty"`
	IsMaxPerUserPerStreamEnabled      *bool  `json:"is_max_per_user_per_stream_enabled,omitempty"`
	MaxPerUserPerStream               *int   `json:"max_per_user_per_stream,omitempty"`
	IsGlobalCooldownEnabled           *bool  `json:"is_global_cooldown_enabled,omitempty"`
	GlobalCooldownSeconds             *int   `json:"global_cooldown_seconds,omitempty"`
	ShouldRedemptionsSkipRequestQueue *bool  `json:"should_redemptions_skip_request_queue,omitempty"`
}

CreateCustomRewardParams contains parameters for CreateCustomReward.

type CreateEventSubSubscriptionParams

type CreateEventSubSubscriptionParams struct {
	Type      string                  `json:"type"`
	Version   string                  `json:"version"`
	Condition map[string]string       `json:"condition"`
	Transport CreateEventSubTransport `json:"transport"`
}

CreateEventSubSubscriptionParams contains parameters for CreateEventSubSubscription.

type CreateEventSubTransport

type CreateEventSubTransport struct {
	Method    string `json:"method"` // webhook, websocket, conduit
	Callback  string `json:"callback,omitempty"`
	Secret    string `json:"secret,omitempty"`
	SessionID string `json:"session_id,omitempty"`
	ConduitID string `json:"conduit_id,omitempty"`
}

CreateEventSubTransport represents the transport when creating a subscription.

type CreatePollChoice

type CreatePollChoice struct {
	Title string `json:"title"`
}

CreatePollChoice represents a choice when creating a poll.

type CreatePollParams

type CreatePollParams struct {
	BroadcasterID              string             `json:"broadcaster_id"`
	Title                      string             `json:"title"`
	Choices                    []CreatePollChoice `json:"choices"`
	Duration                   int                `json:"duration"` // 15-1800 seconds
	ChannelPointsVotingEnabled bool               `json:"channel_points_voting_enabled,omitempty"`
	ChannelPointsPerVote       int                `json:"channel_points_per_vote,omitempty"`
}

CreatePollParams contains parameters for CreatePoll.

type CreatePredictionOutcome

type CreatePredictionOutcome struct {
	Title string `json:"title"`
}

CreatePredictionOutcome represents an outcome when creating a prediction.

type CreatePredictionParams

type CreatePredictionParams struct {
	BroadcasterID    string                    `json:"broadcaster_id"`
	Title            string                    `json:"title"`
	Outcomes         []CreatePredictionOutcome `json:"outcomes"`          // 2-10 outcomes
	PredictionWindow int                       `json:"prediction_window"` // 30-1800 seconds
}

CreatePredictionParams contains parameters for CreatePrediction.

type CreateStreamMarkerParams

type CreateStreamMarkerParams struct {
	UserID      string `json:"user_id"`
	Description string `json:"description,omitempty"`
}

CreateStreamMarkerParams contains parameters for CreateStreamMarker.

type CreatorGoal

type CreatorGoal struct {
	ID               string    `json:"id"`
	BroadcasterID    string    `json:"broadcaster_id"`
	BroadcasterName  string    `json:"broadcaster_name"`
	BroadcasterLogin string    `json:"broadcaster_login"`
	Type             string    `json:"type"` // follower, subscription, subscription_count, new_subscription, new_subscription_count
	Description      string    `json:"description"`
	CurrentAmount    int       `json:"current_amount"`
	TargetAmount     int       `json:"target_amount"`
	CreatedAt        time.Time `json:"created_at"`
}

CreatorGoal represents a creator goal.

type CustomReward

type CustomReward struct {
	BroadcasterID                     string              `json:"broadcaster_id"`
	BroadcasterLogin                  string              `json:"broadcaster_login"`
	BroadcasterName                   string              `json:"broadcaster_name"`
	ID                                string              `json:"id"`
	Title                             string              `json:"title"`
	Prompt                            string              `json:"prompt"`
	Cost                              int                 `json:"cost"`
	Image                             *RewardImage        `json:"image,omitempty"`
	DefaultImage                      RewardImage         `json:"default_image"`
	BackgroundColor                   string              `json:"background_color"`
	IsEnabled                         bool                `json:"is_enabled"`
	IsUserInputRequired               bool                `json:"is_user_input_required"`
	MaxPerStreamSetting               MaxPerStream        `json:"max_per_stream_setting"`
	MaxPerUserPerStreamSetting        MaxPerUserPerStream `json:"max_per_user_per_stream_setting"`
	GlobalCooldownSetting             GlobalCooldown      `json:"global_cooldown_setting"`
	IsPaused                          bool                `json:"is_paused"`
	IsInStock                         bool                `json:"is_in_stock"`
	ShouldRedemptionsSkipRequestQueue bool                `json:"should_redemptions_skip_request_queue"`
	RedemptionsRedeemedCurrentStream  int                 `json:"redemptions_redeemed_current_stream,omitempty"`
	CooldownExpiresAt                 *time.Time          `json:"cooldown_expires_at,omitempty"`
}

CustomReward represents a channel points custom reward.

type CustomRewardRedemption

type CustomRewardRedemption struct {
	BroadcasterID    string    `json:"broadcaster_id"`
	BroadcasterLogin string    `json:"broadcaster_login"`
	BroadcasterName  string    `json:"broadcaster_name"`
	ID               string    `json:"id"`
	UserID           string    `json:"user_id"`
	UserLogin        string    `json:"user_login"`
	UserName         string    `json:"user_name"`
	UserInput        string    `json:"user_input"`
	Status           string    `json:"status"` // CANCELED, FULFILLED, UNFULFILLED
	RedeemedAt       time.Time `json:"redeemed_at"`
	Reward           struct {
		ID     string `json:"id"`
		Title  string `json:"title"`
		Prompt string `json:"prompt"`
		Cost   int    `json:"cost"`
	} `json:"reward"`
}

CustomRewardRedemption represents a redemption of a custom reward.

type DateRange

type DateRange struct {
	StartedAt time.Time `json:"started_at"`
	EndedAt   time.Time `json:"ended_at"`
}

DateRange represents a date range.

type DeleteChatMessagesParams

type DeleteChatMessagesParams struct {
	BroadcasterID string
	ModeratorID   string
	MessageID     string // Optional: Specific message to delete. If empty, deletes all messages.
}

DeleteChatMessagesParams contains parameters for DeleteChatMessages.

type DeleteVideosResponse

type DeleteVideosResponse []string

DeleteVideosResponse represents the response from DeleteVideos.

type DeviceCodeResponse

type DeviceCodeResponse struct {
	DeviceCode      string `json:"device_code"`
	ExpiresIn       int    `json:"expires_in"`
	Interval        int    `json:"interval"`
	UserCode        string `json:"user_code"`
	VerificationURI string `json:"verification_uri"`
}

DeviceCodeResponse represents the response from the device authorization endpoint.

type DropEntitlement

type DropEntitlement struct {
	OrganizationID string    `json:"organization_id"`
	CategoryID     string    `json:"category_id"`
	CategoryName   string    `json:"category_name"`
	CampaignID     string    `json:"campaign_id"`
	UserID         string    `json:"user_id"`
	UserLogin      string    `json:"user_login"`
	UserName       string    `json:"user_name"`
	EntitlementID  string    `json:"entitlement_id"`
	BenefitID      string    `json:"benefit_id"`
	CreatedAt      time.Time `json:"created_at"`
}

DropEntitlement represents a single drop entitlement.

type DropEntitlementGrantEvent

type DropEntitlementGrantEvent struct {
	ID   string            `json:"id"`
	Data []DropEntitlement `json:"data"`
}

DropEntitlementGrantEvent is sent when a drop entitlement is granted.

type DropsEntitlement

type DropsEntitlement struct {
	ID                string    `json:"id"`
	BenefitID         string    `json:"benefit_id"`
	Timestamp         time.Time `json:"timestamp"`
	UserID            string    `json:"user_id"`
	GameID            string    `json:"game_id"`
	FulfillmentStatus string    `json:"fulfillment_status"` // CLAIMED, FULFILLED
	LastUpdated       time.Time `json:"last_updated"`
}

DropsEntitlement represents a drops entitlement.

type Emote

type Emote struct {
	ID         string      `json:"id"`
	Name       string      `json:"name"`
	Images     EmoteImages `json:"images"`
	Tier       string      `json:"tier,omitempty"`
	EmoteType  string      `json:"emote_type,omitempty"`
	EmoteSetID string      `json:"emote_set_id,omitempty"`
	Format     []string    `json:"format"`
	Scale      []string    `json:"scale"`
	ThemeMode  []string    `json:"theme_mode"`
}

Emote represents a Twitch emote.

type EmoteImages

type EmoteImages struct {
	URL1x string `json:"url_1x"`
	URL2x string `json:"url_2x"`
	URL4x string `json:"url_4x"`
}

EmoteImages contains emote image URLs.

type EndPollParams

type EndPollParams struct {
	BroadcasterID string `json:"broadcaster_id"`
	ID            string `json:"id"`
	Status        string `json:"status"` // TERMINATED or ARCHIVED
}

EndPollParams contains parameters for EndPoll.

type EndPredictionParams

type EndPredictionParams struct {
	BroadcasterID    string `json:"broadcaster_id"`
	ID               string `json:"id"`
	Status           string `json:"status"`                       // RESOLVED, CANCELED, or LOCKED
	WinningOutcomeID string `json:"winning_outcome_id,omitempty"` // Required if status is RESOLVED
}

EndPredictionParams contains parameters for EndPrediction.

type ErrorResponse

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

ErrorResponse represents an API error response.

type EventSubBroadcaster

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

EventSubBroadcaster represents a broadcaster in EventSub events.

type EventSubChoice

type EventSubChoice struct {
	ID                 string `json:"id"`
	Title              string `json:"title"`
	BitsVotes          int    `json:"bits_votes"`
	ChannelPointsVotes int    `json:"channel_points_votes"`
	Votes              int    `json:"votes"`
}

EventSubChoice represents a poll choice.

type EventSubContribution

type EventSubContribution struct {
	EventSubUser
	Type  string `json:"type"` // bits, subscription, other
	Total int    `json:"total"`
}

EventSubContribution represents a Hype Train contribution.

type EventSubGlobalCooldown

type EventSubGlobalCooldown struct {
	IsEnabled bool `json:"is_enabled"`
	Seconds   int  `json:"seconds"`
}

EventSubGlobalCooldown represents global cooldown settings.

type EventSubImage

type EventSubImage struct {
	URL1x string `json:"url_1x"`
	URL2x string `json:"url_2x"`
	URL4x string `json:"url_4x"`
}

EventSubImage represents image URLs for rewards.

type EventSubMaxPerStream

type EventSubMaxPerStream struct {
	IsEnabled bool `json:"is_enabled"`
	Value     int  `json:"value"`
}

EventSubMaxPerStream represents max redemptions per stream settings.

type EventSubModerator

type EventSubModerator struct {
	ModeratorUserID    string `json:"moderator_user_id"`
	ModeratorUserLogin string `json:"moderator_user_login"`
	ModeratorUserName  string `json:"moderator_user_name"`
}

EventSubModerator represents a moderator in EventSub events.

type EventSubOutcome

type EventSubOutcome struct {
	ID            string              `json:"id"`
	Title         string              `json:"title"`
	Color         string              `json:"color"` // blue, pink
	Users         int                 `json:"users,omitempty"`
	ChannelPoints int                 `json:"channel_points,omitempty"`
	TopPredictors []EventSubPredictor `json:"top_predictors,omitempty"`
}

EventSubOutcome represents a prediction outcome.

type EventSubPredictor

type EventSubPredictor struct {
	EventSubUser
	ChannelPointsUsed int  `json:"channel_points_used"`
	ChannelPointsWon  *int `json:"channel_points_won,omitempty"`
}

EventSubPredictor represents a top predictor.

type EventSubResponse

type EventSubResponse struct {
	Data         []EventSubSubscription `json:"data"`
	Total        int                    `json:"total"`
	TotalCost    int                    `json:"total_cost"`
	MaxTotalCost int                    `json:"max_total_cost"`
	Pagination   *Pagination            `json:"pagination,omitempty"`
}

EventSubResponse represents the response from EventSub operations.

type EventSubReward

type EventSubReward struct {
	ID     string `json:"id"`
	Title  string `json:"title"`
	Cost   int    `json:"cost"`
	Prompt string `json:"prompt"`
}

EventSubReward represents reward details in redemption events.

type EventSubSubscription

type EventSubSubscription struct {
	ID        string            `json:"id"`
	Status    string            `json:"status"`
	Type      string            `json:"type"`
	Version   string            `json:"version"`
	Condition map[string]string `json:"condition"`
	CreatedAt time.Time         `json:"created_at"`
	Transport EventSubTransport `json:"transport"`
	Cost      int               `json:"cost"`
}

EventSubSubscription represents an EventSub subscription.

type EventSubTransport

type EventSubTransport struct {
	Method         string `json:"method"` // webhook, websocket, conduit
	Callback       string `json:"callback,omitempty"`
	Secret         string `json:"secret,omitempty"`
	SessionID      string `json:"session_id,omitempty"`
	ConduitID      string `json:"conduit_id,omitempty"`
	ConnectedAt    string `json:"connected_at,omitempty"`
	DisconnectedAt string `json:"disconnected_at,omitempty"`
}

EventSubTransport represents the transport for an EventSub subscription.

type EventSubUser

type EventSubUser struct {
	UserID    string `json:"user_id"`
	UserLogin string `json:"user_login"`
	UserName  string `json:"user_name"`
}

EventSubUser represents a user in EventSub events.

type EventSubVoting

type EventSubVoting struct {
	IsEnabled     bool `json:"is_enabled"`
	AmountPerVote int  `json:"amount_per_vote"`
}

EventSubVoting represents voting settings.

type EventSubWSOption

type EventSubWSOption func(*EventSubWebSocketClient)

EventSubWSOption configures the WebSocket client.

func WithWSErrorHandler

func WithWSErrorHandler(fn func(error)) EventSubWSOption

WithWSErrorHandler sets the handler for errors.

func WithWSKeepaliveHandler

func WithWSKeepaliveHandler(fn func()) EventSubWSOption

WithWSKeepaliveHandler sets the handler for keepalive messages.

func WithWSNotificationHandler

func WithWSNotificationHandler(fn func(*EventSubSubscription, json.RawMessage)) EventSubWSOption

WithWSNotificationHandler sets the handler for notification messages.

func WithWSReconnectHandler

func WithWSReconnectHandler(fn func(string)) EventSubWSOption

WithWSReconnectHandler sets the handler for reconnect messages.

func WithWSRevocationHandler

func WithWSRevocationHandler(fn func(*EventSubSubscription)) EventSubWSOption

WithWSRevocationHandler sets the handler for revocation messages.

func WithWSURL

func WithWSURL(url string) EventSubWSOption

WithWSURL sets a custom WebSocket URL (useful for testing).

func WithWSWelcomeHandler

func WithWSWelcomeHandler(fn func(*WebSocketSession)) EventSubWSOption

WithWSWelcomeHandler sets the handler for welcome messages.

type EventSubWebSocket

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

EventSubWebSocket provides a higher-level interface for EventSub WebSocket.

func NewEventSubWebSocket

func NewEventSubWebSocket(helixClient *Client, opts ...EventSubWebSocketOption) *EventSubWebSocket

NewEventSubWebSocket creates a new high-level EventSub WebSocket manager. Returns nil if helixClient is nil.

func (*EventSubWebSocket) Close

func (e *EventSubWebSocket) Close() error

Close closes the WebSocket connection.

func (*EventSubWebSocket) Connect

func (e *EventSubWebSocket) Connect(ctx context.Context) error

Connect establishes the WebSocket connection. If already connected, the existing connection is closed first.

func (*EventSubWebSocket) Subscribe

func (e *EventSubWebSocket) Subscribe(ctx context.Context, eventType, version string, condition map[string]string, handler func(json.RawMessage)) error

Subscribe creates a subscription for the given event type. Returns an error if not connected.

type EventSubWebSocketClient

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

EventSubWebSocketClient manages an EventSub WebSocket connection.

func NewEventSubWebSocketClient

func NewEventSubWebSocketClient(opts ...EventSubWSOption) *EventSubWebSocketClient

NewEventSubWebSocketClient creates a new EventSub WebSocket client.

func (*EventSubWebSocketClient) Close

func (c *EventSubWebSocketClient) Close() error

Close closes the WebSocket connection.

func (*EventSubWebSocketClient) Connect

func (c *EventSubWebSocketClient) Connect(ctx context.Context) (string, error)

Connect establishes a WebSocket connection to EventSub. Returns the session ID that should be used when creating subscriptions. This method is safe for concurrent use - only one connection attempt will proceed.

func (*EventSubWebSocketClient) IsConnected

func (c *EventSubWebSocketClient) IsConnected() bool

IsConnected returns whether the client is connected.

func (*EventSubWebSocketClient) Reconnect

func (c *EventSubWebSocketClient) Reconnect(ctx context.Context, url string) (string, error)

Reconnect connects to a new URL (typically from a reconnect message).

func (*EventSubWebSocketClient) SessionID

func (c *EventSubWebSocketClient) SessionID() string

SessionID returns the current session ID.

type EventSubWebSocketOption added in v1.0.2

type EventSubWebSocketOption func(*EventSubWebSocket)

EventSubWebSocketOption configures the high-level EventSub WebSocket manager.

func WithEventSubErrorHandler added in v1.0.2

func WithEventSubErrorHandler(fn func(error)) EventSubWebSocketOption

WithEventSubErrorHandler sets the handler for WebSocket errors.

func WithEventSubReconnectHandler added in v1.0.2

func WithEventSubReconnectHandler(fn func()) EventSubWebSocketOption

WithEventSubReconnectHandler sets the handler called after a successful reconnect.

func WithEventSubRevocationHandler added in v1.0.2

func WithEventSubRevocationHandler(fn func(eventType string, reason string)) EventSubWebSocketOption

WithEventSubRevocationHandler sets the handler for subscription revocations. The handler receives the event type that was revoked and the reason.

type EventSubWebhookHandler

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

EventSubWebhookHandler handles EventSub webhook requests.

func NewEventSubWebhookHandler

func NewEventSubWebhookHandler(opts ...EventSubWebhookOption) *EventSubWebhookHandler

NewEventSubWebhookHandler creates a new EventSub webhook handler.

func (*EventSubWebhookHandler) ServeHTTP

ServeHTTP implements http.Handler for the webhook handler.

type EventSubWebhookMessage

type EventSubWebhookMessage struct {
	MessageID           string
	MessageTimestamp    time.Time
	MessageType         string
	SubscriptionType    string
	SubscriptionVersion string
	Subscription        EventSubSubscription
	Challenge           string
	Event               json.RawMessage
}

EventSubWebhookMessage represents a message received from EventSub webhooks.

type EventSubWebhookOption

type EventSubWebhookOption func(*EventSubWebhookHandler)

EventSubWebhookOption configures the webhook handler.

func WithMaxTimestampAge

func WithMaxTimestampAge(d time.Duration) EventSubWebhookOption

WithMaxTimestampAge sets the maximum age for message timestamps (default: 10 minutes).

func WithNotificationHandler

func WithNotificationHandler(fn func(*EventSubWebhookMessage)) EventSubWebhookOption

WithNotificationHandler sets the handler for notification messages.

func WithRevocationHandler

func WithRevocationHandler(fn func(*EventSubWebhookMessage)) EventSubWebhookOption

WithRevocationHandler sets the handler for subscription revocations.

func WithVerificationHandler

func WithVerificationHandler(fn func(*EventSubWebhookMessage) bool) EventSubWebhookOption

WithVerificationHandler sets the handler for verification challenges. Return true to accept the subscription, false to reject.

func WithWebhookSecret

func WithWebhookSecret(secret string) EventSubWebhookOption

WithWebhookSecret sets the secret used for signature verification.

type EventSubWebhookPayload

type EventSubWebhookPayload struct {
	Subscription EventSubSubscription `json:"subscription"`
	Challenge    string               `json:"challenge,omitempty"`
	Event        json.RawMessage      `json:"event,omitempty"`
}

EventSubWebhookPayload represents the JSON payload from EventSub.

type Extension

type Extension struct {
	AuthorName                string            `json:"author_name"`
	BitsEnabled               bool              `json:"bits_enabled"`
	CanInstall                bool              `json:"can_install"`
	ConfigurationLocation     string            `json:"configuration_location"`
	Description               string            `json:"description"`
	EULAToSURL                string            `json:"eula_tos_url"`
	HasChatSupport            bool              `json:"has_chat_support"`
	IconURL                   string            `json:"icon_url"`
	IconURLs                  map[string]string `json:"icon_urls"`
	ID                        string            `json:"id"`
	Name                      string            `json:"name"`
	PrivacyPolicyURL          string            `json:"privacy_policy_url"`
	RequestIdentityLink       bool              `json:"request_identity_link"`
	ScreenshotURLs            []string          `json:"screenshot_urls"`
	State                     string            `json:"state"`
	SubscriptionsSupportLevel string            `json:"subscriptions_support_level"`
	Summary                   string            `json:"summary"`
	SupportEmail              string            `json:"support_email"`
	Version                   string            `json:"version"`
	ViewerSummary             string            `json:"viewer_summary"`
	Views                     ExtensionViews    `json:"views"`
	AllowlistedConfigURLs     []string          `json:"allowlisted_config_urls"`
	AllowlistedPanelURLs      []string          `json:"allowlisted_panel_urls"`
}

Extension represents a Twitch extension.

type ExtensionAnalytics

type ExtensionAnalytics struct {
	ExtensionID string    `json:"extension_id"`
	URL         string    `json:"url"`
	Type        string    `json:"type"`
	DateRange   DateRange `json:"date_range"`
}

ExtensionAnalytics represents extension analytics data.

type ExtensionBitsCost

type ExtensionBitsCost struct {
	Amount int    `json:"amount"`
	Type   string `json:"type"` // bits
}

ExtensionBitsCost represents the cost of an extension Bits product.

type ExtensionBitsProduct

type ExtensionBitsProduct struct {
	SKU           string            `json:"sku"`
	Cost          ExtensionBitsCost `json:"cost"`
	InDevelopment bool              `json:"in_development"`
	DisplayName   string            `json:"display_name"`
	Expiration    string            `json:"expiration,omitempty"`
	IsBroadcast   bool              `json:"is_broadcast"`
}

ExtensionBitsProduct represents an extension Bits product.

type ExtensionBitsTransactionCreateEvent

type ExtensionBitsTransactionCreateEvent struct {
	ID                string `json:"id"`
	ExtensionClientID string `json:"extension_client_id"`
	EventSubBroadcaster
	EventSubUser
	Product ExtensionProduct `json:"product"`
}

ExtensionBitsTransactionCreateEvent is sent when an extension bits transaction occurs.

type ExtensionConfigurationSegment

type ExtensionConfigurationSegment struct {
	Segment       string `json:"segment"` // broadcaster, developer, global
	BroadcasterID string `json:"broadcaster_id,omitempty"`
	Content       string `json:"content"`
	Version       string `json:"version"`
}

ExtensionConfigurationSegment represents a configuration segment.

type ExtensionJWT

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

ExtensionJWT represents an extension JWT configuration and signer.

func NewExtensionJWT

func NewExtensionJWT(extensionID, base64Secret, ownerID string) (*ExtensionJWT, error)

NewExtensionJWT creates a new extension JWT signer. The secret should be the base64-encoded secret from the Extension Settings page.

func (*ExtensionJWT) CreateBroadcasterToken

func (e *ExtensionJWT) CreateBroadcasterToken(channelID string, expiration time.Duration) (string, error)

CreateBroadcasterToken creates a token for broadcaster-level operations.

func (*ExtensionJWT) CreateEBSToken

func (e *ExtensionJWT) CreateEBSToken(expiration time.Duration) (string, error)

CreateEBSToken creates a token for Extension Backend Service operations. This is the most common token type for server-to-server extension API calls.

func (*ExtensionJWT) CreatePubSubToken

func (e *ExtensionJWT) CreatePubSubToken(channelID string, listen, send []string, expiration time.Duration) (string, error)

CreatePubSubToken creates a token for PubSub operations.

func (*ExtensionJWT) CreateToken

func (e *ExtensionJWT) CreateToken(claims *ExtensionJWTClaims) (string, error)

CreateToken creates a signed JWT with the given claims. Returns an error if claims is nil.

func (*ExtensionJWT) ExtensionID

func (e *ExtensionJWT) ExtensionID() string

ExtensionID returns the extension ID.

func (*ExtensionJWT) OwnerID

func (e *ExtensionJWT) OwnerID() string

OwnerID returns the extension owner's user ID.

type ExtensionJWTClaims

type ExtensionJWTClaims struct {
	// Required claims
	Exp    int64            `json:"exp"`     // Expiration time (Unix timestamp)
	UserID string           `json:"user_id"` // Twitch user ID
	Role   ExtensionJWTRole `json:"role"`    // User's role

	// Optional claims
	ChannelID    string `json:"channel_id,omitempty"`     // Channel ID for channel-specific operations
	OpaqueUserID string `json:"opaque_user_id,omitempty"` // Opaque user identifier
	IsUnlinked   bool   `json:"is_unlinked,omitempty"`    // Whether user has not shared identity

	// PubSub specific
	PubsubPermsListen []string `json:"pubsub_perms_listen,omitempty"` // Channels to listen to
	PubsubPermsSend   []string `json:"pubsub_perms_send,omitempty"`   // Channels to send to
}

ExtensionJWTClaims represents the claims in a Twitch Extension JWT.

func ParseExtensionJWT

func ParseExtensionJWT(tokenString, base64Secret string) (*ExtensionJWTClaims, error)

ParseExtensionJWT parses and validates an extension JWT. This is useful for verifying JWTs received from the Twitch extension frontend.

type ExtensionJWTRole

type ExtensionJWTRole string

ExtensionJWTRole defines the role in an extension JWT.

const (
	// ExtensionRoleExternal is used for EBS (Extension Backend Service) signed tokens.
	ExtensionRoleExternal ExtensionJWTRole = "external"
	// ExtensionRoleBroadcaster is used when acting as the broadcaster.
	ExtensionRoleBroadcaster ExtensionJWTRole = "broadcaster"
	// ExtensionRoleModerator is used when acting as a moderator.
	ExtensionRoleModerator ExtensionJWTRole = "moderator"
	// ExtensionRoleViewer is used when acting as a viewer.
	ExtensionRoleViewer ExtensionJWTRole = "viewer"
)

type ExtensionLiveChannel

type ExtensionLiveChannel struct {
	BroadcasterID   string `json:"broadcaster_id"`
	BroadcasterName string `json:"broadcaster_name"`
	GameName        string `json:"game_name"`
	GameID          string `json:"game_id"`
	Title           string `json:"title"`
}

ExtensionLiveChannel represents a live channel using an extension.

type ExtensionProduct

type ExtensionProduct struct {
	Name          string `json:"name"`
	Sku           string `json:"sku"`
	Bits          int    `json:"bits"`
	InDevelopment bool   `json:"in_development"`
}

ExtensionProduct represents an extension product.

type ExtensionSecret

type ExtensionSecret struct {
	FormatVersion int                   `json:"format_version"`
	Secrets       []ExtensionSecretData `json:"secrets"`
}

ExtensionSecret represents an extension secret.

type ExtensionSecretData

type ExtensionSecretData struct {
	Content   string `json:"content"`
	ActiveAt  string `json:"active_at"`
	ExpiresAt string `json:"expires_at"`
}

ExtensionSecretData represents the secret data.

type ExtensionTransaction

type ExtensionTransaction struct {
	ID               string                      `json:"id"`
	Timestamp        string                      `json:"timestamp"`
	BroadcasterID    string                      `json:"broadcaster_id"`
	BroadcasterLogin string                      `json:"broadcaster_login"`
	BroadcasterName  string                      `json:"broadcaster_name"`
	UserID           string                      `json:"user_id"`
	UserLogin        string                      `json:"user_login"`
	UserName         string                      `json:"user_name"`
	ProductType      string                      `json:"product_type"`
	ProductData      ExtensionTransactionProduct `json:"product_data"`
}

ExtensionTransaction represents an extension transaction.

type ExtensionTransactionProduct

type ExtensionTransactionProduct struct {
	SKU           string            `json:"sku"`
	Cost          ExtensionBitsCost `json:"cost"`
	DisplayName   string            `json:"display_name"`
	InDevelopment bool              `json:"in_development"`
}

ExtensionTransactionProduct represents the product in a transaction.

type ExtensionView

type ExtensionView struct {
	ViewerURL              string `json:"viewer_url"`
	Height                 int    `json:"height,omitempty"`
	CanLinkExternalContent bool   `json:"can_link_external_content,omitempty"`
}

ExtensionView represents a single view configuration.

type ExtensionViews

type ExtensionViews struct {
	Mobile       ExtensionView `json:"mobile,omitempty"`
	Panel        ExtensionView `json:"panel,omitempty"`
	VideoOverlay ExtensionView `json:"video_overlay,omitempty"`
	Component    ExtensionView `json:"component,omitempty"`
}

ExtensionViews represents the views configuration for an extension.

type FollowedChannel

type FollowedChannel struct {
	BroadcasterID    string    `json:"broadcaster_id"`
	BroadcasterLogin string    `json:"broadcaster_login"`
	BroadcasterName  string    `json:"broadcaster_name"`
	FollowedAt       time.Time `json:"followed_at"`
}

FollowedChannel represents a channel that a user follows.

type Game

type Game struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	BoxArtURL string `json:"box_art_url"`
	IGDBId    string `json:"igdb_id,omitempty"`
}

Game represents a Twitch game/category.

type GameAnalytics

type GameAnalytics struct {
	GameID    string    `json:"game_id"`
	URL       string    `json:"url"`
	Type      string    `json:"type"`
	DateRange DateRange `json:"date_range"`
}

GameAnalytics represents game analytics data.

type GetAuthorizationByUserParams

type GetAuthorizationByUserParams struct {
	UserID string // Required: The ID of a user that granted the application OAuth permissions
}

GetAuthorizationByUserParams contains parameters for GetAuthorizationByUser.

type GetBannedUsersParams

type GetBannedUsersParams struct {
	BroadcasterID string
	UserIDs       []string // Filter by user IDs (max 100)
	*PaginationParams
}

GetBannedUsersParams contains parameters for GetBannedUsers.

type GetBitsLeaderboardParams

type GetBitsLeaderboardParams struct {
	Count     int       // Max entries (1-100)
	Period    string    // day, week, month, year, all
	StartedAt time.Time // Start of the date range
	UserID    string    // Filter to specific user
}

GetBitsLeaderboardParams contains parameters for GetBitsLeaderboard.

type GetBlockedTermsParams

type GetBlockedTermsParams struct {
	BroadcasterID string
	ModeratorID   string
	*PaginationParams
}

GetBlockedTermsParams contains parameters for GetBlockedTerms.

type GetBroadcasterSubscriptionsParams

type GetBroadcasterSubscriptionsParams struct {
	BroadcasterID string
	UserIDs       []string // Filter by user IDs (max 100)
	*PaginationParams
}

GetBroadcasterSubscriptionsParams contains parameters for GetBroadcasterSubscriptions.

type GetChannelFollowersParams

type GetChannelFollowersParams struct {
	BroadcasterID string // Required: The broadcaster's ID
	UserID        string // Optional: Filter by user ID
	*PaginationParams
}

GetChannelFollowersParams contains parameters for GetChannelFollowers.

type GetChannelInformationParams

type GetChannelInformationParams struct {
	BroadcasterIDs []string // Up to 100 broadcaster IDs
}

GetChannelInformationParams contains parameters for GetChannelInformation.

type GetChannelStreamScheduleParams

type GetChannelStreamScheduleParams struct {
	BroadcasterID string
	IDs           []string // Segment IDs
	StartTime     time.Time
	UTCOffset     string // e.g., "-04:00"
	*PaginationParams
}

GetChannelStreamScheduleParams contains parameters for GetChannelStreamSchedule.

type GetCharityCampaignDonationsParams added in v1.2.0

type GetCharityCampaignDonationsParams struct {
	BroadcasterID string
	*PaginationParams
}

GetCharityCampaignDonationsParams contains parameters for GetCharityCampaignDonations.

type GetCharityCampaignParams added in v1.2.0

type GetCharityCampaignParams struct {
	BroadcasterID string
	*PaginationParams
}

GetCharityCampaignParams contains parameters for GetCharityCampaign.

type GetChattersParams

type GetChattersParams struct {
	BroadcasterID string
	ModeratorID   string
	*PaginationParams
}

GetChattersParams contains parameters for GetChatters.

type GetClipsParams

type GetClipsParams struct {
	BroadcasterID string
	GameID        string
	IDs           []string // Clip IDs (max 100)
	StartedAt     time.Time
	EndedAt       time.Time
	IsFeatured    *bool
	*PaginationParams
}

GetClipsParams contains parameters for GetClips.

type GetConduitShardsParams

type GetConduitShardsParams struct {
	ConduitID string
	Status    string // enabled, webhook_callback_verification_pending, webhook_callback_verification_failed, notification_failures_exceeded, websocket_disconnected, websocket_failed_ping_pong, websocket_received_inbound_traffic, websocket_internal_error, websocket_network_timeout, websocket_network_error, websocket_failed_to_reconnect
	*PaginationParams
}

GetConduitShardsParams contains parameters for GetConduitShards.

type GetConduitShardsResponse

type GetConduitShardsResponse struct {
	Data       []ConduitShard `json:"data"`
	Pagination *Pagination    `json:"pagination,omitempty"`
}

GetConduitShardsResponse represents the response from GetConduitShards.

type GetContentClassificationLabelsParams

type GetContentClassificationLabelsParams struct {
	Locale string // Locale for the labels (e.g., "en-US")
}

GetContentClassificationLabelsParams contains parameters for GetContentClassificationLabels.

type GetCustomRewardParams added in v1.2.0

type GetCustomRewardParams struct {
	BroadcasterID         string
	IDs                   []string // Reward IDs (max 50)
	OnlyManageableRewards bool
}

GetCustomRewardParams contains parameters for GetCustomReward.

type GetCustomRewardRedemptionParams added in v1.2.0

type GetCustomRewardRedemptionParams struct {
	BroadcasterID string
	RewardID      string
	Status        string // CANCELED, FULFILLED, UNFULFILLED
	IDs           []string
	Sort          string // OLDEST, NEWEST
	*PaginationParams
}

GetCustomRewardRedemptionParams contains parameters for GetCustomRewardRedemption.

type GetDropsEntitlementsParams

type GetDropsEntitlementsParams struct {
	ID                string // Entitlement ID
	UserID            string // Filter by user
	GameID            string // Filter by game
	FulfillmentStatus string // CLAIMED, FULFILLED
	*PaginationParams
}

GetDropsEntitlementsParams contains parameters for GetDropsEntitlements.

type GetEventSubSubscriptionsParams

type GetEventSubSubscriptionsParams struct {
	Status string // Filter by status
	Type   string // Filter by subscription type
	UserID string // Filter by user ID
	*PaginationParams
}

GetEventSubSubscriptionsParams contains parameters for GetEventSubSubscriptions.

type GetExtensionAnalyticsParams

type GetExtensionAnalyticsParams struct {
	ExtensionID string
	Type        string // overview_v2
	StartedAt   time.Time
	EndedAt     time.Time
	*PaginationParams
}

GetExtensionAnalyticsParams contains parameters for GetExtensionAnalytics.

type GetExtensionBitsProductsParams

type GetExtensionBitsProductsParams struct {
	ShouldIncludeAll bool // Include disabled/expired products
}

GetExtensionBitsProductsParams contains parameters for GetExtensionBitsProducts.

type GetExtensionConfigurationSegmentParams

type GetExtensionConfigurationSegmentParams struct {
	ExtensionID   string
	Segment       []string // broadcaster, developer, global
	BroadcasterID string   // Required if segment includes "broadcaster"
}

GetExtensionConfigurationSegmentParams contains parameters for GetExtensionConfigurationSegment.

type GetExtensionLiveChannelsParams

type GetExtensionLiveChannelsParams struct {
	ExtensionID string
	*PaginationParams
}

GetExtensionLiveChannelsParams contains parameters for GetExtensionLiveChannels.

type GetExtensionTransactionsParams

type GetExtensionTransactionsParams struct {
	ExtensionID string
	IDs         []string // Transaction IDs (max 100)
	*PaginationParams
}

GetExtensionTransactionsParams contains parameters for GetExtensionTransactions.

type GetFollowedChannelsParams

type GetFollowedChannelsParams struct {
	UserID        string // Required: The user's ID
	BroadcasterID string // Optional: Filter by broadcaster ID
	*PaginationParams
}

GetFollowedChannelsParams contains parameters for GetFollowedChannels.

type GetFollowedStreamsParams

type GetFollowedStreamsParams struct {
	UserID string // Required: The user's ID
	*PaginationParams
}

GetFollowedStreamsParams contains parameters for GetFollowedStreams.

type GetGameAnalyticsParams

type GetGameAnalyticsParams struct {
	GameID    string
	Type      string // overview_v2
	StartedAt time.Time
	EndedAt   time.Time
	*PaginationParams
}

GetGameAnalyticsParams contains parameters for GetGameAnalytics.

type GetGamesParams

type GetGamesParams struct {
	IDs     []string // Game IDs (max 100)
	Names   []string // Game names (max 100)
	IGDBIDs []string // IGDB IDs (max 100)
}

GetGamesParams contains parameters for GetGames.

type GetHypeTrainEventsParams

type GetHypeTrainEventsParams struct {
	BroadcasterID string
	*PaginationParams
}

GetHypeTrainEventsParams contains parameters for GetHypeTrainEvents.

type GetModeratedChannelsParams

type GetModeratedChannelsParams struct {
	UserID string
	*PaginationParams
}

GetModeratedChannelsParams contains parameters for GetModeratedChannels.

type GetModeratorsParams

type GetModeratorsParams struct {
	BroadcasterID string
	UserIDs       []string // Filter by user IDs (max 100)
	*PaginationParams
}

GetModeratorsParams contains parameters for GetModerators.

type GetPollsParams

type GetPollsParams struct {
	BroadcasterID string
	IDs           []string // Poll IDs (max 100)
	*PaginationParams
}

GetPollsParams contains parameters for GetPolls.

type GetPredictionsParams

type GetPredictionsParams struct {
	BroadcasterID string
	IDs           []string // Prediction IDs (max 100)
	*PaginationParams
}

GetPredictionsParams contains parameters for GetPredictions.

type GetRequest

type GetRequest struct {
	Endpoint string
	Query    url.Values
	Result   interface{}
}

GetRequest represents a GET request for batch operations.

type GetStreamMarkersParams

type GetStreamMarkersParams struct {
	UserID  string // Either UserID or VideoID is required
	VideoID string
	*PaginationParams
}

GetStreamMarkersParams contains parameters for GetStreamMarkers.

type GetStreamsParams

type GetStreamsParams struct {
	UserIDs    []string // Filter by user IDs (max 100)
	UserLogins []string // Filter by user logins (max 100)
	GameIDs    []string // Filter by game IDs (max 100)
	Type       string   // "all" or "live"
	Language   []string // Filter by language
	*PaginationParams
}

GetStreamsParams contains parameters for GetStreams.

type GetTeamsParams

type GetTeamsParams struct {
	Name string // Team name
	ID   string // Team ID
}

GetTeamsParams contains parameters for GetTeams.

type GetTopGamesParams

type GetTopGamesParams struct {
	*PaginationParams
}

GetTopGamesParams contains parameters for GetTopGames.

type GetUnbanRequestsParams

type GetUnbanRequestsParams struct {
	BroadcasterID string
	ModeratorID   string
	Status        string // pending, approved, denied, acknowledged, canceled
	UserID        string // Filter by user
	*PaginationParams
}

GetUnbanRequestsParams contains parameters for GetUnbanRequests.

type GetUserBlockListParams

type GetUserBlockListParams struct {
	BroadcasterID string
	*PaginationParams
}

GetUserBlockListParams contains parameters for GetUserBlockList.

type GetUserEmotesParams

type GetUserEmotesParams struct {
	UserID        string
	BroadcasterID string // Optional: filter to specific channel
	*PaginationParams
}

GetUserEmotesParams contains parameters for GetUserEmotes.

type GetUsersParams

type GetUsersParams struct {
	IDs    []string // User IDs (max 100)
	Logins []string // User login names (max 100)
}

GetUsersParams contains parameters for GetUsers.

type GetVIPsParams

type GetVIPsParams struct {
	BroadcasterID string
	UserIDs       []string // Filter by user IDs (max 100)
	*PaginationParams
}

GetVIPsParams contains parameters for GetVIPs.

type GetVideosParams

type GetVideosParams struct {
	IDs      []string // Video IDs (max 100)
	UserID   string
	GameID   string
	Language string
	Period   string // all, day, week, month
	Sort     string // time, trending, views
	Type     string // all, archive, highlight, upload
	*PaginationParams
}

GetVideosParams contains parameters for GetVideos.

type GlobalCooldown

type GlobalCooldown struct {
	IsEnabled             bool `json:"is_enabled"`
	GlobalCooldownSeconds int  `json:"global_cooldown_seconds"`
}

GlobalCooldown represents global cooldown settings.

type GlobalUserState

type GlobalUserState struct {
	UserID      string            // User's Twitch ID
	DisplayName string            // Display name
	Color       string            // Chat color
	Badges      map[string]string // Global badges
	BadgeInfo   map[string]string // Badge info
	EmoteSets   []string          // Available emote set IDs
	Raw         string            // Raw IRC message
}

GlobalUserState represents a GLOBALUSERSTATE message.

type GuestStarAudioSettings

type GuestStarAudioSettings struct {
	IsHostEnabled bool `json:"is_host_enabled"`
	IsSelfMuted   bool `json:"is_self_muted"`
	IsAvailable   bool `json:"is_available"`
}

GuestStarAudioSettings represents audio settings for a guest.

type GuestStarGuest

type GuestStarGuest struct {
	SlotID          string                 `json:"slot_id"`
	IsLive          bool                   `json:"is_live"`
	UserID          string                 `json:"user_id"`
	UserDisplayName string                 `json:"user_display_name"`
	UserLogin       string                 `json:"user_login"`
	Volume          int                    `json:"volume"`
	AssignedAt      string                 `json:"assigned_at"`
	AudioSettings   GuestStarAudioSettings `json:"audio_settings"`
	VideoSettings   GuestStarVideoSettings `json:"video_settings"`
}

GuestStarGuest represents a guest in a Guest Star session.

type GuestStarInvite

type GuestStarInvite struct {
	UserID           string `json:"user_id"`
	InvitedAt        string `json:"invited_at"`
	Status           string `json:"status"` // INVITED, ACCEPTED, READY
	IsVideoEnabled   bool   `json:"is_video_enabled"`
	IsAudioEnabled   bool   `json:"is_audio_enabled"`
	IsVideoAvailable bool   `json:"is_video_available"`
	IsAudioAvailable bool   `json:"is_audio_available"`
}

GuestStarInvite represents a Guest Star invite.

type GuestStarSession

type GuestStarSession struct {
	ID     string           `json:"id"`
	Guests []GuestStarGuest `json:"guests"`
}

GuestStarSession represents a Guest Star session.

type GuestStarSettings

type GuestStarSettings struct {
	IsModeratorSendLiveEnabled  bool   `json:"is_moderator_send_live_enabled"`
	SlotCount                   int    `json:"slot_count"`
	IsBrowserSourceAudioEnabled bool   `json:"is_browser_source_audio_enabled"`
	GroupLayout                 string `json:"group_layout"` // TILED_LAYOUT, SCREENSHARE_LAYOUT, HORIZONTAL_LAYOUT, VERTICAL_LAYOUT
	BrowserSourceToken          string `json:"browser_source_token,omitempty"`
}

GuestStarSettings represents channel Guest Star settings.

type GuestStarVideoSettings

type GuestStarVideoSettings struct {
	IsHostEnabled bool `json:"is_host_enabled"`
	IsSelfMuted   bool `json:"is_self_muted"`
	IsAvailable   bool `json:"is_available"`
}

GuestStarVideoSettings represents video settings for a guest.

type HypeTrainContribution

type HypeTrainContribution struct {
	Total int    `json:"total"`
	Type  string `json:"type"` // BITS, SUBS, OTHER
	User  string `json:"user"`
}

HypeTrainContribution represents a contribution to a hype train.

type HypeTrainEvent

type HypeTrainEvent struct {
	ID             string             `json:"id"`
	EventType      string             `json:"event_type"`
	EventTimestamp time.Time          `json:"event_timestamp"`
	Version        string             `json:"version"`
	EventData      HypeTrainEventData `json:"event_data"`
}

HypeTrainEvent represents a hype train event.

type HypeTrainEventData

type HypeTrainEventData struct {
	ID               string                  `json:"id"`
	BroadcasterID    string                  `json:"broadcaster_id"`
	CooldownEndTime  time.Time               `json:"cooldown_end_time"`
	ExpiresAt        time.Time               `json:"expires_at"`
	Goal             int                     `json:"goal"`
	LastContribution HypeTrainContribution   `json:"last_contribution"`
	Level            int                     `json:"level"`
	StartedAt        time.Time               `json:"started_at"`
	TopContributions []HypeTrainContribution `json:"top_contributions"`
	Total            int                     `json:"total"`
}

HypeTrainEventData contains the hype train event data.

type HypeTrainParticipant added in v1.0.0

type HypeTrainParticipant struct {
	BroadcasterID    string `json:"broadcaster_id"`
	BroadcasterLogin string `json:"broadcaster_login"`
	BroadcasterName  string `json:"broadcaster_name"`
}

HypeTrainParticipant represents a participant in a shared hype train (v2 only).

type HypeTrainStatus

type HypeTrainStatus struct {
	ID               string                  `json:"id"`
	BroadcasterID    string                  `json:"broadcaster_id"`
	Level            int                     `json:"level"`
	Total            int                     `json:"total"`
	Goal             int                     `json:"goal"`
	TopContributions []HypeTrainContribution `json:"top_contributions"`
	LastContribution HypeTrainContribution   `json:"last_contribution"`
	StartedAt        time.Time               `json:"started_at"`
	ExpiresAt        time.Time               `json:"expires_at"`
	CooldownEndTime  time.Time               `json:"cooldown_end_time"`
}

HypeTrainStatus represents the current hype train status.

type HypeTrainType added in v1.0.0

type HypeTrainType string

HypeTrainType represents the type of hype train (v2 only).

const (
	HypeTrainTypeRegular     HypeTrainType = "regular"
	HypeTrainTypeGoldenKappa HypeTrainType = "golden_kappa"
	HypeTrainTypeShared      HypeTrainType = "shared"
)

type IDTokenClaims

type IDTokenClaims struct {
	Iss               string `json:"iss"`
	Sub               string `json:"sub"`
	Aud               string `json:"aud"`
	Exp               int64  `json:"exp"`
	Iat               int64  `json:"iat"`
	Nonce             string `json:"nonce,omitempty"`
	PreferredUsername string `json:"preferred_username,omitempty"`
	Email             string `json:"email,omitempty"`
	EmailVerified     bool   `json:"email_verified,omitempty"`
	Picture           string `json:"picture,omitempty"`
	UpdatedAt         int64  `json:"updated_at,omitempty"`
}

IDTokenClaims represents the claims in an OIDC ID token.

func ParseIDToken

func ParseIDToken(idToken string) (*IDTokenClaims, error)

ParseIDToken parses an ID token without validating the signature. WARNING: This function does NOT verify the JWT signature. For secure validation, use VerifyAndParseIDToken instead.

type IDTokenHeader added in v1.0.2

type IDTokenHeader struct {
	Alg string `json:"alg"`
	Typ string `json:"typ"`
	Kid string `json:"kid"`
}

IDTokenHeader represents the header of a JWT ID token.

func ParseIDTokenHeader added in v1.0.2

func ParseIDTokenHeader(idToken string) (*IDTokenHeader, error)

ParseIDTokenHeader parses the header of an ID token.

type IRCClient

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

IRCClient manages a connection to Twitch IRC.

func NewIRCClient

func NewIRCClient(nick, token string, opts ...IRCOption) *IRCClient

NewIRCClient creates a new IRC client. Deprecated: Use NewIRCClientE instead which returns an error for invalid inputs. This function returns nil if nick or token is empty.

func NewIRCClientE added in v1.0.2

func NewIRCClientE(nick, token string, opts ...IRCOption) (*IRCClient, error)

NewIRCClientE creates a new IRC client with error handling. Returns an error if nick or token is empty.

func (*IRCClient) Close

func (c *IRCClient) Close() error

Close closes the IRC connection.

func (*IRCClient) Connect

func (c *IRCClient) Connect(ctx context.Context) error

Connect establishes a connection to Twitch IRC.

func (*IRCClient) GetGlobalUserState

func (c *IRCClient) GetGlobalUserState() *GlobalUserState

GetGlobalUserState returns the global user state.

func (*IRCClient) GetJoinedChannels

func (c *IRCClient) GetJoinedChannels() []string

GetJoinedChannels returns the list of joined channels.

func (*IRCClient) IsConnected

func (c *IRCClient) IsConnected() bool

IsConnected returns whether the client is connected.

func (*IRCClient) Join

func (c *IRCClient) Join(channels ...string) error

Join joins one or more channels. Channel names are sanitized to prevent IRC command injection.

func (*IRCClient) Part

func (c *IRCClient) Part(channels ...string) error

Part leaves one or more channels. Channel names are sanitized to prevent IRC command injection.

func (*IRCClient) Ping

func (c *IRCClient) Ping(ctx context.Context) error

Ping sends a PING and waits for PONG.

func (*IRCClient) Reply

func (c *IRCClient) Reply(channel, parentMsgID, message string) error

Reply sends a reply to a message. The channel name, parent message ID, and message are sanitized to prevent IRC command injection.

func (*IRCClient) Say

func (c *IRCClient) Say(channel, message string) error

Say sends a message to a channel. The channel name and message are sanitized to prevent IRC command injection.

func (*IRCClient) Whisper

func (c *IRCClient) Whisper(user, message string) error

Whisper sends a whisper to a user. Note: Whispers require verified bot status for high volume. The message is sanitized to prevent IRC command injection.

type IRCEmote

type IRCEmote struct {
	ID    string // Emote ID
	Name  string // Emote name/code
	Start int    // Start position in message
	End   int    // End position in message
	Count int    // Number of times used
}

IRCEmote represents an emote used in an IRC message.

type IRCMessage

type IRCMessage struct {
	Raw      string            // Raw message
	Tags     map[string]string // IRCv3 tags
	Prefix   string            // Source prefix (nick!user@host)
	Command  string            // IRC command
	Params   []string          // Command parameters
	Trailing string            // Trailing parameter (after :)
}

IRCMessage represents a parsed IRC message.

type IRCOption

type IRCOption func(*IRCClient)

IRCOption configures the IRC client.

func WithAutoReconnect

func WithAutoReconnect(enabled bool) IRCOption

WithAutoReconnect enables or disables auto-reconnect.

func WithClearChatHandler

func WithClearChatHandler(fn func(*ClearChat)) IRCOption

WithClearChatHandler sets the handler for clear chat events.

func WithClearMessageHandler

func WithClearMessageHandler(fn func(*ClearMessage)) IRCOption

WithClearMessageHandler sets the handler for clear message events.

func WithConnectHandler

func WithConnectHandler(fn func()) IRCOption

WithConnectHandler sets the handler for successful connections.

func WithDisconnectHandler

func WithDisconnectHandler(fn func()) IRCOption

WithDisconnectHandler sets the handler for disconnections.

func WithGlobalUserStateHandler

func WithGlobalUserStateHandler(fn func(*GlobalUserState)) IRCOption

WithGlobalUserStateHandler sets the handler for global user state.

func WithIRCErrorHandler

func WithIRCErrorHandler(fn func(error)) IRCOption

WithIRCErrorHandler sets the handler for errors.

func WithIRCURL

func WithIRCURL(url string) IRCOption

WithIRCURL sets a custom WebSocket URL.

func WithJoinHandler

func WithJoinHandler(fn func(channel, user string)) IRCOption

WithJoinHandler sets the handler for join events.

func WithMessageHandler

func WithMessageHandler(fn func(*ChatMessage)) IRCOption

WithMessageHandler sets the handler for chat messages.

func WithNoticeHandler

func WithNoticeHandler(fn func(*Notice)) IRCOption

WithNoticeHandler sets the handler for notice messages.

func WithPartHandler

func WithPartHandler(fn func(channel, user string)) IRCOption

WithPartHandler sets the handler for part events.

func WithRawMessageHandler

func WithRawMessageHandler(fn func(string)) IRCOption

WithRawMessageHandler sets the handler for raw IRC messages.

func WithReconnectDelay

func WithReconnectDelay(d time.Duration) IRCOption

WithReconnectDelay sets the delay between reconnection attempts.

func WithReconnectHandler

func WithReconnectHandler(fn func()) IRCOption

WithReconnectHandler sets the handler for reconnection events.

func WithRoomStateHandler

func WithRoomStateHandler(fn func(*RoomState)) IRCOption

WithRoomStateHandler sets the handler for room state changes.

func WithUserNoticeHandler

func WithUserNoticeHandler(fn func(*UserNotice)) IRCOption

WithUserNoticeHandler sets the handler for user notices (subs, raids, etc.).

func WithUserStateHandler

func WithUserStateHandler(fn func(*UserState)) IRCOption

WithUserStateHandler sets the handler for user state.

func WithWhisperHandler

func WithWhisperHandler(fn func(*Whisper)) IRCOption

WithWhisperHandler sets the handler for whisper messages.

type IngestServer

type IngestServer struct {
	ID           int     `json:"_id"`
	Availability float64 `json:"availability"`
	Default      bool    `json:"default"`
	Name         string  `json:"name"`
	URLTemplate  string  `json:"url_template"`
	Priority     int     `json:"priority"`
}

IngestServer represents a Twitch ingest server for live video streaming.

func (*IngestServer) GetRTMPURL

func (s *IngestServer) GetRTMPURL(streamKey string) string

GetRTMPURL returns the RTMP URL for this ingest server with the stream key inserted.

type IngestServersResponse

type IngestServersResponse struct {
	Ingests []IngestServer `json:"ingests"`
}

IngestServersResponse represents the response from the ingest servers endpoint.

func (*IngestServersResponse) GetIngestServerByName

func (r *IngestServersResponse) GetIngestServerByName(name string) *IngestServer

GetIngestServerByName finds an ingest server by its name (location). Returns nil if no server with the given name is found.

type JWK

type JWK struct {
	Kty string `json:"kty"` // Key type (RSA)
	E   string `json:"e"`   // Exponent
	N   string `json:"n"`   // Modulus
	Kid string `json:"kid"` // Key ID
	Alg string `json:"alg"` // Algorithm
	Use string `json:"use"` // Usage (sig)
}

JWK represents a JSON Web Key.

func (*JWK) RSAPublicKey

func (k *JWK) RSAPublicKey() (*rsa.PublicKey, error)

RSAPublicKey converts the JWK to an RSA public key.

type JWKS

type JWKS struct {
	Keys []JWK `json:"keys"`
}

JWKS represents a JSON Web Key Set.

func (*JWKS) GetKeyByID

func (j *JWKS) GetKeyByID(kid string) *JWK

GetKeyByID returns the JWK with the specified key ID.

type ManageHeldAutoModMessageParams

type ManageHeldAutoModMessageParams struct {
	UserID string `json:"user_id"`
	MsgID  string `json:"msg_id"`
	Action string `json:"action"` // ALLOW or DENY
}

ManageHeldAutoModMessageParams contains parameters for ManageHeldAutoModMessages.

type MaxPerStream

type MaxPerStream struct {
	IsEnabled    bool `json:"is_enabled"`
	MaxPerStream int  `json:"max_per_stream"`
}

MaxPerStream represents max per stream settings.

type MaxPerUserPerStream

type MaxPerUserPerStream struct {
	IsEnabled           bool `json:"is_enabled"`
	MaxPerUserPerStream int  `json:"max_per_user_per_stream"`
}

MaxPerUserPerStream represents max per user per stream settings.

type MemoryCache

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

MemoryCache is an in-memory cache implementation.

func NewMemoryCache

func NewMemoryCache(maxSize int) *MemoryCache

NewMemoryCache creates a new in-memory cache.

func (*MemoryCache) Clear

func (c *MemoryCache) Clear(ctx context.Context)

Clear removes all cached responses.

func (*MemoryCache) Delete

func (c *MemoryCache) Delete(ctx context.Context, key string)

Delete removes a cached response.

func (*MemoryCache) Get

func (c *MemoryCache) Get(ctx context.Context, key string) []byte

Get retrieves a cached response. The returned byte slice is a copy to prevent callers from mutating cached data.

func (*MemoryCache) Set

func (c *MemoryCache) Set(ctx context.Context, key string, value []byte, ttl time.Duration)

Set stores a response in the cache. The value is copied to prevent external mutations from affecting cached data.

func (*MemoryCache) Size

func (c *MemoryCache) Size() int

Size returns the number of entries in the cache.

type MessageDeduplicator

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

MessageDeduplicator helps prevent processing duplicate EventSub messages. It is safe for concurrent use.

func NewMessageDeduplicator

func NewMessageDeduplicator(maxAge time.Duration, maxSize int) *MessageDeduplicator

NewMessageDeduplicator creates a new message deduplicator.

func (*MessageDeduplicator) Clear

func (d *MessageDeduplicator) Clear()

Clear removes all tracked message IDs. This method is safe for concurrent use.

func (*MessageDeduplicator) IsDuplicate

func (d *MessageDeduplicator) IsDuplicate(messageID string) bool

IsDuplicate returns true if this message ID has been seen before. It also marks the message as seen. This method is safe for concurrent use.

type Middleware

type Middleware func(ctx context.Context, req *Request, next MiddlewareNext) (*MiddlewareResponse, error)

Middleware is a function that wraps request execution. It receives the request context, the request, and a next function to call. Middleware can modify the request before calling next, and modify/inspect the response after next returns.

func HeaderMiddleware

func HeaderMiddleware(headers map[string]string) Middleware

HeaderMiddleware creates middleware that adds custom headers to requests.

func LoggingMiddleware

func LoggingMiddleware(logger func(format string, args ...interface{})) Middleware

LoggingMiddleware creates middleware that logs requests and responses.

func MetricsMiddleware

func MetricsMiddleware(collector func(metrics RequestMetrics)) Middleware

func RetryMiddleware

func RetryMiddleware(maxRetries int, retryableStatuses ...int) Middleware

RetryMiddleware creates middleware that retries failed requests. This is separate from the built-in rate limit retry and handles other transient errors.

type MiddlewareNext

type MiddlewareNext func(ctx context.Context, req *Request) (*MiddlewareResponse, error)

MiddlewareNext is a function that continues the middleware chain.

type MiddlewareResponse

type MiddlewareResponse struct {
	StatusCode int
	Headers    http.Header
	Body       []byte
}

MiddlewareResponse contains the response data available to middleware.

type ModerateAutomodTerms

type ModerateAutomodTerms struct {
	Action      string   `json:"action"`
	List        string   `json:"list"`
	Terms       []string `json:"terms"`
	FromAutomod bool     `json:"from_automod"`
}

ModerateAutomodTerms represents automod terms update.

type ModerateBan

type ModerateBan struct {
	UserID    string  `json:"user_id"`
	UserLogin string  `json:"user_login"`
	UserName  string  `json:"user_name"`
	Reason    *string `json:"reason,omitempty"`
}

ModerateBan represents ban details.

type ModerateDelete

type ModerateDelete struct {
	UserID      string `json:"user_id"`
	UserLogin   string `json:"user_login"`
	UserName    string `json:"user_name"`
	MessageID   string `json:"message_id"`
	MessageBody string `json:"message_body"`
}

ModerateDelete represents message deletion details.

type ModerateFollowers

type ModerateFollowers struct {
	FollowDurationMinutes int `json:"follow_duration_minutes"`
}

ModerateFollowers represents followers-only mode settings.

type ModerateRaid

type ModerateRaid struct {
	UserID      string `json:"user_id"`
	UserLogin   string `json:"user_login"`
	UserName    string `json:"user_name"`
	ViewerCount int    `json:"viewer_count"`
}

ModerateRaid represents raid details.

type ModerateSharedChatBan

type ModerateSharedChatBan struct {
	UserID    string  `json:"user_id"`
	UserLogin string  `json:"user_login"`
	UserName  string  `json:"user_name"`
	Reason    *string `json:"reason,omitempty"`
}

ModerateSharedChatBan represents a ban in shared chat.

type ModerateSharedChatDelete

type ModerateSharedChatDelete struct {
	UserID    string `json:"user_id"`
	UserLogin string `json:"user_login"`
	UserName  string `json:"user_name"`
	MessageID string `json:"message_id"`
}

ModerateSharedChatDelete represents message deletion in shared chat.

type ModerateSharedChatTimeout

type ModerateSharedChatTimeout struct {
	UserID    string    `json:"user_id"`
	UserLogin string    `json:"user_login"`
	UserName  string    `json:"user_name"`
	Reason    *string   `json:"reason,omitempty"`
	ExpiresAt time.Time `json:"expires_at"`
}

ModerateSharedChatTimeout represents a timeout in shared chat.

type ModerateSlow

type ModerateSlow struct {
	WaitTimeSeconds int `json:"wait_time_seconds"`
}

ModerateSlow represents slow mode settings.

type ModerateTimeout

type ModerateTimeout struct {
	UserID    string    `json:"user_id"`
	UserLogin string    `json:"user_login"`
	UserName  string    `json:"user_name"`
	Reason    *string   `json:"reason,omitempty"`
	ExpiresAt time.Time `json:"expires_at"`
}

ModerateTimeout represents timeout details.

type ModerateUnbanRequest

type ModerateUnbanRequest struct {
	IsApproved       bool    `json:"is_approved"`
	UserID           string  `json:"user_id"`
	UserLogin        string  `json:"user_login"`
	UserName         string  `json:"user_name"`
	ModeratorMessage *string `json:"moderator_message,omitempty"`
}

ModerateUnbanRequest represents unban request resolution.

type ModerateUser

type ModerateUser struct {
	UserID    string `json:"user_id"`
	UserLogin string `json:"user_login"`
	UserName  string `json:"user_name"`
}

ModerateUser represents a user in moderation actions.

type ModerateWarn

type ModerateWarn struct {
	UserID         string   `json:"user_id"`
	UserLogin      string   `json:"user_login"`
	UserName       string   `json:"user_name"`
	Reason         *string  `json:"reason,omitempty"`
	ChatRulesCited []string `json:"chat_rules_cited,omitempty"`
}

ModerateWarn represents warning details.

type ModeratedChannel

type ModeratedChannel struct {
	BroadcasterID    string `json:"broadcaster_id"`
	BroadcasterLogin string `json:"broadcaster_login"`
	BroadcasterName  string `json:"broadcaster_name"`
}

ModeratedChannel represents a channel where the user is a moderator.

type Moderator

type Moderator struct {
	UserID    string `json:"user_id"`
	UserLogin string `json:"user_login"`
	UserName  string `json:"user_name"`
}

Moderator represents a channel moderator.

type ModifyChannelInformationParams

type ModifyChannelInformationParams struct {
	BroadcasterID               string                              `json:"-"`
	GameID                      string                              `json:"game_id,omitempty"`
	BroadcasterLanguage         string                              `json:"broadcaster_language,omitempty"`
	Title                       string                              `json:"title,omitempty"`
	Delay                       *int                                `json:"delay,omitempty"`
	Tags                        []string                            `json:"tags,omitempty"`
	ContentClassificationLabels []ContentClassificationLabelSetting `json:"content_classification_labels,omitempty"`
	IsBrandedContent            *bool                               `json:"is_branded_content,omitempty"`
}

ModifyChannelInformationParams contains parameters for ModifyChannelInformation.

type MutedSegment

type MutedSegment struct {
	Duration int `json:"duration"`
	Offset   int `json:"offset"`
}

MutedSegment represents a muted segment in a video.

type Notice

type Notice struct {
	Channel string // Channel name (may be empty for global notices)
	Message string // Notice message
	MsgID   string // Notice type identifier
	Raw     string // Raw IRC message
}

Notice represents a NOTICE message from the server.

type OIDCResponseType

type OIDCResponseType string

OIDCResponseType represents OIDC response types.

const (
	ResponseTypeCode         OIDCResponseType = "code"
	ResponseTypeToken        OIDCResponseType = "token"
	ResponseTypeIDToken      OIDCResponseType = "id_token"
	ResponseTypeTokenIDToken OIDCResponseType = "token id_token"
	ResponseTypeCodeIDToken  OIDCResponseType = "code id_token"
)

type OIDCToken

type OIDCToken struct {
	Token
	IDToken string `json:"id_token,omitempty"`
}

OIDCToken extends Token with OIDC-specific fields.

type OIDCUserInfo

type OIDCUserInfo struct {
	Sub               string `json:"sub"`
	PreferredUsername string `json:"preferred_username"`
	Email             string `json:"email,omitempty"`
	EmailVerified     bool   `json:"email_verified,omitempty"`
	Picture           string `json:"picture,omitempty"`
	UpdatedAt         int64  `json:"updated_at,omitempty"`
}

OIDCUserInfo represents the response from the OIDC UserInfo endpoint.

type OpenIDConfiguration

type OpenIDConfiguration struct {
	Issuer                            string   `json:"issuer"`
	AuthorizationEndpoint             string   `json:"authorization_endpoint"`
	TokenEndpoint                     string   `json:"token_endpoint"`
	UserInfoEndpoint                  string   `json:"userinfo_endpoint"`
	JWKSUri                           string   `json:"jwks_uri"`
	ResponseTypesSupported            []string `json:"response_types_supported"`
	SubjectTypesSupported             []string `json:"subject_types_supported"`
	IDTokenSigningAlgValuesSupported  []string `json:"id_token_signing_alg_values_supported"`
	ScopesSupported                   []string `json:"scopes_supported"`
	TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported"`
	ClaimsSupported                   []string `json:"claims_supported"`
}

OpenIDConfiguration represents the OIDC discovery document.

type Option

type Option func(*Client)

Option is a function that configures the client.

func WithBaseURL

func WithBaseURL(url string) Option

WithBaseURL sets a custom base URL (useful for testing).

func WithCache

func WithCache(cache Cache, ttl time.Duration) Option

WithCache sets a cache for the client.

func WithCacheEnabled

func WithCacheEnabled(enabled bool) Option

WithCacheEnabled enables or disables caching.

func WithExponentialBackoff

func WithExponentialBackoff(baseDelay time.Duration) Option

WithExponentialBackoff enables exponential backoff for retries. baseDelay is the initial delay, which doubles with each retry attempt.

func WithExtensionJWT

func WithExtensionJWT(jwt *ExtensionJWT) Option

WithExtensionJWT returns an Option to configure extension JWT authentication.

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient sets a custom HTTP client.

func WithIngestBaseURL

func WithIngestBaseURL(url string) Option

WithIngestBaseURL sets a custom ingest base URL (useful for testing).

func WithMaxRetryWait

func WithMaxRetryWait(d time.Duration) Option

WithMaxRetryWait sets the maximum time to wait for a retry.

func WithMiddleware

func WithMiddleware(mw ...Middleware) Option

WithMiddleware adds middleware to the client.

func WithRetry

func WithRetry(enabled bool, maxRetries int) Option

WithRetry configures retry behavior for rate-limited requests.

type Pagination

type Pagination struct {
	Cursor string `json:"cursor,omitempty"`
}

Pagination contains pagination information. Some Twitch endpoints (e.g. Get Extension Live Channels) return pagination as an empty string instead of an object. UnmarshalJSON handles both formats.

func (*Pagination) UnmarshalJSON added in v1.2.0

func (p *Pagination) UnmarshalJSON(data []byte) error

UnmarshalJSON handles both object ({"cursor":"..."}) and string ("") pagination formats.

type PaginationParams

type PaginationParams struct {
	First  int    // Maximum number of items to return (1-100)
	After  string // Cursor for forward pagination
	Before string // Cursor for backward pagination
}

PaginationParams contains common pagination parameters.

type ParsedTopic added in v1.0.0

type ParsedTopic struct {
	Type        string // e.g., "channel-bits-events", "channel-points-channel"
	ChannelID   string // broadcaster/channel ID
	UserID      string // user ID (for whispers, moderator actions)
	ModeratorID string // moderator ID (for automod)
}

ParsedTopic represents a parsed PubSub topic string.

func ParseTopic added in v1.0.0

func ParseTopic(topic string) (*ParsedTopic, error)

ParseTopic parses a PubSub topic string into its components.

type Poll

type Poll 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                    []PollChoice `json:"choices"`
	BitsVotingEnabled          bool         `json:"bits_voting_enabled"`
	BitsPerVote                int          `json:"bits_per_vote"`
	ChannelPointsVotingEnabled bool         `json:"channel_points_voting_enabled"`
	ChannelPointsPerVote       int          `json:"channel_points_per_vote"`
	Status                     string       `json:"status"` // ACTIVE, COMPLETED, TERMINATED, ARCHIVED, MODERATED, INVALID
	Duration                   int          `json:"duration"`
	StartedAt                  time.Time    `json:"started_at"`
	EndedAt                    time.Time    `json:"ended_at,omitempty"`
}

Poll represents a channel poll.

type PollChoice

type PollChoice struct {
	ID                 string `json:"id"`
	Title              string `json:"title"`
	Votes              int    `json:"votes"`
	ChannelPointsVotes int    `json:"channel_points_votes"`
	BitsVotes          int    `json:"bits_votes"`
}

PollChoice represents a choice in a poll.

type PowerUp

type PowerUp struct {
	Type string `json:"type"`
}

PowerUp represents a bits power-up.

type Prediction

type Prediction struct {
	ID               string              `json:"id"`
	BroadcasterID    string              `json:"broadcaster_id"`
	BroadcasterName  string              `json:"broadcaster_name"`
	BroadcasterLogin string              `json:"broadcaster_login"`
	Title            string              `json:"title"`
	WinningOutcomeID string              `json:"winning_outcome_id,omitempty"`
	Outcomes         []PredictionOutcome `json:"outcomes"`
	PredictionWindow int                 `json:"prediction_window"`
	Status           string              `json:"status"` // ACTIVE, CANCELED, LOCKED, RESOLVED
	CreatedAt        time.Time           `json:"created_at"`
	EndedAt          time.Time           `json:"ended_at,omitempty"`
	LockedAt         time.Time           `json:"locked_at,omitempty"`
}

Prediction represents a channel prediction.

type PredictionOutcome

type PredictionOutcome struct {
	ID            string                `json:"id"`
	Title         string                `json:"title"`
	Users         int                   `json:"users"`
	ChannelPoints int                   `json:"channel_points"`
	TopPredictors []PredictionPredictor `json:"top_predictors,omitempty"`
	Color         string                `json:"color"`
}

PredictionOutcome represents an outcome of a prediction.

type PredictionPredictor

type PredictionPredictor struct {
	UserID            string `json:"user_id"`
	UserLogin         string `json:"user_login"`
	UserName          string `json:"user_name"`
	ChannelPointsUsed int    `json:"channel_points_used"`
	ChannelPointsWon  int    `json:"channel_points_won"`
}

PredictionPredictor represents a top predictor.

type PubSubClient added in v1.0.0

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

PubSubClient provides a PubSub-style API backed by EventSub. This enables migration from the deprecated Twitch PubSub to EventSub while maintaining familiar topic-based semantics.

func NewPubSubClient added in v1.0.0

func NewPubSubClient(helixClient *Client, opts ...PubSubOption) *PubSubClient

NewPubSubClient creates a new PubSub compatibility client. The client uses EventSub WebSocket internally but exposes a PubSub-style API. Returns nil if helixClient is nil.

func (*PubSubClient) Close added in v1.0.0

func (c *PubSubClient) Close(ctx context.Context) error

Close closes the PubSub client and cleans up all subscriptions.

func (*PubSubClient) Connect added in v1.0.0

func (c *PubSubClient) Connect(ctx context.Context) error

Connect establishes the WebSocket connection.

func (*PubSubClient) IsConnected added in v1.0.0

func (c *PubSubClient) IsConnected() bool

IsConnected returns whether the client is connected.

func (*PubSubClient) Listen added in v1.0.0

func (c *PubSubClient) Listen(ctx context.Context, topic string) error

Listen subscribes to a PubSub topic. The topic is translated to the equivalent EventSub subscription(s).

func (*PubSubClient) SessionID added in v1.0.0

func (c *PubSubClient) SessionID() string

SessionID returns the EventSub session ID.

func (*PubSubClient) Topics added in v1.0.0

func (c *PubSubClient) Topics() []string

Topics returns the list of topics currently being listened to.

func (*PubSubClient) Unlisten added in v1.0.0

func (c *PubSubClient) Unlisten(ctx context.Context, topic string) error

Unlisten unsubscribes from a PubSub topic.

type PubSubMessage added in v1.0.0

type PubSubMessage struct {
	Type string          `json:"type"` // EventSub subscription type
	Data json.RawMessage `json:"data"` // EventSub event payload
}

PubSubMessage wraps EventSub events in a PubSub-style envelope.

type PubSubOption added in v1.0.0

type PubSubOption func(*PubSubClient)

PubSubOption configures the PubSubClient.

func WithPubSubConnectHandler added in v1.0.0

func WithPubSubConnectHandler(fn func()) PubSubOption

WithPubSubConnectHandler sets the handler for connection events.

func WithPubSubErrorHandler added in v1.0.0

func WithPubSubErrorHandler(fn func(error)) PubSubOption

WithPubSubErrorHandler sets the handler for errors.

func WithPubSubMessageHandler added in v1.0.0

func WithPubSubMessageHandler(fn func(topic string, message json.RawMessage)) PubSubOption

WithPubSubMessageHandler sets the handler for topic messages.

func WithPubSubReconnectHandler added in v1.0.0

func WithPubSubReconnectHandler(fn func()) PubSubOption

WithPubSubReconnectHandler sets the handler for reconnection events.

func WithPubSubWSURL added in v1.0.0

func WithPubSubWSURL(url string) PubSubOption

WithPubSubWSURL sets a custom WebSocket URL (useful for testing).

type Raid

type Raid struct {
	CreatedAt time.Time `json:"created_at"`
	IsMature  bool      `json:"is_mature"`
}

Raid represents a raid.

type RateLimitError

type RateLimitError struct {
	ResetAt    time.Time     // When the rate limit resets
	Remaining  int           // Points remaining (usually 0)
	Limit      int           // Total bucket size
	RetryAfter time.Duration // How long until reset
}

RateLimitError is returned when the API rate limit is exceeded and retries are exhausted.

func (*RateLimitError) Error

func (e *RateLimitError) Error() string

type RateLimitInfo

type RateLimitInfo struct {
	Limit     int       // Points added per minute (bucket size)
	Remaining int       // Points remaining in bucket
	ResetAt   time.Time // When the bucket resets to full
}

RateLimitInfo contains rate limit status information.

type RemoveSuspiciousStatusFromChatUserParams added in v1.2.0

type RemoveSuspiciousStatusFromChatUserParams struct {
	BroadcasterID string `json:"-"`
	ModeratorID   string `json:"-"`
	UserID        string `json:"-"`
}

RemoveSuspiciousStatusFromChatUserParams contains parameters for RemoveSuspiciousStatusFromChatUser.

type Request

type Request struct {
	Method   string
	Endpoint string
	Query    url.Values
	Body     interface{}
}

Request represents an API request.

type RequestMetrics

type RequestMetrics struct {
	Method     string
	Endpoint   string
	StatusCode int
	Duration   int64 // milliseconds
	Error      error
}

MetricsMiddleware creates middleware that tracks request metrics.

type ResolveUnbanRequestParams

type ResolveUnbanRequestParams struct {
	BroadcasterID  string `json:"-"`
	ModeratorID    string `json:"-"`
	UnbanRequestID string `json:"-"`
	Status         string `json:"status"` // approved or denied
	ResolutionText string `json:"resolution_text,omitempty"`
}

ResolveUnbanRequestParams contains parameters for ResolveUnbanRequest.

type Response

type Response[T any] struct {
	Data         []T         `json:"data"`
	Pagination   *Pagination `json:"pagination,omitempty"`
	Total        *int        `json:"total,omitempty"`
	TotalCost    *int        `json:"total_cost,omitempty"`
	MaxTotalCost *int        `json:"max_total_cost,omitempty"`
}

Response represents a generic API response.

type RewardImage

type RewardImage struct {
	URL1x string `json:"url_1x"`
	URL2x string `json:"url_2x"`
	URL4x string `json:"url_4x"`
}

RewardImage represents images for a reward.

type RoomState

type RoomState struct {
	Channel       string // Channel name
	EmoteOnly     bool   // Emote-only mode
	FollowersOnly int    // Followers-only mode (-1 = off, 0+ = minutes required)
	R9K           bool   // R9K/unique mode
	Slow          int    // Slow mode (seconds between messages, 0 = off)
	SubsOnly      bool   // Subscribers-only mode
	RoomID        string // Channel/room ID
	Raw           string // Raw IRC message
}

RoomState represents a ROOMSTATE message.

type Schedule

type Schedule struct {
	Segments         []ScheduleSegment `json:"segments"`
	BroadcasterID    string            `json:"broadcaster_id"`
	BroadcasterName  string            `json:"broadcaster_name"`
	BroadcasterLogin string            `json:"broadcaster_login"`
	Vacation         *Vacation         `json:"vacation,omitempty"`
}

Schedule represents a channel's stream schedule.

type ScheduleResponse

type ScheduleResponse struct {
	Data       Schedule    `json:"data"`
	Pagination *Pagination `json:"pagination,omitempty"`
}

ScheduleResponse represents the response from GetChannelStreamSchedule.

type ScheduleSegment

type ScheduleSegment 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,omitempty"`
	Category      *Category  `json:"category,omitempty"`
	IsRecurring   bool       `json:"is_recurring"`
}

ScheduleSegment represents a segment in a schedule.

type SearchCategoriesParams

type SearchCategoriesParams struct {
	Query string
	*PaginationParams
}

SearchCategoriesParams contains parameters for SearchCategories.

type SearchCategory

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

SearchCategory represents a search result for categories.

type SearchChannel

type SearchChannel struct {
	BroadcasterLanguage string    `json:"broadcaster_language"`
	BroadcasterLogin    string    `json:"broadcaster_login"`
	DisplayName         string    `json:"display_name"`
	GameID              string    `json:"game_id"`
	GameName            string    `json:"game_name"`
	ID                  string    `json:"id"`
	IsLive              bool      `json:"is_live"`
	Tags                []string  `json:"tags"`
	ThumbnailURL        string    `json:"thumbnail_url"`
	Title               string    `json:"title"`
	StartedAt           time.Time `json:"started_at,omitempty"`
}

SearchChannel represents a search result for channels.

type SearchChannelsParams

type SearchChannelsParams struct {
	Query    string
	LiveOnly bool
	*PaginationParams
}

SearchChannelsParams contains parameters for SearchChannels.

type SendChatAnnouncementParams

type SendChatAnnouncementParams struct {
	BroadcasterID string `json:"-"`
	ModeratorID   string `json:"-"`
	Message       string `json:"message"`
	Color         string `json:"color,omitempty"` // blue, green, orange, purple, primary
}

SendChatAnnouncementParams contains parameters for SendChatAnnouncement.

type SendChatMessageParams

type SendChatMessageParams struct {
	BroadcasterID        string `json:"broadcaster_id"`
	SenderID             string `json:"sender_id"`
	Message              string `json:"message"`
	ReplyParentMessageID string `json:"reply_parent_message_id,omitempty"`
}

SendChatMessageParams contains parameters for SendChatMessage.

type SendChatMessageResponse

type SendChatMessageResponse struct {
	MessageID  string `json:"message_id"`
	IsSent     bool   `json:"is_sent"`
	DropReason *struct {
		Code    string `json:"code"`
		Message string `json:"message"`
	} `json:"drop_reason,omitempty"`
}

SendChatMessageResponse represents the response from SendChatMessage.

type SendExtensionChatMessageParams

type SendExtensionChatMessageParams struct {
	BroadcasterID    string `json:"broadcaster_id"`
	Text             string `json:"text"`
	ExtensionID      string `json:"extension_id"`
	ExtensionVersion string `json:"extension_version"`
}

SendExtensionChatMessageParams contains parameters for SendExtensionChatMessage.

type SendExtensionPubSubMessageParams

type SendExtensionPubSubMessageParams struct {
	Target            []string `json:"target"` // broadcast, global, whisper-<user_id>
	BroadcasterID     string   `json:"broadcaster_id"`
	IsGlobalBroadcast bool     `json:"is_global_broadcast,omitempty"`
	Message           string   `json:"message"`
}

SendExtensionPubSubMessageParams contains parameters for SendExtensionPubSubMessage.

type SendShoutoutParams

type SendShoutoutParams struct {
	FromBroadcasterID string
	ToBroadcasterID   string
	ModeratorID       string
}

SendShoutoutParams contains parameters for SendShoutout.

type SendWhisperParams

type SendWhisperParams struct {
	FromUserID string `json:"-"`
	ToUserID   string `json:"-"`
	Message    string `json:"message"`
}

SendWhisperParams contains parameters for SendWhisper.

type SetExtensionConfigurationSegmentParams

type SetExtensionConfigurationSegmentParams struct {
	ExtensionID   string `json:"extension_id"`
	Segment       string `json:"segment"` // broadcaster, developer, global
	BroadcasterID string `json:"broadcaster_id,omitempty"`
	Content       string `json:"content,omitempty"`
	Version       string `json:"version,omitempty"`
}

SetExtensionConfigurationSegmentParams contains parameters for SetExtensionConfigurationSegment.

type SetExtensionRequiredConfigurationParams

type SetExtensionRequiredConfigurationParams struct {
	BroadcasterID         string `json:"-"`
	ExtensionID           string `json:"extension_id"`
	ExtensionVersion      string `json:"extension_version"`
	RequiredConfiguration string `json:"required_configuration"`
}

SetExtensionRequiredConfigurationParams contains parameters for SetExtensionRequiredConfiguration.

type SharedChatParticipant

type SharedChatParticipant struct {
	BroadcasterID string `json:"broadcaster_id"`
}

SharedChatParticipant represents a participant in a shared chat session.

type SharedChatSession

type SharedChatSession struct {
	SessionID         string                  `json:"session_id"`
	HostBroadcasterID string                  `json:"host_broadcaster_id"`
	Participants      []SharedChatParticipant `json:"participants"`
	CreatedAt         string                  `json:"created_at"`
	UpdatedAt         string                  `json:"updated_at"`
}

SharedChatSession represents a shared chat session.

type ShieldModeStatus

type ShieldModeStatus struct {
	IsActive        bool      `json:"is_active"`
	ModeratorID     string    `json:"moderator_id"`
	ModeratorLogin  string    `json:"moderator_login"`
	ModeratorName   string    `json:"moderator_name"`
	LastActivatedAt time.Time `json:"last_activated_at"`
}

ShieldModeStatus represents shield mode status.

type SnoozeNextAdResponse

type SnoozeNextAdResponse struct {
	SnoozeCount     int       `json:"snooze_count"`
	SnoozeRefreshAt time.Time `json:"snooze_refresh_at"`
	NextAdAt        time.Time `json:"next_ad_at"`
}

SnoozeNextAdResponse represents the response from SnoozeNextAd.

type StartCommercialParams

type StartCommercialParams struct {
	BroadcasterID string `json:"broadcaster_id"`
	Length        int    `json:"length"` // 30, 60, 90, 120, 150, or 180 seconds
}

StartCommercialParams contains parameters for StartCommercial.

type StartRaidParams

type StartRaidParams struct {
	FromBroadcasterID string // The broadcaster initiating the raid
	ToBroadcasterID   string // The broadcaster being raided
}

StartRaidParams contains parameters for StartRaid.

type Stream

type Stream 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"` // "live" or ""
	Title        string    `json:"title"`
	ViewerCount  int       `json:"viewer_count"`
	StartedAt    time.Time `json:"started_at"`
	Language     string    `json:"language"`
	ThumbnailURL string    `json:"thumbnail_url"`
	Tags         []string  `json:"tags"`
	IsMature     bool      `json:"is_mature"`
}

Stream represents a live stream.

type StreamKey

type StreamKey struct {
	StreamKey string `json:"stream_key"`
}

StreamKey represents a stream key.

type StreamMarker

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

StreamMarker represents a stream marker.

type StreamOfflineEvent

type StreamOfflineEvent struct {
	EventSubBroadcaster
}

StreamOfflineEvent is sent when a stream goes offline.

type StreamOnlineEvent

type StreamOnlineEvent struct {
	ID string `json:"id"`
	EventSubBroadcaster
	Type      string    `json:"type"` // live, playlist, watch_party, premiere, rerun
	StartedAt time.Time `json:"started_at"`
}

StreamOnlineEvent is sent when a stream goes online.

type Subscription

type Subscription struct {
	BroadcasterID    string `json:"broadcaster_id"`
	BroadcasterLogin string `json:"broadcaster_login"`
	BroadcasterName  string `json:"broadcaster_name"`
	GifterID         string `json:"gifter_id,omitempty"`
	GifterLogin      string `json:"gifter_login,omitempty"`
	GifterName       string `json:"gifter_name,omitempty"`
	IsGift           bool   `json:"is_gift"`
	PlanName         string `json:"plan_name"`
	Tier             string `json:"tier"` // 1000, 2000, 3000
	UserID           string `json:"user_id"`
	UserLogin        string `json:"user_login"`
	UserName         string `json:"user_name"`
}

Subscription represents a channel subscription.

type SubscriptionEmote

type SubscriptionEmote struct {
	Begin int    `json:"begin"`
	End   int    `json:"end"`
	ID    string `json:"id"`
}

SubscriptionEmote represents an emote in a subscription message.

type SubscriptionMessage

type SubscriptionMessage struct {
	Text   string              `json:"text"`
	Emotes []SubscriptionEmote `json:"emotes,omitempty"`
}

SubscriptionMessage represents the message in a subscription event.

type SubscriptionsResponse

type SubscriptionsResponse struct {
	Data       []Subscription `json:"data"`
	Pagination *Pagination    `json:"pagination,omitempty"`
	Total      int            `json:"total"`
	Points     int            `json:"points"` // Subscriber points (based on tiers)
}

SubscriptionsResponse represents the response from GetBroadcasterSubscriptions.

type SuspiciousFragment

type SuspiciousFragment struct {
	Type      string              `json:"type"`
	Text      string              `json:"text"`
	Cheermote *ChatEventCheermote `json:"cheermote,omitempty"`
	Emote     *ChatEventEmote     `json:"emote,omitempty"`
}

SuspiciousFragment represents a fragment in a suspicious user message.

type SuspiciousUserMessage

type SuspiciousUserMessage struct {
	MessageID string               `json:"message_id"`
	Text      string               `json:"text"`
	Fragments []SuspiciousFragment `json:"fragments"`
}

SuspiciousUserMessage represents a message from a suspicious user.

type SuspiciousUserStatus added in v1.1.0

type SuspiciousUserStatus string

SuspiciousUserStatus represents the status of a suspicious user.

const (
	// SuspiciousUserStatusRestricted indicates the user is restricted from chatting.
	SuspiciousUserStatusRestricted SuspiciousUserStatus = "restricted"
	// SuspiciousUserStatusMonitored indicates the user is being monitored.
	SuspiciousUserStatusMonitored SuspiciousUserStatus = "monitored"
)

type Team

type Team struct {
	ID                 string     `json:"id"`
	TeamName           string     `json:"team_name"`
	TeamDisplayName    string     `json:"team_display_name"`
	Info               string     `json:"info"`
	ThumbnailURL       string     `json:"thumbnail_url"`
	BackgroundImageURL string     `json:"background_image_url"`
	Banner             string     `json:"banner"`
	CreatedAt          time.Time  `json:"created_at"`
	UpdatedAt          time.Time  `json:"updated_at"`
	Users              []TeamUser `json:"users,omitempty"`
}

Team represents a Twitch team.

type TeamUser

type TeamUser struct {
	UserID    string `json:"user_id"`
	UserLogin string `json:"user_login"`
	UserName  string `json:"user_name"`
}

TeamUser represents a user in a team.

type Token

type Token struct {
	AccessToken  string    `json:"access_token"`
	RefreshToken string    `json:"refresh_token,omitempty"`
	TokenType    string    `json:"token_type"`
	ExpiresIn    int       `json:"expires_in"`
	Scope        []string  `json:"scope,omitempty"`
	ExpiresAt    time.Time `json:"-"`
}

Token represents an OAuth token from Twitch.

func (*Token) IsExpired

func (t *Token) IsExpired() bool

IsExpired returns true if the token has expired.

func (*Token) Valid

func (t *Token) Valid() bool

Valid returns true if the token is non-empty and not expired.

type TokenProvider

type TokenProvider interface {
	GetToken() *Token
}

TokenProvider is an interface for providing access tokens.

type TopicMapping added in v1.0.0

type TopicMapping struct {
	EventSubTypes []string                                    // EventSub subscription types
	Condition     func(parsed *ParsedTopic) map[string]string // Build condition from parsed topic
}

TopicMapping defines how a PubSub topic maps to EventSub subscriptions.

type UnbanRequest

type UnbanRequest struct {
	ID               string `json:"id"`
	BroadcasterID    string `json:"broadcaster_id"`
	BroadcasterLogin string `json:"broadcaster_login"`
	BroadcasterName  string `json:"broadcaster_name"`
	ModeratorID      string `json:"moderator_id,omitempty"`
	ModeratorLogin   string `json:"moderator_login,omitempty"`
	ModeratorName    string `json:"moderator_name,omitempty"`
	UserID           string `json:"user_id"`
	UserLogin        string `json:"user_login"`
	UserName         string `json:"user_name"`
	Text             string `json:"text"`
	Status           string `json:"status"` // pending, approved, denied, acknowledged, canceled
	CreatedAt        string `json:"created_at"`
	ResolvedAt       string `json:"resolved_at,omitempty"`
	ResolutionText   string `json:"resolution_text,omitempty"`
}

UnbanRequest represents an unban request.

type UnlockedEmote

type UnlockedEmote struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

UnlockedEmote represents an unlocked emote reward.

type UpdateAutoModSettingsParams

type UpdateAutoModSettingsParams struct {
	BroadcasterID           string `json:"-"`
	ModeratorID             string `json:"-"`
	OverallLevel            *int   `json:"overall_level,omitempty"`
	Disability              *int   `json:"disability,omitempty"`
	Aggression              *int   `json:"aggression,omitempty"`
	SexualitySexOrGender    *int   `json:"sexuality_sex_or_gender,omitempty"`
	Misogyny                *int   `json:"misogyny,omitempty"`
	Bullying                *int   `json:"bullying,omitempty"`
	Swearing                *int   `json:"swearing,omitempty"`
	RaceEthnicityOrReligion *int   `json:"race_ethnicity_or_religion,omitempty"`
	SexBasedTerms           *int   `json:"sex_based_terms,omitempty"`
}

UpdateAutoModSettingsParams contains parameters for UpdateAutoModSettings.

type UpdateChannelGuestStarSettingsParams

type UpdateChannelGuestStarSettingsParams struct {
	BroadcasterID               string `json:"-"`
	IsModeratorSendLiveEnabled  *bool  `json:"is_moderator_send_live_enabled,omitempty"`
	SlotCount                   *int   `json:"slot_count,omitempty"`
	IsBrowserSourceAudioEnabled *bool  `json:"is_browser_source_audio_enabled,omitempty"`
	GroupLayout                 string `json:"group_layout,omitempty"`
	RegenerateBrowserSources    *bool  `json:"regenerate_browser_sources,omitempty"`
}

UpdateChannelGuestStarSettingsParams contains parameters for UpdateChannelGuestStarSettings.

type UpdateChannelStreamScheduleParams

type UpdateChannelStreamScheduleParams struct {
	BroadcasterID     string     `json:"-"`
	IsVacationEnabled *bool      `json:"is_vacation_enabled,omitempty"`
	VacationStartTime *time.Time `json:"vacation_start_time,omitempty"`
	VacationEndTime   *time.Time `json:"vacation_end_time,omitempty"`
	Timezone          string     `json:"timezone,omitempty"`
}

UpdateChannelStreamScheduleParams contains parameters for UpdateChannelStreamSchedule.

type UpdateChannelStreamScheduleSegmentParams

type UpdateChannelStreamScheduleSegmentParams struct {
	BroadcasterID string     `json:"-"`
	ID            string     `json:"-"`
	StartTime     *time.Time `json:"start_time,omitempty"`
	Duration      *int       `json:"duration,omitempty"`
	CategoryID    *string    `json:"category_id,omitempty"`
	Title         *string    `json:"title,omitempty"`
	IsCanceled    *bool      `json:"is_canceled,omitempty"`
	Timezone      string     `json:"timezone,omitempty"`
}

UpdateChannelStreamScheduleSegmentParams contains parameters for UpdateChannelStreamScheduleSegment.

type UpdateChatSettingsParams

type UpdateChatSettingsParams struct {
	BroadcasterID                 string `json:"-"`
	ModeratorID                   string `json:"-"`
	EmoteMode                     *bool  `json:"emote_mode,omitempty"`
	FollowerMode                  *bool  `json:"follower_mode,omitempty"`
	FollowerModeDuration          *int   `json:"follower_mode_duration,omitempty"`
	NonModeratorChatDelay         *bool  `json:"non_moderator_chat_delay,omitempty"`
	NonModeratorChatDelayDuration *int   `json:"non_moderator_chat_delay_duration,omitempty"`
	SlowMode                      *bool  `json:"slow_mode,omitempty"`
	SlowModeWaitTime              *int   `json:"slow_mode_wait_time,omitempty"`
	SubscriberMode                *bool  `json:"subscriber_mode,omitempty"`
	UniqueChatMode                *bool  `json:"unique_chat_mode,omitempty"`
}

UpdateChatSettingsParams contains parameters for UpdateChatSettings.

type UpdateConduitParams

type UpdateConduitParams struct {
	ID         string `json:"id"`
	ShardCount int    `json:"shard_count"`
}

UpdateConduitParams contains parameters for UpdateConduit.

type UpdateConduitShardParams

type UpdateConduitShardParams struct {
	ID        string                      `json:"id"`
	Transport UpdateConduitShardTransport `json:"transport"`
}

UpdateConduitShardParams represents parameters for a single shard update.

type UpdateConduitShardTransport

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

UpdateConduitShardTransport represents transport parameters for shard update.

type UpdateConduitShardsParams

type UpdateConduitShardsParams struct {
	ConduitID string                     `json:"conduit_id"`
	Shards    []UpdateConduitShardParams `json:"shards"`
}

UpdateConduitShardsParams contains parameters for UpdateConduitShards.

type UpdateConduitShardsResponse

type UpdateConduitShardsResponse struct {
	Data   []ConduitShard `json:"data"`
	Errors []struct {
		ID      string `json:"id"`
		Message string `json:"message"`
		Code    string `json:"code"`
	} `json:"errors,omitempty"`
}

UpdateConduitShardsResponse represents the response from UpdateConduitShards.

type UpdateCustomRewardParams

type UpdateCustomRewardParams struct {
	BroadcasterID                     string `json:"-"`
	ID                                string `json:"-"`
	Title                             string `json:"title,omitempty"`
	Cost                              *int   `json:"cost,omitempty"`
	Prompt                            string `json:"prompt,omitempty"`
	IsEnabled                         *bool  `json:"is_enabled,omitempty"`
	BackgroundColor                   string `json:"background_color,omitempty"`
	IsUserInputRequired               *bool  `json:"is_user_input_required,omitempty"`
	IsMaxPerStreamEnabled             *bool  `json:"is_max_per_stream_enabled,omitempty"`
	MaxPerStream                      *int   `json:"max_per_stream,omitempty"`
	IsMaxPerUserPerStreamEnabled      *bool  `json:"is_max_per_user_per_stream_enabled,omitempty"`
	MaxPerUserPerStream               *int   `json:"max_per_user_per_stream,omitempty"`
	IsGlobalCooldownEnabled           *bool  `json:"is_global_cooldown_enabled,omitempty"`
	GlobalCooldownSeconds             *int   `json:"global_cooldown_seconds,omitempty"`
	ShouldRedemptionsSkipRequestQueue *bool  `json:"should_redemptions_skip_request_queue,omitempty"`
	IsPaused                          *bool  `json:"is_paused,omitempty"`
}

UpdateCustomRewardParams contains parameters for UpdateCustomReward.

type UpdateDropsEntitlementsParams

type UpdateDropsEntitlementsParams struct {
	EntitlementIDs    []string `json:"entitlement_ids"`    // Max 100
	FulfillmentStatus string   `json:"fulfillment_status"` // CLAIMED, FULFILLED
}

UpdateDropsEntitlementsParams contains parameters for UpdateDropsEntitlements.

type UpdateDropsEntitlementsResponse

type UpdateDropsEntitlementsResponse struct {
	Status string   `json:"status"` // SUCCESS, INVALID_ID, NOT_FOUND, UNAUTHORIZED, UPDATE_FAILED
	IDs    []string `json:"ids"`
}

UpdateDropsEntitlementsResponse represents the response from UpdateDropsEntitlements.

type UpdateExtensionBitsProductParams

type UpdateExtensionBitsProductParams struct {
	SKU           string            `json:"sku"`
	Cost          ExtensionBitsCost `json:"cost"`
	DisplayName   string            `json:"display_name"`
	InDevelopment bool              `json:"in_development,omitempty"`
	Expiration    string            `json:"expiration,omitempty"`
	IsBroadcast   bool              `json:"is_broadcast,omitempty"`
}

UpdateExtensionBitsProductParams contains parameters for UpdateExtensionBitsProduct.

type UpdateGuestStarSlotParams

type UpdateGuestStarSlotParams struct {
	BroadcasterID     string `json:"-"`
	ModeratorID       string `json:"-"`
	SessionID         string `json:"-"`
	SourceSlotID      string `json:"-"`
	DestinationSlotID string `json:"-"`
}

UpdateGuestStarSlotParams contains parameters for UpdateGuestStarSlot.

type UpdateGuestStarSlotSettingsParams

type UpdateGuestStarSlotSettingsParams struct {
	BroadcasterID  string `json:"-"`
	ModeratorID    string `json:"-"`
	SessionID      string `json:"-"`
	SlotID         string `json:"-"`
	IsAudioEnabled *bool  `json:"is_audio_enabled,omitempty"`
	IsVideoEnabled *bool  `json:"is_video_enabled,omitempty"`
	IsLive         *bool  `json:"is_live,omitempty"`
	Volume         *int   `json:"volume,omitempty"`
}

UpdateGuestStarSlotSettingsParams contains parameters for UpdateGuestStarSlotSettings.

type UpdateRedemptionStatusParams

type UpdateRedemptionStatusParams struct {
	BroadcasterID string   `json:"-"`
	RewardID      string   `json:"-"`
	IDs           []string `json:"-"`      // Redemption IDs (max 50)
	Status        string   `json:"status"` // CANCELED or FULFILLED
}

UpdateRedemptionStatusParams contains parameters for UpdateRedemptionStatus.

type UpdateShieldModeStatusParams

type UpdateShieldModeStatusParams struct {
	BroadcasterID string `json:"-"`
	ModeratorID   string `json:"-"`
	IsActive      bool   `json:"is_active"`
}

UpdateShieldModeStatusParams contains parameters for UpdateShieldModeStatus.

type UpdateUserExtensionsParams

type UpdateUserExtensionsParams struct {
	Data UserActiveExtensions `json:"data"`
}

UpdateUserExtensionsParams contains parameters for UpdateUserExtensions.

type UpdateUserParams

type UpdateUserParams struct {
	Description string `json:"description,omitempty"`
}

UpdateUserParams contains parameters for UpdateUser.

type User

type User struct {
	ID              string    `json:"id"`
	Login           string    `json:"login"`
	DisplayName     string    `json:"display_name"`
	Type            string    `json:"type"`
	BroadcasterType string    `json:"broadcaster_type"`
	Description     string    `json:"description"`
	ProfileImageURL string    `json:"profile_image_url"`
	OfflineImageURL string    `json:"offline_image_url"`
	ViewCount       int       `json:"view_count"` // Deprecated
	Email           string    `json:"email,omitempty"`
	CreatedAt       time.Time `json:"created_at"`
}

User represents a Twitch user.

type UserActiveExtensions

type UserActiveExtensions struct {
	Panel     map[string]ActiveExtension `json:"panel"`
	Overlay   map[string]ActiveExtension `json:"overlay"`
	Component map[string]ActiveExtension `json:"component"`
}

UserActiveExtensions represents a user's active extensions.

type UserAuthorization

type UserAuthorization struct {
	ClientID string   `json:"client_id"`
	UserID   string   `json:"user_id"`
	Login    string   `json:"login"`
	Scopes   []string `json:"scopes"`
}

UserAuthorization represents the authorization scopes granted by a user.

type UserAuthorizationGrantEvent

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

UserAuthorizationGrantEvent is sent when a user grants authorization.

type UserAuthorizationRevokeEvent

type UserAuthorizationRevokeEvent struct {
	ClientID  string  `json:"client_id"`
	UserID    string  `json:"user_id"`
	UserLogin *string `json:"user_login,omitempty"`
	UserName  *string `json:"user_name,omitempty"`
}

UserAuthorizationRevokeEvent is sent when a user revokes authorization.

type UserChatColor

type UserChatColor struct {
	UserID    string `json:"user_id"`
	UserLogin string `json:"user_login"`
	UserName  string `json:"user_name"`
	Color     string `json:"color"`
}

UserChatColor represents a user's chat color.

type UserEmote

type UserEmote struct {
	ID         string   `json:"id"`
	Name       string   `json:"name"`
	EmoteType  string   `json:"emote_type"`
	EmoteSetID string   `json:"emote_set_id"`
	OwnerID    string   `json:"owner_id"`
	Format     []string `json:"format"`
	Scale      []string `json:"scale"`
	ThemeMode  []string `json:"theme_mode"`
}

UserEmote represents a user's emote.

type UserEmotesResponse

type UserEmotesResponse struct {
	Data       []UserEmote `json:"data"`
	Template   string      `json:"template"`
	Pagination *Pagination `json:"pagination,omitempty"`
}

UserEmotesResponse represents the response from GetUserEmotes.

type UserExtension

type UserExtension struct {
	ID          string   `json:"id"`
	Version     string   `json:"version"`
	Name        string   `json:"name"`
	CanActivate bool     `json:"can_activate"`
	Type        []string `json:"type"`
}

UserExtension represents a user's extension.

type UserNotice

type UserNotice struct {
	Type          string            // sub, resub, subgift, raid, ritual, etc.
	Channel       string            // Channel name
	User          string            // Username
	UserID        string            // User's Twitch ID
	DisplayName   string            // Display name
	Message       string            // Optional user message
	SystemMessage string            // System-generated message
	MsgParams     map[string]string // Type-specific parameters
	Badges        map[string]string // User badges
	BadgeInfo     map[string]string // Badge info
	Color         string            // User color
	Emotes        []IRCEmote        // Emotes in message
	Timestamp     time.Time         // Server timestamp
	Raw           string            // Raw IRC message
}

UserNotice represents a USERNOTICE message (subs, raids, etc.).

type UserState

type UserState struct {
	Channel      string            // Channel name
	DisplayName  string            // Display name
	Color        string            // Chat color
	Badges       map[string]string // Channel-specific badges
	BadgeInfo    map[string]string // Badge info
	EmoteSets    []string          // Available emote set IDs
	IsMod        bool              // Is moderator
	IsSubscriber bool              // Is subscriber
	Raw          string            // Raw IRC message
}

UserState represents a USERSTATE message.

type UserSubscription

type UserSubscription struct {
	BroadcasterID    string `json:"broadcaster_id"`
	BroadcasterLogin string `json:"broadcaster_login"`
	BroadcasterName  string `json:"broadcaster_name"`
	GifterID         string `json:"gifter_id,omitempty"`
	GifterLogin      string `json:"gifter_login,omitempty"`
	GifterName       string `json:"gifter_name,omitempty"`
	IsGift           bool   `json:"is_gift"`
	Tier             string `json:"tier"`
}

UserSubscription represents a user's subscription to a channel.

type UserUpdateEvent

type UserUpdateEvent struct {
	UserID        string `json:"user_id"`
	UserLogin     string `json:"user_login"`
	UserName      string `json:"user_name"`
	Email         string `json:"email,omitempty"` // Requires user:read:email scope
	EmailVerified bool   `json:"email_verified,omitempty"`
	Description   string `json:"description"`
}

UserUpdateEvent is sent when a user updates their account.

type UserWhisperMessageEvent

type UserWhisperMessageEvent struct {
	FromUserID    string      `json:"from_user_id"`
	FromUserLogin string      `json:"from_user_login"`
	FromUserName  string      `json:"from_user_name"`
	ToUserID      string      `json:"to_user_id"`
	ToUserLogin   string      `json:"to_user_login"`
	ToUserName    string      `json:"to_user_name"`
	WhisperID     string      `json:"whisper_id"`
	Whisper       WhisperBody `json:"whisper"`
}

UserWhisperMessageEvent is sent when a whisper is received.

type VIP

type VIP struct {
	UserID    string `json:"user_id"`
	UserLogin string `json:"user_login"`
	UserName  string `json:"user_name"`
}

VIP represents a VIP user in a channel.

type Vacation

type Vacation struct {
	StartTime time.Time `json:"start_time"`
	EndTime   time.Time `json:"end_time"`
}

Vacation represents a vacation period.

type ValidationResponse

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

ValidationResponse represents the response from the /validate endpoint.

type Video

type Video struct {
	ID            string         `json:"id"`
	StreamID      string         `json:"stream_id,omitempty"`
	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     int            `json:"view_count"`
	Language      string         `json:"language"`
	Type          string         `json:"type"` // archive, highlight, upload
	Duration      string         `json:"duration"`
	MutedSegments []MutedSegment `json:"muted_segments,omitempty"`
}

Video represents a Twitch video (VOD, highlight, or upload).

type VideoStreamMarkers

type VideoStreamMarkers struct {
	UserID    string `json:"user_id"`
	UserLogin string `json:"user_login"`
	UserName  string `json:"user_name"`
	Videos    []struct {
		VideoID string         `json:"video_id"`
		Markers []StreamMarker `json:"markers"`
	} `json:"videos"`
}

VideoStreamMarkers represents markers for a video.

type WarnChatUserData

type WarnChatUserData struct {
	UserID string `json:"user_id"`
	Reason string `json:"reason"`
}

WarnChatUserData contains the warning data.

type WarnChatUserParams

type WarnChatUserParams struct {
	BroadcasterID string           `json:"-"`
	ModeratorID   string           `json:"-"`
	Data          WarnChatUserData `json:"data"`
}

WarnChatUserParams contains parameters for WarnChatUser.

type WebSocketMessage

type WebSocketMessage struct {
	Metadata WebSocketMetadata `json:"metadata"`
	Payload  json.RawMessage   `json:"payload"`
}

WebSocketMessage represents a message received from EventSub WebSocket.

type WebSocketMetadata

type WebSocketMetadata struct {
	MessageID           string    `json:"message_id"`
	MessageType         string    `json:"message_type"`
	MessageTimestamp    time.Time `json:"message_timestamp"`
	SubscriptionType    string    `json:"subscription_type,omitempty"`
	SubscriptionVersion string    `json:"subscription_version,omitempty"`
}

WebSocketMetadata contains metadata about the WebSocket message.

type WebSocketNotificationPayload

type WebSocketNotificationPayload struct {
	Subscription EventSubSubscription `json:"subscription"`
	Event        json.RawMessage      `json:"event"`
}

WebSocketNotificationPayload is the payload for notification messages.

type WebSocketReconnectPayload

type WebSocketReconnectPayload struct {
	Session WebSocketSession `json:"session"`
}

WebSocketReconnectPayload is the payload for reconnect messages.

type WebSocketSession

type WebSocketSession struct {
	ID                      string    `json:"id"`
	Status                  string    `json:"status"`
	ConnectedAt             time.Time `json:"connected_at"`
	KeepaliveTimeoutSeconds int       `json:"keepalive_timeout_seconds"`
	ReconnectURL            string    `json:"reconnect_url,omitempty"`
}

WebSocketSession contains session information.

type WebSocketWelcomePayload

type WebSocketWelcomePayload struct {
	Session WebSocketSession `json:"session"`
}

WebSocketWelcomePayload is the payload for welcome messages.

type Whisper

type Whisper struct {
	From        string            // Sender username
	FromID      string            // Sender user ID
	To          string            // Recipient username
	Message     string            // Message content
	DisplayName string            // Sender display name
	Color       string            // Sender color
	Badges      map[string]string // Sender badges
	Emotes      []IRCEmote        // Emotes in message
	MessageID   string            // Unique message ID
	ThreadID    string            // Thread ID
	Raw         string            // Raw IRC message
}

Whisper represents a WHISPER message (direct message).

type WhisperBody

type WhisperBody struct {
	Text string `json:"text"`
}

WhisperBody represents the whisper message body.

Jump to

Keyboard shortcuts

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