Writing an IRC bot in PHP

From SHellium Wiki
Jump to: navigation, search
Geographylogo.png In other languages: English | Afrikaans | Albanian | Arabic | Brazilian | Bulgarian | Catalan | Chinese | Croatian | Czech | Danish | Dutch | Esperanto | Estonian | Filipino | Finnish | Flemish | French | German | Greek | Hebrew | Hindi | Hungarian | Indonesian | Italian | Japanese | Latvian | Lithuanian | Macedonian | Malay | Malayalam | Norwegian (Bokmål) | Norwegian (Nynorsk) | Persian | Polish | Portuguese | Romanian | Russian | Serbian | Slovak | Slovenian | Spanish | Swedish | Turkish | Ukrainian | Urdu




So, you want to write your own IRC bot in PHP, do you? I'm here to help you! This tutorial requires you to have a somewhat working knowledge of PHP to begin with.

Contents

Download the library

First, we want to download Net_SmartIRC from at the PHP website or at softpedia Yes, this is a “tarball,” or a TAR archive file inside a gzip archive. If you do not have software to extract this, you need not worry! We can extract it once we upload it to Shellium. If you do have software, great! Go right ahead and extract it. If you still need to extract the file, simply run this command:

tar -zxf Net_SmartIRC-1.0.0.tgz

Directory Structure

We do not need the files “package.sig” or “package.xml,” so just delete these. You should now have a directory called “Net_SmartIRC-1.0.0.” Cd into this directory. You can keep any or all of these files, or only the bare essentials. All you really need to get a PHP IRC bot up and running is:

  • The directory “SmartIRC”
    • defines.php
    • irccommands.php
    • messagehandler.php
  • The file “SmartIRC.php”

Yes, that's all. However, I'd recommend keeping the directories “docs” and “examples,” as they can help you with stuff this tutorial can't offer.


The bot file

Okay, let's get started. Make a blank text file with the extension “php.” Into this file, insert the following.

Import the library:

    <?php
    include_once('SmartIRC.php');

Class mybot

    class mybot
    {
        function test(&$irc, &$data)
        {
            $irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, $data->nick.': It works!');
        }
        function quit(&$irc, &$data)
        {
            if ($data->nick == "YourNickHere")
            {
                $irc->disconnect();
            }
        }
    }

This class is your bot. All programmed responses are defined here. We can see that we have a function named “test” that takes two arguments. “irc” and “data.” The irc object is so we can interact with the IRC channel within the bot. The data object contains most of the data of the message. We'll talk about this later. Now, let's look at the statement inside the function inside this class. We're calling a function inside the IRC object, message. We're sending a message with the type "SMARTIRC_TYPE_CHANNEL," which means we're sending it to a channel. Our message target is $data->channel, which is automatically set to the channel of origin. Our message is $data->nick.': It works!', which is quite easy to understand if you know your PHP. We also define a quit function, which is nice, since we'll have to restart the bot every time we add functions. The quit function only works if "you" are the one saying the command, so please edit this line.

Initialising connection

    $bot = &new mybot();
    $irc = &new Net_SmartIRC();
    $irc->setDebug(SMARTIRC_DEBUG_ALL);
    $irc->setUseSockets(TRUE);
    $irc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!test', $bot, 'test');
    $irc->connect('irc.server.net', 6667);
    $irc->login('Net_SmartIRC', 'Net_SmartIRC Client '.SMARTIRC_VERSION.' (yourfilename.php)', 0, 'Net_SmartIRC');

Please go through and edit basic things like your channel, and your server's name.

Whoa, lots of stuff here. Okay, on the first line we create an instance of mybot, stored in the variable $bot. We also create a new instance of the library, Net_SmartIRC, and store it in $irc. We enable all debug messages, although you can change this to SMARTIRC_DEBUG_NONE if you feel like it. The next line has no importance, but it's needed, so don't remove it.

Okay, now we're at an important line. An action handler. You'll be using a lot of these, in fact, IRC bots are built on a platform of action handlers. This one basically tells $bot to call the function test whenever someone says something starting with !test in the IRC channel.

Join, listen, quit

