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

如何在TwitchIO中获取用户ID?解决Chatter对象ID为空问题

解决TwitchIO中Chatter/PartialChatter获取用户ID的问题

问题背景

我正在开发一个Twitch机器人,需要统计用户评论发布数量并做排名,因此得用Twitch ID在数据库中标记用户。我编写了如下getId函数,但遇到两个问题:

  1. 按文档说明Chatter对象应包含id属性,但实际该属性为空
  2. 尝试通过chatter.channel.user()获取ID时,报错AttributeError: 'coroutine' object has no attribute 'id'

原代码:

def getId(chatter : Union[twitchio.Chatter, twitchio.PartialChatter]):                                                                                                                               
    if isinstance(chatter,twitchio.chatter.Chatter):                            
        userVar = chatter.channel.user()                                        
        print("NormalChatter", type(userVar))                                   
        return userVar                                                          
        #return chatter.channel.user().id                                       
        #return chatter.id                                                      
    elif isinstance(chatter, twitchio.PartialChatter):                          
        return chatter.user().id                                                
    else:                                                                       
        print("NoneBoy")   

核心问题

  • chatter.channel.user()和chatter.user()都是协程函数,直接调用只会返回协程对象,必须用await关键字执行才能拿到实际的User实例
  • 部分场景下Chatter.id为空,是因为TwitchIO未自动拉取完整用户数据,需要主动通过协程获取

修正后的代码

由于要使用await,函数需改为异步函数:

from typing import Union, Optional
import twitchio

async def get_user_id(chatter: Union[twitchio.Chatter, twitchio.PartialChatter]) -> Optional[str]:
    if isinstance(chatter, twitchio.Chatter):
        # 优先使用本地已有的id,避免额外API请求
        if chatter.id:
            return chatter.id
        # 本地id为空时,通过协程拉取完整用户数据
        user = await chatter.channel.user()
        return user.id
    elif isinstance(chatter, twitchio.PartialChatter):
        # PartialChatter的user()是协程,必须await
        user = await chatter.user()
        return user.id
    else:
        print("无法识别的用户类型")
        return None

使用说明

  1. 调用该函数时,必须在异步上下文(比如TwitchIO的事件回调函数中)使用await:
# 示例:在消息事件中获取用户ID
async def event_message(self, message):
    user_id = await get_user_id(message.author)
    print(f"用户ID:{user_id}")
  1. 优先检查chatter.id可以减少Twitch API调用次数,提升性能
  2. 函数返回Optional[str],处理时需注意空值情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 16:52:42