bilidanmaku

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Jun 3, 2020 License: MIT Imports: 20 Imported by: 0

README

bilidanmaku

B 站直播弹幕 Go 版。 在原项目 基础上作了以下修改:

  • 更换tcp(直播姬)的方式为websocket
  • 部分修改

安装

go get github.com/dongshimou/bilidanmaku

示例

实时打印弹幕
package main

import "github.com/dongshimou/bilidanmaku"

func main() {
	bili := bilidanmaku.NewBiliBiliClient()
	bili.RegHandleFunc(bilidanmaku.CmdAll, bilidanmaku.DefaultHandler)
	bili.ConnectServer(102)
}
事件订阅

如果你希望订阅不同的事件,请尝试bilidanmaku.Cmd*开头的一系列常量。 以下是一些示例,你也可以随时在example目录下查看.

订阅弹幕事件,并输出弹幕信息

bili := bilidanmaku.NewBiliBiliClient()
bili.RegHandleFunc(bilidanmaku.CmdDanmuMsg, func(c *bilidanmaku.Context) {
	dinfo := c.GetDanmuInfo()
	log.Printf("[%d]%d 说: %s\r\n", c.RoomID, dinfo.UID, dinfo.Text)
})

进入房间

bili.RegHandleFunc(bilidanmaku.CmdWelcome, func(c *bilidanmaku.Context) {
	winfo := c.GetWelcomeInfo()
	if winfo.Uname != "" {
		log.Printf("[%d]%s 进入了房间\r\n", c.RoomID, winfo.Uname)
	} else {
		log.Printf("[%d]%d 进入了房间\r\n", c.RoomID, winfo.UID)
	}
})

投喂礼物

bili.RegHandleFunc(bilidanmaku.CmdSendGift, func(c *bilidanmaku.Context) {
	gInfo := c.GetGiftInfo()
	log.Printf("[%d]%s %s 了 %s x %d (价值%.3f)\r\n", c.RoomID, gInfo.Uname, gInfo.Action, gInfo.GiftName, gInfo.Num, float32(gInfo.Price*gInfo.Num)/1000)
})

在线人数变动

bili.RegHandleFunc(bilidanmaku.CmdOnlineChange, func(c *bilidanmaku.Context) bool {
	online := c.GetOnlineNumber()
	log.Printf("[%d]房间里当前在线:%d\r\n", c.RoomID, online)
})

状态切换为直播开始

bili.RegHandleFunc(bilidanmaku.CmdLive, func(c *bilidanmaku.Context) bool {
	online := c.GetOnlineNumber()
	log.Println("主播诈尸啦!")
})

状态切换为准备中

bili.RegHandleFunc(bilidanmaku.CmdPreparing, func(c *bilidanmaku.Context) bool {
	online := c.GetOnlineNumber()
	log.Println("主播正在躺尸")
})

返回值 Handler和HandleFunc的返回值用于控制调用链是否继续向下执行。 如果你希望其它调用链不响应,调用c.Abort()

消息调试

通过注册 bilidanmaku.DebugHandler,可以在收到直播消息时查看原始消息。

package main

import "github.com/dongshimou/bilidanmaku"

func main() {
	bili := bilidanmaku.NewBiliBiliClient()
	bili.RegHandleFunc(bilidanmaku.CmdAll, bilidanmaku.DebugHandler)
	bili.ConnectServer(102)
}

运行后,当直播间发生事件时,将会输出类似格式的JSON输出:

{
  "cmd": "DANMU_MSG",
  "info": [
    [
      0,
      1,
      25,
      16777215,
      1517402685,
      -136720455,
      0,
      "c42d0814",
      0
    ],
    "干嘛不播啦",
    [
      30731115,
      "Ed在",
      0,
      0,
      0,
      10000,
      1,
      ""
    ],
    [],
    [
      1,
      0,
      9868950,
      "\u003e50000"
    ],
    [],
    0,
    0,
    {
      "uname_color": ""
    }
  ]
}

