This commit is contained in:
Akiba
2022-07-27 17:28:07 +08:00
parent 454ea5ef9a
commit 8bd1296df8
3 changed files with 31 additions and 14 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

@@ -125,6 +125,7 @@ func (c *Client) heartBeatLoop() {
}
}
// Start 启动弹幕 Client 初始化并连接 ws、发送心跳包
func (c *Client) Start() error {
if err := c.init(); err != nil {
return err
@@ -137,6 +138,7 @@ func (c *Client) Start() error {
return nil
}
// Stop 停止弹幕 Client
func (c *Client) Stop() {
c.cancel()
}

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)