Reputation: 89
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?
Upvotes: 1
Views: 1923
Reputation: 1
Are you terminating the chat before iterating through the messages? I got the same error when doing so.
You might want to check if the chat is still alive before iterating.
Upvotes: 0
Reputation: 1
This problem occurs because in "pytchat", "pytchat.creat()" will return a "PytchatCore" object, and the "get()" method in "PytchatCore" is like this:
def get(self):
if self.is_alive():
chat_component = self._get_chat_component()
return self.processor.process([chat_component])
else:
return []
So when "chat.get().is_alive()" return "False", you will get an empty list "[]" to do ".sync_items()" method on, so an error occur. In my test, if you run "for c in chat.get().sync_items():" as high frequency, this "AttributeError" will occur in every 60 mins. However, if you spend more time to run your code for each round of "for c in chat.get().sync_items():" (like me, I do TTS and play the voice for each chat), this "AttributeError" won't occur as frequently.
To solve this problem, my solution is to capture the error and include some logic to handle it. For example, "If 'AttributeError' occurs more than 10 times" or "If 'AttributeError' occurs over 5 times in 5 mins". If the condition is met, then save the state(to skip the initialization of your script) of your program and restart your script.
I would improve your code like this:
import pytchat
import os
import sys
video_id = "uIx8l2xlYVY"
chat = pytchat.create(video_id=video_id)
attribute_error_count = 0
#Check config folder to save the state when restarting.
if not os.path.exists("./config"):
os.makedirs("./config")
#Set last_message
#When restart, sometime you get repeated chat, so you need last_message to avoid this.
if not os.path.exists("./config/last_message.txt"):
with open("./config/last_message.txt", "w", encoding="utf-8") as file:
pass
with open("./config/last_message.txt", "r", encoding="utf-8") as file:
last_message = file.read()
while True:
if attribute_error_count >= 10:
with open("./config/last_message.txt", "w", encoding="utf-8") as file:
file.write(last_message)
"""
State saving code
"""
print("Restarting program...")
os.execv(sys.executable, ["python"] + sys.argv)
try:
for c in chat.get().sync_items():
message = f"{c.datetime} [{c.author.name}]- {c.message}"
if message == last_message:
continue
else:
last_message = message
print(message)
except AttributeError:
print("AttributeError")
chat = pytchat.create(video_id=video_id)#Reset chat. Not sure if this line work, maybe you can delete it.
attribute_error_count += 1
Upvotes: 0
Reputation: 180
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")
Upvotes: 0