I’m working on a Python script that fetches chat data from Twitch streams and finds the most active chat moments. The goal is to analyze message volume over time and export the top chat spikes to a file for later review. My code keeps failing and I think there’s an issue with how I’m handling the client ID authentication but I’m not sure what’s wrong.
import requests
import json
import tkinter as tk
from tkinter import messagebox
def fetch_stream_chat(api_key, stream_id):
endpoint = f"https://api.twitch.tv/v5/videos/{stream_id}/comments"
request_headers = {"Client-ID": api_key}
api_response = requests.get(endpoint, headers=request_headers)
print(f"Request URL: {endpoint}")
print(f"Response status: {api_response.status_code}")
if api_response.status_code == 200:
return api_response.json()
else:
messagebox.showerror("API Error", "Failed to fetch chat data. Check your credentials.")
return []
def analyze_chat_activity(chat_data):
activity_map = {}
for entry in chat_data:
time_offset = entry["content_offset_seconds"]
msg_list = entry["messages"]
if time_offset not in activity_map:
activity_map[time_offset] = 0
activity_map[time_offset] += len(msg_list)
return activity_map
def get_peak_moments(activity_data):
ranked_moments = sorted(activity_data.items(), key=lambda item: item[1], reverse=True)
return ranked_moments[:10]
def setup_interface():
root = tk.Tk()
root.title("Chat Activity Analyzer")
tk.Label(root, text="API Key:").pack()
api_input = tk.Entry(root)
api_input.pack()
tk.Label(root, text="Stream ID:").pack()
stream_input = tk.Entry(root)
stream_input.pack()
analyze_btn = tk.Button(root, text="Analyze")
analyze_btn.pack()
return api_input, stream_input, analyze_btn, root
def process_data(api_field, stream_field, btn):
api_key = api_field.get()
stream_id = stream_field.get()
if not api_key or not stream_id:
messagebox.showerror("Input Error", "Both fields are required.")
return
chat_data = fetch_stream_chat(api_key, stream_id)
activity_data = analyze_chat_activity(chat_data)
peak_moments = get_peak_moments(activity_data)
with open("chat_peaks.txt", "w") as output_file:
for timestamp, count in peak_moments:
output_file.write(f"Time: {timestamp}s - Messages: {count}\n")
messagebox.showinfo("Complete", "Results saved to chat_peaks.txt")
if __name__ == "__main__":
api_field, stream_field, btn, root = setup_interface()
btn.config(command=lambda: process_data(api_field, stream_field, btn))
root.mainloop()
I’ve been debugging this for hours but the API calls keep failing. Any ideas what might be wrong with the authentication setup?