Python3.7 Twitch IRC chat bot failing with websocket connection timeout

I’m having trouble with my Python Twitch chat bot

I’ve been working on a chat bot for Twitch using Python 3.7 and the twitchio library. After setting up my virtual environment and installing all the dependencies, my bot keeps crashing with a timeout error.

The error shows that it’s timing out after 10 seconds when trying to join channels, and then throws a KeyError. It seems like the websocket connection is established but something goes wrong during the channel joining process.

Here’s my bot code:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
from datetime import *
from pwnlib.term import text
from setproctitle import setproctitle
from twitchio.ext import commands

target_channel = ""
if len(sys.argv) > 1:
    target_channel = sys.argv[1]

chat_bot = commands.Bot(
    irc_token=os.environ['IRC_TOKEN'],
    client_id=os.environ['APP_ID'],
    nick=os.environ['USERNAME'],
    prefix=os.environ['CMD_PREFIX'],
    initial_channels=[os.environ['MAIN_CHANNEL'], target_channel]
)

@chat_bot.event
async def event_ready():
    print(f"{os.environ['USERNAME']} has connected!")
    websocket = chat_bot._ws
    await websocket.send_privmsg(os.environ['MAIN_CHANNEL'], f"/me is now active!")

@chat_bot.event
async def event_message(message):
    if message.author.name.lower() == os.environ['USERNAME'].lower():
        return
    
    await chat_bot.handle_commands(message)
    
    if 'hey' in message.content.lower():
        await message.channel.send(f"Hello there, @{message.author.name}!")

if __name__ == "__main__":
    from commands import Handler as cmd_handler
    chat_bot.run()

I’m using an OAuth token from Twitch in my environment variables. The connection seems to work initially but then fails. What could be causing this timeout issue?

Had the same issue a few months ago. Your problem’s probably in event_ready() where you’re hitting chat_bot._ws directly and sending messages right away. The websocket connects but channel joining isn’t done yet. Ditch the direct websocket access and use a regular channel send with a short delay instead. Also check your target_channel variable formatting - if it’s empty or messed up from the command line args, it’ll hang the join process. Adding error handling around channel joining and avoiding direct websocket stuff fixed my timeout issues.

Your timeout issue is probably a twitchio version compatibility problem with Python 3.7. I hit this exact same thing last year - newer twitchio versions have stricter websocket handling that breaks with older Python versions. That KeyError happens when the bot tries accessing channel data before the IRC handshake finishes. Downgrade to twitchio 1.2.3 - it’s way more forgiving with timeouts. And drop that direct _ws access in your event_ready function. You’re hitting private websocket methods that create race conditions during connection.