chzzk

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Jul 15, 2026 License: MIT Imports: 9 Imported by: 0

README

chzzk-go

chzzk-go is a Go client library for accessing Chzzk. This library provides official ways for accessing to Chzzk. Unofficial APIs will be provided in the near future.

Korean Documentation is available:

Installation

go get github.com/sdkim96/chzzk-go

will resolve and add external dependencies.

Usage


import chzzk "github.com/sdkim96/chzzk-go"

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 300*time.Second)
    defer cancel()

    c := chzzk.New(nil).WithAPIKey("your-chzzk-api-key-here")
    user, err := c.User.Me(ctx)
    if err != nil {
        panic(err)
    }
    fmt.Println("ChannelID: ", user.ChannelID)
    fmt.Println("ChannelName: ", user.ChannelName)
}

To use this example, you should register your application to Chzzk.

How to Make Application

First of all, You must register your application to Chzzk server. Open the browser, access to https://developers.chzzk.naver.com

alt text

You can register your application like this.

alt text

Note: You MUST fill the redirection URL field out http://localhost:57777/callback.

Finds out why you have to hard-code as :57777: https://github.com/sdkim96/chzzk-go/blob/main/internal/login/login.go#L9-L17

If you have registered, your application will be recorded as:

alt text

Well done!

How to Login

You can find the guide here.

Authentication

There are two ways to authenticate:

Client Credentials

Use WithClientAuth for server-to-server API calls (e.g., session auth, token management).

c := chzzk.New(nil).WithClientAuth("your-client-id", "your-client-secret")
API Key (User Access Token)

Use WithAPIKey for user-scoped API calls (e.g., user info, chat subscription).

c := chzzk.New(nil).WithAPIKey("your-access-token")

Services

Token
c := chzzk.New(nil).WithClientAuth(clientID, clientSecret)

// Issue a new token
token, err := c.Token.New(ctx, chzzk.TokenNewRequest{
    TokenRequest: chzzk.TokenRequest{
        GrantType:    chzzk.GrantTypeAuthorizationCode,
        ClientID:     clientID,
        ClientSecret: clientSecret,
    },
    Code:  code,
    State: state,
})

// Refresh a token
token, err := c.Token.Refresh(ctx, chzzk.TokenRefreshRequest{
    TokenRequest: chzzk.TokenRequest{
        GrantType:    chzzk.GrantTypeRefreshToken,
        ClientID:     clientID,
        ClientSecret: clientSecret,
    },
    RefreshToken: "your-refresh-token",
})

// Revoke a token
err := c.Token.Revoke(ctx, chzzk.RevokeTokenRequest{
    ClientID:      clientID,
    ClientSecret:  clientSecret,
    Token:         "token-to-revoke",
    TokenTypeHint: "access_token",
})
User
c := chzzk.New(nil).WithAPIKey("your-access-token")

user, err := c.User.Me(ctx)
fmt.Println(user.ChannelID, user.ChannelName)
Channel
// Get channel info (WithClientAuth)
c := chzzk.New(nil).WithClientAuth(clientID, clientSecret)
channels, err := c.Channel.Get(ctx, "channelId1", "channelId2")

// Managers, Followers, Subscribers (WithAPIKey)
c := chzzk.New(nil).WithAPIKey("your-access-token")

managers, err := c.Channel.Managers(ctx)
followers, nextPage, err := c.Channel.Followers(ctx, nil, nil)
subscribers, nextPage, err := c.Channel.Subscribers(ctx, nil, nil, nil)
Live
// List live streams (WithClientAuth)
c := chzzk.New(nil).WithClientAuth(clientID, clientSecret)
lives, next, err := c.Live.Get(ctx, nil, nil)

// Stream key, settings (WithAPIKey)
c := chzzk.New(nil).WithAPIKey("your-access-token")
key, err := c.Live.Key(ctx)
setting, err := c.Live.Setting(ctx)

// Update settings
title := "My Stream"
err := c.Live.PatchSetting(ctx, &chzzk.PatchLiveSettingRequest{
    Title:    &title,
    Category: &chzzk.Category{Type: "GAME", ID: "League_of_Legends"},
})
Category
c := chzzk.New(nil).WithClientAuth(clientID, clientSecret)
categories, err := c.Category.Search(ctx, "리그", nil)
Session (Real-time Events)
c := chzzk.New(nil).WithClientAuth(clientID, clientSecret)

