Documentation
¶
Overview ¶
Example (Authenticated) ¶
package main
import (
"context"
"fmt"
"os"
"os/signal"
dm "github.com/MatchaCake/bilibili_dm_lib"
)
func main() {
// With cookies, you receive richer danmaku data (full medal info, etc.)
client := dm.NewClient(
dm.WithRoomID(510),
dm.WithCookie("your_SESSDATA", "your_bili_jct"),
)
client.OnDanmaku(func(d *dm.Danmaku) {
medal := ""
if d.MedalName != "" {
medal = fmt.Sprintf("[%s %d] ", d.MedalName, d.MedalLevel)
}
fmt.Printf("%s%s: %s\n", medal, d.Sender, d.Content)
})
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
_ = client.Start(ctx)
}
Example (Callback) ¶
package main
import (
"context"
"fmt"
"os"
"os/signal"
dm "github.com/MatchaCake/bilibili_dm_lib"
)
func main() {
// Create a client for room 510 (short ID is resolved automatically).
client := dm.NewClient(
dm.WithRoomID(510),
)
// Register typed callbacks.
client.OnDanmaku(func(d *dm.Danmaku) {
fmt.Printf("[弹幕] %s: %s\n", d.Sender, d.Content)
})
client.OnGift(func(g *dm.Gift) {
fmt.Printf("[礼物] %s %s %s x%d\n", g.User, g.Action, g.GiftName, g.Num)
})
client.OnSuperChat(func(sc *dm.SuperChat) {
fmt.Printf("[SC ¥%d] %s: %s\n", sc.Price, sc.User, sc.Message)
})
// Start blocks until context is cancelled.
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
if err := client.Start(ctx); err != nil && ctx.Err() == nil {
fmt.Println("error:", err)
}
}
Example (ChannelSubscribe) ¶
package main
import (
"context"
"fmt"
dm "github.com/MatchaCake/bilibili_dm_lib"
)
func main() {
client := dm.NewClient(
dm.WithRoomID(21452505),
)
// Channel-based subscription receives all events.
events := client.Subscribe()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
if err := client.Start(ctx); err != nil && ctx.Err() == nil {
fmt.Println("error:", err)
}
}()
// Process events from the channel.
for ev := range events {
switch d := ev.Data.(type) {
case *dm.Danmaku:
fmt.Printf("[%d] %s: %s\n", ev.RoomID, d.Sender, d.Content)
case *dm.Gift:
fmt.Printf("[%d] Gift: %s x%d from %s\n", ev.RoomID, d.GiftName, d.Num, d.User)
}
}
}
Example (MultiRoom) ¶
package main
import (
"context"
"fmt"
"os"
"os/signal"
dm "github.com/MatchaCake/bilibili_dm_lib"
)
func main() {
// Subscribe to multiple rooms at once.
client := dm.NewClient(
dm.WithRoomID(510),
dm.WithRoomID(21452505),
)
client.OnDanmaku(func(d *dm.Danmaku) {
fmt.Printf("%s: %s\n", d.Sender, d.Content)
})
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
_ = client.Start(ctx)
}
Index ¶
- Constants
- type Client
- func (c *Client) AddRoom(roomID int64) error
- func (c *Client) OnDanmaku(fn func(*Danmaku))
- func (c *Client) OnGift(fn func(*Gift))
- func (c *Client) OnGuardBuy(fn func(*GuardBuy))
- func (c *Client) OnHeartbeat(fn func(*HeartbeatData))
- func (c *Client) OnInteractWord(fn func(*InteractWord))
- func (c *Client) OnLive(fn func(*LiveEvent))
- func (c *Client) OnPreparing(fn func(*LiveEvent))
- func (c *Client) OnRawEvent(fn func(cmd string, raw []byte))
- func (c *Client) OnSuperChat(fn func(*SuperChat))
- func (c *Client) RemoveRoom(roomID int64)
- func (c *Client) SendDanmaku(ctx context.Context, roomID int64, msg string) error
- func (c *Client) Start(ctx context.Context) error
- func (c *Client) Subscribe() <-chan Event
- type Danmaku
- type DanmakuMode
- type Event
- type Gift
- type GuardBuy
- type HeartbeatData
- type InteractWord
- type LiveEvent
- type Option
- type Packet
- type SendError
- type Sender
- type SenderOption
- type SuperChat
Examples ¶
Constants ¶
const ( EventDanmaku = "danmaku" EventGift = "gift" EventSuperChat = "superchat" EventGuardBuy = "guard" EventLive = "live" EventPreparing = "preparing" EventInteract = "interact" EventRaw = "raw" EventHeartbeat = "heartbeat" )
Event type constants.
const ( ProtoCommand uint16 = 0 // Raw JSON command ProtoSpecial uint16 = 1 // Special (heartbeat, auth) ProtoCommandZlib uint16 = 2 // Zlib-compressed commands ProtoCommandBrotli uint16 = 3 // Brotli-compressed commands )
Packet protocol versions.
const ( OpHeartbeat uint32 = 2 OpHeartbeatReply uint32 = 3 OpCommand uint32 = 5 OpCertificate uint32 = 7 OpCertificateResp uint32 = 8 )
Packet operation types.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client subscribes to danmaku streams from one or more Bilibili live rooms. It can also send danmaku via the built-in Sender (see SendDanmaku).
func (*Client) OnGuardBuy ¶
OnGuardBuy registers a callback for guard purchases.
func (*Client) OnHeartbeat ¶
func (c *Client) OnHeartbeat(fn func(*HeartbeatData))
OnHeartbeat registers a callback for heartbeat reply (popularity) events.
func (*Client) OnInteractWord ¶
func (c *Client) OnInteractWord(fn func(*InteractWord))
OnInteractWord registers a callback for user interactions (entry, follow, share).
func (*Client) OnPreparing ¶
OnPreparing registers a callback for when a room goes offline.
func (*Client) OnRawEvent ¶
OnRawEvent registers a catch-all callback for any command event. This receives events that are not parsed into typed structs.
func (*Client) OnSuperChat ¶
OnSuperChat registers a callback for Super Chat messages.
func (*Client) RemoveRoom ¶
RemoveRoom disconnects from a room.
func (*Client) SendDanmaku ¶
SendDanmaku sends a danmaku message to the given room. It uses the Client's credentials (set via WithCookie) and sender settings (WithMaxDanmakuLength, WithSendCooldown). Long messages are auto-split.
type Danmaku ¶
type Danmaku struct {
Sender string
UID int64
Content string
Timestamp time.Time
MedalName string
MedalLevel int
EmoticonURL string
}
Danmaku represents a chat message.
type DanmakuMode ¶
type DanmakuMode int
DanmakuMode controls how the danmaku is displayed in the live room.
const ( ModeScroll DanmakuMode = 1 // scrolling (default) ModeBottom DanmakuMode = 4 // pinned at bottom ModeTop DanmakuMode = 5 // pinned at top )
type Gift ¶
type Gift struct {
User string
UID int64
GiftName string
GiftID int64
Num int
Price int64 // in gold/silver coins
CoinType string
Action string
}
Gift represents a gift event.
type GuardBuy ¶
type GuardBuy struct {
User string
UID int64
GuardLevel int // 1=总督, 2=提督, 3=舰长
Price int64
Num int
}
GuardBuy represents a captain/admiral/governor purchase.
type HeartbeatData ¶
type HeartbeatData struct {
Popularity uint32
}
HeartbeatData carries the popularity value from heartbeat responses.
type InteractWord ¶
InteractWord represents user interactions (entry, follow, share).
type Option ¶
type Option func(*clientConfig)
Option configures a Client.
func WithCookie ¶
WithCookie sets the SESSDATA and bili_jct cookies for authenticated access. Authenticated connections receive richer danmaku data (e.g., full medal info).
func WithHTTPClient ¶
WithHTTPClient overrides the default HTTP client used for API calls.
func WithMaxDanmakuLength ¶
WithMaxDanmakuLength sets the maximum rune length per danmaku message for the Client's built-in Sender. Default is 20; UL20+ users can set 30.
func WithRoomID ¶
WithRoomID adds a room to connect to on Start.
func WithSendCooldown ¶
WithSendCooldown sets the minimum interval between sends to the same room for the Client's built-in Sender. Default is 5 seconds.
type Sender ¶
type Sender struct {
// contains filtered or unexported fields
}
Sender sends danmaku messages to Bilibili live rooms. It is safe for concurrent use.
func NewSender ¶
func NewSender(opts ...SenderOption) *Sender
NewSender creates a standalone Sender for sending danmaku without subscribing.
func (*Sender) Send ¶
Send sends a danmaku message to the given room using the default scroll mode. Long messages are automatically split into chunks of maxLength runes, with cooldown pauses between each chunk.
func (*Sender) SendWithMode ¶
func (s *Sender) SendWithMode(ctx context.Context, roomID int64, msg string, mode DanmakuMode) error
SendWithMode sends a danmaku message with the specified display mode.
type SenderOption ¶
type SenderOption func(*senderConfig)
SenderOption configures a Sender.
func WithCooldown ¶
func WithCooldown(d time.Duration) SenderOption
WithCooldown sets the minimum interval between sends to the same room. Default is 5 seconds.
func WithMaxLength ¶
func WithMaxLength(n int) SenderOption
WithMaxLength sets the maximum rune length per danmaku message. Messages exceeding this limit are auto-split into multiple sends. Default is 20. Users with UL20+ can set this to 30.
func WithSenderCookie ¶
func WithSenderCookie(sessdata, biliJCT string) SenderOption
WithSenderCookie sets the SESSDATA and bili_jct cookies for sending. Both values are required — bili_jct is used as the CSRF token.
func WithSenderHTTPClient ¶
func WithSenderHTTPClient(hc *http.Client) SenderOption
WithSenderHTTPClient overrides the default HTTP client used by the Sender.