My Stuff
Username

Password

Articles/Snippets
ASP Classic
C
C#
C++
CSS
HTML
Java
Javascript
MySQL
Perl
PHP
Python
Ruby
Unix/Linux/BSD
VB 6
VB.NET


How To Make a Simple IRC Bot From Scratch In PHP


Your rating: None Average: 4 (1 vote)

I came across this article by nzknzknzk on Digg and I ported the bot over to PHP.

All does is opens a socket, joins a channel, prints some text to the channel, and listens for a string.

I run this script from the command line, not through a web page. Most linux systems will have a php binary available to execute from the command line.

To test this out, make a simple script called hellow_world.php:

<?
echo "hello world\n";
?>

Now run the command: $ php hello_world.php You should see 'hello world' print on the command line. If it didn't work, you need to find out where the PHP binary is so you can execute it through the full path. There is also a binary made specifically to run via command line called php-cgi which you may want to try as well.

Once you know you can successfully execute the PHP script from the command line, make a new script called irc_bot.php. Below is the source code:

<?
// define your variables
$host = "irc.freenode.net";
$port=6667;
$nick="MyBot";
$ident="MyBot";
$chan="#asdf";
$readbuffer="";
$realname = "MyBot";
 
// open a socket connection to the IRC server
$fp = fsockopen($host, $port, $erno, $errstr, 30);
 
// print the error if ther eis no connection
if (!$fp) {
	echo $errstr." (".$errno.")<br />\n";
} else {
	// write data through the socket to join the channel
	fwrite($fp, "NICK ".$nick."\r\n");
	fwrite($fp, "USER ".$ident." ".$host." bla :".$realname."\r\n");
	fwrite($fp, "JOIN :".$chan."\r\n");
 
	// write data through the socket to print text to the channel
	fwrite($fp, "PRIVMSG ".$chan." :Hello There!\r\n");
	fwrite($fp, "PRIVMSG ".$chan." :I am a bot\r\n");
 
	// loop through each line to look for ping
 	while (!feof($fp)) {
 
		$line =  fgets($fp, 128);
		echo $line."\n";
 
		$line = explode(":ping ", $line);
 
		echo $line[0]."\n";
 
		if ($line[1]) {
 
			fwrite($fp, "PONG ".$line[1]."\r\n"); 
		}
 
	}
 
	fclose($fp);
}
?>

Now, join the IRC channel #asdf on irc.freenode.net and then execute your new script: $ php irc_bot.php

The bot doesn't do anything useful, but it is a fun exercise, and with a little imagination, you could probably make some cool bots!

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
  • You can use BBCode tags in the text.
  • You can enable syntax highlighting of source code with the following tags: [code], [blockcode], [asp], [awk], [c], [cpp], [csharp], [drupal5], [drupal6], [java], [javascript], [jquery], [mysql], [perl], [perl6], [php], [python], [ruby], [sql], [vb], [vbnet], [xml].
  • Use to create page breaks.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.