openblive

package module
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2024 License: MIT Imports: 16 Imported by: 0

README

open-bilibili-live

个人维护的Bilibili直播开放平台SDK For Golang

官方文档请查看 documentation

Bilibili直播开放平台SDK Golang

Installation

go get github.com/aynakeya/open-bilibili-live

Usage

Create App

bliveApp := &openblive.BLiveApp{
		AppID:        1692609633998,
		AccessKey:    os.Getenv("openblive_access_key_id"),
		AccessSecret: os.Getenv("openblive_access_key_secret"),
	}

Create & Start & End Client

client := bliveApp.CreateClient("BPCRO8L9EOE82")
fmt.Println(client.Start())
fmt.Println(client.End())

Establish Long Connection

conn := client.GetLongConn()
conn.OnDanmu(func(data openblive.DanmakuData) {
	fmt.Println(data.UName, data.FansMedalName, data.Msg)
})
fmt.Println(conn.EstablishConnection(context.Background()))
quit := make(chan os.Signal)
signal.Notify(quit, os.Interrupt)
<-quit
fmt.Println(conn.CloseConnection())

Documentation

Index

Constants

View Source
const (
	UrlAppStart          = "/v2/app/start"
	UrlAppStop           = "/v2/app/end"
	UrlAppHeartBeat      = "/v2/app/heartbeat"
	UrlAppBatchHeartBeat = "/v2/app/batchHeartbeat"
)
View Source
const (
	CmdDanmu        string = "LIVE_OPEN_PLATFORM_DM"
	CmdGift                = "LIVE_OPEN_PLATFORM_SEND_GIFT"
	CmdSuperChat           = "LIVE_OPEN_PLATFORM_SUPER_CHAT"
	CmdSuperChatDel        = "LIVE_OPEN_PLATFORM_SUPER_CHAT_DEL"
	CmdNewGuard            = "LIVE_OPEN_PLATFORM_GUARD"
	CmdLike                = "LIVE_OPEN_PLATFORM_LIKE"
)
View Source
const (
	// OpHandshake handshake
	OpHandshake = 0
	// OpHandshakeReply handshake reply
	OpHandshakeReply = 1

	// OpHeartbeat heartbeat
	OpHeartbeat = 2
	// OpHeartbeatReply heartbeat reply
	OpHeartbeatReply = 3

	// OpSendMsg send message.
	OpSendMsg = 4
	// OpSendMsgReply  send message reply
	OpSendMsgReply = 5

	// OpDisconnectReply disconnect reply
	OpDisconnectReply = 6

	// OpAuth auth connnect
	OpAuth = 7
	// OpAuthReply auth connect reply
	OpAuthReply = 8

	// OpRaw  raw message
	OpRaw = 9

	// OpProtoReady proto ready
	OpProtoReady = 10
	// OpProtoFinish proto finish
	OpProtoFinish = 11

	// OpChangeRoom change room
	OpChangeRoom = 12
	// OpChangeRoomReply change room reply
	OpChangeRoomReply = 13

	// OpRegister register operation
	OpRegister = 14
	// OpRegisterReply register operation
	OpRegisterReply = 15

	// OpUnregister unregister operation
	OpUnregister = 16
	// OpUnregisterReply unregister operation reply
	OpUnregisterReply = 17

	// MinBusinessOp min business operation
	MinBusinessOp = 1000
	// MaxBusinessOp max business operation
	MaxBusinessOp = 10000
)

Variables

