@hyext/communication

A communication lib for huya miniapp business development

Usage no npm install needed!

<script type="module">
  import hyextCommunication from 'https://cdn.skypack.dev/@hyext/communication';
</script>

README

@hyext/communication

基于虎牙小程序open-api封装的专用库。

安装

$ npm i @hyext/communication

引用

import { createOpenWS } from "@hyext/communication"; // 虎牙小程序 or 虎牙小游戏

const createOpenWS = require('@hyext/communication').createOpenWS // nodejs

note: nodejs宿主需要安装ws模块,操作如下:npm i ws。

模块

OpenWS

OpenWS 模块是对虎牙小程序open-api基于websocket部分的封装, 可以接受弹幕、礼物、贵族入场等等消息。

createOpenWS(options)

创建一个OpenWS实例,其options数据结构如下:

Name Type Required Default Description
roomId number true void 直播间 Id,一般可以通过 SDK 的接口获取
extUuid string true void 小程序 uuid, 可在 开发者平台->概要->小程序 ID 查看
appId string true void 开发者平台网页右上角点击头像可查看
secret string true void 开发者平台网页右上角点击头像可查看
expireTimeDelta number true void 内部token到期时间差,例如:600,代表当前时间 + 600 秒到期
debug boolean false void 开启debug日志

Interfaces

  • ws.on(event: string, handler: (data:any) => void):void - 监听事件。
  • ws.close():void - 主动关闭连接,此时ws不会再重新建立连接

Events

内置事件

该库暴露了一个 WS 事件 ID 对象WSEventIds, 内含几个内置事件:

  • WSEventIds.open - socket 建立连接事件。
  • WSEventIds.close - socket 被关闭事件,此时ws会尝试重新建立连接,并恢复已订阅的事件。
open-api 事件
  • 普通事件

    • getMessageNotice: 弹幕消息
    • getVipEnterBannerNotice: 高级用户进场消息
    • getSendItemNotice: 送礼消息
    • getOnTVAwardNotice: 上电视中奖
    • getOpenNobleNotice: 开通续费贵族
    • getOpenGuardianNotice: 开通续费守护
    • getUserMutedNotice: 房管禁言
    • getShareLiveNotice: 分享直播间
  • 高级事件(需要向hy-ext@huya.com发送邮件申请权限)

    • getVipBarNotice:用户进入贵宾席前100
    • getConferVFansNotice:授予钻粉
    • getOpenSuperFansNotice:开通续费超粉
    • getFansBadgeNotice:首次获得粉丝徽章

具体每个事件返回的数据结构,可在该页查询

Demo

Client
import { UI } from '@hyext/hy-ui'
import React, { Component } from 'react'
import './app.hycss'
import { createOpenWS, WSEventIds } from "@hyext/communication";

const { View, Text } = UI

class App extends Component {
  componentDidMount() {
    const ws = createOpenWS({
      appId: 'your_appid',
      secret: 'your_secret',
      expireTimeDelta: 60 * 10, // 10分钟
      extUuid: 'your_extUuid',
      roomId: 111222, // 直播间ID
      debug: true
    })

    // 监听ws内置事件
    ws.on(WSEventIds.close, (data) => {
      console.log('The ws has closed.')
    })

    // 监听open-api弹幕事件
    ws.on('getMessageNotice', (data) => {
      console.log(data, 'getMessageNotice')
    })
  }

  render () {
    return (
      <View className="container"><Text>hello world</Text></View>
    )
  }
}

export default App

其中roomId可通过hyExt.context.getStreamerInfo接口获取,详情点这里

Server
const createOpenWS = require('@hyext/communication').createOpenWS

const ws = createOpenWS({
  appId: 'your_appid',
  secret: 'your_secret',
  expireTimeDelta: 60 * 10, // 10分钟
  extUuid: 'your_extUuid',
  roomId: 111222, // 直播间ID
  debug: true
})

// 监听弹幕的消息
ws.on('getMessageNotice', (data) => {
  console.log(data, 'getMessageNotice')
})

其中roomId可通过client端或其他方式获取。