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

使用pytchat获取YouTube直播聊天时遇AttributeError问题求助

解决pytchat获取YouTube直播聊天的AttributeError问题及自动重启方案

一、针对性修复(避免报错终止)

这个错误是因为chat.get()偶尔会返回列表而非预期的可调用sync_items()的对象,大概率是网络波动或YouTube API返回异常导致的。可以通过类型判断+异常捕获来处理:

修改后的脚本:

import pytchat

chat = pytchat.create(video_id="uIx8l2xlYVY")
while chat.is_alive():
    try:
        chat_data = chat.get()
        # 先判断是否有sync_items方法,再调用
        if hasattr(chat_data, 'sync_items'):
            for c in chat_data.sync_items():
                print(f"{c.datetime} [{c.author.name}]- {c.message}")
        else:
            # 遇到返回列表的情况,直接遍历
            for c in chat_data:
                print(f"{c.datetime} [{c.author.name}]- {c.message}")
    except AttributeError as e:
        # 捕获到错误时跳过当前循环,继续运行
        print(f"临时错误:{e},继续获取聊天内容")
        continue

二、自动重启方案(彻底兜底)

如果上述修复仍无法避免崩溃,可以用以下两种方式实现自动重启:

1. 脚本内部自重启

通过os.execv实现脚本自身重启,修改后的代码:

import pytchat
import os
import sys

def run_chat_monitor():
    chat = pytchat.create(video_id="uIx8l2xlYVY")
    while chat.is_alive():
        try:
            chat_data = chat.get()
            if hasattr(chat_data, 'sync_items'):
                for c in chat_data.sync_items():
                    print(f"{c.datetime} [{c.author.name}]- {c.message}")
            else:
                for c in chat_data:
                    print(f"{c.datetime} [{c.author.name}]- {c.message}")
        except Exception as e:
            print(f"程序出错:{e},正在重启...")
            # 重启当前脚本
            os.execv(sys.executable, ['python'] + sys.argv)

if __name__ == "__main__":
    run_chat_monitor()

2. 外部监控脚本

写一个简单的监控脚本,检测目标脚本是否运行,终止后自动重启:
监控脚本monitor.py:

import subprocess
import time
import sys

TARGET_SCRIPT = "你的聊天脚本文件名.py"

while True:
    # 启动目标脚本
    process = subprocess.Popen([sys.executable, TARGET_SCRIPT])
    # 等待脚本结束
    process.wait()
    # 脚本崩溃后等待3秒再重启
    print("聊天脚本已终止,3秒后重启...")
    time.sleep(3)

运行时直接启动monitor.py即可,它会自动维护聊天脚本的运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 21:01:55