View Source
var (
	ErrUnknown                 = NewPublicError(0, "unknown error", "")
	ErrInvalidParameter        = NewPublicError(4000, "参数错误", "请检查必填参数,参数大小限制")
	ErrInvalidApp              = NewPublicError(4001, "应用无效", "请检查header的x-bili-accesskeyid是否为空,或者有效")
	ErrSignature               = NewPublicError(4002, "签名异常", "请检查header的Authorization")
	ErrExpiredRequest          = NewPublicError(4003, "请求过期", "请检查header的x-bili-timestamp")
	ErrDuplicateRequest        = NewPublicError(4004, "重复请求", "请检查header的x-bili-nonce")
	ErrInvalidSignatureMethod  = NewPublicError(4005, "签名method异常", "请检查header的x-bili-signature-method")
	ErrInvalidVersion          = NewPublicError(4006, "版本异常", "请检查header的x-bili-version")
	ErrIPWhitelist             = NewPublicError(4007, "IP白名单限制", "请确认请求服务器是否在报备的白名单内")
	ErrPermission              = NewPublicError(4008, "权限异常", "请确认接口权限")
	ErrAPILimit                = NewPublicError(4009, "接口访问限制", "请确认接口权限及请求频率")
	ErrNotFound                = NewPublicError(4010, "接口不存在", "请确认请求接口url")
	ErrInvalidContentType      = NewPublicError(4011, "Content-Type不为application/json", "请检查header的Content-Type")
	ErrMD5Validation           = NewPublicError(4012, "MD5校验失败", "请检查header的x-bili-content-md5")
	ErrInvalidAcceptType       = NewPublicError(4013, "Accept不为application/json", "请检查header的Accept")
	ErrService                 = NewPublicError(5000, "服务异常", "请联系B站对接同学")
	ErrRequestTimeout          = NewPublicError(5001, "请求超时", "请求超时")
	ErrInternal                = NewPublicError(5002, "内部错误", "请联系B站对接同学")
	ErrConfiguration           = NewPublicError(5003, "配置错误", "请联系B站对接同学")
	ErrRoomWhitelist           = NewPublicError(5004, "房间白名单限制", "请联系B站对接同学")
	ErrRoomBlacklist           = NewPublicError(5005, "房间黑名单限制", "请联系B站对接同学")
	ErrInvalidVerificationCode = NewPublicError(6000, "验证码错误", "验证码校验失败")
	ErrInvalidPhoneNumber      = NewPublicError(6001, "手机号码错误", "检查手机号码")
	ErrExpiredVerificationCode = NewPublicError(6002, "验证码已过期", "验证码超过规定有效期")
	ErrVerificationRateLimit   = NewPublicError(6003, "验证码频率限制", "检查获取验证码的频率")
	ErrNotInGame               = NewPublicError(7000, "不在游戏内", "当前房间未进行互动游戏")
	ErrRequestCooldown         = NewPublicError(7001, "请求冷却期", "上个游戏正在结算中,建议10秒后进行重试")
	ErrRoomInGame              = NewPublicError(7002, "房间重复游戏", "当前房间正在进行游戏,无法开启下一局互动游戏")
	ErrExpiredHeartbeat        = NewPublicError(7003, "心跳过期", "当前game_id错误或互动游戏已关闭")
	ErrMaxHeartbeatBatchSize   = NewPublicError(7004, "批量心跳超过最大值", "批量心跳单次最大值为200")
	ErrDuplicateHeartbeatID    = NewPublicError(7005, "批量心跳ID重复", "批量心跳game_id存在重复,请检查参数")
	ErrInvalidIdentityCode     = NewPublicError(7007, "身份码错误", "请检查身份码是否正确")
	ErrNoProjectAccess         = NewPublicError(8002, "项目无权限访问", "确认项目ID是否正确")
)
View Source
var ApiBase = "https://live-open.biliapi.com"

Functions

func MakeWSPacket

func MakeWSPacket(operation int, data []byte) []byte

func ZlibCompress

func ZlibCompress(src []byte) []byte

func ZlibDeCompress

func ZlibDeCompress(compressSrc []byte) ([]byte, error)

Types

type AnchorInfo

type AnchorInfo struct {
	RoomID int    `json:"room_id"`
	Uname  string `json:"uname"`
	Uface  string `json:"uface"`
	UID    int    `json:"uid"`
}

type ApiClient

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

func NewApiClient

func NewApiClient(accessKey string, accessSecret string) *ApiClient

func (*ApiClient) AppEnd

func (c *ApiClient) AppEnd(appId int64, gameId string) *PublicError