Then we connect to the IRC server, (you'll really want to change the address here!) and send our information, which you can also edit.

    $irc->join(array('#test'));
    $irc->listen();
    $irc->disconnect();
    ?>

We then join an array of channels. (You may change this line to $irc->join(array('#test','#test2')); , or add as many channels as you want, or need. We then call $irc->listen(), which is simply an infinite loop responding to server pings, checking for event handlers, and other fun stuff. If listen() terminates for any reason, we make sure we're disconnected from IRC, and... Then the file ends! You can run this bot simply by running "php yourfilename.php", or visiting the php file in a web browser.

Testing

Now, let's test our bot! Connect to the server and join the channel you specified. Type !test. Your bot should respond. Type !quit. Your bot should quit. It should be an easy thing to expand on this and make your bot great!

Another example

<?php
   include_once('SmartIRC.php');
   include_once('SmartIRC/defines.php');
   include_once('SmartIRC/irccommands.php');
   include_once('SmartIRC/messagehandler.php');
 
/*Next, create the bot-class:*/
 
class mybot
{
 
/*A Greet function*/
 
    function onjoin_greeting(&$irc, &$data)
    { // if we join, don't greet ourself, just jump out via return
        if ($data->nick == $irc->_nick)
           return;
 
        // now check if this is the right channel
        if ($data->channel == '#bebs_sp')
        // it is, lets greet the joined user
           $irc->message(SMARTIRC_TYPE_CHANNEL, '#bebs_sp', 'hi '.$data->nick);
    }
 
 
/*Quit Function*/
 
    function quit(&$irc, &$data)
    {
        // Only run the command if the nick is an owner.
        if(($data->nick == "glaucom" || $data->nick == "exOOr" || $data->nick == "PoOoL_" || $data->nick == "Angie")) {
             $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "adios.");
             exit(); 
             Return ;
        }
    }
 
/*Kick-Function*/
 
    function kick(&$irc, &$data)
    {
        if(($data->nick == "glaucom" || $data->nick == "exOOr" || $data->nick == "PoOoL_" || $data->nick == "Angie")) {
            if(isset($data->messageex[1],$data->messageex[2])) {
                $nickname = $data->messageex[1];
                $reason = $data->messageex[2];
                $channel = $data->channel;
                $irc->kick($channel, $nickname, $reason);
            } else {
                $irc->message( $data->type, $data->nick, 'Invalid Parameter' );
                $irc->message( $data->type, $data->nick, 'use: !kick $nick' );
            }
        }
    }
 
/*If the bot gets kicked, let it rejoin*/
 
    function kick_response(&$irc, &$data)
    { //if bot is kicked
       if ($data->nick == $irc->_nick) {
           $irc->join(array('#bebs_sp')); 
           $irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, "dont kick me... please");
           Return ;
       }
    }
 
 
/*Function to change channelmodes*/
 
    function mode($channel, $newmode = null, $priority = SMARTIRC_MEDIUM) 
    {
       if ($newmode !== null) {
          $irc->_send('MODE '.$channel.' '.$newmode, $priority);
       } else { 
          $irc->_send('MODE '.$channel, $priority);
       }
    }
 
/*Devoice Function*/
 
    function devoice(&$irc, &$data) 
    {
       if(($data->nick == "glaucom" || $data->nick == "exOOr" || $data->nick == "PoOoL_" || $data->nick == "Angie")) { if(isset($data->messageex[1])) { $nickname = $data->messageex[1];
           $channel = $data->channel;  
           $irc->devoice($channel, $nickname );
       }
    }
 
/*Op Function*/
 
    function op(&$irc, &$data)  
    {
        if(($data->nick == "glaucom" || $data->nick == "exOOr" || $data->nick == "PoOoL_" || $data->nick == "Angie")) {
            if(isset($data->messageex[1])) {    
                $nickname = $data->messageex[1];
                $channel = $data->channel;  
                $irc->op($channel, $nickname );
            }
        }
    }
 
/*Deop Function*/
 
    function deop(&$irc, &$data)
    {
        if(($data->nick == "glaucom" || $data->nick == "exOOr" || $data->nick == "PoOoL_" || $data->nick == "Angie")) {
            if(isset($data->messageex[1])) {    
                $nickname = $data->messageex[1];
                $channel = $data->channel;  
                $irc->deop($channel, $nickname );
            }
        }
    }
 
/*Join Function*/
 
    function join(&$irc, &$data)
    {
        if(($data->nick == "glaucom" || $data->nick == "exOOr" || $data->nick == "PoOoL_" || $data->nick == "Angie")) {
            if(isset($data->messageex[1])) {    
                $channel = $data->messageex[1];
                $irc->join($channel);
            }
        }      
    }
 
/*Part Function*/
 
    function part(&$irc, &$data)
    {
        if(($data->nick == "glaucom" || $data->nick == "exOOr" || $data->nick == "PoOoL_" || $data->nick == "Angie")) {
            if(isset($data->messageex[1])) {    
                $channel = $data->messageex[1];
                $irc->part($channel);
            }
        }      
    }
 
/*Function to rejoin a channel*/
 
    function rejoin(&$irc, &$data)
    {
        if(($data->nick == "glaucom" || $data->nick == "exOOr" || $data->nick == "PoOoL_" || $data->nick == "Angie")) {
            if(isset($data->messageex[1])) {    
                $channel = $data->messageex[1];
                $irc->part($channel);
                $irc->join($channel);
            }
        }      
    }
 
/*Ban Function*/
 
    function ban(&$irc, &$data)
    {
        if(($data->nick == "glaucom" || $data->nick == "exOOr" || $data->nick == "PoOoL_" || $data->nick == "Angie")) {
            if(isset($data->messageex[1])) {
                $hostmask = $data->messageex[1];    
                $channel = $data->channel;
                $irc->ban($channel, $hostmask);
            } else {
                $irc->message( $data->type, $data->nick, 'Invalid Parameter' );
                $irc->message( $data->type, $data->nick, 'use: !ban $nick' );
            }
        }
    }
 
/*Function for the nickchange-command*/
 
    function nick(&$irc, &$data)
    {
        if(($data->nick == "glaucom" || $data->nick == "exOOr" || $data->nick == "PoOoL_" || $data->nick == "Angie")) {
            if(isset($data->messageex[1])) {    
                $newnick = $data->messageex[1];
                $channel = $data->channel;  
                $irc->changeNick($newnick );
            }
        }      
    }
 
/*Function that does the actual nickchange*/
 
    function changeNick($newnick, $priority = SMARTIRC_MEDIUM)
    {
        $this->_send('NICK '.$newnick, $priority);
        $this->_nick = $newnick;
    }
 
 
/*End the Bot-class*/
 
}
 
 
/*Start the bot and set some settings*/
 
$bot = &new mybot();
$irc = &new Net_SmartIRC();
$irc->setDebug(SMARTIRC_DEBUG_ALL);
$irc->setUseSockets(TRUE);
 
/*Bind IRC Commands to the above defined functions and end the PHP-file*/
 
$irc->registerActionhandler(SMARTIRC_TYPE_JOIN, '.*', $bot, 'onjoin_greeting');
$irc->connect('irc.brasvip.org', 6667);
$irc->registerActionhandler(SMARTIRC_TYPE_KICK, '.*', $bot, 'kick_response');
$irc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '!restart', $bot, 'quit');
$irc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!kick', $bot, 'kick');
$irc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!voice', $bot, 'voice');
$irc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!devoice', $bot, 'devoice');
$irc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!op', $bot, 'op');
$irc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!deop', $bot, 'deop');
$irc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!join', $bot, 'join');
$irc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!part', $bot, 'part');
$irc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!rejoin', $bot, 'rejoin');
$irc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!ban', $bot, 'ban');
$irc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!nick', $bot, 'nick'); 
 
// nick , nome , realname , ident, senha do nick
$irc->login('nick', 'name'.'realname', 8, 'ident','password');   
$irc->join(array('#bebs_sp','#eggfly'));
$irc->listen( );
$irc->disconnect( );
?>

Have fun!

Personal tools
Namespaces

Variants
Actions
Navigation
Indexes
SHellium Sites
Toolbox