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

Twitch直播标题设置失败排查:TypeError读取undefined的'0'属性

问题修复方案

错误原因分析

  1. 获取主播ID的API调用逻辑错误
    Twitch Helix API的/channels GET接口不支持用broadcaster_name作为查询参数,你用这个参数请求会直接返回400错误,导致后续无法获取合法的broadcaster_id。要通过用户名获取主播ID,必须调用/users接口,使用login参数传递用户名。

  2. 缺少API错误响应处理
    当API返回错误状态码时,你没有检查响应是否成功就直接解析JSON,此时返回的data.data是undefined,访问data.data[0]必然触发Cannot read properties of undefined (reading '0')的类型错误。

修复后的完整代码

#!/usr/bin/env node
const twitchAPI = 'https://api.twitch.tv/helix';
const clientId = 'censored';
const clientSecret = 'censored';
const refreshToken = 'censored';
const accessToken = 'censored';
const channelName = 'censored';
const url = 'https://api.kyroskoh.xyz/valorant/v1/mmr/eu/CEN%20Astro/EUWE?show=combo&display=0';

// Set initial title
let currentRank = '';
setTitle('OMW to Diamond [Unknown Rank] | !rank !sens');

// Poll for updates every 5 seconds
setInterval(async () => {
  try {
    const module = await import('node-fetch');
    const fetch = module.default;
    
    const response = await fetch(url);
    const data = await response.text();
    // Extract rank from response data
    const rankRegex = /<body>(.*)<\/body>/;
    const match = data.match(rankRegex);
    if (match) {
      const rank = match[1];
      if (rank !== currentRank) {
        currentRank = rank;
        setTitle(`OMW to Diamond [${rank}] | !rank !sens`);
        console.log(`Title updated to: OMW to Diamond [${rank}] | !rank !sens`);
      }
    }
  } catch (error) {
    console.error(`Failed to fetch rank: ${error}`);
  }
}, 5000);

// Helper function to set the stream title using Twitch API
async function setTitle(title) {
    try {
      const module = await import('node-fetch');
      const fetch = module.default;

      // 第一步:通过用户名获取主播ID
      const userResponse = await fetch(`${twitchAPI}/users?login=${channelName}`, {
        headers: {
          'Client-ID': clientId,
          'Authorization': `Bearer ${accessToken}`,
        },
      });
      
      if (!userResponse.ok) {
        throw new Error(`获取用户信息失败: ${userResponse.status} - ${await userResponse.text()}`);
      }
      
      const userData = await userResponse.json();
      if (!userData.data || userData.data.length === 0) {
        throw new Error(`未找到用户: ${channelName}`);
      }
      
      const broadcasterId = userData.data[0].id; // 注意字段是id,不是broadcaster_id

      // 第二步:更新直播标题
      const patchResponse = await fetch(`${twitchAPI}/channels?broadcaster_id=${broadcasterId}`, {
        method: 'PATCH',
        headers: {
          'Client-ID': clientId,
          'Authorization': `Bearer ${accessToken}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ title }),
      });
      
      if (!patchResponse.ok) {
        throw new Error(`更新标题失败: ${patchResponse.status} - ${await patchResponse.text()}`);
      }
      
      console.log(`Successfully set title to: ${title}`);
    } catch (error) {
      console.error(`Failed to set title: ${error}`);
    }
}

额外注意事项

  • 确保你的accessToken拥有channel:manage:broadcast权限,否则更新标题会返回403权限错误。
  • 建议把node-fetch作为依赖安装(npm install node-fetch),替代每次动态import的方式,提升脚本稳定性。
  • 可添加accessToken过期自动刷新逻辑,避免token失效后脚本停止工作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 21:35:16