// Get a session URL
sessionURL, err := c.Session.AuthClient(ctx)

// Subscribe/unsubscribe to chat events
err := c.Session.SubscribeChat(ctx, sessionKey)
err := c.Session.UnSubscribeChat(ctx, sessionKey)
Socket.IO

The socketio package provides a Socket.IO v2 client for receiving real-time events.

import "github.com/sdkim96/chzzk-go/socketio"

conn := socketio.New(wsURL,
    socketio.WithHandler("CHAT", func(data []byte) error {
        fmt.Println("Chat:", string(data))
        return nil
    }),
    socketio.WithHandler("DONATION", func(data []byte) error {
        fmt.Println("Donation:", string(data))
        return nil
    }),
)

err := conn.Dial(ctx)
defer conn.Close(ctx, 1000, "done")

err = conn.Loop(ctx) // blocks until context is cancelled or error
Unofficial Chat (WebSocket)

The unofficial package provides direct WebSocket access to Chzzk chat, including both reading and writing messages.

Warning: These features use undocumented APIs. Use at your own risk.

import (
    "github.com/sdkim96/chzzk-go"
    "github.com/sdkim96/chzzk-go/unofficial"
)

ctx := context.Background()
chz := chzzk.New(nil)
uc, _ := unofficial.New(chz, nil)

// Read-only (no auth required)
liveID, _ := uc.Live.ID(ctx, "channel-hash")
token, _ := uc.Chat.Token(ctx, liveID)

recv, _ := uc.Chat.ReadOnlyConnect(ctx, liveID, token)
for msg := range recv {
    fmt.Println(string(msg))
}

// Bidirectional (requires NID cookies)
uc, _ = uc.WithCookie(ctx, "NID_AUT_value", "NID_SES_value")

liveID, _ = uc.Live.ID(ctx, "channel-hash")
token, _ = uc.Chat.Token(ctx, liveID)
recv, send, sid, _ := uc.Chat.Connect(ctx, liveID, token)

Testing

# Unit tests
go test ./...

# Integration tests (requires CHZZK_CLIENT_ID and CHZZK_CLIENT_SECRET)
go test -tags=integration ./...

# Unofficial integration tests (requires NID cookies)
NID_AUT="..." NID_SES="..." CHZZK_CHANNEL_ID="..." \
  go test -tags=integration ./unofficial/ -v

License

MIT

Documentation

Index

Constants

View Source
const (
	NoticeMessage              NoticeKind        = "message"
	NoticeMessageID            NoticeKind        = "messageId"
	ChatAvailableForAll        ChatAvailableKind = "all"
	ChatAvailableForFollower   ChatAvailableKind = "follower"
	ChatAvailableForManager    ChatAvailableKind = "manager"
	ChatAvailableForSubscriber ChatAvailableKind = "subscriber"
	AuthorityModeAll           AuthorityKind     = "all"
	AuthorityModelRealName     AuthorityKind     = "realName"
)
View Source
const (
	Version     = "0.5.0"
	BaseURL     = "https://openapi.chzzk.naver.com"
	OpenV1      = "/open/v1"
	AuthV1      = "/auth/v1"
	ContentType = "application/json"
	UserAgent   = "chzzk-go/" + Version
)

Variables

View Source
var ErrInvalidNoticeKind = errors.New("chzzk: invalid notice kind")

Functions

func MightError added in v0.4.0

func MightError(resp Response) error

MightError checks the response body for inspecting error from the server.

The Chzzk API does not return HTTP error. Rather, it always embeds the Response field in the response body, which contains the error code and message.

func Ptr added in v0.5.0

func Ptr[T any](v T) *T

Ptr returns a pointer to the given value.

Types

type AuthorityKind added in v0.5.0

type AuthorityKind string

type Category added in v0.3.0

type Category struct {
	ID       string `json:"categoryId"`
	Type     string `json:"categoryType"`
	Value    string `json:"categoryValue"`
	ImageURL string `json:"posterImageUrl"`
}