以上示例的是一个弹幕消息. 其中"cmd": "DANMU_MSG"中的"DANMU_MSG",就是调用bili.RegHandleFunc时需要传入的cmd参数。 你可以通过bilidanmaku.CmdType("嘿,我是CmdType"),将string转换为CmdType. 在这之后,你可以使用 bili.RegHandleFunc 或 bili.RegHandler 注册这个CmdType.

扩展

通过读取gobilibili.Context传入的Msg,可以处理尚未进行支持的事件. 请搭配上一节的消息调试进行食用。 以下是DefaultHandler的实现。

func DefaultHandler(c *Context) bool {
	cmd, err := c.Msg.Get("cmd").String()
	if err != nil {
		return true
	}
	if cmd == "LIVE" {
		fmt.Println("直播开始。。。")
		return false
	}
	if cmd == "PREPARING" {
		fmt.Println("房主准备中。。。")
		return false
	}
	if cmd == "DANMU_MSG" {
		commentText, err := c.Msg.Get("info").GetIndex(1).String()
		if err != nil {
			fmt.Println("Json decode error failed: ", err)
			return false
		}

		commentUser, err := c.Msg.Get("info").GetIndex(2).GetIndex(1).String()
		if err != nil {
			fmt.Println("Json decode error failed: ", err)
			return false
		}
		fmt.Println(commentUser, " say: ", commentText)
		return false
	}
	return false
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DebugHandler

func DebugHandler(c *Context)

DebugHandler debug msg info

func DefaultHandler

func DefaultHandler(c *Context)

DefaultHandler print cmd msg log

Types

type BiliLiveClient

type BiliLiveClient struct {
	ChatPort int

	ChatHost string
	// contains filtered or unexported fields
}

func NewBiliBiliClient

func NewBiliBiliClient() *BiliLiveClient

新客户端

func (*BiliLiveClient) ConnectServer

func (bili *BiliLiveClient) ConnectServer(roomID int) error

ConnectServer define

func (*BiliLiveClient) GetRoomID

func (bili *BiliLiveClient) GetRoomID() int

GetRoomID Get the current room ID

func (*BiliLiveClient) RegHandleFunc

func (bili *BiliLiveClient) RegHandleFunc(cmd CmdType, hfunc HandleFunc)

func (*BiliLiveClient) Run

func (bili *BiliLiveClient) Run()

事件处理

func (*BiliLiveClient) SendJoinChannel

func (bili *BiliLiveClient) SendJoinChannel(channelID int) error

SendJoinChannel define

func (*BiliLiveClient) Write

func (bili *BiliLiveClient) Write(data []byte) error

type CmdType

type CmdType string
const (
	// CmdAll 订阅所有cmd事件时使用
	CmdAll CmdType = ""
	// CmdLive 直播开始
	CmdLive CmdType = "LIVE"
	// CmdPreparing 直播准备中
	CmdPreparing CmdType = "PREPARING"

	// CmdDanmuMsg 弹幕消息
	// {"cmd":"DANMU_MSG","info":[[0,1,25,16777215,1591004454028,-1464052061,0,"034722a0",0,0,0],"我改一下",[23624052,"星云之音喵",0,0,0,10000,1,""],[1,"谜酥","谜之声",5082,6406234,"",0],[12,0,6406234,"\u003e50000"],["",""],0,0,null,{"ts":1591004454,"},0,0,null,null,0]}
	CmdDanmuMsg CmdType = "DANMU_MSG"

	// CmdWelcomeGuard 管理进房
	// {"cmd":"WELCOME_GUARD","data":{"uid":2721583,"username":"超高校级的无节操","gul":3,"mock_effect":0}}
	CmdWelcomeGuard CmdType = "WELCOME_GUARD"

	// CmdWelcome 群众进房
	CmdWelcome CmdType = "WELCOME"
	// CmdSendGift 赠送礼物
	CmdSendGift CmdType = "SEND_GIFT"
	// CmdNoticeMsg 系统消息通知
	CmdNoticeMsg CmdType = "NOTICE_MSG"
	// CmdOnlineChange 在线人数变动,这不是一个标准cmd类型,仅为了统一handler接口而加入
	CmdOnlineChange CmdType = "ONLINE_CHANGE"

	CmdSuperChatMsg CmdType = "SUPER_CHAT_MESSAGE" // 付费留言

)

type ConnType

type ConnType string

连接类型

type Context

type Context struct {
	Msg    *simplejson.Json
	RoomID int
	Cmd    CmdType
	// contains filtered or unexported fields
}

Context 消息上下文环境,提供快捷提取消息数据的功能

func (*Context) Abort

func (c *Context) Abort()

func (*Context) GetDanmuInfo

func (p *Context) GetDanmuInfo() *DanmuInfo

GetDanmuInfo 在Handler中调用,从simplejson.Json中提取弹幕信息

func (*Context) GetGiftInfo

func (p *Context) GetGiftInfo() *GiftInfo

GetGiftInfo 获取礼物信息

func (*Context) GetNoticeMsg

func (p *Context) GetNoticeMsg() *NoticeMsg

GetNoticeMsg 获取系统消息通知

func (*Context) GetOnlineNumber

func (p *Context) GetOnlineNumber() int

GetOnlineNumber 在Handler中调用,从simplejson.Json中提取房间在线人气值

func (*Context) GetSuperChatMsg

func (p *Context) GetSuperChatMsg() *SuperChatMsg

获取付费留言

func (*Context) GetWelcomeGuardInfo

func (p *Context) GetWelcomeGuardInfo() *WelcomeGuardInfo

GetWelcomeGuardInfo 在Handler中调用,从一个simplejson.Json中提取管理进房信息

func (*Context) GetWelcomeInfo

func (p *Context) GetWelcomeInfo() *WelcomeInfo

GetWelcomeInfo 在Handler中调用,从一个simplejson.Json中提取普通人员进房信息

func (*Context) IsAbort

func (c *Context) IsAbort() bool

type DanmuInfo

type DanmuInfo struct {
	UID         int    `json:"uid"`          //用户ID
	Uname       string `json:"uname"`        //用户名称
	Rank        int    `json:"rank"`         //用户排名
	Level       int    `json:"level"`        //用户等级
	Text        string `json:"text"`         //说的话
	MedalLevel  int    `json:"medal_level"`  //勋章等级
	MedalName   string `json:"medal_name"`   //勋章名称
	MedalAnchor string `json:"medal_anchor"` //勋章所属主播
}

DanmuInfo 弹幕信息

type GiftInfo

type GiftInfo struct {
	Action    string `json:"action"`
	AddFollow int    `json:"addFollow"`
	BeatID    string `json:"beatId"`
	BizSource string `json:"biz_source"`
	Capsule   struct {
		Colorful struct {
			Change   int `json:"change"`
			Coin     int `json:"coin"`
			Progress struct {
				Max int `json:"max"`
				Now int `json:"now"`
			} `json:"progress"`
		} `json:"colorful"`
		Normal struct {
			Change   int `json:"change"`
			Coin     int `json:"coin"`
			Progress struct {
				Max int `json:"max"`
				Now int `json:"now"`
			} `json:"progress"`
		} `json:"normal"`
	} `json:"capsule"`
	EventNum   int    `json:"eventNum"`
	EventScore int    `json:"eventScore"`
	GiftID     int    `json:"giftId"`
	GiftName   string `json:"giftName"`
	GiftType   int    `json:"giftType"`
	CoinType   string `json:"coin_type"` // 礼物类型 silver(银瓜子) gold(金瓜子)
	TotalCoin  int    `json:"total_coin"`
	Gold       int    `json:"gold"`
	// Medal       interface{} `json:"medal"`
	Metadata string `json:"metadata"`
	NewMedal int    `json:"newMedal"`
	NewTitle int    `json:"newTitle"`
	// NoticeMsg   interface{} `json:"notice_msg"`
	Num    int    `json:"num"`
	Price  int    `json:"price"`
	Rcost  int    `json:"rcost"`
	Remain int    `json:"remain"`
	Rnd    string `json:"rnd"`
	Silver int    `json:"silver"`
	// SmalltvMsg  interface{} `json:"smalltv_msg"`
	// SpecialGift interface{} `json:"specialGift"`
	Super     int    `json:"super"`
	Timestamp int    `json:"timestamp"`
	Title     string `json:"title"`
	TopList   *[]struct {
		Face       string `json:"face"`
		GuardLevel int    `json:"guard_level"`
		IsSelf     int    `json:"isSelf"`
		Rank       int    `json:"rank"`
		Score      int    `json:"score"`
		UID        int    `json:"uid"`
		Uname      string `json:"uname"`
	} `json:"top_list"`
	UID   int    `json:"uid"`
	Uname string `json:"uname"`
	Face  string `json:"face"`
}

GiftInfo 礼物信息

type HandleFunc

type HandleFunc func(c *Context)

func (HandleFunc) HandleFunc

func (f HandleFunc) HandleFunc(context *Context)

type NoticeMsg

type NoticeMsg struct {
	MsgCommon string `json:msg_common`
}

type SuperChatMsg

type SuperChatMsg struct {
	Id                    int64   `json:"id"`
	Uid                   int64   `json:"uid"`     // 用户id
	Price                 float64 `json:"price"`   // 价值
	Rate                  float64 `json:"rate"`    // (可能是金瓜子与rmb的比例)
	Message               string  `json:"message"` // 留言消息
	TransMark             int     `json:"trans_mark"`
	IsRanked              int     `json:"is_ranked"`
	MessageTrans          string  `json:"message_trans"`
	BackgroundImage       string  `json:"background_image"`
	BackgroundColor       string  `json:"background_color"`
	BackgroundIcon        string  `json:"background_icon"`
	BackgroundPriceColor  string  `json:"background_price_color"`
	BackgroundBottomColor string  `json:"background_bottom_color"`
	Ts                    int64   `json:"ts"`
	Token                 string  `json:"token"`
	// MedalInfo object
	UserInfo struct {
		Uname      string `json:"uname"`
		Face       string `json:"face"`
		FaceFrame  string `json:"face_frame"`
		GuardLevel int    `json:"guard_level"`
		UserLevel  int    `json:"user_level"`
		LevelColor string `json:"level_color"`
		IsVip      int    `json:"is_vip"`
		IsSvip     int    `json:"is_svip"`
		IsMainVip  int    `json:"is_main_vip"`
		Title      string `json:"title"`
		Manager    int    `json:"manager"`
	} `json:"user_info"` // 用户信息
	Time      int64 `json:"time"`       // 持续秒
	StartTime int64 `json:"start_time"` // 开始时间戳
	EndTime   int64 `json:"end_time"`   // 结束时间戳
	Gift      struct {
		Num      int    `json:"num"`
		GiftId   int    `json:"gift_id"`
		GiftName string `json:"gift_name"`
	} `json:"gift"`
}

type WelcomeGuardInfo

type WelcomeGuardInfo struct {
	GuardLevel string `json:"guard_level"`
	UID        int    `json:"uid"`
	Username   string `json:"username"`
}

WelcomeGuardInfo 管理进房信息

type WelcomeInfo

type WelcomeInfo struct {
	IsAdmin bool   `json:"is_admin"`
	UID     int    `json:"uid"`
	Uname   string `json:"uname"`
	Vip     int    `json:"vip"`
	Svip    int    `json:"svip"`
}

WelcomeInfo 普通人员进房信息

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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