func (*ApiClient) AppStart

func (c *ApiClient) AppStart(code string, appId int64) (*AppStartResult, *PublicError)

func (*ApiClient) HearBeat

func (c *ApiClient) HearBeat(gameId string) *PublicError

type AppStartResult

type AppStartResult struct {
	GameInfo      GameInfo      `json:"game_info"`
	WebSocketInfo WebSocketInfo `json:"websocket_info"`
	AnchorInfo    AnchorInfo    `json:"anchor_info"`
}

type BLiveApp

type BLiveApp struct {
	AppID        int64
	AccessKey    string
	AccessSecret string
}

func (*BLiveApp) CreateClient

func (app *BLiveApp) CreateClient(code string) *BLiveClient

type BLiveClient

type BLiveClient struct {
	AppID int64
	Code  string // 主播身份码

	AppInfo *AppStartResult

	HearbeatInterval time.Duration
	// contains filtered or unexported fields
}

func NewBliveClient added in v0.0.3

func NewBliveClient(appID int64, code string, client IApiClient) *BLiveClient

func (*BLiveClient) End

func (c *BLiveClient) End() error

func (*BLiveClient) GetLongConn

func (c *BLiveClient) GetLongConn() BLiveLongConnection

func (*BLiveClient) SetLongConn

func (c *BLiveClient) SetLongConn(conn BLiveLongConnection)

func (*BLiveClient) Start

func (c *BLiveClient) Start() error

func (*BLiveClient) Status

func (c *BLiveClient) Status() bool

type BLiveLongConnection

type BLiveLongConnection interface {
	Status() bool
	EstablishConnection(ctx context.Context) error
	CloseConnection() error
	OnDanmu(handlers ...DanmuHandler)
	OnGift(handlers ...GiftHandler)
	OnSuperChat(handlers ...SuperChatHandler)
	OnSuperChatDel(handlers ...SuperChatDelHandler)
	OnNewGuard(handlers ...NewGuardHandler)
	OnLike(handlers ...LikeHandler)
	OnDisconnect(callback DisconnectCallback)
	OnError(callback ConnErrorHandler)
}

func NewOpenBLiveLongConn

func NewOpenBLiveLongConn(
	wssInfo WebSocketInfo) BLiveLongConnection

type CmdData

type CmdData struct {
	Cmd  string          `json:"cmd"`
	Data json.RawMessage `json:"data"`
}

func (*CmdData) ToDanmu

func (d *CmdData) ToDanmu() DanmakuData

func (*CmdData) ToGift

func (d *CmdData) ToGift() GiftData

func (*CmdData) ToLike

func (d *CmdData) ToLike() LikeData

func (*CmdData) ToNewGuard

func (d *CmdData) ToNewGuard() NewGuardData

func (*CmdData) ToSuperChat

func (d *CmdData) ToSuperChat() SuperChatData

func (*CmdData) ToSuperChatDel

func (d *CmdData) ToSuperChatDel() SuperChatDelData

type CommonResponse

type CommonResponse struct {
	Code    int             `json:"code"`
	Message string          `json:"message"`
	Data    json.RawMessage `json:"data"`
}

type ConnErrorHandler

type ConnErrorHandler func(err error)

type DanmakuData

type DanmakuData struct {
	RoomID    int    `json:"room_id"` // 弹幕接收的直播间
	UID       int    `json:"uid"`     // 用户UID
	OpenID    string `json:"open_id"` // 用户唯一标识
	UName     string `json:"uname"`   // 用户昵称
	Msg       string `json:"msg"`     // 弹幕内容
	MsgID     string `json:"msg_id"`  // 消息唯一id
	MedalInfo        // 对应房间勋章信息
	//FansMedalLevel         int    `json:"fans_medal_level"`          // 对应房间勋章信息
	//FansMedalName          string `json:"fans_medal_name"`           // 粉丝勋章名
	//FansMedalWearingStatus bool   `json:"fans_medal_wearing_status"` // 该房间粉丝勋章佩戴情况
	GuardLevel  int    `json:"guard_level"`   // 对应房间大航海 1总督 2提督 3舰长
	Timestamp   int64  `json:"timestamp"`     // 弹幕发送时间秒级时间戳
	UFace       string `json:"uface"`         // 用户头像
	EmojiImgURL string `json:"emoji_img_url"` // 表情包图片地址
	DanMuType   int    `json:"dm_type"`       // 弹幕类型 0:普通弹幕 1:表情包弹幕
}

