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

Twitch报错:Client ID与OAuth令牌不匹配,Discord bot开发求助

问题描述

开发Discord机器人,实现特定主播开播且标题包含指定关键词时发送通知,调用Twitch API时出现以下401错误:

{'error': 'Unauthorized', 'status': 401, 'message': 'Client ID and OAuth token do not match'}

代码如下:

import discord
import requests
import asyncio

intents = discord.Intents.default()
intents.guilds = True
intents.guild_messages = True

client = discord.Client(intents=intents)

client_id = 'CLIENT_ID'
access_token = 'ACCESS_TOKEN'
streamer_id = 'STREAMER_ID'

@client.event
async def on_ready():
    client.loop.create_task(run_stream_check())

async def check_stream():
    headers = {
        'Client-ID': client_id,
        'Authorization': f'Bearer {access_token}'
    }
    url = f'https://api.twitch.tv/helix/streams?user_id={streamer_id}'
    response = requests.get(url, headers=headers)
    print(response.json())
    data = response.json()
    if 'data' in data:
        if data['data']:
            if 'TEST' in data['data'][0]['title']:
                channel = client.get_channel(1057814763087872212)
                await channel.send('Streamer is live with TEST in the title')

async def run_stream_check():
    while True:
        await check_stream()
        await asyncio.sleep(300)

client.run('DISCORD_BOT_TOKEN')

已替换所有占位符,确认client_id、access_token、Discord机器人token均正确,且用curl测试access_token可正常工作,请求解决该报错。


解决方案

1. 校验Client ID与Access Token的绑定关系

Twitch的Access Token是和生成它的Client ID绑定的,哪怕token本身有效,只要代码里的Client ID和生成token时用的不一致,就会触发该错误:

  • 核对生成Access Token时使用的Client ID,确保和代码中的client_id完全一致(注意大小写、无多余空格)。
  • 如果是通过OAuth授权流程获取的token,确认授权页面用的是当前代码的Client ID;如果是客户端凭证流生成的token,确保请求token时用的是当前代码的Client ID和对应的Client Secret。

2. 检查请求头格式是否严格符合要求

Twitch Helix API对请求头格式要求严格:

  • 确保Client-ID的键名完全正确(是Client-ID,不是ClientId或其他变体)。
  • 确认Authorization头格式为Bearer {access_token},其中Bearer后必须有且仅有一个空格,token无截断、无多余字符。

3. 避免混用不同类型的Access Token

Twitch有两种常用token类型,需确保类型匹配:

  • 用户访问令牌:用于代表用户操作,需OAuth授权生成。
  • 客户端凭证令牌:用于代表应用本身操作,通过Client ID+Client Secret生成。
  • 确认你使用的token类型和API调用场景匹配,且生成时对应的Client ID正确。

4. 优化异步请求(额外建议)

当前代码用同步的requests.get在Discord异步事件循环中可能造成阻塞,建议替换为异步HTTP库aiohttp:

import aiohttp

async def check_stream():
    headers = {
        'Client-ID': client_id,
        'Authorization': f'Bearer {access_token}'
    }
    url = f'https://api.twitch.tv/helix/streams?user_id={streamer_id}'
    async with aiohttp.ClientSession() as session:
        async with session.get(url, headers=headers) as response:
            data = await response.json()
            print(data)
            if 'data' in data and data['data']:
                if 'TEST' in data['data'][0]['title']:
                    channel = client.get_channel(1057814763087872212)
                    if channel:  # 增加通道存在检查,避免NoneType错误
                        await channel.send('Streamer is live with TEST in the title')

5. 重新生成匹配的Access Token

若以上检查均无问题,建议重新生成Access Token:

  • 客户端凭证流:用正确的Client ID和Client Secret发送POST请求到https://id.twitch.tv/oauth2/token,参数为client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=client_credentials。
  • 用户授权流:重新走OAuth授权流程,确保使用当前代码的Client ID。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 21:25:32