"""
Standalone function for the background process. Connects to <REDACTED> chat,
listens for messages, extracts option plays, and puts data into the queue.
Args:
video_id (str): The YouTube Live Stream Video ID.
message_queue (multiprocessing.Queue): Queue for communication with main process.
stop_event (multiprocessing.Event): Event to signal when to stop.
"""
try:
# Create a dedicated pytchat instance in this process
logging.info(f"Worker process starting for video ID: {video_id}")
message_queue.put("STATUS: Initializing connection...")
chat = None
try:
logging.info("Attempting to create pytchat object")
message_queue.put("STATUS: Connecting to <REDACTED> chat...")
# Create the pytchat object with explicit parameters
chat = pytchat.create(
video_id=video_id,
interruptable=False, # Disable signal handling in pytchat
force_replay=False # Don't use replay mode
)
logging.info("Successfully created pytchat object")
message_queue.put("STATUS: Connected to chat successfully")
except Exception as e:
logging.error(f"Error creating pytchat: {str(e)}")
message_queue.put(f"ERROR: {str(e)}")
return
# Main loop - continue until stop flag is set
logging.info("Starting main chat processing loop")
message_queue.put("STATUS: Listening for option plays...")
while not stop_event.is_set():
try:
# Check if chat is still active
if not chat.is_alive():
logging.warning("Chat is no longer alive")
message_queue.put("STATUS: Chat connection ended")
break
# Get new messages from chat
chat_data = chat.get()
if not chat_data.items:
# No new messages, wait a bit
time.sleep(0.5)
continue
logging.info(f"Received {len(chat_data.items)} chat messages")
# Process the messages
for c in chat_data.items:
if stop_event.is_set():
break
# Put message data in queue for main process
message_queue.put({
"author": c.author.name,
"message": c.message
})
# Brief pause to avoid high CPU usage
time.sleep(0.1)
except Exception as e:
logging.error(f"Error processing chat: {str(e)}")
message_queue.put(f"WARNING: {str(e)}")
time.sleep(1) # Wait after error
except Exception as e:
logging.error(f"Unhandled exception in worker: {str(e)}")
message_queue.put(f"ERROR: {str(e)}")
finally:
logging.info("Worker process shutting down")
if chat:
try:
chat.terminate()
logging.info("Chat terminated")
except Exception as e:
logging.error(f"Error terminating chat: {str(e)}")
message_queue.put("LISTENER_STOPPED")
--- Main Application Class ---
class StockChatTrackerApp:
code
"""
A GUI application to track option play mentions in <REDACTED> live chat.
"""
def __init__(self, root_window):
"""
Initializes the application, sets up the GUI, and prepares data structures.
Args:
root_window: The main tkinter window.
"""
self.root = root_window
self.root.title("YouTube Option Chat Tracker")
self.root.geometry("600x450") # Made window wider for option plays
# Data storage: <REDACTED> for latest option plays, Set for unique plays found
self.latest_plays = collections.deque(maxlen=MAX_TICKERS_DISPLAYED)
self.all_mentioned_plays = set()
# Process-safe queue for communication between chat listener and GUI
<URL>ssage_queue = multiprocessing.Queue()
# Thread management attributes
self.chat_listener_thread = None
self.stop_thread_flag = multiprocessing.Event() # Event to signal thread termination
# Build the GUI elements
self._setup_gui()
# Set up window close behavior
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
# Start the periodic check of the message queue
self.check_queue()
def _setup_gui(self):
"""Creates and arranges all the GUI widgets."""
# --- Input Frame ---
self.input_frame = tk.Frame(self.root)
self.input_frame.pack(pady=10, padx=10, fill=tk.X) # Allow horizontal expansion
self.video_id_label = tk.Label(self.input_frame, text="YouTube Video ID:")
self.video_id_label.pack(side=tk.LEFT, padx=(0, 5)) # Padding only on the right
self.video_id_entry = tk.Entry(self.input_frame) # Let it expand
self.video_id_entry.pack(side=tk.LEFT, padx=5, expand=True, fill=tk.X)
# Example placeholder (optional):
# self.video_id_entry.insert(0, "YOUR_TEST_VIDEO_ID")
self.start_button = tk.Button(self.input_frame, text="Start", command=self.start_listening, width=6)
self.start_button.pack(side=tk.LEFT, padx=5)
self.stop_button = tk.Button(self.input_frame, text="Stop", command=self.stop_listening, state=tk.DISABLED, width=6)
self.stop_button.pack(side=tk.LEFT, padx=(0, 0)) # No right padding for the last button
# --- Status Label ---
self.status_label = tk.Label(
self.root,
text="Status: Idle",
fg="grey",
font=("TkDefaultFont", 10, "bold"),
relief=tk.SUNKEN,
bd=1,
padx=5,
pady=3
)
self.status_label.pack(pady=5, padx=10, fill=tk.X)
# --- Display Area ---
self.display_label = tk.Label(self.root, text="Chat Plays")
self.display_label.pack(pady=(10, 2)) # Less padding below label
# Use a frame to hold the text widget and scrollbar for better padding control
self.display_frame = tk.Frame(self.root)
# Pack frame to expand and fill available space
self.display_frame.pack(pady=5, padx=10, expand=True, fill=tk.BOTH)
self.ticker_display = scrolledtext.ScrolledText(
self.display_frame,
height=15, # Increased height to show more plays
width=70, # Made wider for option plays
wrap=tk.WORD, # Wrap lines at word boundaries
state=tk.DISABLED, # Start as read-only
font=("TkDefaultFont", 9) # Slightly smaller font
)
# Pack text widget inside its frame to expand
self.ticker_display.pack(expand=True, fill=tk.BOTH)
def update_status(self, message, <REDACTED>"):
"""Updates the status label text and color safely."""
self.status_label.config(text=f"Status: {message}", fg=color)
def find_option_plays(self, message):
"""
Uses regex to find option plays in a message string.
Args:
message (str): The chat message text.
Returns:
list: A list of found option plays as dictionaries.
"""
plays = []
for match in OPTION_REGEX.finditer(message):
ticker, strike, option_type, expiry, price = match.groups()
# Standardize the date format
if len(expiry) == 6: # If format is <REDACTED>
expiry = f"{expiry[:2]}/{expiry[2:4]}/{expiry[4:]}"
else: # If format is <REDACTED>/DD/YY or MM-DD-YY or MM.DD.YY
expiry = expiry.replace('-', '/').replace('.', '/')
# Determine if this is an entry or exit play
action = "in"
if any(word in <REDACTED>() for word in ["out", "exit", "sold", "closed"]):
action = "out"
# Standardize strike price format (remove trailing zeros after decimal)
strike = str(float(strike))
plays.append({
'ticker': ticker,
'strike': strike,
'option_type': option_type, # 'c' for call, 'p' for put
'expiry': expiry,
'price': price or 'N/A', # Use 'N/A' if no price provided
'action': action
})
return plays
def add_play_to_display(self, play, author):
"""
Formats and adds an option play mention to the display queue and updates the GUI.
Args:
play (dict): The option play details.
author (str): The name of the user who mentioned the play.
"""
timestamp = time.strftime("%H:%M:%S")
# Format: [HH:MM:SS] TICKER STRIKEc/p EXPIRY in/out PRICE (by Author Name)
display_string = f"[{timestamp}] {play['ticker']} {play['strike']}{play['option_type']} {play['expiry']}"
if play['price'] != 'N/A':
display_string += f" {play['action']} {play['price']}"
display_string += f" (by {author})"
# Add to the left (front) of the deque to keep newest items first
self.latest_plays.appendleft(display_string)
# Create a unique key for this play
play_key = f"{play['ticker']}_{play['strike']}_{play['expiry']}"
self.all_mentioned_plays.add(play_key)
# Update the text display widget
self.update_ticker_display()
def update_ticker_display(self):
"""Refreshes the ScrolledText widget with the latest option plays from the deque."""
# Enable the widget for modification
self.ticker_display.config(state=tk.NORMAL)
# Clear the current content
self.ticker_display.delete('1.0', tk.END)
# Insert items from the deque, newest first (already ordered by appendleft)
for item in self.latest_plays:
self.ticker_display.insert(tk.END, item + "\n")
# Disable the widget to make it read-only again
self.ticker_display.config(state=tk.DISABLED)
# Ensure the view scrolls to the top to show the latest entry
self.ticker_display.yview_moveto(0.0)
def check_queue(self):
"""
Periodically checks the message queue for data from the listener process
and updates the GUI accordingly. Runs in the main GUI thread.
"""
try:
# Process all messages currently in the queue without blocking
while True:
try:
# Use get_nowait with a small timeout for multiprocessing queue
message_data = <URL>ssage_queue.get(block=False)
# Handle different types of messages from the queue
if isinstance(message_data, str):
# Handle control signals or error messages (strings)
if message_data == "LISTENER_STOPPED":
self.update_status("Stopped", "grey")
self.start_button.config(state=tk.NORMAL)
self.stop_button.config(state=tk.DISABLED)
self.video_id_entry.config(state=tk.NORMAL)
if self.chat_listener_thread:
self.chat_listener_thread.join(timeout=0.1) # Clean up
self.chat_listener_thread = None
elif message_data.startswith("ERROR:"):
error_msg = message_data[len("ERROR: "):] # Extract error details
self.update_status(f"Error: {error_msg}", "red")
messagebox.showerror("Listener Error", error_msg)
# Reset GUI state on error
self.start_button.config(state=tk.NORMAL)
self.stop_button.config(state=tk.DISABLED)
self.video_id_entry.config(state=tk.NORMAL)
if self.chat_listener_thread:
self.chat_listener_thread.join(timeout=0.1)
self.chat_listener_thread = None
elif message_data.startswith("STATUS:"):
status_msg = message_data[len("STATUS: "):]
# Use different colors based on the initialization stage
if "Initializing" in status_msg:
color = "blue"
elif "Connecting" in status_msg:
color = "orange"
elif "Connected" in status_msg:
color = "green"
elif "Listening" in status_msg:
color = "green"
else:
color = "blue"
self.update_status(status_msg, color)
# Update the window title with the current status
self.root.title(f"YouTube Option Chat Tracker - {status_msg}")
elif message_data.startswith("WARNING:"):
warning_msg = message_data[len("WARNING: "):]
self.update_status(f"Warning: {warning_msg}", "orange")
elif isinstance(message_data, dict):
# Process chat messages (dictionaries)
author = <REDACTED>', 'Unknown')
message_text = <REDACTED>', '')
# Find option plays in the message
plays_found = self.find_option_plays(message_text)
for play in plays_found:
# Add each found play to the display
self.add_play_to_display(play, author)
except multiprocessing.queues.Empty:
# Empty queue, exit the loop
break
except Exception as e:
print(f"Error in check_queue: {e}")
finally:
# Schedule the next check after 100 milliseconds
self.root.after(100, self.check_queue)
def start_listening(self):
"""
Handles the 'Start' button click. Validates input, clears old data,
and starts the background chat listener process.
"""
video_id = self.video_id_entry.get().strip()
if not video_id:
messagebox.showwarning("Input Required", "Please enter a YouTube Video ID.")
return
# Prevent starting multiple listeners
if self.chat_listener_thread and self.chat_listener_thread.is_alive():
messagebox.showwarning("Already Running", "Chat listener is already active.")
return
# Clear previous session data
self.latest_plays.clear()
self.all_mentioned_plays.clear()
self.update_ticker_display() # Show empty display
# Reset the stop signal and update GUI state
self.stop_thread_flag.clear()
self.start_button.config(state=tk.DISABLED)
self.stop_button.config(state=tk.NORMAL)
self.video_id_entry.config(state=tk.DISABLED) # Prevent editing while running
self.update_status("Preparing to start listener...", "blue")
# Log the start attempt
logging.info(f"Starting listener process for video ID: {video_id}")
try:
# Create and start the listener process
self.chat_listener_thread = multiprocessing.Process(
target=chat_listener_worker,
args=(video_id, <URL>ssage_queue, self.stop_thread_flag),
daemon=True # Allows main program to exit even if process hangs
)
self.chat_listener_thread.start()
logging.info(f"Process started with PID: {self.chat_listener_thread.pid}")
except Exception as e:
logging.error(f"Error starting process: {str(e)}")
messagebox.showerror("Error", f"Failed to start listener: {str(e)}")
self.start_button.config(state=tk.NORMAL)
self.stop_button.config(state=tk.DISABLED)
self.video_id_entry.config(state=tk.NORMAL)
self.update_status("Error starting listener", "red")
# Set a timeout to check if the process is running
self.root.after(5000, self.check_process_started)
def stop_listening(self):
"""
Handles the 'Stop' button click. Signals the listener thread to terminate.
"""
if self.chat_listener_thread and self.chat_listener_thread.is_alive():
self.update_status("Requesting stop...", "orange")
self.stop_thread_flag.set() # Set the event to signal the thread
self.stop_button.config(state=tk.DISABLED) # Disable stop until confirmed
# Reset the window title
self.root.title("YouTube Option Chat Tracker")
else:
self.update_status("Listener not running.", "grey")
# Reset the window title
self.root.title("YouTube Option Chat Tracker")
def on_closing(self):
"""
Handles the event when the user tries to close the main window.
Prompts for confirmation and ensures the listener process is stopped.
"""
if messagebox.askokcancel("Quit", "Stop listener and exit the application?"):
# Signal the process to stop if it's running
if self.chat_listener_thread and self.chat_listener_thread.is_alive():
self.stop_thread_flag.set()
# Wait a short time for process to terminate
self.chat_listener_thread.join(timeout=0.5)
# If still running, terminate forcefully
if self.chat_listener_thread.is_alive():
print("Terminating process forcefully")
self.chat_listener_thread.terminate()
# Destroy the main window
self.root.destroy()
def check_process_started(self):
"""
Checks if the chat listener process started successfully.
Shows an error if it's stuck in initialization.
"""
if not self.chat_listener_thread or not self.chat_listener_thread.is_alive():
# Process not running
logging.warning("Process not running during check")
self.update_status("Failed to start - check logs", "red")
messagebox.showerror("Error", "Listener process failed to start or exited unexpectedly.")
self.start_button.config(state=tk.NORMAL)
self.stop_button.config(state=tk.DISABLED)
self.video_id_entry.config(state=tk.NORMAL)
return
# Get the current status from the label
current_status = self.status_label.cget("text")
if "Initializing" in current_status or "Connecting" in current_status:
# Still in initialization after 5 seconds - likely stuck
logging.warning("Process appears to be stuck in initialization")
if messagebox.askyesno("Process Stuck",
"The listener seems stuck in initialization.\n\nWould you like to stop it and try again?"):
# User chose to stop the stuck process
self.stop_listening()
else:
# User chose to wait longer - check again in 5 more seconds
self.root.after(5000, self.check_process_started)
--- Main Execution Block ---
if name == "main":
code
# For Windows, multiprocessing needs this protection
multiprocessing.freeze_support()
# Initialize logging to help debug
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
logging.info("Application starting")
# Create the main Tkinter window
root = tk.Tk()
# Instantiate the application class
app = StockChatTrackerApp(root)
# Start the <REDACTED> event loop
root.mainloop()
Your code looks well thought out, and it's clear you’ve put effort into covering multiple formatting cases and handling GUI–background process communication. A few questions and ideas come to mind:
Process vs. Thread:You’re using a multiprocessing process for the chat listener. Given that pytchat is likely I/O bound, did you consider using a thread instead? Multiprocessing bypasses the but comes with extra overhead and complexity. Is there a specific reason you opted for a process?
Regex Robustness:Your regex covers a lot of ground for option play formats. Have you run into any edge cases that weren’t caught? It might be worth adding unit tests to ensure all intended variations are handled correctly.
Queue Handling:Thecheck_queuemethod continuously polls the message queue. In a high-volume chat, could the queue grow too quickly or cause lag in the GUI? Have you seen any performance issues under heavy load?
Error Recovery & Logging:I like that you log different stages and handle errors gracefully. In cases where the connection fails or becomes unstable, have you thought about a reconnection strategy or more detailed error feedback for the user?
Process Cleanup:The cleanup logic inon_closinglooks good, but sometimes daemon processes can be a bit unpredictable when terminating. Have you experienced any lingering processes, or does everything shut down cleanly?
Process vs. Thread:You’re using a multiprocessing process for the chat listener. Given that pytchat is likely I/O bound, did you consider using a thread instead? Multiprocessing bypasses the but comes with extra overhead and complexity. Is there a specific reason you opted for a process?
Regex Robustness:Your regex covers a lot of ground for option play formats. Have you run into any edge cases that weren’t caught? It might be worth adding unit tests to ensure all intended variations are handled correctly.
Queue Handling:Thecheck_queuemethod continuously polls the message queue. In a high-volume chat, could the queue grow too quickly or cause lag in the GUI? Have you seen any performance issues under heavy load?
Error Recovery & Logging:I like that you log different stages and handle errors gracefully. In cases where the connection fails or becomes unstable, have you thought about a reconnection strategy or more detailed error feedback for the user?
Process Cleanup:The cleanup logic inon_closinglooks good, but sometimes daemon processes can be a bit unpredictable when terminating. Have you experienced any lingering processes, or does everything shut down cleanly?
I’m curious—are there any specific issues or unexpected behaviors you’ve encountered with this implementation?