user775171
user775171

Reputation:

PHP IRC bot connect?

I need a little help with an IRC bot I'm creating (very simple).

<?php

$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$yonk = socket_connect($sock, "127.0.0.1", 6667);

$wut = socket_read($sock, 1024);
socket_write($sock, "NICK FikesPHPThingy\r\n");
socket_write($sock, "USER fikeh fikeh fikeh :Fike's PHP thang.\r\n");
socket_write($sock, "JOIN #LightSpike\r\n");

echo $wut;

while (True) {

}
?>

It connects and reads

:de.blank.net NOTICE Auth :*** Looking up your hostname...
:de.blank.net NOTICE 00AAAAAZ4 :*** Skipping host resolution (disabled by server administrator)

But it doesn't do anything after that. I'm creating this without any tutorials, just by myself. But I can't seem to get it working. Any ideas?

PS: Sorry for the odd variable names.

Upvotes: 1

Views: 1687

Answers (1)

Another Code
Another Code

Reputation: 3151

You'll have to put the (blocking) read inside your infinite loop, like this:

while (True) {
$wut = socket_read($sock, 1024, PHP_NORMAL_READ); // $wut will now be a single line sent by the server
echo $wut; // Do anything with the line
}

This way your client will continue waiting for and handling response messages until the socket loses connection or you manually break the loop. I've added the PHP_NORMAL_READ parameter so the client will read only a single line at a time, this is probably way more practical for processing.

On a related note, you shouldn't join a channel right away but rather wait for the 001 response code. This ensures the server has accepted your identification and is ready to receive commands. The way you're doing it now, the JOIN might (and probably will) be rejected by the server.

Upvotes: 3

Related Questions