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

Python脚本读取YouTube Chat莫名停止,如何实现24/7运行?

YouTube聊天监控脚本自动终止问题排查与修复

问题描述

我编写了一段使用pytchat库读取YouTube Chat的Python脚本,用于保存以/topic开头的消息。该脚本通常运行半小时后会无报错自动终止(经CMD运行测试仍未出现报错信息,仅自行停止)。请问我的代码是否存在错误?如何实现脚本24小时不间断运行?

原代码

# -*- coding: utf-8 -*-
import pytchat

video_id = "iAa3fFY1Hg0"
chat = pytchat.create(video_id)

file_path = "C:/Users/80nin/ai/Assets/chat_log.txt"

def write_to_file(author, message):
    cleaned_message = message[len("/topic"):].strip()
    with open(file_path, "a", encoding="utf-8") as file:
        file.write(f"{author.name} - {cleaned_message}\n")

while True:
    try:
        for c in chat.get().sync_items():
            print(f"{c.author.name} - {c.message}")
            if c.message.startswith("/topic"):
                write_to_file(c.author, c.message)
    except pytchat.ChatDataFinished:
        print("Chat data finished, waiting for new messages...")
        time.sleep(10)  # Adjust the wait time as needed
    except Exception as e:
        print(f"An error occurred: {str(e)}")
        time.sleep(10)  # Wait before trying again to avoid continuous errors

问题排查

  1. 缺失time模块导入:代码中使用了time.sleep()函数,但未导入time模块,这会触发未捕获的NameError,直接导致脚本终止(部分环境下异常未被打印,所以看起来是无报错停止)。
  2. chat对象失效问题:当pytchat返回ChatDataFinished后,原有的chat对象可能无法继续获取后续新消息,重复使用同一对象会导致循环无法捕获新内容,最终脚本陷入无操作状态甚至终止。

修复方案

  1. 添加time模块导入,解决NameError问题。
  2. 每次捕获异常后重新创建chat对象,确保能持续获取最新聊天数据。
  3. 优化循环逻辑,确保任何异常发生后都能重启监控流程。

修复后的代码

# -*- coding: utf-8 -*-
import pytchat
import time  # 新增导入time模块

video_id = "iAa3fFY1Hg0"
file_path = "C:/Users/80nin/ai/Assets/chat_log.txt"

def write_to_file(author, message):
    cleaned_message = message[len("/topic"):].strip()
    with open(file_path, "a", encoding="utf-8") as file:
        file.write(f"{author.name} - {cleaned_message}\n")

while True:
    # 每次循环重新创建chat对象,避免失效
    chat = pytchat.create(video_id)
    try:
        for c in chat.get().sync_items():
            print(f"{c.author.name} - {c.message}")
            if c.message.startswith("/topic"):
                write_to_file(c.author, c.message)
    except pytchat.ChatDataFinished:
        print("Chat data finished, waiting 10s to reconnect...")
        time.sleep(10)
    except NameError as e:
        print(f"Missing module error: {str(e)}")
        time.sleep(10)
    except Exception as e:
        print(f"Unexpected error: {str(e)}")
        time.sleep(10)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 22:38:09