Code Newbie
News     Forums     Search     Members     Sign Up    

My Code Newbie
Username

Password

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

C.N. Friends
  Planet Rome

Link to Us!
Code Newbie
  Code Newbie
    php
  » How To Make a Simple IRC Bot From Scratch In PHP
      by Mike Milano
 Page 1 of 1 
   

(Login to remove green text ads)
PHP IRC Bot
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:
PHP Code:
<?
echo "hello world\n";
?>
Now run the command:
Code:
$ 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:
PHP 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$errstr30);

// 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($fp128);
        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:
Code:
$ php irc_bot.php
This isn't really an in-depth tutorial and the bot doesn't really do anything useful, but it is a fun excersize and with a little imagination, you could probably make some cool bots.




 
 Page 1 of 1 
   

Rate This Article
1 2 3 4 5 6 7 8 9 10





Copyright © 2000-2006, Milano Interactive
Web Hosting provided by Portal 360 Web Hosting
Open Circle