type CategoryService added in v0.3.0

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

CategoryService serves an API for searching broadcast categories such as:

  • games
  • sports
  • music
  • news
  • just chatting.

func (*CategoryService) Search added in v0.3.0

func (s *CategoryService) Search(ctx context.Context, query string, size *int) ([]Category, error)

Search retrieves a list of categories matching the given query string.

  • pattern: List
  • credential: [Chzzk.WithClientAuth]

Check the documentation for more details: https://chzzk.gitbook.io/chzzk/chzzk-api/category#undefined

type Channel added in v0.2.0

type Channel struct {
	ID            string `json:"channelId"`
	Name          string `json:"channelName"`
	ImageURL      string `json:"imageUrl"`
	FollowerCount int    `json:"followerCount"`
	Verified      bool   `json:"verified"`
}

type ChannelService added in v0.2.0

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

func (*ChannelService) Followers added in v0.2.0

func (s *ChannelService) Followers(ctx context.Context, page, size *int) ([]Follower, int, error)

Followers retrieves the list of followers for a channel with pagination support.

  • pattern: List
  • credential: [Chzzk.WithAPIKey]

Check the documentation for more details: https://chzzk.gitbook.io/chzzk/chzzk-api/channel#undefined-2

func (*ChannelService) Get added in v0.3.0

func (s *ChannelService) Get(ctx context.Context, ids ...string) ([]Channel, error)

Get retrieves information for multiple channels by their IDs.

  • pattern: BatchGet
  • credential: [Chzzk.WithClientAuth]

Check the documentation for more details: https://chzzk.gitbook.io/chzzk/chzzk-api/channel#undefined

func (*ChannelService) Managers added in v0.2.0

func (s *ChannelService) Managers(ctx context.Context) ([]Manager, error)

Managers retrieves the list of managers for a channel. Unlike the original List operation, this API does not require pagination, as it returns all managers in a single response.

  • pattern: List
  • credential: [Chzzk.WithAPIKey]

Check the documentation for more details: https://chzzk.gitbook.io/chzzk/chzzk-api/channel#undefined-1

func (*ChannelService) Subscribers added in v0.2.0

func (s *ChannelService) Subscribers(ctx context.Context, page, size *int, sort *SubscriptionSort) ([]Subscriber, int, error)

Subscribers retrieves the list of subscribers for a channel with pagination support.

  • pattern: List
  • credential: [Chzzk.WithAPIKey]

Check the documentation for more details: https://chzzk.gitbook.io/chzzk/chzzk-api/channel#undefined-3

type ChatAvailableKind added in v0.5.0

type ChatAvailableKind string

type ChatBlindMessageReq added in v0.5.0

type ChatBlindMessageReq struct {
	ChatChannelID   string `json:"chatChannelId"`
	MessageTime     int64  `json:"messageTime"`
	SenderChannelID string `json:"senderChannelId"`
}

ChatBlindMessageReq represents a request to blind (hide) a specific chat message.

type ChatFollowerSetting added in v0.5.0

type ChatFollowerSetting struct {
	MinFollowerMinute              int
	AllowSubscriberInFollowerModel bool
}

type ChatNoticeReq added in v0.5.0

type ChatNoticeReq struct {
	Kind    NoticeKind
	Content string
}

ChatNoticeReq represents a request to Notice API. It can be used to set a notice message or a notice message ID.

type ChatService added in v0.4.2

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

ChatService handles APIs prefixed with /chats

func (*ChatService) BlindMessage added in v0.5.0

func (s *ChatService) BlindMessage(ctx context.Context, req ChatBlindMessageReq) error

BlindMessage blinds (hides) a specific chat message.

Check the documentation for more details: https://chzzk.gitbook.io/chzzk/chzzk-api/chat#undefined-4

func (*ChatService) Notice added in v0.4.2

func (s *ChatService) Notice(ctx context.Context, req ChatNoticeReq) error

Notice sets or updates the chat notice. Use NoticeMessage to set by message text, or NoticeMessageID to set by an existing message ID.

Check the documentation for more details: https://chzzk.gitbook.io/chzzk/chzzk-api/chat#undefined-1

