bilibili-ws-client
TypeScript icon, indicating that this package has built-in type declarations

2.3.1 • Public • Published

bilibili-ws-client

适用于 Bilibili 直播的 WebSocket 客户端。

可用于实时获取弹幕 DANMU_MSG、收到礼物 SEND_GIFT、开播 LIVE、下播 PREPARING 等信息。

起步

bilibili-ws-client 支持以 CommonJSESM 的方式使用。

也支持从 HTML 文件和 script 标签开始。

在网页中直接使用

将 js 添加到 HTML 中,且无需安装,即可立即开始使用。

添加 script 标签,应该如下所示:

<script src="https://unpkg.com/bilibili-ws-client/lib/index.umd.js"></script>
<script>
  const sub = new Client(1);

  sub.on('open', () => {
    // ...
    console.log('authorized');
  });

  sub.on('message', ({ ver, op, cmd, body, ts }) => {
    if (op === 3) {
      console.log('online: ' + body);
    } else if (op === 5) {
      switch (cmd) {
        case 'LIVE':
          // 开播
          // ...
          break;
        case 'PREPARING':
          // 闲置(下播)
          // ...
          break;
        case 'DANMU_MSG':
          console.log(body);
          break;
        default:
          break;
      }
    }
  });
</script>

通过以下方式安装

npm install bilibili-ws-client

或者

yarn add bilibili-ws-client

在 node.js 使用

作为 CommonJS 模块使用:

const Client = require('bilibili-ws-client');

const sub = new Client(roomId);

sub.on('open', () => {
  // ...
  console.log('authorized');
});

sub.on('close', () => {
  // ...
});

sub.on('message', ({ ver, op, cmd, body, ts }) => {
  if (op === 3) {
    console.log('online: ' + body);
  } else if (op === 5) {
    switch (cmd) {
      case 'LIVE':
        // 开播
        // ...
        break;
      case 'PREPARING':
        // 闲置(下播)
        // ...
        break;
      case 'DANMU_MSG':
        console.log(body);
        break;
      default:
        break;
    }
  } else {
    // ...
    console.log('op: ' + op);
    console.log('body: ' + body);
  }
});

sub.on('error', (err) => {
  throw new Error(err);
});

在前端项目使用

作为 ESM 模块使用:

import Client from 'bilibili-ws-client';

const sub = new Client(roomId);
// ...

配置

token

Type:

type Token =
  | number // roomId
  | Partial<{
      uid: number;
      roomid: number; // roomId
      protover: Ver; // 1 | 2 | 3
      buvid: string;
      platform: string; // 'web'
      clientver: string;
      type: number;
      key: string;
    }>;

需要连接的房间号或一个包含登录信息的对象。

enableLog

Type:

type enableLog = boolean | undefined;

默认值:false

是否记录日志,将通过 console.log 输出。

maxConnectTimes

Type:

type maxConnectTimes = number | undefined;

默认值:10

WebSocket 触发 close 时,最多重试再次连接的次数。

delay

Type:

type delay = number | undefined;

默认值:15000

WebSocket 触发 close 时,间隔特定毫秒后重试。

开发

npm run prettier
npm run build

Package Sidebar

Install

npm i bilibili-ws-client

Weekly Downloads

6

Version

2.3.1

License

MIT

Unpacked Size

141 kB

Total Files

9

Last publish

Collaborators

  • varieget