How to establish connection with Twitch IRC for bot development

Issue connecting to Twitch IRC for chatbot creation

I’m working on building a basic chatbot for Twitch and I need to connect to their IRC system. However, I keep running into problems when trying to establish the connection.

Here’s my current approach:

<?php

set_time_limit(0);
ini_set('display_errors', 'on');

function createTwitchBot()
{
    function connectToIRC()
    {
        $settings = array(
                'host'     => 'irc.twitch.tv', 
                'port'     => 6667, 
                'room'     => '#streamername',
                'username' => 'mybotname', 
                'nickname' => 'MyBot', 
                'password' => 'oauth:##########################'
        );

        echo 'Starting connection...';
        $connection = array();
        $connection['socket'] = fsockopen($settings['host'], $settings['port']);

        if($connection['socket'])
        {
            echo 'Connected successfully';
            transmitCommand("PASS " . $settings['password'] . "\n\r");
            transmitCommand("NICK " . $settings['nickname'] . "\n\r");
            transmitCommand("USER " . $settings['nickname'] . "\n\r");
            transmitCommand("JOIN " . $settings['room'] . "\n\r");

            while(!feof($connection['socket']))
            {
                echo 'Listening for messages...';
            }
        }
    }

    function transmitCommand($message)
    {
        global $connection;
        fwrite($connection['socket'], $message, strlen($message));
        echo "[SENT] $message <br>";
    }

    connectToIRC();
}

createTwitchBot();

?>

The connection attempt fails and I’m not sure what’s causing the problem. Has anyone successfully connected to Twitch IRC using PHP? Any suggestions on what might be wrong with my implementation would be really helpful!

Had the same issue when I started with Twitch IRC. Your main problem is the transmitCommand function - it’s trying to use a global $connection variable, but you declared $connection as a local array inside connectToIRC(). The function can’t write to the socket because of this. Either pass the connection as a parameter or restructure so transmitCommand can actually access it. Double-check your OAuth token too - make sure it’s from the Twitch developer console with proper chat scopes. Also try \r\n instead of \n\r for line endings. Some IRC servers get picky about that. Twitch IRC is pretty forgiving, but proper formatting prevents random disconnects during longer sessions.