Python 3.7 Twitch IRC bot fails with websocket timeout exception

Getting websocket errors with my Twitch chat bot

I’m working on a Twitch IRC chat bot using Python 3.7 and twitchio library. After setting up my environment with pipenv and installing all dependencies, my bot crashes with a timeout error.

The error I’m getting:

Task exception was never retrieved
future: <Task finished coro=<WebsocketConnection.auth_seq()> exception=KeyError('channel_name')>
Traceback (most recent call last):
  File "websocket.py", line 280, in _join_channel
    await asyncio.wait_for(fut, timeout=10)
  File "asyncio/tasks.py", line 449, in wait_for
    raise futures.TimeoutError()
concurrent.futures._base.TimeoutError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "websocket.py", line 228, in auth_seq
    await self.join_channels(*channels)
  File "websocket.py", line 271, in join_channels
    await asyncio.gather(*[self._join_channel(x) for x in channels])
  File "websocket.py", line 282, in _join_channel
    self._pending_joins.pop(channel)
KeyError: 'channel_name'

My bot code:

#!/usr/bin/env python3
import os
import sys
from datetime import *
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_CLIENT_ID'],
    nick=os.environ['USERNAME'],
    prefix=os.environ['CMD_PREFIX'],
    initial_channels=[os.environ['DEFAULT_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['DEFAULT_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 'hi' in message.content.lower():
        await message.channel.send(f"Hello, @{message.author.name}!")

if __name__ == "__main__":
    chat_bot.run()

The bot seems to connect initially but then crashes after 10 seconds with this KeyError. I’m using a proper OAuth token from Twitch. What could be causing this connection issue?

Had the same problem when I accidentally passed an empty string to initial_channels. Your target_channel variable is empty by default, so you’re trying to join a channel that doesn’t exist - that’s what’s causing the timeout. Try this fix: initial_channels=[os.environ['DEFAULT_CHANNEL']] + ([target_channel] if target_channel else []). It’ll only add target_channel if it’s actually set. Also check your DEFAULT_CHANNEL env variable for extra whitespace - that can mess up the connection too.

Yeah, classic empty channel name problem. When target_channel is blank, it tries connecting to nothing and Twitch hates that lol. Filter it out before the bot constructor or use: initial_channels=[ch for ch in [os.environ['DEFAULT_CHANNEL'], target_channel] if ch.strip()]

This timeout happens when the bot tries joining channels that don’t exist or can’t be accessed. The KeyError for ‘channel_name’ means twitchio can’t track which channels it’s trying to join. I’ve hit this before - it’s usually because twitchio doesn’t handle invalid entries in the initial_channels list well. Your target_channel defaults to an empty string, so you’re basically telling the bot to join a channel with no name. The library tries to join this non-existent channel, times out after 10 seconds, then can’t clean up its internal tracking properly. Filter out empty values before passing them to initial_channels, and make sure your DEFAULT_CHANNEL environment variable has a valid channel name without the # prefix.