You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用YouTube Data API v3获取直播聊天消息时遇无效page token错误

YouTube Data API V3 直播聊天page token无效问题修复

错误原因分析

你遇到的page token is not valid错误,核心问题有两个:

  1. 未遵守轮询间隔要求:YouTube Live Chat API返回的nextPageToken有严格时效性,必须等待接口返回的pollingIntervalMillis时长后,才能使用该token请求下一页。你的代码拿到token后立即递归调用,导致token还未生效或已过期。
  2. 缺少错误处理逻辑:当token无效时,没有重置请求流程,无法恢复正常拉取消息。

修复后的代码

gapi.load('client', start);

function start() {
  fetch('config.json')
    .then(response => response.json())
    .then(config => {
      gapi.client.init({
        apiKey: config.apiKey,
        discoveryDocs: ["https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest"]
      }).then(function() {
        const liveChatId = config.liveChatId;

        function getChatMessages(pageToken) {
          gapi.client.youtube.liveChatMessages.list({
            liveChatId: liveChatId,
            part: 'snippet',
            pageToken: pageToken
          }).then(function(response) {
            const chatDiv = document.getElementById('chat');

            // 渲染聊天消息
            response.result.items.forEach(function(item) {
              const message = item.snippet.displayMessage;
              const messageElement = document.createElement('div');
              messageElement.className = 'chat-message';
              messageElement.textContent = message;
              chatDiv.appendChild(messageElement);

              setTimeout(function() {
                messageElement.style.transform = 'translateX(100%)';
                setTimeout(function() {
                  chatDiv.removeChild(messageElement);
                }, 500);
              }, 10000);
            });

            // 按照API指定的间隔,请求下一页消息
            if (response.result.nextPageToken) {
              const pollingInterval = response.result.pollingIntervalMillis;
              setTimeout(() => {
                getChatMessages(response.result.nextPageToken);
              }, pollingInterval);
            }
          }).catch(function(error) {
            console.error('拉取聊天消息失败:', error);
            // 如果是token无效错误,重新从第一页开始拉取
            if (error.result?.error?.errors?.some(e => e.reason === 'pageTokenInvalid')) {
              setTimeout(() => {
                getChatMessages();
              }, 1000); // 等待1秒后重试
            }
          });
        }

        getChatMessages();
      });
    }).catch(error => {
      console.error('加载配置文件失败: ' + error);
    });
}

关键修改点

  • 添加轮询间隔控制:使用response.result.pollingIntervalMillis作为下一次请求的等待时间,严格遵守API要求,避免token失效。
  • 增加错误处理:捕获接口调用错误,当检测到pageTokenInvalid时,自动重置请求(不带pageToken重新拉取第一页),保证流程能恢复。
  • 代码可读性优化:使用const替代var,添加注释说明关键逻辑。

内容的提问来源于stack exchange,提问作者EinfachSimmi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 14:13:14