Site Statistics
Total Members: 510
Total Tutorials: 242
Newsest User: Hp
Todays Unique Hits: 59
0 Users 2 Guests Online

# PHP IRC Bot

Alright. I have made a PHP IRC Bot to run on my network but recently I took down my network for a while so I can find out how to link another server to it. So, to start off you will need to modify some things.

This bot has been coded in all OOP with a very simple database wrapper that you can always edit at a later point in time to something better.

To start off, php has to be installed on your computer. You may also need MySQL installed for a later section of this tutorial which will manage channel modes and a simple game.

If they are installed, you will want to make PHP accessible from anywhere on the computer. To achieve this you will need to edit the environmental variable named Path. To do this, you can follow the simple steps below.

• Start -> Right click My Computer

• Left click Properties

• Click the "Environmental Variables" button down near the bottom of the screen

After doing that, a small screen will appear that contains all your environmental variables.

We will be altering one of the System variables named Path. Select the variable then click the Edit button.

At the end of the line add the following
Code

;C:\path\to\php

After you do that you will need to restart your computer for these changes to take effect.

Next, you are ready to start making the bot.

Lets create a new directory and name it Extensions, or just ext.

After you have done that in the root directory make a file named YourBot.php

In this file will be all your core settings for the bot and MySQL. I have mine set up so its all run in the PHP CLI.

