Search code examples
phpirc

PHP IRC bot not responding to commands


Here's my code:

<?php

$sock = fsockopen("localhost", 6667);
fwrite($sock, "NICK PHP_thang\r\n");
fwrite($sock, "USER fikeh fikeh fikeh :Fikeh's Thang\r\n");
fwrite($sock, "JOIN #LightSpike\r\n");

while (True) {
        echo fgets($sock);
        if (strpos(fgets($sock), "!about")) {
                fwrite($sock, "PRIVMSG #LightSpike :\x02Fike's PHP Bot:\x02 Fike's test bot.\r\n");
        }
}
?>

Basically, it looks through the lines received from the socket and if it finds "!about", it writes a message to the channel. But it doesn't. Can anyone help me out? Thanks!


Solution

  • You are reading the stream with echo fgets($sock); which clears the stream. When the execution gets to the conditional next line, fgets( $sock ) is empty. Either remove the echo line or put the contents to a variable first:

    while (True) {
        $buffer = fgets( $sock );
        echo $buffer;
        if( strpos( $buffer, "!about" ) !== false ) {
            ...
        }
    }
    

    Also note that strpos() returns 0 if the search string is at the start of the line and 0 == false. With strpos() you should always use strpos( $needle, $haystack ) === false (or !== false).