B站直播API完整集成指南:20+核心接口实战与RESTful调用详解
B站直播API完整集成指南20核心接口实战与RESTful调用详解【免费下载链接】Bilibili-Live-APIBILIBILI 直播/番剧 API项目地址: https://gitcode.com/gh_mirrors/bil/Bilibili-Live-APIBilibili-Live-API是一套全面覆盖B站直播生态的API接口集合为开发者提供完整的直播功能集成解决方案。本项目包含20核心RESTful接口和WebSocket协议实现涵盖房间管理、弹幕互动、礼物系统、用户认证等关键功能模块帮助开发者快速构建B站直播相关的应用程序。技术概览与架构设计Bilibili-Live-API采用模块化设计将B站直播API按功能划分为多个独立文档每个接口都经过实际验证并包含详细的参数说明和返回示例。项目架构遵循RESTful设计原则同时支持WebSocket实时通信协议满足不同场景下的技术需求。核心架构组件RESTful HTTP接口用于房间信息查询、用户认证、礼物发送等同步操作WebSocket实时协议用于弹幕推送、在线人数统计、礼物通知等实时交互WBI签名机制B站最新的安全验证体系保护接口调用安全Cookie/Token认证支持多种认证方式适应不同应用场景核心接口分类与功能矩阵房间管理接口房间初始化检测房间初始化接口是直播API的基础用于验证房间状态和获取基础信息// 房间初始化示例 const response await fetch(https://api.live.bilibili.com/room/v1/Room/room_init?id123456); const data await response.json(); // 安全验证逻辑 if (data.data.is_hidden false data.data.is_locked false data.data.encrypted false) { console.log(房间状态正常可以连接); }参数必选传递方式类型说明id是GETstring房间IDcookie否GETstring用户Cookie需与Cookies账号一致批量房间信息获取批量获取多个直播间的基础信息支持高效的数据聚合// 批量获取房间信息 const roomIds [123456, 789012, 345678]; const promises roomIds.map(id fetch(https://api.live.bilibili.com/room/v1/Room/get_info?room_id${id}) ); const results await Promise.all(promises);实时通信接口WebSocket连接配置B站直播WebSocket协议提供实时弹幕和互动消息推送// WebSocket连接配置示例 const ws new WebSocket(wss://broadcastlv.chat.bilibili.com/sub); ws.onopen () { const authPacket { uid: 0, roomid: 545068, protover: 3, platform: web, type: 2, key: your_danmu_token_here }; ws.send(JSON.stringify(authPacket)); }; ws.onmessage (event) { // 处理弹幕、礼物、在线人数等实时消息 console.log(收到消息:, event.data); };协议版本压缩方式适用场景protover: 2zlib压缩兼容旧客户端protover: 3brotli压缩新版网页端用户互动接口弹幕发送接口实现直播间弹幕发送功能支持多种消息类型// 发送弹幕示例 const sendDanmaku async (roomId, message, color 16777215) { const params new URLSearchParams({ roomid: roomId, csrf: your_csrf_token, msg: message, color: color, fontsize: 25, mode: 1, bubble: 0, dm_type: 0 }); const response await fetch(https://api.live.bilibili.com/msg/send, { method: POST, headers: { Content-Type: application/x-www-form-urlencoded }, body: params.toString() }); return await response.json(); };礼物发送接口从用户背包发送礼物到指定直播间// 发送礼物示例 const sendGift async (bagId, giftId, roomId, num 1) { const response await fetch(https://api.live.bilibili.com/gift/v2/live/bag_send, { method: POST, headers: { Content-Type: application/x-www-form-urlencoded }, body: new URLSearchParams({ bag_id: bagId, gift_id: giftId, ruid: roomId, num: num, csrf: your_csrf_token }).toString() }); return await response.json(); };用户信息接口用户基本信息获取获取用户公开资料和直播权限信息// 获取用户信息 const getUserInfo async (mid) { const response await fetch(https://api.bilibili.com/x/space/acc/info?mid${mid}); const data await response.json(); return { name: data.data.name, face: data.data.face, level: data.data.level, vipStatus: data.data.vip.status, liveStatus: data.data.live_room?.liveStatus || 0 }; };粉丝勋章管理管理用户在直播间的粉丝勋章佩戴状态// 佩戴粉丝勋章 const wearFansMedal async (medalId) { const response await fetch(https://api.live.bilibili.com/i/ajaxWearFansMedal, { method: POST, body: new URLSearchParams({ medal_id: medalId, csrf: your_csrf_token }).toString() }); return await response.json(); };快速集成与配置指南环境准备与项目初始化克隆项目仓库git clone https://gitcode.com/gh_mirrors/bil/Bilibili-Live-API cd Bilibili-Live-API安装依赖npm install # 或 yarn install配置认证信息创建配置文件.envBILIBILI_SESSDATAyour_sessdata_here BILIBILI_CSRFyour_csrf_token_here BILIBILI_UIDyour_user_id_here认证机制详解Bilibili-Live-API支持多种认证方式开发者需要根据接口要求选择合适的认证策略认证类型适用接口获取方式Cookie认证用户相关操作登录后从浏览器获取SESSDATACSRF Token写操作接口从Cookie中的bili_jct字段获取WBI签名新版接口通过API动态获取mixin keyAccess Key移动端接口OAuth授权获取WBI签名实现// WBI签名生成函数 const generateWbiSignature (params, mixinKey) { // 参数排序 const sortedParams Object.keys(params) .sort() .map(key ${key}${encodeURIComponent(params[key])}) .join(); // 添加时间戳 const wts Math.floor(Date.now() / 1000); const signStr ${sortedParams}wts${wts}${mixinKey}; // 计算MD5 const w_rid md5(signStr); return { wts, w_rid }; };实战案例与最佳实践直播监控系统实现实时弹幕监控class LiveMonitor { constructor(roomId) { this.roomId roomId; this.ws null; this.messageHandlers new Map(); } async connect() { // 1. 获取房间信息 const roomInfo await this.getRoomInfo(); // 2. 获取弹幕Token const danmuInfo await this.getDanmuInfo(); // 3. 建立WebSocket连接 this.ws new WebSocket(wss://${danmuInfo.host_list[0].host}:${danmuInfo.host_list[0].wss_port}/sub); this.ws.onopen () { this.sendAuthPacket(danmuInfo.token); this.startHeartbeat(); }; this.ws.onmessage (event) { this.handleMessage(event.data); }; } async getRoomInfo() { const response await fetch(https://api.live.bilibili.com/room/v1/Room/room_init?id${this.roomId}); return await response.json(); } async getDanmuInfo() { const response await fetch(https://api.live.bilibili.com/xlive/web-room/v1/index/getDanmuInfo?id${this.roomId}type0); return await response.json(); } sendAuthPacket(token) { const authData { uid: 0, roomid: parseInt(this.roomId), protover: 3, platform: web, type: 2, key: token }; this.ws.send(JSON.stringify(authData)); } startHeartbeat() { setInterval(() { const heartbeat new Uint8Array([0x00, 0x00, 0x00, 0x10, 0x00, 0x10, 0x00, 0x01]); this.ws.send(heartbeat); }, 30000); } handleMessage(data) { // 解析WebSocket数据包 // 处理不同类型的消息弹幕、礼物、在线人数等 } }礼物统计与分析系统class GiftAnalyzer { constructor() { this.giftStats new Map(); this.topGivers new Map(); } processGiftMessage(message) { const { uid, giftId, giftName, price, num } message; // 更新礼物统计 const giftKey ${giftId}_${giftName}; const current this.giftStats.get(giftKey) || { count: 0, totalValue: 0 }; current.count num; current.totalValue price * num; this.giftStats.set(giftKey, current); // 更新送礼人统计 const giverKey uid; const giverStats this.topGivers.get(giverKey) || { totalValue: 0, gifts: [] }; giverStats.totalValue price * num; giverStats.gifts.push({ giftName, num, timestamp: Date.now() }); this.topGivers.set(giverKey, giverStats); // 实时输出统计信息 this.outputStats(); } outputStats() { console.log( 礼物统计 ); console.log(总礼物种类:, this.giftStats.size); // 按价值排序 const sortedGifts [...this.giftStats.entries()] .sort((a, b) b[1].totalValue - a[1].totalValue) .slice(0, 5); sortedGifts.forEach(([giftKey, stats], index) { console.log(${index 1}. ${giftKey.split(_)[1]}: ${stats.count}个, 总价值: ${stats.totalValue}); }); } }常见问题与调试技巧认证失败问题排查Cookie过期问题// Cookie有效性检查 const checkCookieValid async () { try { const response await fetch(https://api.bilibili.com/x/web-interface/nav, { headers: { Cookie: SESSDATA${process.env.BILIBILI_SESSDATA} } }); const data await response.json(); return data.code 0; } catch (error) { return false; } };CSRF Token不匹配// 自动获取CSRF Token const getCsrfToken () { const cookies document.cookie.split(;); for (const cookie of cookies) { const [name, value] cookie.trim().split(); if (name bili_jct) { return value; } } return null; };WebSocket连接问题连接超时处理class WebSocketWithTimeout { constructor(url, timeout 10000) { this.url url; this.timeout timeout; this.ws null; this.connectTimeout null; } connect() { return new Promise((resolve, reject) { this.ws new WebSocket(this.url); this.connectTimeout setTimeout(() { this.ws.close(); reject(new Error(WebSocket连接超时)); }, this.timeout); this.ws.onopen () { clearTimeout(this.connectTimeout); resolve(this.ws); }; this.ws.onerror (error) { clearTimeout(this.connectTimeout); reject(error); }; }); } }断线重连机制class AutoReconnectWebSocket { constructor(url, maxRetries 5) { this.url url; this.maxRetries maxRetries; this.retryCount 0; this.reconnectDelay 1000; this.ws null; } connect() { this.ws new WebSocket(this.url); this.ws.onopen () { console.log(WebSocket连接成功); this.retryCount 0; this.reconnectDelay 1000; }; this.ws.onclose () { console.log(WebSocket连接断开尝试重连...); this.scheduleReconnect(); }; this.ws.onerror (error) { console.error(WebSocket错误:, error); }; } scheduleReconnect() { if (this.retryCount this.maxRetries) { console.error(达到最大重试次数停止重连); return; } setTimeout(() { this.retryCount; this.reconnectDelay Math.min(this.reconnectDelay * 2, 30000); console.log(第${this.retryCount}次重连延迟${this.reconnectDelay}ms); this.connect(); }, this.reconnectDelay); } }性能优化与扩展建议接口调用优化批量请求优化// 批量房间信息查询优化 class BatchRoomQuery { constructor(batchSize 10) { this.batchSize batchSize; this.cache new Map(); this.cacheTTL 300000; // 5分钟缓存 } async getRoomsInfo(roomIds) { const results {}; const uncachedIds []; // 检查缓存 for (const roomId of roomIds) { const cached this.cache.get(roomId); if (cached Date.now() - cached.timestamp this.cacheTTL) { results[roomId] cached.data; } else { uncachedIds.push(roomId); } } // 分批请求未缓存的数据 for (let i 0; i uncachedIds.length; i this.batchSize) { const batch uncachedIds.slice(i, i this.batchSize); const batchResults await this.fetchBatch(batch); // 更新缓存和结果 for (const [roomId, data] of Object.entries(batchResults)) { this.cache.set(roomId, { data, timestamp: Date.now() }); results[roomId] data; } // 避免请求过快 await this.delay(100); } return results; } async fetchBatch(roomIds) { const promises roomIds.map(roomId fetch(https://api.live.bilibili.com/room/v1/Room/get_info?room_id${roomId}) .then(res res.json()) .then(data ({ roomId, data })) ); const results await Promise.all(promises); return results.reduce((acc, { roomId, data }) { acc[roomId] data; return acc; }, {}); } delay(ms) { return new Promise(resolve setTimeout(resolve, ms)); } }WebSocket消息处理优化class MessageProcessor { constructor() { this.messageQueue []; this.processing false; this.batchSize 50; } addMessage(message) { this.messageQueue.push(message); if (!this.processing this.messageQueue.length this.batchSize) { this.processBatch(); } } async processBatch() { if (this.processing || this.messageQueue.length 0) return; this.processing true; // 取出批处理的消息 const batch this.messageQueue.splice(0, this.batchSize); try { // 按消息类型分组处理 const groupedMessages this.groupByType(batch); for (const [type, messages] of Object.entries(groupedMessages)) { await this.handleMessageType(type, messages); } } catch (error) { console.error(消息处理失败:, error); // 重新加入队列 this.messageQueue.unshift(...batch); } finally { this.processing false; // 如果队列中还有消息继续处理 if (this.messageQueue.length 0) { setTimeout(() this.processBatch(), 0); } } } groupByType(messages) { return messages.reduce((groups, message) { const type message.cmd || unknown; if (!groups[type]) groups[type] []; groups[type].push(message); return groups; }, {}); } async handleMessageType(type, messages) { switch (type) { case DANMU_MSG: await this.processDanmuMessages(messages); break; case SEND_GIFT: await this.processGiftMessages(messages); break; case INTERACT_WORD: await this.processInteractMessages(messages); break; default: console.log(未处理的消息类型: ${type}, 数量: ${messages.length}); } } }扩展建议监控与告警系统class APIMonitor { constructor() { this.metrics { requests: 0, errors: 0, avgResponseTime: 0, lastError: null }; this.alertThresholds { errorRate: 0.1, // 10%错误率 responseTime: 5000 // 5秒响应时间 }; } async trackRequest(apiCall) { const startTime Date.now(); this.metrics.requests; try { const result await apiCall(); const duration Date.now() - startTime; // 更新平均响应时间 this.metrics.avgResponseTime (this.metrics.avgResponseTime * (this.metrics.requests - 1) duration) / this.metrics.requests; // 检查性能告警 if (duration this.alertThresholds.responseTime) { this.triggerAlert(slow_response, { duration, threshold: this.alertThresholds.responseTime }); } return result; } catch (error) { this.metrics.errors; this.metrics.lastError error; // 检查错误率告警 const errorRate this.metrics.errors / this.metrics.requests; if (errorRate this.alertThresholds.errorRate) { this.triggerAlert(high_error_rate, { errorRate, threshold: this.alertThresholds.errorRate }); } throw error; } } triggerAlert(type, data) { console.warn(API告警: ${type}, data); // 这里可以集成到监控系统如Prometheus、Sentry等 } }数据持久化方案class DataPersistence { constructor(storageBackend local) { this.backend storageBackend; this.batchSize 100; this.buffer []; } async saveMessage(message) { this.buffer.push({ ...message, timestamp: Date.now(), source: bilibili_live }); if (this.buffer.length this.batchSize) { await this.flushBuffer(); } } async flushBuffer() { if (this.buffer.length 0) return; const batch [...this.buffer]; this.buffer []; try { switch (this.backend) { case local: await this.saveToLocalStorage(batch); break; case database: await this.saveToDatabase(batch); break; case elasticsearch: await this.saveToElasticsearch(batch); break; } } catch (error) { console.error(数据保存失败:, error); // 重新加入缓冲区 this.buffer.unshift(...batch); } } async saveToLocalStorage(batch) { const key bilibili_live_${Date.now()}; localStorage.setItem(key, JSON.stringify(batch)); } async saveToDatabase(batch) { // 实现数据库保存逻辑 // 可以使用MySQL、PostgreSQL、MongoDB等 } async saveToElasticsearch(batch) { // 实现Elasticsearch保存逻辑 // 适合日志分析和搜索场景 } }通过以上优化方案和扩展建议开发者可以构建高性能、可扩展的B站直播应用系统。Bilibili-Live-API提供了完整的接口文档和实战示例帮助开发者快速集成B站直播功能构建丰富的直播互动应用。【免费下载链接】Bilibili-Live-APIBILIBILI 直播/番剧 API项目地址: https://gitcode.com/gh_mirrors/bil/Bilibili-Live-API创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考