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
  • Select the advanced tab
  • 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.
TutorialNinja Image
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
PHP Code
  1. ;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. <?php
  2. require("ext/botCore.php");
  3. $YourBot = new botCore();
  4. $MySQL_Config = array(
  5. "sql_host" => "localhost", //MySQL Host
  6. "sql_user" => "root", //MySQL user
  7. "sql_pass" => "", //MySQL Pass
  8. "sql_data" => "test" //MySQL Database
  9. );//end MySQL Configuration
  10. $mIRC_Config = array(
  11. "irc_server" => "irc.freenode.net", //IRC Network to connect to
  12. "irc_port" => "6667", //IRC Port
  13. "irc_nick" => "YourBot", //Bot name
  14. "irc_pass" => "", //Bot password for ident
  15. "irc_host" => "rmb-scripting.com", //the bots host
  16. "irc_real" => "Your Bot", //Bots real name
  17. "irc_defchan" => "#YourChannel" //default channel to join.
  18. );
  19. $YourBot->botConnect($MySQL_Config, $mIRC_Config);
  20. ?>


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. <?php
  2. set_time_limit(0); //Don't time the script out
  3. require ("botExt.php"); //get the bot extension for different things like channel commands.
  4. class botCore extends botExt //Lets extend the bot extensions
  5. {
  6. private $mIRC_Socket; //This is the bots socket
  7. private $mIRC_Config; //This is the bots configuration settings
  8. function botConnect($MySQL_Config = null, $mIRC_Config = null) //lets have our bot connect.
  9. {
  10. $this->mIRC_Config = $mIRC_Config; //Lets assign our configuration
  11. if (!is_array($MySQL_Config)) { //Wrong MySQL Data type
  12. die("[CORE.botConnect] MySQL Config invalid");
  13. } elseif (!is_array($mIRC_Config)) { //Wrong mIRC data type
  14. die("[CORE.botConnect] mIRC Config invalid");
  15. } else {
  16. $this->mIRC_Socket = @fsockopen($this->mIRC_Config["irc_host"], $this->
  17. mIRC_Config["irc_port"]) or die("[CORE.botConnect] Socket Error. Can not connect to host."); //connect to the server or die with an error.
  18. parent::MySQL_Connect($MySQL_Config, $this->mIRC_Socket); //forward the MySQL configuration and mIRC Socket
  19. $this->botInitialize(); //Lets initialize the bot! :)
  20. }
  21. }
  22. private function botInitialize() //This will send our mIRC config to the server to set our nickname and such.
  23. {
  24. fputs($this->mIRC_Socket, "USER " . $this->mIRC_Config["irc_nick"] . " " . $this->
  25. mIRC_Config["irc_host"] . " Remedy Designs: " . $this->mIRC_Config["irc_real"] .
  26. "\n"); //Place the data into the server and send to the socket.
  27. fputs($this->mIRC_Socket, "NICK " . $this->mIRC_Config["irc_nick"] . "\n"); //this will set the bots nickname
  28. $this->botReceiveData(); //Now we can receive data coming FROM the server.
  29. }
  30. private function botReceiveData() //Lets start receiving data!
  31. {
  32. while (1) { //lets make a loop to get all data.
  33. while ($getData = fgets($this->mIRC_Socket, 4096)) { //lets get data from the server now.
  34. echo $getData; //echo the data coming in from the server.
  35. flush(); //flush the buffer
  36. $exData = explode(" ", $getData); //Lets split up the data for easier management
  37. if ($exData[0] == "PING") { //see if we got ping'd
  38. 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.
  39. }
  40. if ($exData[3] == ":please") { //THe nickname is already registered.
  41. fputs($this->mIRC_Socket, "PRIVMSG NickServ IDENTIFY " . $this->mIRC_Config["irc_pass"] .
  42. " \n"); //Tell nickserv that we own this nickname and would like to identify
  43. parent::joinChannel($this->mIRC_Config["irc_defchan"]); //Lets join our default channel! :)
  44. }
  45. $nickArr = explode(":", $exData[0]); //Gets nickname
  46. $nickArrx = explode("!", $nickArr[1]); //gets realname
  47. parent::channelCommands($this->prepareCommands($exData['3']), $exData['2'], $nickArrx['0'],
  48. $exData); //This is used for channel commands.
  49. if ($exData['2'] == $this->mIRC_Config["irc_nick"]) { //these are private message commands
  50. parent::privateCommands($this->prepareCommands($exData['3']), $exData, $nickArrx['0']); //lets handle them!
  51. }
  52. }
  53. }
  54. }
  55. private function prepareCommands($text) //This will prepare commands for processing.
  56. {
  57. $command_Characters = str_replace(array(chr(10), chr(13), chr(3)), '', $text); //remove odd characters
  58. $command_Comma = str_replace(",", '', $command_Characters); //strip commas from a foreground and background color
  59. $command_Numbers = str_replace(array('1', '2', '3', '4', '5', '6', '7', '8', '9',
  60. '0'), '', $command_Comma); //get rid of the color numbers
  61. $command = str_replace(":", "", $command_Numbers); //get rid of the : for the actual message
  62. return $command; //return the command as clean as can be ;D
  63. }
  64. }
  65. ?>


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. <?php
  2. require ("botDbWrapper.php");
  3. class botExt extends botDbWrapper
  4. {
  5. private $MySQL_Socket;
  6. private $mIRC_Socket;
  7. function MySQL_Connect($MySQL_Config, $mIRC_Socket) //Lets get our config then connect
  8. {
  9. $this->mIRC_Socket = $mIRC_Socket; //This is the mIRC Socket forwarded from botCore.
  10. if (!is_array($MySQL_Config)) { //invalid format
  11. die("[EXT.MySQL_Connect] MySQL Config invalid");
  12. } else {
  13. $this->MySQL_Socket = parent::__Connect($MySQL_Config); //Lets connect!
  14. }
  15. }
  16. function channelCommands($command, $data, $user, $allData) //these commands are said in the channel
  17. {
  18. switch ($command) { //lets check to see which command was said!
  19. case '!sayit': //default command O_o change if you want.
  20. fputs($this->mIRC_Socket, "PRIVMSG $data :Hello! I am a bot.\n"); //send a simple message to the channel.
  21. break;
  22. }
  23. }
  24. function privateCommands($command, $data, $user) //all private message commands
  25. {
  26. switch($command){ //lets check and see what command was said
  27. case '!botstat':
  28. 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.
  29. break;
  30. }
  31. }
  32. function joinChannel($channel) //lets join a channel!
  33. {
  34. fputs($this->mIRC_Socket, "JOIN $channel\n"); //join $channel now.
  35. }
  36. function leaveChannel($channel)
  37. {
  38. fputs($this->mIRC_Socket, "JOIN $channel\n"); //lets leave the channel!
  39. }
  40. }
  41. ?>


