# Pip install pytchat
# Pip install pandas


import pytchat
import pandas as pd
import winsound

# URL of the YouTube video
video_url = "VIDEO_URL"

# Replace VIDEO_URL with the actual video ID
video_id = video_url.split("v=")[1]

# Initialize pytchat
chat = pytchat.create(video_id=video_id)

# List to hold chat data
chat_data = []

# Fetch chat messages
print("Fetching live chat... Press Ctrl+C to stop.")
try:
    while chat.is_alive():
        for c in chat.get().sync_items():
            chat_data.append({
                "Date-Time": c.datetime,
                "Author": c.author.name,
                "Message": c.message,
                })
except KeyboardInterrupt:
    print("Chat fetching stopped.")

# Convert to a DataFrame
df = pd.DataFrame(chat_data)

# Save to CSV
output_file = "live_chat.csv"
df.to_csv(output_file, index=False, encoding='utf-8')
print(f"Live chat saved to {output_file}")

# Play notification sound
frequency = 440  # Frequency in Hertz
duration = 2000  # Duration in milliseconds (2 seconds)
winsound.Beep(frequency, duration)
