🚀 BiliBili Live WebSocket Protocol SDK in Golang

logo

BiliGO-LIVE

BiliBili Live WebSocket Protocol SDK in Golang


Go Reference

简介

v0版本不保证对外函数、结构的不变性,请勿大规模用于生产环境

哔哩哔哩直播 WebSocket 协议的 Golang 封装

特性

  • 良好的设计,自定义程度高
  • 代码、结构体注释完善,开箱即用
  • 功能简单,封装程度高

说明

  • 该项目永远不会编写直接涉及滥用的接口
  • 该项目仅供学习,请勿用于商业用途。任何使用该项目造成的后果由开发者自行承担

参考

快速开始

安装

go get -u github.com/iyear/biligo-live
import "github.com/iyear/biligo-live"

使用

查看代码
package main

import (
	"context"
	"fmt"
	"github.com/gorilla/websocket"
	"github.com/iyear/biligo-live"
	"log"
	"time"
)

// 同 README.md 的快速开始

func main() {
	const room int64 = 48743

	// 获取一个Live实例
	// debug: debug模式,输出一些额外的信息
	// heartbeat: 心跳包发送间隔。不发送心跳包,70 秒之后会断开连接,通常每 30 秒发送 1 次
	// cache: Rev channel 的缓存
	// recover: panic recover后的操作函数
	l := live.NewLive(true, 30*time.Second, 0, func(err error) {
		log.Println("panic:", err)
		// do something...
	})

	// 连接ws服务器
	// dialer: ws dialer
	// host: bilibili live ws host
	if err := l.Conn(websocket.DefaultDialer, live.WsDefaultHost); err != nil {
		log.Fatal(err)
		return
	}

	ctx, stop := context.WithCancel(context.Background())

	go func() {
		// 进入房间
		// room: room id(真实ID,短号需自行转换)
		// key: 用户标识,可留空
		// uid: 用户UID,可随机生成
		if err := l.Enter(ctx, room, "", 12345678); err != nil {
			log.Fatal(err)
			return
		}
	}()

	go rev(ctx, l)

	// 15s的演示
	after := time.NewTimer(15 * time.Second)
	defer after.Stop()
	<-after.C
	fmt.Println("I want to stop")
	// 关闭ws连接与相关协程
	stop()
	// 为了使安全退出效果可见,进行阻塞,真实场景中可以移除
	select {}
}
func rev(ctx context.Context, l *live.Live) {
	for {
		select {
		case tp := <-l.Rev:
			if tp.Error != nil {
				// do something...
				log.Println(tp.Error)
				continue
			}
			handle(tp.Msg)
		case <-ctx.Done():
			log.Println("rev func stopped")
			return
		}
	}
}
func handle(msg live.Msg) {
	// 使用 msg.(type) 进行事件跳转和处理,常见事件基本都完成了解析(Parse)功能,不常见的功能有一些实在太难抓取
	// 更多注释和说明等待添加
	switch msg.(type) {
	// 心跳回应直播间人气值
	case *live.MsgHeartbeatReply:
		log.Printf("hot: %d\n", msg.(*live.MsgHeartbeatReply).GetHot())
	// 弹幕消息	
	case *live.MsgDanmaku:
		dm, err := msg.(*live.MsgDanmaku).Parse()
		if err != nil {
			log.Println(err)
			return
		}
		fmt.Printf("弹幕: %s (%d:%s) 【%s】| %d\n", dm.Content, dm.MID, dm.Uname, dm.MedalName, dm.Time)
	// 礼物消息	
	case *live.MsgSendGift:
		g, err := msg.(*live.MsgSendGift).Parse()
		if err != nil {
			log.Println(err)
			return
		}
		fmt.Printf("%s: %s %d个%s\n", g.Action, g.Uname, g.Num, g.GiftName)
	// 直播间粉丝数变化消息	
	case *live.MsgFansUpdate:
		f, err := msg.(*live.MsgFansUpdate).Parse()
		if err != nil {
			log.Println(err)
			return
		}
		fmt.Printf("room: %d,fans: %d,fansClub: %d\n", f.RoomID, f.Fans, f.FansClub)
	// case:......

	// General 表示live未实现的CMD命令,请自行处理raw数据。也可以提issue更新这个CMD
	case *live.MsgGeneral:
		fmt.Println("unknown msg type|raw:", string(msg.Raw()))
	}
}

LICENSE

GPLv3

Similar Resources

Turn any program that uses STDIN/STDOUT into a WebSocket server. Like inetd, but for WebSockets.

websocketd websocketd is a small command-line tool that will wrap an existing command-line interface program, and allow it to be accessed via a WebSoc

Dec 31, 2022