func (*ChatService) Send added in v0.4.2

func (s *ChatService) Send(ctx context.Context, msg string) (string, error)

Send sends a chat message and returns the message ID.

Check the documentation for more details: https://chzzk.gitbook.io/chzzk/chzzk-api/chat#undefined

func (*ChatService) Settings added in v0.5.0

func (s *ChatService) Settings(ctx context.Context) (*ChatSettings, error)

Settings retrieves the current chat settings for the authenticated user's channel.

Check the documentation for more details: https://chzzk.gitbook.io/chzzk/chzzk-api/chat#undefined-2

func (*ChatService) UpdateSettings added in v0.5.0

func (s *ChatService) UpdateSettings(ctx context.Context, req ChatSettings) error

UpdateSettings updates the chat settings for the authenticated user's channel.

Check the documentation for more details: https://chzzk.gitbook.io/chzzk/chzzk-api/chat#undefined-3

type ChatSettings added in v0.5.0

type ChatSettings struct {
	Kind            ChatAvailableKind
	FollowerSetting *ChatFollowerSetting
	AuthorityMode   *AuthorityKind
	SlowModeSec     *int
	IsEmojiMode     *bool
}

ChatSettings represents the chat settings for a channel. It is used in the Settings and UpdateSettings APIs.

type Client added in v0.4.2

type Client struct {

	// The services
	Token    *TokenService
	User     *UserService
	Session  *SessionService
	Channel  *ChannelService
	Category *CategoryService
	Live     *LiveService
	Chat     *ChatService
	// contains filtered or unexported fields
}

func New

func New(httpClient *http.Client) *Client

New creates a new Chzzk client with the provided http.Client. If the provided http.Client is nil, a new http.Client will be created.

func (*Client) WithAPIKey added in v0.4.2

func (c *Client) WithAPIKey(apiKey string) *Client

WithAPIKey returns a new Chzzk client with the provided API key.

func (*Client) WithClientAuth added in v0.4.2

func (c *Client) WithClientAuth(ID, secret string) *Client

WithClientAuth returns a new Chzzk client with the provided client ID and secret. You must either use WithClientAuth or WithAPIKey, not both. Using both will cause unexpected behavior.

Check the Chzzk API documentation to see further details: https://chzzk.gitbook.io/chzzk/chzzk-api/tips#access-token-api

func (*Client) WithHooks added in v0.4.2

func (c *Client) WithHooks(bef func(req *http.Request), aft func(resp *http.Response)) *Client

WithHooks returns a new Chzzk client with the provided hooks for request and response. Do not modify (read or write req or resp) in the hooks, as it may cause unexpected behavior. The recommended way is to clone the request and response in the hooks, and modify the cloned objects. Or just log the request and response in the hooks, without modifying them.

type Follower added in v0.2.0

type Follower struct {
	ID          string `json:"ChannelId"`
	Name        string `json:"ChannelName"`
	CreatedDate string `json:"createdDate"`
}

type GrantType

type GrantType string
const (
	GrantTypeAuthorizationCode GrantType = "authorization_code"
	GrantTypeRefreshToken      GrantType = "refresh_token"
)

type Live added in v0.3.0

type Live struct {
	ID                int      `json:"liveId"`
	Title             string   `json:"liveTitle"`
	ThumbnailImageURL string   `json:"liveThumbnailImageUrl"`
	ViewerCount       int      `json:"concurrentUserCount"`
	StartDate         string   `json:"openDate"`
	IsAdult           bool     `json:"adult"`
	Tags              []string `json:"tags"`
	CategoryID        string   `json:"liveCategory"`
	CategoryType      string   `json:"categoryType"`
	CategoryValue     string   `json:"liveCategoryValue"`
	ChannelID         string   `json:"channelId"`
	ChannelName       string   `json:"channelName"`
	ChannelImageURL   string   `json:"channelImageUrl"`
}

type LiveService added in v0.3.0

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

LiveService provides methods for accessing live streaming features of the Chzzk API.

func (*LiveService) Get added in v0.3.0

func (s *LiveService) Get(ctx context.Context, size *int, next *string) ([]Live, string, error)

