I’m trying to build a bot for Twitch chat using PHP but running into connection issues with their IRC server.
I’ve been working on this for a while and can’t figure out what’s going wrong. The connection attempt fails and I’m not sure if it’s my code structure or something with the authentication.
Here’s what I have so far:
<?php
set_time_limit(0);
error_reporting(E_ALL);
class TwitchChatBot {
private $socket;
private $settings = [
'host' => 'irc.twitch.tv',
'port' => 6667,
'room' => '#testchannel',
'username' => 'mychatbot',
'nickname' => 'MyChatBot',
'token' => 'oauth:your_token_here'
];
public function startBot() {
$this->connectToIRC();
}
private function connectToIRC() {
echo 'Attempting connection...';
$this->socket = fsockopen($this->settings['host'], $this->settings['port']);
if ($this->socket) {
echo 'Connected successfully';
$this->authenticate();
$this->joinChannel();
$this->listenForMessages();
}
}
private function authenticate() {
$this->sendCommand("PASS " . $this->settings['token']);
$this->sendCommand("NICK " . $this->settings['nickname']);
$this->sendCommand("USER " . $this->settings['username']);
}
private function joinChannel() {
$this->sendCommand("JOIN " . $this->settings['room']);
}
private function listenForMessages() {
while (!feof($this->socket)) {
// Listen for incoming data
}
}
private function sendCommand($message) {
fwrite($this->socket, $message . "\r\n");
echo "[SENT] $message\n";
}
}
$bot = new TwitchChatBot();
$bot->startBot();
?>
The connection fails right at the fsockopen part. Has anyone successfully connected to Twitch IRC using PHP? What am I missing here?