blivemsg 0.2.0

Bilibili Live Message Library
Documentation
blivemsg-0.2.0 has been yanked.

blivemsg

轻量级 B站直播弹幕获取库,提供强类型消息接口和 Stream API。

✨ 特性

  • Stream 模式优先:符合 Rust 异步编程范式,支持 filter/map 等操作符
  • 回调模式辅助:提供便捷的 on_danmuon_gift 等方法
  • 52 种消息类型:完整支持所有 B站直播消息类型
  • 类型安全:强类型结构体,无需手动解析 JSON
  • 模块隔离:底层实现完全私有,API 简洁稳定
  • 可选功能:通过 Cargo features 控制依赖大小

🚀 快速开始

作为库使用(最小依赖)

添加到项目

[dependencies]
blivemsg = "0.2.0"
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
futures-util = "0.3"

默认不包含的功能

  • ❌ CLI 工具
  • ❌ Protobuf 支持
  • ❌ 浏览器指纹模拟

启用可选功能

[dependencies]
# 启用 Protobuf 支持(用于 INTERACT_WORD_V2 消息)
blivemsg = { version = "0.2.0", features = ["protobuf-support"] }

# 启用浏览器指纹模拟
blivemsg = { version = "0.2.0", features = ["emulation"] }

# 启用所有功能
blivemsg = { version = "0.2.0", features = ["protobuf-support", "emulation"] }

Stream 模式(推荐)

use blivemsg::{BliveClient, types::Message};
use futures_util::StreamExt;

#[tokio::main]
async fn main() -> Result<(), blivemsg::Error> {
    let mut client = BliveClient::new(7734200, "cookies.json")?;
    let mut stream = client.stream().await?;
    
    while let Some(message) = stream.next().await {
        match message {
            Message::Danmu(d) => println!("[{}] {}: {}", d.medal_level, d.username, d.content),
            Message::Gift(g) => println!("{} 送了 {} x{}", g.username, g.gift_name, g.num),
            Message::SuperChat(sc) => println!("[SC] ¥{:.2}", sc.price),
            _ => {}
        }
    }
    
    Ok(())
}

回调模式

use blivemsg::BliveClient;

#[tokio::main]
async fn main() -> Result<(), blivemsg::Error> {
    let mut client = BliveClient::new(7734200, "cookies.json")?;
    
    client.on_danmu(|danmu| {
        println!("[{}] {}: {}", danmu.medal_level, danmu.username, danmu.content);
    }).await?;
    
    Ok(())
}

🛠️ CLI 工具

安装

# 方法 1:从 crates.io 安装
cargo install blivemsg --features cli

# 方法 2:从源码编译
git clone https://github.com/your-username/blivemsg.git
cd blivemsg
cargo install --path . --features cli

快速使用

# 基本用法:指定直播间和 Cookie
blivemsg-cli -r 3151244 -c cookies.json

# 筛选指定消息类型
blivemsg-cli -c cookie.json -t "DANMU_MSG,SEND_GIFT"

# 使用配置文件
blivemsg-cli -C my_config.toml

命令行参数

Usage: blivemsg-cli [OPTIONS]

Options:
  -r, --room-id <ROOM_ID>          直播间 ID [default: 3151244]
  -c, --cookie <COOKIE>            Cookie(JSON文件路径/JSON字符串/内联字符串)
  -t, --message-types <TYPES>      消息类型筛选 [default: user]
  -q, --quiet                      静默模式(纯文本输出,适合管道处理)
  -C, --config <CONFIG>            配置文件路径(TOML格式)
  -h, --help                       Print help
  -V, --version                    Print version

Cookie 输入方式(自动检测)

# 1. JSON 文件路径
-c cookies.json

# 2. JSON 字符串
-c '{"SESSDATA":"xxx","buvid3":"xxx"}'

# 3. 内联字符串
-c "SESSDATA=xxx;buvid3=xxx"

消息类型筛选

# 预设类别
-t user          # 用户消息(默认)
-t system        # 系统消息
-t all           # 全部消息

# 具体类型(逗号分隔)
-t DANMU_MSG                     # 弹幕
-t DANMU_MSG,SEND_GIFT           # 弹幕+礼物
-t SUPER_CHAT_MESSAGE,GUARD_BUY  # SC+舰长

消息类型列表:完整列表请参考 MESSAGES.md

配置文件

# blivemsg.toml
room_id = 7734200
cookie = "cookies.json"
message_types = ["DANMU_MSG", "SEND_GIFT"]

优先级:命令行参数 > 配置文件 > 默认值


📦 Features 说明

Feature 说明 额外依赖 适用场景
cli CLI 工具(自动包含 protobuf-support clap, toml, prost, bytes, base64 需要命令行工具
protobuf-support Protobuf 消息解析 prost, bytes, base64 库用户需要 INTERACT_WORD_V2 消息
emulation 浏览器指纹模拟 wreq-util 高级反爬虫场景
默认(无) 核心库功能 作为库集成到其他项目

关键设计决策

1. 为什么 TOML 是可选的?

  • 库用户不需要 - 大多数库用户通过代码配置,不需要 TOML 文件解析
  • CLI 才需要 - 只有 CLI 工具使用 --config 参数时才需要 TOML
  • 减少依赖 - 库模式节省约 15 个依赖(toml、serde_spanned 等)

2. 为什么 CLI 自动启用 Protobuf?

  • 完整功能 - CLI 作为独立工具应该支持所有 52 种消息类型
  • 用户体验 - 用户无需手动指定 --features "cli,protobuf-support"
  • 一致性 - 避免 CLI 和库的功能差异造成困惑

3. dev-dependencies 为什么被移除?

  • 未使用 - 项目当前没有测试文件(tests/ 目录为空)
  • 按需添加 - 未来添加测试时再引入必要的测试依赖
  • 保持精简 - 避免不必要的依赖污染

依赖大小对比

# 库模式(最小依赖)
cargo tree --edges normal 2>&1 | grep "^├" | wc -l
# 约 80 个依赖

# CLI 模式(完整依赖,含 Protobuf)
cargo tree --features cli --edges normal 2>&1 | grep "^├" | wc -l
# 约 135 个依赖(增加 clap、toml、prost、bytes、base64)

📚 文档结构


🏗️ 架构设计

src/
├── lib.rs              # 公共 API 导出
├── client.rs           # BliveClient 实现
├── message.rs          # 52 种消息类型定义
├── error.rs            # 统一错误类型
└── internal/           # 私有实现(不导出)
    ├── ws.rs           # WebSocket 连接
    ├── http.rs         # HTTP API 调用
    ├── parser.rs       # JSON → Message 转换
    └── cookie.rs       # Cookie 管理

📄 许可证

MIT

🔗 相关链接