[SOLVED] Fetching youtube live chat with pytchat

Issue

This Content is from Stack Overflow. Question asked by Martin

import pytchat
chat = pytchat.create(video_id="uIx8l2xlYVY")
while chat.is_alive():
    for c in chat.get().sync_items():
        print(f"{c.datetime} [{c.author.name}]- {c.message}")

Im using this one pytchat script to fetch youtube live chat. Usually its working fine but sometimes i got an error:

Traceback (most recent call last):
  File "pytchat.py", line 14, in <module>
    for c in chat.get().sync_items():
AttributeError: 'list' object has no attribute 'sync_items'

After that its stop working and i need to restart it manually.

Any idea how could i solve this issue? Maybe some kind of auto restart if there is no better option?



Solution

You can use a try-except block to catch the error and restart the script.

import pytchat
chat = pytchat.create(video_id="uIx8l2xlYVY")
while chat.is_alive():
    try:
        for c in chat.get().sync_items():
            print(f"{c.datetime} [{c.author.name}]- {c.message}")
    except AttributeError:
        print("Error occurred. Restarting...")
        chat = pytchat.create(video_id="uIx8l2xlYVY")


This Question was asked in StackOverflow by Martin and Answered by James It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?