So, now to start the code.
PHP Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

 <?php require("ext/botCore.php"); $YourBot = new botCore();$MySQL_Config = array(     "sql_host" => "localhost", //MySQL Host     "sql_user" => "root", //MySQL user     "sql_pass" => "", //MySQL Pass     "sql_data" => "test" //MySQL Database );//end MySQL Configuration $mIRC_Config = array( "irc_server" => "irc.freenode.net", //IRC Network to connect to "irc_port" => "6667", //IRC Port "irc_nick" => "YourBot", //Bot name "irc_pass" => "", //Bot password for ident "irc_host" => "rmb-scripting.com", //the bots host "irc_real" => "Your Bot", //Bots real name "irc_defchan" => "#YourChannel" //default channel to join. );$YourBot->botConnect($MySQL_Config,$mIRC_Config); ?> 

Next, in your ext folder you will want to make the file botCore.php
In this file, you will want to place the following.

PHP Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

 <?php set_time_limit(0); //Don't time the script out require ("botExt.php"); //get the bot extension for different things like channel commands. class botCore extends botExt //Lets extend the bot extensions {     private $mIRC_Socket; //This is the bots socket private$mIRC_Config; //This is the bots configuration settings     function botConnect($MySQL_Config = null,$mIRC_Config = null) //lets have our bot connect.     {         $this->mIRC_Config =$mIRC_Config; //Lets assign our configuration         if (!is_array($MySQL_Config)) { //Wrong MySQL Data type die("[CORE.botConnect] MySQL Config invalid"); } elseif (!is_array($mIRC_Config)) { //Wrong mIRC data type             die("[CORE.botConnect] mIRC Config invalid");         } else {             $this->mIRC_Socket = @fsockopen($this->mIRC_Config["irc_host"], $this-> mIRC_Config["irc_port"]) or die("[CORE.botConnect] Socket Error. Can not connect to host."); //connect to the server or die with an error. parent::MySQL_Connect($MySQL_Config, $this->mIRC_Socket); //forward the MySQL configuration and mIRC Socket$this->botInitialize(); //Lets initialize the bot! :)         }     }     private function botInitialize() //This will send our mIRC config to the server to set our nickname and such.     {         fputs($this->mIRC_Socket, "USER " .$this->mIRC_Config["irc_nick"] . " " . $this-> mIRC_Config["irc_host"] . " Remedy Designs: " .$this->mIRC_Config["irc_real"] .             "\n"); //Place the data into the server and send to the socket.         fputs($this->mIRC_Socket, "NICK " .$this->mIRC_Config["irc_nick"] . "\n"); //this will set the bots nickname         $this->botReceiveData(); //Now we can receive data coming FROM the server. } private function botReceiveData() //Lets start receiving data! { while (1) { //lets make a loop to get all data. while ($getData = fgets($this->mIRC_Socket, 4096)) { //lets get data from the server now. echo$getData; //echo the data coming in from the server.                 flush(); //flush the buffer                 $exData = explode(" ",$getData); //Lets split up the data for easier management                 if ($exData[0] == "PING") { //see if we got ping'd fputs($this->mIRC_Socket, "PONG " . $exData[1] . "\n");//if the server sends us a ping, lets send a pong back so we don't time out. } if ($exData[3] == ":please") { //THe nickname is already registered.                     fputs($this->mIRC_Socket, "PRIVMSG NickServ IDENTIFY " .$this->mIRC_Config["irc_pass"] .                         " \n"); //Tell nickserv that we own this nickname and would like to identify                     parent::joinChannel($this->mIRC_Config["irc_defchan"]); //Lets join our default channel! :) }$nickArr = explode(":", $exData[0]); //Gets nickname$nickArrx = explode("!", $nickArr[1]); //gets realname parent::channelCommands($this->prepareCommands($exData['3']),$exData['2'], $nickArrx['0'],$exData); //This is used for channel commands.                 if ($exData['2'] ==$this->mIRC_Config["irc_nick"]) { //these are private message commands                     parent::privateCommands($this->prepareCommands($exData['3']), $exData,$nickArrx['0']); //lets handle them!                 }             }         }     }     private function prepareCommands($text) //This will prepare commands for processing. {$command_Characters = str_replace(array(chr(10), chr(13), chr(3)), '', $text); //remove odd characters$command_Comma = str_replace(",", '', $command_Characters); //strip commas from a foreground and background color$command_Numbers = str_replace(array('1', '2', '3', '4', '5', '6', '7', '8', '9',             '0'), '', $command_Comma); //get rid of the color numbers$command = str_replace(":", "", $command_Numbers); //get rid of the : for the actual message return$command; //return the command as clean as can be ;D     } } ?> 

This is your bot's core file. Not much will change in this file unless you wish to add auto-rehashing of the server if the bot is a server operator or net admin.

Your next to last file will be botExt.php located still in the ext folder.

Now, in this file we will handle the commands coming in and the MySQL functions. This tutorial however will not cover the MySQL portions. I will post a new tutorial later on which will handle an !up command to give people channel modes.

PHP Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

 <?php require ("botDbWrapper.php"); class botExt extends botDbWrapper {     private $MySQL_Socket; private$mIRC_Socket;     function MySQL_Connect($MySQL_Config,$mIRC_Socket) //Lets get our config then connect     {         $this->mIRC_Socket =$mIRC_Socket; //This is the mIRC Socket forwarded from botCore.         if (!is_array($MySQL_Config)) { //invalid format die("[EXT.MySQL_Connect] MySQL Config invalid"); } else {$this->MySQL_Socket = parent::__Connect($MySQL_Config); //Lets connect! } } function channelCommands($command, $data,$user, $allData) //these commands are said in the channel { switch ($command) { //lets check to see which command was said!             case '!sayit': //default command O_o change if you want.                 fputs($this->mIRC_Socket, "PRIVMSG$data :Hello! I am a bot.\n"); //send a simple message to the channel.                 break;         }     }     function privateCommands($command,$data, $user) //all private message commands { switch($command){ //lets check and see what command was said             case '!botstat':                 fputs($this->mIRC_Socket, "PRIVMSG$user :Oh hai! this bot was coded as a tutorial for the RMB-Scripting community at rmb-scripting.com It was posted by MOD-Shadow.\n"); //simple bot descripion.                 break;            }        }        function joinChannel($channel) //lets join a channel! { fputs($this->mIRC_Socket, "JOIN $channel\n"); //join$channel now.     }     function leaveChannel($channel) { fputs($this->mIRC_Socket, "JOIN $channel\n"); //lets leave the channel! } } ?>  Now for the final PHP file. Name this botDbWrapper.php and place it in the ext folder. PHP Code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41   <?php class botDbWrapper{ private$activeConnection; //the active MySQL Server connection     /**      * Connect to MySQL Server      * @param Array $MySQL_Config */ function __Connect($MySQL_Config){ //connect to the DB with the forwarded info         $this->activeConnection = @mysql_connect($MySQL_Config["sql_host"], $MySQL_Config["sql_user"],$MySQL_Config["sql_pass"]) or die("[EXT.DbWrapper.MySQL_Connect] MySQL Error. Can not connect to host."); //connect or die in the screen. Likely to close the window x:         mysql_select_db($MySQL_Config["sql_data"],$this->activeConnection) or die("[EXT.DbWrapper.MySQL_Connect] MySQL Error. Can not select database."); //Select the Database.     }     /**      * Query the database      * @param String $sql * @return Mixed */ function sqlQuery($sql){ //lets query the database         $query = @mysql_query($sql, $this->activeConnection); //Use the active connection and query the database with$sql         return $query; } /** * Count rows * @param Mixed$sql      * @return Integer      */     function sqlCount($sql){ //count rows in a table$query = @mysql_num_rows($sql); //count now return$query; //return the number of rows     }     /**      * Array Data      * @param Mixed $sql * @return Mixed */ function sqlFetch($sql){         $query = @mysql_fetch_object($sql); //array the data         return \$query; //then return the array.     } } ?> 

That is all the PHP you should need. Now, say you dont want to use Command Prompt to open the file but instead want an easier way. Open notepad and add the following to it
Code

@echo off
title YourBot -- IRC Bot
php -q C:\path\to\YourBot.php

NOw that thats done you can go to file, save as, YourBot change file type to all files and filename needs to be YourBot.bat
You can save this to anywhere on your PC and have it work. Another thing you can do is drag it to Start -> All Programs -> Startup to have the bot run at startup.

This concludes the tutorial and some addons will be posted in the future. If you would like to request a feature for the bot feel free to post a command. My final result is up for download in the Scripts section of the downloads area. click Here to get it.

Quick note: Everytime you send something to the server you MUST append a \n to the end of the string or else it will not work. I will soon be making another part to this [2/19/09]
Author:
Views:
6834
Rating:
Posted on Friday 20th February 2009 at 07:20 PM
Sorry read that wrong. irc_host is the bots hosting Ie where you are hosting it. irc_server is where you want the bot to connect to such as localhost ;)
Posted on Wednesday 18th February 2009 at 09:38 PM
Read the very top of the tutorial. for the PHP error. Also, you must have an IRCd running in order for it to connect. say UnrealIRCd
Posted on Tuesday 17th February 2009 at 10:43 PM
When I tried to run the bat file.. I get "php is not recognized as an internal or external command"

whaaa
Posted on Tuesday 17th February 2009 at 10:41 PM
What the hell . I copied all exact files into my wamp/www and I have localhost on. And I tried to do that notepad file... here is the code

Code
@echo off
title GuardBot - IRC Bot
php -q C:wampwwwphpIRCbotyourbot.php

Grrr. it's not work... I have the IRC Host set to localhost
"irc_host" => "localhost", //the bots host

Hallp
Posted on Tuesday 17th February 2009 at 10:36 PM
Shouldn't "irc_host" => "rmb-scripting.com", //the bots host

be localhost?
Posted on Tuesday 17th February 2009 at 10:04 PM
Let's say I extracted the PHP into my C:

Would I put in the path... like after all the other text in the envireomental thingy...

;C:php-5.2.8 ?

Also.. I run them on my localhost and run notepad/bat file?
Posted on Tuesday 17th February 2009 at 09:13 PM
You can use pjIRC to set-up a client then use Mibbit to connect yourself or use the pjIRC client. Or, more formally use mIRC itself =P that's what I did ;)
Posted on Tuesday 17th February 2009 at 08:43 PM
Ah, ok. I REALLY REALLY want this work. I really want a IRC bot.

By the way, do I need miRC for this to work? Or can I get on using a web-client?
Posted on Tuesday 17th February 2009 at 04:13 PM
Host it on your localhost and run it with PHP CLI as if you run it on a web server you risk getting suspended for CPU usage problems. I've mentioned that in the tutorial near the top then here at the bottom there is a thing you can save as a .bat to run it on the system with CLI.

In the ZIP file it is a lot more advanced then this it has different commands to reboot the bot, shutdown the bot and some other nifty things. I'm going to re-make the zip file when I get home though because I don't think the MySQL table is in there.
Posted on Tuesday 17th February 2009 at 05:36 AM
Should these files be hosted on my website or localhost?