Get retrieves a list of live streams sorted by viewer count, with optional pagination.

  • pattern: List
  • credential: [Chzzk.WithClientAuth]

Check the documentation for more details: https://chzzk.gitbook.io/chzzk/chzzk-api/live#undefined

func (*LiveService) Key added in v0.3.0

func (s *LiveService) Key(ctx context.Context) (string, error)

Key retrieves the live streaming key for the authenticated user. Returns empty string if the user is not currently broadcasting.

  • pattern: Get
  • credential: [Chzzk.WithAPIKey]

Check the documentation for more details: https://chzzk.gitbook.io/chzzk/chzzk-api/live#undefined-1

func (*LiveService) PatchSetting added in v0.3.0

func (s *LiveService) PatchSetting(ctx context.Context, p *PatchLiveSettingRequest) error

PatchSetting updates the live streaming settings for the authenticated user.

  • pattern: Update
  • credential: [Chzzk.WithAPIKey]

Example — set category (categoryType is required when categoryId is non-empty):

c.Live.PatchSetting(ctx, &chzzk.PatchLiveSettingRequest{
    Category: &chzzk.Category{Type: "GAME", ID: "League_of_Legends"},
})

Example — clear category:

c.Live.PatchSetting(ctx, &chzzk.PatchLiveSettingRequest{
    Category: &chzzk.Category{ID: ""},
})

Example — set title and tags:

title := "My Stream"
c.Live.PatchSetting(ctx, &chzzk.PatchLiveSettingRequest{
    Title: &title,
    Tags:  []string{"game", "lol"},
})

Check the documentation for more details: https://chzzk.gitbook.io/chzzk/chzzk-api/live#undefined-3

func (*LiveService) Setting added in v0.3.0

func (s *LiveService) Setting(ctx context.Context) (*LiveSetting, error)

Setting retrieves the default live streaming settings for the authenticated user.

  • pattern: Get
  • credential: [Chzzk.WithAPIKey]

Check the documentation for more details: https://chzzk.gitbook.io/chzzk/chzzk-api/live#undefined-2

type LiveSetting added in v0.3.0

type LiveSetting struct {
	Title            string   `json:"defaultLiveTitle"`
	Tags             []string `json:"tags"`
	CategoryID       string   `json:"categoryId"`
	CategoryType     string   `json:"categoryType"`
	CategoryValue    string   `json:"categoryValue"`
	CategoryImageURL string   `json:"posterImageUrl"`
}

type Manager added in v0.2.0

type Manager struct {
	ID          string `json:"managerChannelId"`
	Name        string `json:"managerChannelName"`
	Role        string `json:"userRole"`
	CreatedDate string `json:"createdDate"`
}

type NoticeKind added in v0.4.2

type NoticeKind string

type PatchLiveSettingRequest added in v0.3.0

type PatchLiveSettingRequest struct {
	Title    *string   `json:"defaultLiveTitle,omitempty"`
	Tags     []string  `json:"tags,omitempty"`
	Category *Category `json:"category,omitempty"`
}

type Response added in v0.2.0

type Response struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

Response is a struct that Chzzk always returns in the response body, with the actual response type in the Content field.

Each Service should embed Response to its own response struct, including the Content field with the actual response type.

type RevokeTokenRequest

type RevokeTokenRequest struct {
	ClientID      string `json:"clientId"`
	ClientSecret  string `json:"clientSecret"`
	Token         string `json:"token"`
	TokenTypeHint string `json:"tokenTypeHint"`
}

type SessionService

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

func (*SessionService) AuthClient

func (s *SessionService) AuthClient(ctx context.Context) (string, error)

AuthClient returns a URL for connecting to the Chzzk session service via client credentials.

  • pattern: Get
  • credential: [Chzzk.WithClientAuth]

Check the documentation for more details: https://chzzk.gitbook.io/chzzk/chzzk-api/session#undefined

func (*SessionService) AuthUser

func (s *SessionService) AuthUser(ctx context.Context) (string, error)

AuthUser returns a URL for connecting to the Chzzk session service via user credentials.

  • pattern: Get
  • credential: [Chzzk.WithAPIKey]

