基本上我有这个 python 脚本,它使用 pytchat 读取 youtube 聊天并保存以 /topic 开头的消息。它通常会工作半小时,最终关闭而不会出现任何错误(我尝试通过cmd运行它,但仍然没有错误,它只是停止)。我如何让它 24/7 工作,代码中是否有任何错误?
# -*- 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
我尝试通过cmd运行它,仍然没有错误,它只是停止了
代码有同样的问题:
while chat.is_alive():
try:
for message in chat.get().sync_items():
sender = message.author.name
text = message.message
if text:
if use_image:
await bot.send_message(chat_id, f"<a href='{message.author.channelUrl}'>{sender}</a>, "
f"<a href='{message.author.imageUrl}'>‍</a>: {text}",
parse_mode=ParseMode.HTML)
else:
await bot.send_message(chat_id, f"<a href='{message.author.channelUrl}'>{sender}</a>: "
f"{text}", parse_mode=ParseMode.HTML)
except Exception as e:
print(f"Error occurred while processing chat: {e}")
# handle the error here, for example, by sending an error message to the user
if not is_running:
break
await asyncio.sleep(1)
print("chat is not alive!")
return
它工作了 60 分钟,之后我会说“聊天不活跃”。无论我什么时候开始获取 10:00、14:37 或 21:49,它只会工作 60 分钟。这个问题持续了两个月,然后可能会工作几个小时并因其他原因停止,而不是因为 while chat.is_alive() 。另外,如果我在 10:00 开始代码并在 10:55 手动取消,然后重新启动它 - 代码无论如何都会在 11:00 停止。重启后我还有 60 分钟的时间来获取。 pc 是台式机和 rpi 3b 有相同的结果