Merge pull request #6 from Akegarasu/v3

V3
This commit is contained in:
秋葉杏
2022-08-03 22:22:44 +08:00
committed by GitHub
5 changed files with 154 additions and 60 deletions

View File

@@ -2,6 +2,8 @@
bilibili 直播弹幕 golang 库
**注意此分支为V3重构部分api的版本使用例子请看 example**
## 安装
```shell
go get github.com/Akegarasu/blivedm-go
@@ -25,36 +27,47 @@ import (
"fmt"
"github.com/Akegarasu/blivedm-go/client"
"github.com/Akegarasu/blivedm-go/message"
_ "github.com/Akegarasu/blivedm-go/utils"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
)
func main() {
c := client.NewClient("8792912")
// 弹幕事件
c.OnDanmaku(func(danmuku *message.Danmaku) {
fmt.Printf("[弹幕] %s%s\n", danmuku.Sender.Uname, danmuku.Content)
log.SetLevel(log.DebugLevel)
c := client.NewClient("732")
//弹幕事件
c.OnDanmaku(func(danmaku *message.Danmaku) {
if danmaku.Type == message.EmoticonDanmaku {
fmt.Printf("[弹幕表情] %s表情URL %s\n", danmaku.Sender.Uname, danmaku.Emoticon.Url)
} else {
fmt.Printf("[弹幕] %s%s\n", danmaku.Sender.Uname, danmaku.Content)
}
})
// 醒目留言事件
c.OnSuperChat(func(superChat *message.SuperChat) {
fmt.Printf("[SC] %s: %s, %d 元\n", superChat.UserInfo.Uname, superChat.Message, superChat.Price)
fmt.Printf("[SC|%d元] %s: %s\n", superChat.Price, superChat.UserInfo.Uname, superChat.Message)
})
// 礼物事件
c.OnGift(func(gift *message.Gift) {
fmt.Printf("[礼物] %s 的 %s %d 个\n", gift.Uname, gift.GiftName, gift.Num)
if gift.CoinType == "gold" {
fmt.Printf("[礼物] %s 的 %s %d 个 共%.2f元\n", gift.Uname, gift.GiftName, gift.Num, float64(gift.Num*gift.Price)/1000)
}
})
// 上舰事件
c.OnGuardBuy(func(guardBuy *message.GuardBuy) {
fmt.Printf("%v\n", guardBuy)
fmt.Printf("[大航海] %s 开通了 %d 等级的大航海,金额 %d 元\n", guardBuy.Username, guardBuy.GuardLevel, guardBuy.Price/1000)
})
// 【可选】设置弹幕服务器,不设置就会从 api 获取服务器地址
// 该函数设置服务器为 wss://broadcastlv.chat.bilibili.com/sub
c.UseDefaultHost()
// 启动
err := c.ConnectAndStart()
// 监听自定义事件
c.RegisterCustomEventHandler("STOP_LIVE_ROOM_LIST", func(s string) {
data := gjson.Get(s, "data").String()
fmt.Printf("STOP_LIVE_ROOM_LIST: %s\n", data)
})
err := c.Start()
if err != nil {
fmt.Println(err)
log.Fatal(err)
}
fmt.Println("started")
log.Println("started")
// 需要自行阻塞什么方法都可以
select {}
}

View File

@@ -15,7 +15,7 @@ import (
type Client struct {
conn *websocket.Conn
roomID string
realRoomID string
tempID string
token string
host string
hostList []string
@@ -25,10 +25,11 @@ type Client struct {
done <-chan struct{}
}
// NewClient 创建一个新的弹幕 client
func NewClient(roomID string) *Client {
ctx, cancel := context.WithCancel(context.Background())
return &Client{
roomID: roomID,
tempID: roomID,
eventHandlers: &eventHandlers{},
customEventHandlers: &customEventHandlers{},
done: ctx.Done(),
@@ -36,21 +37,21 @@ func NewClient(roomID string) *Client {
}
}
func (c *Client) Connect() error {
retryCount := 0
rid, _ := strconv.Atoi(c.roomID)
if rid <= 1000 && c.realRoomID == "" {
realID, err := api.GetRoomRealID(c.roomID)
// init 初始化 获取真实 roomID 和 弹幕服务器 host
func (c *Client) init() error {
rid, _ := strconv.Atoi(c.tempID)
// 处理 shortID
if rid <= 1000 && c.roomID == "" {
realID, err := api.GetRoomRealID(c.tempID)
if err != nil {
return err
}
c.roomID = realID
c.realRoomID = realID
} else {
c.realRoomID = c.roomID
c.roomID = c.tempID
}
if c.host == "" {
info, err := api.GetDanmuInfo(c.realRoomID)
info, err := api.GetDanmuInfo(c.roomID)
if err != nil {
c.hostList = []string{"broadcastlv.chat.bilibili.com"}
} else {
@@ -60,25 +61,31 @@ func (c *Client) Connect() error {
}
c.token = info.Data.Token
}
return nil
}
func (c *Client) connect() error {
retryCount := 0
retry:
// 随着重连会自动切换弹幕服务器
c.host = c.hostList[retryCount%len(c.hostList)]
retryCount++
conn, res, err := websocket.DefaultDialer.Dial(fmt.Sprintf("wss://%s/sub", c.host), nil)
if err != nil {
log.Error("connect dial failed, retry...")
log.Errorf("connect dial failed, retry %d times", retryCount)
time.Sleep(2 * time.Second)
goto retry
}
c.conn = conn
res.Body.Close()
if err = c.sendEnterPacket(); err != nil {
log.Error("connect enter packet send failed, retry...")
log.Errorf("failed to send enter packet, retry %d times", retryCount)
goto retry
}
return nil
}
func (c *Client) listen() {
func (c *Client) wsLoop() {
for {
select {
case <-c.done:
@@ -89,11 +96,11 @@ func (c *Client) listen() {
if err != nil {
log.Info("reconnect")
time.Sleep(time.Duration(3) * time.Millisecond)
_ = c.Connect()
_ = c.connect()
continue
}
if msgType != websocket.BinaryMessage {
log.Error("packet not binary", data)
log.Error("packet not binary")
continue
}
for _, pkt := range packet.DecodePacket(data).Parse() {
@@ -103,33 +110,7 @@ func (c *Client) listen() {
}
}
func (c *Client) Start() {
go c.listen()
go c.heartBeat()
}
func (c *Client) Stop() {
c.cancel()
}
func (c *Client) ConnectAndStart() error {
if err := c.Connect(); err != nil {
return err
}
c.Start()
return nil
}
func (c *Client) SetHost(host string) {
c.host = host
}
// UseDefaultHost 使用默认 host broadcastlv.chat.bilibili.com
func (c *Client) UseDefaultHost() {
c.SetHost("broadcastlv.chat.bilibili.com")
}
func (c *Client) heartBeat() {
func (c *Client) heartBeatLoop() {
pkt := packet.NewHeartBeatPacket()
for {
select {
@@ -144,8 +125,35 @@ func (c *Client) heartBeat() {
}
}
// Start 启动弹幕 Client 初始化并连接 ws、发送心跳包
func (c *Client) Start() error {
if err := c.init(); err != nil {
return err
}
if err := c.connect(); err != nil {
return err
}
go c.wsLoop()
go c.heartBeatLoop()
return nil
}
// Stop 停止弹幕 Client
func (c *Client) Stop() {
c.cancel()
}
func (c *Client) SetHost(host string) {
c.host = host
}
// UseDefaultHost 使用默认 host broadcastlv.chat.bilibili.com
func (c *Client) UseDefaultHost() {
c.hostList = []string{"broadcastlv.chat.bilibili.com"}
}
func (c *Client) sendEnterPacket() error {
rid, err := strconv.Atoi(c.realRoomID)
rid, err := strconv.Atoi(c.roomID)
if err != nil {
return errors.New("error roomID")
}

View File

@@ -63,6 +63,7 @@ func (c *Client) OnLive(f func(*message.Live)) {
c.eventHandlers.liveHandlers = append(c.eventHandlers.liveHandlers, f)
}
// Handle 处理一个包
func (c *Client) Handle(p packet.Packet) {
switch p.Operation {
case packet.Notification:
@@ -124,6 +125,7 @@ func (c *Client) Handle(p packet.Packet) {
}
}
// parseCmd 获取 JSON 报文的 CMD
func parseCmd(d []byte) string {
// {"cmd":"DANMU_MSG", ...
l := len(d)

72
example/main.go Normal file
View File

@@ -0,0 +1,72 @@
package main
import (
"fmt"
"github.com/Akegarasu/blivedm-go/api"
"github.com/Akegarasu/blivedm-go/client"
"github.com/Akegarasu/blivedm-go/message"
_ "github.com/Akegarasu/blivedm-go/utils"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
)
func main() {
log.SetLevel(log.DebugLevel)
c := client.NewClient("732")
//弹幕事件
c.OnDanmaku(func(danmaku *message.Danmaku) {
if danmaku.Type == message.EmoticonDanmaku {
fmt.Printf("[弹幕表情] %s表情URL %s\n", danmaku.Sender.Uname, danmaku.Emoticon.Url)
} else {
fmt.Printf("[弹幕] %s%s\n", danmaku.Sender.Uname, danmaku.Content)
}
})
// 醒目留言事件
c.OnSuperChat(func(superChat *message.SuperChat) {
fmt.Printf("[SC|%d元] %s: %s\n", superChat.Price, superChat.UserInfo.Uname, superChat.Message)
})
// 礼物事件
c.OnGift(func(gift *message.Gift) {
if gift.CoinType == "gold" {
fmt.Printf("[礼物] %s 的 %s %d 个 共%.2f元\n", gift.Uname, gift.GiftName, gift.Num, float64(gift.Num*gift.Price)/1000)
}
})
// 上舰事件
c.OnGuardBuy(func(guardBuy *message.GuardBuy) {
fmt.Printf("[大航海] %s 开通了 %d 等级的大航海,金额 %d 元\n", guardBuy.Username, guardBuy.GuardLevel, guardBuy.Price/1000)
})
// 监听自定义事件
c.RegisterCustomEventHandler("STOP_LIVE_ROOM_LIST", func(s string) {
data := gjson.Get(s, "data").String()
fmt.Printf("STOP_LIVE_ROOM_LIST: %s\n", data)
})
err := c.Start()
if err != nil {
log.Fatal(err)
}
log.Println("started")
// 需要自行阻塞什么方法都可以
select {}
}
func sendDanmaku() error {
dmReq := &api.DanmakuRequest{
Msg: "official_13",
RoomID: "732",
Bubble: "0",
Color: "16777215",
FontSize: "25",
Mode: "1",
DmType: "1",
}
d, err := api.SendDanmaku(dmReq, &api.BiliVerify{
Csrf: "",
SessData: "",
})
if err != nil {
return err
}
fmt.Println(d)
return nil
}

View File

@@ -16,7 +16,7 @@ type Enter struct {
}
// NewEnterPacket 构造进入房间的包
// uid可以为0key不需要
// uid 可以为 0, key 在使用 broadcastlv 服务器的时候不需要
func NewEnterPacket(uid int, roomID int, key string) []byte {
ent := &Enter{
UID: uid,
@@ -28,8 +28,7 @@ func NewEnterPacket(uid int, roomID int, key string) []byte {
Key: key,
}
pkt := NewPlainPacket(RoomEnter, ent.Json())
upkt := pkt.Build()
return upkt
return pkt.Build()
}
func (e *Enter) Json() []byte {