LoginSignup
36
18

More than 3 years have passed since last update.

NodeでAPIを使わずにYouTubeLiveのチャットを取得する

Last updated at Posted at 2019-12-24

本記事はVTuber Tech #1 Advent Calendar 2019の24日目の記事です。

YouTubeLiveのチャットを取得するやつを作った話

そういうことです。YouTube、クリスマスカラーっぽいでしょ。
非公式手法なので自己責任重点な。

TL;DR

作ったので使って、どうぞ。
youtube-chat
GitHub

何故作ったのか

自分で配信するようのコメビュを作っていろいろやろうと思い、最初は普通にAPIで取得すればいいやと考えていた。が、ウカツ!
毎秒取得したら数分でAPI上限に達してしまうではないか!ブッダシット!

使用技術

  • Node.js
  • TypeScript

使い方

  1. 普通にインストールする

    npm i youtube-chat
    
  2. require(import)する

    import {LiveChat} from 'youtube-chat'
    
  3. チャンネルIDか、ライブIDを入力してインスタンス化

    // If channelId is specified, liveId in the current stream is automatically acquired.
    const liveChat = new LiveChat({channelId: 'UCxkOLgdNumvVIQqn5ps_bJA?'})
    
    // Or specify LiveID in Stream manually.
    const liveChat = new LiveChat({liveId: 'bc5DoKBZRIo'})
    
  4. イベント登録

    // Emit at start of observation chat.
    liveChat.on('start', (liveId: string) => {})
    // Emit at end of observation chat.
    liveChat.on('end', (reason: string) => {})
    // Emit at receive chat.
    liveChat.on('comment', (comment: CommentItem) => {})
    // Emit when an error occurs
    liveChat.on('error', (err: Error) => {})
    

イベントをもうちょいkwsk

start

  • チャット読み取り開始時に呼び出し
  • 引数
    • liveId: string
      • 読み取り開始したライブのID

end

  • 読み取り終了時に呼び出し
  • 引数
    • reason: string
      • 終了した理由の文字列

comment

  • チャットがされた時に呼び出し
  • 引数
    • comment: CommentItem
      • チャットのデータ

error

  • エラー時に呼び出し
  • 引数
    • err: Error
      • エラーオブジェクト

コメントデータの型

interface CommentItem {
  id: string
  author: {
    name: string
    thumbnail?: ImageItem
    channelId: string
    badge?: {
      thumbnail: ImageItem
      label: string
    }
  }
  message: MessageItem[]
  superchat?: {
    amount: string
    color: number
  }
  membership: boolean
  isOwner: boolean
  timestamp: number
}

※詳しくはReadMe重点な

使用例

  • エアスパチャ
    • チャットからコマンドを解析してアラートを鳴らす
  • 上記を始めとした簡単なチャット内コマンドの実装等

どうやってるのか

おまけとしてどうやってるか書こうと思う

コメント取得

  • チャットをポップアウトしたURLに&pbj=1を足してチャットのjsonを取得
  • addChatItemActionのitemをCommentItem型にパース
  • コメント1つごとにcommentイベントを発火
    • 以上をintervalの値(1000ms)ごとに繰り返す

チャンネルIDからライブ配信のURL特定

  • https://www.youtube.com/channel/(チャンネルID)/liveをGET
  • metaタグにあるサムネイル画像のURLからライブIDを特定

課題

  • パーサーしか自動テストされてないお酒飲みながら書いてたので無かったことになってた
    • CIとかやってない
  • コメント投稿や、アーカイブのチャットを取得等の機能
    • やる気次第

最後に

  • 初めてのプルリクに小躍りした
  • 感謝された
    • 一部の人には刺さるものを作れた気がして嬉しい
  • こいつを使って今度は自作コメビュを作る予定
    • MultiCommentViewerさんを超えたい

スペシャルサンクス

36
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
36
18