type DanmuHandler

type DanmuHandler func(data DanmakuData)

type DisconnectCallback

type DisconnectCallback func(conn BLiveLongConnection)

type GameInfo

type GameInfo struct {
	GameID string `json:"game_id"`
}

type GiftData

type GiftData struct {
	RoomID   int    `json:"room_id"`   // 直播间 (In auditorium mode, it represents the auditorium live room; otherwise, it represents the gifting live room)
	UID      int    `json:"uid"`       // 送礼用户 UID
	OpenID   string `json:"open_id"`   // 用户唯一标识
	UName    string `json:"uname"`     // 送礼用户昵称
	UFace    string `json:"uface"`     // 送礼用户头像
	GiftID   int    `json:"gift_id"`   // 道具 ID (For blind boxes: the ID of the item obtained)
	GiftName string `json:"gift_name"` // 道具名 (For blind boxes: the name of the item obtained)
	GiftNum  int    `json:"gift_num"`  // 赠送道具数量
	Price    int    `json:"price"`     // 礼物单价 (1000 = 1元 = 10电池); for blind boxes: the value of the obtained item
	Paid     bool   `json:"paid"`      // 是否是付费道具
	MedalInfo
	//FansMedalLevel         int      `json:"fans_medal_level"`          // 实际收礼人的勋章信息
	//FansMedalName          string   `json:"fans_medal_name"`           // 粉丝勋章名
	//FansMedalWearingStatus bool     `json:"fans_medal_wearing_status"` // 该房间粉丝勋章佩戴情况
	GuardLevel int      `json:"guard_level"` // room_id 对应的大航海等级
	Timestamp  int64    `json:"timestamp"`   // 收礼时间秒级时间戳
	MsgID      string   `json:"msg_id"`      // 消息唯一 ID
	AnchorInfo UserInfo `json:"anchor_info"` // 收礼主播
	GiftIcon   string   `json:"gift_icon"`   // 道具 icon (新增)
	ComboGift  bool     `json:"combo_gift"`  // 是否是 combo 道具
	ComboInfo  struct {
		ComboBaseNum int    `json:"combo_base_num"` // 每次连击赠送的道具数量
		ComboCount   int    `json:"combo_count"`    // 连击次数
		ComboID      string `json:"combo_id"`       // 连击 ID
		ComboTimeout int    `json:"combo_timeout"`  // 连击有效期秒
	} `json:"combo_info"`
}

type GiftHandler

type GiftHandler func(data GiftData)

type IApiClient added in v0.0.3

type IApiClient interface {
	AppStart(code string, appId int64) (*AppStartResult, *PublicError)
	AppEnd(appId int64, gameId string) *PublicError
	HearBeat(gameId string) *PublicError
}

type LikeData

type LikeData struct {
	UserInfo
	Timestamp int64  `json:"timestamp"` // 时间戳
	LikeText  string `json:"like_text"` // 点赞文本
	MedalInfo
	//FansMedalWearingStatus bool   `json:"fans_medal_wearing_status"` // 该房间粉丝勋章佩戴情况
	//FansMedalName          string `json:"fans_medal_name"`           // 粉丝勋章名
	//FansMedalLevel         int    `json:"fans_medal_level"`          // 粉丝勋章等级
	MsgID  string `json:"msg_id"`  // 消息唯一 ID
	RoomID int    `json:"room_id"` // 直播间 ID
}

type LikeHandler

type LikeHandler func(data LikeData)

type MedalInfo