WebSocket Command Line Client written in Go

ws-cli WebSocket Command Line Client written in Go Installation go get github.com/kseo/ws-cli Usage $ ws-cli -url ws://echo.websocket.org connected (

Nov 12, 2021

proxy your traffic through CDN using websocket

go-cdn2proxy proxy your traffic through CDN using websocket what does it do example server client thanks what does it do you can use this as a library

Dec 7, 2022

Tiny WebSocket library for Go.

RFC6455 WebSocket implementation in Go.

Dec 28, 2022

Simple example for using Turbos Streams in Go with the Gorilla WebSocket toolkit.

Go Example for TurboStreams over WebSockets Simple example for using Turbos Streams in Go with the Gorilla WebSocket toolkit.

Dec 22, 2022

Minimal and idiomatic WebSocket library for Go

websocket websocket is a minimal and idiomatic WebSocket library for Go. Install go get nhooyr.io/websocket Highlights Minimal and idiomatic API First

Dec 31, 2022

:notes: Minimalist websocket framework for Go

:notes: Minimalist websocket framework for Go

melody 🎶 Minimalist websocket framework for Go. Melody is websocket framework based on github.com/gorilla/websocket that abstracts away the tedious p

Dec 23, 2022

A modern, fast and scalable websocket framework with elegant API written in Go

A modern, fast and scalable websocket framework with elegant API written in Go

About neffos Neffos is a cross-platform real-time framework with expressive, elegant API written in Go. Neffos takes the pain out of development by ea

Dec 29, 2022

Terminal on browser via websocket

Terminal on browser via websocket. Supportted OS Linux Mac

Dec 27, 2022
Comments
  • [BUG] 直播间room_id超过32767会提示房間無效,已略過

    [BUG] 直播间room_id超过32767会提示房間無效,已略過

    直播间room_id超过int16的范围就会报错

    2021/12/26 17:20:38 房間 3415150 無效,已略過 
    2021/12/26 17:20:38 Resolving Error: *json.UnmarshalTypeError
    2021/12/26 17:20:38 json: cannot unmarshal number 88615 into Go struct field RoomInfoData.data.short_id of type int16
    [GIN] 2021/12/26 - 17:20:38 | 500 |   40.804101ms |       127.0.0.1 | PUT      "/subscribe/add"
    Error #01: json: cannot unmarshal number 88615 into Go struct field RoomInfoData.data.short_id of type int16
    
Awesome WebSocket CLient - an interactive command line client for testing websocket servers
Awesome WebSocket CLient - an interactive command line client for testing websocket servers

Awesome WebSocket CLient - an interactive command line client for testing websocket servers

Dec 30, 2022
Websocket-chat - A simple websocket chat application
Websocket-chat - A simple websocket chat application

WebSocket Chat App This is a simple chat app based on websockets. It allows user

Jan 25, 2022
gatews - Gate.io WebSocket SDK

gatews - Gate.io WebSocket SDK gatews provides new Gate.io WebSocket V4 implementations. It is intended to work along with gateapi-* series to provide

Dec 31, 2022
Chat bots (& more) for Zoom by figuring out their websocket protocol
Chat bots (& more) for Zoom by figuring out their websocket protocol

zoomer - Bot library for Zoom meetings Good bot support is part of what makes Discord so nice to use. Unfortunately, the official Zoom API is basicall

Dec 14, 2022
BrisGolang is a Go implementation of the game of briscola using the WebSocket protocol for client/server communication.

BrisGolang BrisGolang is a Go implementation of the game of briscola using the WebSocket protocol for client/server communication. Usage You can play

Nov 1, 2021
A websocket powered discord wrapper for Sugaroid written in golang

sg-discord A thin discord wrapper built on top of Sugaroid Websocket implementation. Build go build . Run export DISCORD_BOT_TOKEN="supersecrettoken"

Dec 30, 2021
A websocket powered telegram wrapper for Sugaroid written in golang

sg-telegram A thin telegram wrapper built on top of Sugaroid Websocket

Nov 4, 2021
Simle websocket chat on Golang

WebsocketChat Simle websocket chat on Golang Installation (with comiling binary files): cd projectDir/cmd/app/server - change current directory go bui

Nov 1, 2021
Go-distributed-websocket - Distributed Web Socket with Golang and Redis
Go-distributed-websocket - Distributed Web Socket with Golang and Redis

go-distributed-websocket Distributed Web Socket with Golang and Redis Dependenci

Oct 13, 2022
A fast, well-tested and widely used WebSocket implementation for Go.

Gorilla WebSocket Gorilla WebSocket is a Go implementation of the WebSocket protocol. Documentation API Reference Chat example Command example Client

Jan 2, 2023