Check the documentation for more details: https://chzzk.gitbook.io/chzzk/chzzk-api/session#undefined-1

func (*SessionService) SubscribeChat

func (s *SessionService) SubscribeChat(ctx context.Context, sk string) error

SubscribeChat subscribes to chat events for the given session key.

  • pattern: Create
  • credential: [Chzzk.WithClientAuth] or [Chzzk.WithAPIKey]

Check the documentation for more details: https://chzzk.gitbook.io/chzzk/chzzk-api/session#undefined-5

func (*SessionService) UnSubscribeChat

func (s *SessionService) UnSubscribeChat(ctx context.Context, sk string) error

UnSubscribeChat unsubscribes from chat events for the given session key.

  • pattern: Delete
  • credential: [Chzzk.WithClientAuth] or [Chzzk.WithAPIKey]

Check the documentation for more details: https://chzzk.gitbook.io/chzzk/chzzk-api/session#undefined-6

type Subscriber added in v0.2.0

type Subscriber struct {
	ID          string `json:"ChannelId"`
	Name        string `json:"ChannelName"`
	Month       int    `json:"month"`
	Tier        int    `json:"tierNo"`
	CreatedDate string `json:"createdDate"`
}

type SubscriptionSort added in v0.2.0

type SubscriptionSort string
const (
	Recent SubscriptionSort = "RECENT"
	Longer SubscriptionSort = "LONGER"
)

type TokenNewRequest

type TokenNewRequest struct {
	TokenRequest
	Code  string `json:"code"`
	State string `json:"state"`
}

type TokenRefreshRequest

type TokenRefreshRequest struct {
	TokenRequest
	RefreshToken string `json:"refreshToken"`
}

type TokenRequest

type TokenRequest struct {
	GrantType    GrantType `json:"grantType"`
	ClientID     string    `json:"clientId"`
	ClientSecret string    `json:"clientSecret"`
}

type TokenResponse

type TokenResponse struct {
	AccessToken  string  `json:"accessToken"`
	RefreshToken string  `json:"refreshToken"`
	ExpiresIn    int     `json:"expiresIn"`
	TokenType    string  `json:"tokenType"`
	Scope        *string `json:"scope,omitempty"`
}

type TokenService

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

func (*TokenService) New added in v0.2.0

New requests a new access token using the provided authorization code and state.

  • pattern: Create
  • credential: [Chzzk.WithClientAuth]

Check the documentation for more details: https://chzzk.gitbook.io/chzzk/chzzk-api/authorization#access-token

func (*TokenService) Refresh added in v0.2.0

Refresh requests a new access token using the provided refresh token.

  • pattern: Create
  • credential: [Chzzk.WithClientAuth]

Check the documentation for more details: https://chzzk.gitbook.io/chzzk/chzzk-api/authorization#access-token-1

func (*TokenService) Revoke added in v0.2.0

Revoke revokes the provided access or refresh token.

  • pattern: Delete
  • credential: [Chzzk.WithClientAuth]

Check the documentation for more details: https://chzzk.gitbook.io/chzzk/chzzk-api/authorization#access-token-2

type User

type User struct {
	ChannelID   string `json:"channelId"`
	ChannelName string `json:"channelName"`
}

type UserService

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

UserService handles APIs prefixed with /users

func (*UserService) Me

func (s *UserService) Me(ctx context.Context) (*User, error)

Me retrieves the current user's information from the Chzzk API.

  • pattern: Get
  • credential: [Chzzk.WithAPIKey]

Check the documentation for more details: https://chzzk.gitbook.io/chzzk/chzzk-api/user

Directories

Path Synopsis
cmd
chzzk-login command
collect command
internal
package realtime provides a WebSocket client that has a full-duplex communication channel over a single TCP connection.
package realtime provides a WebSocket client that has a full-duplex communication channel over a single TCP connection.
Package socketio provides a Go implementation of the Socket.IO v2 (Engine.IO v3) protocol.
Package socketio provides a Go implementation of the Socket.IO v2 (Engine.IO v3) protocol.
package unofficial provides useful, but unofficial features for accessing to Chzzk.
package unofficial provides useful, but unofficial features for accessing to Chzzk.

Jump to

Keyboard shortcuts

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