type MedalInfo struct {
	FansMedalLevel         int    `json:"fans_medal_level"`          // 粉丝勋章等级
	FansMedalName          string `json:"fans_medal_name"`           // 粉丝勋章名
	FansMedalWearingStatus bool   `json:"fans_medal_wearing_status"` // 该房间粉丝勋章佩戴情况
}

type NewGuardData

type NewGuardData struct {
	UserInfo   UserInfo `json:"user_info"`   // 用户信息
	GuardLevel int      `json:"guard_level"` // 对应的大航海等级 1 总督 2 提督 3 舰长
	GuardNum   int      `json:"guard_num"`   // 舰长数量
	GuardUnit  string   `json:"guard_unit"`  // 舰长数量单位 (个月)
	MedalInfo           // 该房间粉丝勋章
	//FansMedalLevel         int      `json:"fans_medal_level"`          // 粉丝勋章等级
	//FansMedalName          string   `json:"fans_medal_name"`           // 粉丝勋章名
	//FansMedalWearingStatus bool     `json:"fans_medal_wearing_status"` // 该房间粉丝勋章佩戴情况
	Timestamp int64  `json:"timestamp"` // 时间戳
	RoomID    int    `json:"room_id"`   // 直播间 ID
	MsgID     string `json:"msg_id"`    // 消息唯一 ID
}

type NewGuardHandler

type NewGuardHandler func(data NewGuardData)

type PublicError

type PublicError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Detail  string `json:"-"`
}

func GetErrorFromCode

func GetErrorFromCode(errcode int) *PublicError

func NewPublicError

func NewPublicError(code int, msg string, detail string) *PublicError

func (*PublicError) Error

func (e *PublicError) Error() string

func (*PublicError) WithDetail

func (e *PublicError) WithDetail(detail error) *PublicError

type SuperChatData

type SuperChatData struct {
	RoomID     int    `json:"room_id"`     // 直播间 ID
	UID        int    `json:"uid"`         // 购买用户 UID
	OpenID     string `json:"open_id"`     // 用户唯一标识
	UName      string `json:"uname"`       // 购买的用户昵称
	UFace      string `json:"uface"`       // 购买用户头像
	MessageID  int    `json:"message_id"`  // 留言 ID (In case of risk control, this may be used to recall the message)
	Message    string `json:"message"`     // 留言内容
	MsgID      string `json:"msg_id"`      // 消息唯一 ID
	RMB        int    `json:"rmb"`         // 支付金额 (元)
	Timestamp  int64  `json:"timestamp"`   // 赠送时间秒级
	StartTime  int64  `json:"start_time"`  // 生效开始时间
	EndTime    int64  `json:"end_time"`    // 生效结束时间
	GuardLevel int    `json:"guard_level"` // 对应房间大航海等级 (新增)
	MedalInfo
}

type SuperChatDelData

type SuperChatDelData struct {
	RoomID     int    `json:"room_id"`     // 直播间 ID
	MessageIDs []int  `json:"message_ids"` // 留言 ID 列表
	MsgID      string `json:"msg_id"`      // 消息唯一 ID
}

type SuperChatDelHandler

type SuperChatDelHandler func(data SuperChatDelData)

type SuperChatHandler

type SuperChatHandler func(data SuperChatData)

type UserInfo

type UserInfo struct {
	UID    int    `json:"uid"`     // 用户uid
	OpenID string `json:"open_id"` // 用户唯一标识
	UName  string `json:"uname"`   // 用户昵称
	UFace  string `json:"uface"`   // 用户头像
}

type WebSocketInfo

type WebSocketInfo struct {
	AuthBody string   `json:"auth_body"`
	WssLink  []string `json:"wss_link"` //
}

type WsHeader

type WsHeader struct {
	PacketLength    uint32
	HeaderLength    uint16
	ProtocolVersion uint16
	Operation       uint32
	Sequence        uint32
}

type WsPacket

type WsPacket struct {
	Header WsHeader
	Data   []byte
}

func ResolveWSPacket

func ResolveWSPacket(data []byte) (WsPacket, bool)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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