pythonpython-3.xtkintertwitchtwitch-api

Having trouble with the Twitch API


I am trying to get chat, then turn that into a number of chatters per time period and then take the top 10 moments and print into a text file so that I can edit easier, however I cant seem to get it to work, it seems something wrong with the client id which I don't fully understand.

import requests
import logging
import json
import tkinter as tk
import tkinter.messagebox as messagebox
import functools

# Function to get the chat logs for a given video
def get_chat_logs(client_id, video_id):
  # Make a GET request to the Twitch API to retrieve the chat logs for the given video
  url = f"https://api.twitch.tv/v5/videos/{video_id}/comments"
  headers = { "Client-ID": client_id }
  response = requests.get(url, headers=headers)

  # Print the URL and status code for debugging purposes
  print(f"URL: {url}")
  print(f"Status code: {response.status_code}")

  # If the request was successful, return the chat logs
  if response.status_code == 200:
    return response.json()
  # If the request was unsuccessful, display an error message and return an empty list
  else:
    messagebox.showerror("Error", "An error occurred while retrieving the chat logs. Please check your client ID and video ID and try again.")
    return []


# Function to parse the chat logs and extract the chat volume for each moment in the video
def parse_chat_logs(chat_logs):
  chat_volume_by_moment = {}

  # Iterate through each chat log and extract the timestamp and number of messages
  for chat_log in chat_logs:
    timestamp = chat_log["content_offset_seconds"]
    messages = chat_log["messages"]

    # If this moment has not been seen before, initialize the chat volume to 0
    if timestamp not in chat_volume_by_moment:
      chat_volume_by_moment[timestamp] = 0

    # Add the number of messages for this moment to the chat volume
    chat_volume_by_moment[timestamp] += len(messages)

  return chat_volume_by_moment

# Function to identify the top 10 moments with the highest chat volume
def find_top_moments(chat_volume_by_moment):
  # Sort the moments by chat volume in descending order
  sorted_moments = sorted(chat_volume_by_moment.items(), key=lambda x: x[1], reverse=True)

  # Return the top 10 moments
  return sorted_moments[:10]

# Function to add textboxes and a submit button to the UI
def add_ui_elements(main):
  # Create the main window
  window = tk.Tk()
  window.title("Twitch Chat Logs")

  # Create a label for the client ID textbox
  client_id_label = tk.Label(text="Enter your client ID:")
  client_id_label.pack()

  # Create a textbox for the client ID
  client_id_textbox = tk.Entry()
  client_id_textbox.pack()

  # Create a label for the video ID textbox
  video_id_label = tk.Label(text="Enter the video ID:")
  video_id_label.pack()

  # Create a textbox for the video ID
  video_id_textbox = tk.Entry()
  video_id_textbox.pack()

  # Create a submit button
  submit_button = tk.Button(text="Submit")
  submit_button.pack()

  # Return the client ID and video ID textboxes and submit button
  return client_id_textbox, video_id_textbox, submit_button, window

# Function to create a submit button
def create_submit_button(main):
  # Create a submit button
  submit_button = tk.Button(text="Submit")
  submit_button.pack()
  return submit_button

# Main function
def main(client_id_textbox, video_id_textbox, submit_button):
  # Get the client ID and video ID from the UI
  client_id = client_id_textbox.get()
  video_id = video_id_textbox.get()

  # Check if the user has entered a client ID and video ID
  if not client_id or not video_id:
    messagebox.showerror("Error", "Please enter a valid client ID and video ID.")
    return

  # If a client ID and video ID have been entered, make the API request
  chat_logs = get_chat_logs(client_id, video_id)

  # Parse the chat logs and extract the chat volume for each moment in the video
  chat_volume_by_moment = parse_chat_logs(chat_logs)

  # Find the top 10 moments with the highest chat volume
  top_moments = find_top_moments(chat_volume_by_moment)

  # Write the top moments to a file
  with open("top_moments.txt", "w") as f:
    for moment in top_moments:
      f.write(f"{moment[0]}: {moment[1]}\n")
  messagebox.showinfo("Success", "The top moments have been written to top_moments.txt.")

# Add the UI elements and get the client ID and video ID textboxes and submit button
client_id_textbox, video_id_textbox, submit_button, window = add_ui_elements(main)

# Bind the main function to the submit button's "Button-1" event
submit_button.bind("<Button-1>", functools.partial(main, client_id_textbox, video_id_textbox))

# Run the main loop for the GUI
window.mainloop()

# Run the main function
if __name__ == "__main__":
  client_id_textbox, video_id_textbox = add_ui_elements(main)
  main(client_id_textbox, video_id_textbox, submit_button)

I have tried many things for the past few hours, making sure that the code was proper and it was making the API call but it isn't.


Solution

  • The issue you're having is that you're attempting to use an endpoint https://api.twitch.tv/v5/videos/{video_id}/comments which is undocumented and never intended for 3rd party usage, as such it can and will break/change at any time and without warning.

    As you've just experienced that endpoint has been changed to no longer support 3rd party usage such as this.

    The only supported way to get information about chat is to connect to Twitch Chat, as documented https://dev.twitch.tv/docs/irc, and capture chat data as it happens in real time. Historical chat data, such as from VoDs, has no supported 3rd party endpoints.