javascript - 如何在 YouTube API 中监听来自特定 channel 的新上传内容?

标签 javascript node.js youtube-api

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

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

这可能吗?我该怎么做?

编辑:尝试过 PubSubHubbub,但它非常困惑,我无法让它工作

最佳答案

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

我写了一些评论来解释正在发生的事情:

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))
    }
  })

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

关于javascript - 如何在 YouTube API 中监听来自特定 channel 的新上传内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62525052/

相关文章:

node.js - 错误 : uncaughtException: require(. ..).invokeRolesPolicies 不是函数

node.js - 使用不同的值更新 mongoDb 集合的每个文档的相同属性

javascript - Array.prototype.includes 在 Node js 版本 <= 4

javascript - $.getJSON 只返回部分和一个空数组

javascript - 如何使用jquery依次执行一系列动画?

php - 向上滑动 DIV 容器

javascript - 如何触发带有类标签的按钮?

javascript - 是否可以捕获在 iframe(同一域)内部导航的用户的 JS 事件?

通过 API 进行 YouTube 安全搜索和评级

android - jquery mobile + phonegap 构建中的 Youtube iframe