Now for the final PHP file. Name this botDbWrapper.php and place it in the ext folder.
PHP Code
  1. <?php
  2. class botDbWrapper{
  3. private $activeConnection; //the active MySQL Server connection
  4. /**
  5.   * Connect to MySQL Server
  6.   * @param Array $MySQL_Config
  7.   */
  8. function __Connect($MySQL_Config){ //connect to the DB with the forwarded info
  9. $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:
  10. mysql_select_db($MySQL_Config["sql_data"], $this->activeConnection) or die("[EXT.DbWrapper.MySQL_Connect] MySQL Error. Can not select database."); //Select the Database.
  11. }
  12. /**
  13.   * Query the database
  14.   * @param String $sql
  15.   * @return Mixed
  16.   */
  17. function sqlQuery($sql){ //lets query the database
  18. $query = @mysql_query($sql, $this->activeConnection); //Use the active connection and query the database with $sql
  19. return $query;
  20. }
  21. /**
  22.   * Count rows
  23.   * @param Mixed $sql
  24.   * @return Integer
  25.   */
  26. function sqlCount($sql){ //count rows in a table
  27. $query = @mysql_num_rows($sql); //count now
  28. return $query; //return the number of rows
  29. }
  30. /**
  31.   * Array Data
  32.   * @param Mixed $sql
  33.   * @return Mixed
  34.   */
  35. function sqlFetch($sql){
  36. $query = @mysql_fetch_object($sql); //array the data
  37. return $query; //then return the array.
  38. }
  39. }
  40. ?>


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
PHP Code
  1. @echo off
  2. title YourBot -- IRC Bot
  3. 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.

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]
ShadowMage's Avatar
Author:
Views:
9,548
Rating:
Posted on Monday 5th June 2023 at 11:45 PM
Mintgalaxy
Mintgalaxy's Avatar
Hi, could you please upload the mentioned zip file with MySQL queries.
Posted on Friday 20th February 2009 at 07:20 PM
ShadowMage
ShadowMage's Avatar
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
ShadowMage
ShadowMage's Avatar
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
Posted on Tuesday 17th February 2009 at 10:43 PM
UrbanTwitch
UrbanTwitch's Avatar
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
UrbanTwitch
UrbanTwitch's Avatar
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
UrbanTwitch
UrbanTwitch's Avatar
Shouldn't "irc_host" => "rmb-scripting.com", //the bots host

be localhost?
Posted on Tuesday 17th February 2009 at 10:04 PM
UrbanTwitch
UrbanTwitch's Avatar
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
ShadowMage
ShadowMage's Avatar
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
UrbanTwitch
UrbanTwitch's Avatar
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
ShadowMage
ShadowMage's Avatar
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.