【问题标题】:How do I listen for new uploads from a specific channel in the YouTube API?如何在 YouTube API 中收听来自特定频道的新上传内容?
【发布时间】:2020-10-12 22:36:13
【问题描述】:

我正在制作一个 Discord 机器人,我希望它能够使用 YouTube API 从特定频道获取新的上传内容。

我在其他地方搜索过,但他们都说如何上传视频,而不是如何跟踪上传。

这可能吗,我该怎么做?

编辑:尝试了 PubSubHubbub,但它非常混乱,我无法让它工作

【问题讨论】:

标签: javascript node.js youtube-api


【解决方案1】:

这里是一个基于 Node.js (v12) 和 Fastify 并使用 ngrok 发布的示例:

我写了一些 cmets 来解释它发生了什么:

const fastify = require('fastify')({ logger: true })

const xmlParser = require('fast-xml-parser')

const { URLSearchParams } = require('url')
const fetch = require('node-fetch')

// add an xml parser
fastify.addContentTypeParser('application/atom+xml', { parseAs: 'string' }, function (req, xmlString, done) {
  try {
    const body = xmlParser.parse(xmlString, {
      attributeNamePrefix: '',
      ignoreAttributes: false
    })
    done(null, body)
  } catch (error) {
    done(error)
  }
})

// this endpoint needs for authentication
fastify.get('/', (request, reply) => {
  reply.send(request.query['hub.challenge'])
})

// this endpoint will get the updates
fastify.post('/', (request, reply) => {
  console.log(JSON.stringify(request.body, null, 2))
  reply.code(204)
  reply.send('ok')
})

fastify.listen(8080)
  .then(() => {
    // after the server has started, subscribe to the hub

    // Parameter list: https://pubsubhubbub.github.io/PubSubHubbub/pubsubhubbub-core-0.4.html#rfc.section.5.1
    const params = new URLSearchParams()
    params.append('hub.callback', 'https://1f3dd0c63e78.ngrok.io') // you must have a public endpoint. get it with "ngrok http 8080"
    params.append('hub.mode', 'subscribe')
    params.append('hub.topic', 'https://www.youtube.com/xml/feeds/videos.xml?channel_id=UCfWbGF64qBSVM2Wq9fwrfrg')
    params.append('hub.lease_seconds', '')
    params.append('hub.secret', '')
    params.append('hub.verify', 'sync')
    params.append('hub.verify_token', '')

    return fetch('https://pubsubhubbub.appspot.com/subscribe', {
      headers: { 'content-type': 'application/x-www-form-urlencoded' },
      body: params,
      method: 'POST'
    })
  })
  .then((res) => {
    console.log(`The status must be 204. Received ${res.status}`)

    // shows the error if something went wrong
    if (res.status !== 204) {
      return res.text().then(txt => console.log(txt))
    }
  })

我用我的频道ID做了一些测试,考虑到通知不是实时的,通常几分钟后会触发POST。

【讨论】:

  • 谢谢,这就是我要找的东西
猜你喜欢
  • 2019-07-27
  • 2017-02-12
  • 2011-09-11
  • 2013-02-03
  • 2015-10-30
  • 2013-03-24
  • 2022-12-18
  • 2017-08-08
  • 2016-04-16
相关资源
最近更新 更多