Writing an IRC bot in Python

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

Mybot in action
Here I'll show you how to create a very simple IRC bot that is easy to build upon.

To begin, this tutorial requires that you have the basic knowledge of Python. The bot will be built with one single file and functions for each command, there are more efficient ways to build it but I want to keep it simple. I will call my bot "Mybot", but you can of course name your bot anyway you like.

The bot will do three things:

  • Connect and join a channel
  • Be able to respond to PINGs from the server
  • Respond to the very simple "Hello Mybot" command.
  • Later we will show you how to add new commands


Contents

Step 1

First, create a file named something like "Mybot.py". All the necessary code will be placed in there. In that file, we'll place the first bit of code.

# Import some necessary libraries.
import socket  

# Some basic variables used to configure the bot        
server = "irc.freenode.net" # Server
channel = "#youcoolchan" # Channel
botnick = "Mybot" # Your bots nick


Okay, lets go through these seven lines of code. The first 3 are pretty obvious. They simply import the socket library so that you can connect to the server using sockets. The other four lines of code define some basic variables, which server to connect to, which channel to join and your bots nick.

Step 2

Next thing we'll add are the functions, it is those functions that will do the handling of the data the server sends us. But ways to get to find out who the sender is will not be covered in this tutorial.

def ping(): # This is our first function! It will respond to server Pings.
  ircsock.send("PONG :Pong\n")  
def sendmsg(chan , msg): # This is the send message function, it simply sends messages to the channel.
  ircsock.send("PRIVMSG "+ chan +" :"+ msg +"\n") 

def joinchan(chan): # This function is used to join channels.
  ircsock.send("JOIN "+ chan +"\n")

def hello(newnick): # This function responds to a user that inputs "Hello Mybot"
  ircsock.send("PRIVMSG "+ channel +" :Hello!\n")

This was maybe a bit much to take at once, but my comments describe most of it. The function ping() will be called when the server tries to ping us, the function sendmsg() can be used whenever we want to send a message to a user or to a channel, the joinchan() function will be called whenever the bot joins a channel and the last function will write a response to "Hello Mybot".

Step 4

The next part is a bit tricky, here we will connect and join the configured channel.

ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ircsock.connect((server, 6667)) # Here we connect to the server using port 6667
ircsock.send("USER "+ botnick +" "+ botnick +" "+ botnick +" :This bot is a result of a tutorial covered on http://shellium.org/wiki.\n") # user authentication
ircsock.send("NICK "+ botnick +"\n") # here we actually assign the nick to the bot

joinchan(channel) # Join the channel using the functions we previously defined

The two first lines are used to connect to the server through port 6667 which is the most used irc-port. The third line sends the username, realname etc. The fourth line assigns a nick to the bot and the last line then joins the configured channel.

Step 5

The last piece of code is where we receive all the data from the server.

while 1: # Be careful with these! It might send you to an infinite loop
  ircmsg = ircsock.recv(2048) # receive data from the server
  ircmsg = ircmsg.strip('\n\r') # removing any unnecessary linebreaks.
  print(ircmsg) # Here we print what's coming from the server

  if ircmsg.find(":Hello "+ botnick) != -1: # If we can find "Hello Mybot" it will call the function hello()
    hello()
  if ircmsg.find("PING :") != -1: # if the server pings us then we've got to respond!
    ping()

Here we start an infinite loop that will process and receive all the data from the server. The second line is where all the data is received and the line after it is removing any unnecessary line-breaks from the data. The fourth line prints all the data received from the server, when finally running on SHellium, it is best to comment out this line. At the sixth line we check if someone wrote hello, if someone did, it will call the hello() function. The 9th line is similar to the sixth but instead here we checking if there was a ping.

The full code.

As I'm probably bad at explaining, I'll include the whole code. :)

# Import some necessary libraries.
import socket 

# Some basic variables used to configure the bot        
server = "irc.freenode.net" # Server
channel = "#doxer" # Channel
botnick = "Mybot" # Your bots nick


def ping(): # This is our first function! It will respond to server Pings.
  ircsock.send("PONG :pingis\n")  

def sendmsg(chan , msg): # This is the send message function, it simply sends messages to the channel.
  ircsock.send("PRIVMSG "+ chan +" :"+ msg +"\n") 

def joinchan(chan): # This function is used to join channels.
  ircsock.send("JOIN "+ chan +"\n")

def hello(): # This function responds to a user that inputs "Hello Mybot"
  ircsock.send("PRIVMSG "+ channel +" :Hello!\n")
                  
ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ircsock.connect((server, 6667)) # Here we connect to the server using the port 6667
ircsock.send("USER "+ botnick +" "+ botnick +" "+ botnick +" :This bot is a result of a tutoral covered on http://shellium.org/wiki.\n") # user authentication
ircsock.send("NICK "+ botnick +"\n") # here we actually assign the nick to the bot

joinchan(channel) # Join the channel using the functions we previously defined

while 1: # Be careful with these! it might send you to an infinite loop
  ircmsg = ircsock.recv(2048) # receive data from the server
  ircmsg = ircmsg.strip('\n\r') # removing any unnecessary linebreaks.
  print(ircmsg) # Here we print what's coming from the server

  if ircmsg.find(":Hello "+ botnick) != -1: # If we can find "Hello Mybot" it will call the function hello()
    hello()

  if ircmsg.find("PING :") != -1: # if the server pings us then we've got to respond!
    ping()

How to run

If you want to run your bot on SHellium 24/7 you can just run the following commands:

nano bot.py

And paste the code into the file. When you are done, save and exit.

Then write:

screen python bot.py

And you'll have a 24/7 bot responding to ping and one other command

Note:

Remember, to use a bot in the Shellium channel you must first have premission from an admin. Or else it will be against the Shellium rules. Also remember that jou can not run more than 2 background processes, or this will also be against the Shellium rules

Help

Feel free to join #shellium and ask J3r3my or any of the other users about your issues or problems. They would surely be able to spare a few minutes. If the people in #shellium can't help you, ask in #python @ freenode.

Adding new Commands

Adding new commands once you are this far is simple. You might, however, want to create a separate function to handle this. Let's create a simple bot function that responds to two more commands. In this example, we will have the bot do two more things:

* Say Shellium is awesome
* Tell whats its commands are with the help command

Handling the Data

def commands(nick,channel,message):
   if message.find(botnick+': shellium')!=-1:
      ircsock.send('PRIVMSG %s :%s: Shellium is awesome!\r\n' % (channel,nick))
   elif message.find(botnick+': help')!=-1:
      ircsock.send('PRIVMSG %s :%s: My other command is shellium.\r\n' % (channel,nick))

Getting the Data to the Function

And then we will also need to pass the data to this command, so we add these lines to the code:

   if ircmsg.find(' PRIVMSG ')!=-1:
      nick=ircmsg.split('!')[0][1:]
      channel=ircmsg.split(' PRIVMSG ')[-1].split(' :')[0]
      commands(nick,channel,ircmsg)

So the full code looks like this:

# Import some necessary libraries.
import socket 
# Set up our commands function
def commands(nick,channel,message):
   if message.find(botnick+': shellium')!=-1:
      ircsock.send('PRIVMSG %s :%s: Shellium is awesome!\r\n' % (channel,nick))
   elif message.find(botnick+': help')!=-1:
      ircsock.send('PRIVMSG %s :%s: My other command is shellium.\r\n' % (channel,nick))

# Some basic variables used to configure the bot        
server = "irc.freenode.net" # Server
channel = "#doxer" # Channel
botnick = "Mybot" # Your bots nick


def ping(): # This is our first function! It will respond to server Pings.
  ircsock.send("PONG :pingis\n")  

def sendmsg(chan , msg): # This is the send message function, it simply sends messages to the channel.
  ircsock.send("PRIVMSG "+ chan +" :"+ msg +"\n") 

def joinchan(chan): # This function is used to join channels.
  ircsock.send("JOIN "+ chan +"\n")

def hello(): # This function responds to a user that inputs "Hello Mybot"
  ircsock.send("PRIVMSG "+ channel +" :Hello!\n")
                  
ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ircsock.connect((server, 6667)) # Here we connect to the server using the port 6667
ircsock.send("USER "+ botnick +" "+ botnick +" "+ botnick +" :This bot is a result of a tutoral covered on http://shellium.org/wiki.\n") # user authentication
ircsock.send("NICK "+ botnick +"\n") # here we actually assign the nick to the bot

joinchan(channel) # Join the channel using the functions we previously defined

while 1: # Be careful with these! it might send you to an infinite loop
  ircmsg = ircsock.recv(2048) # receive data from the server
  ircmsg = ircmsg.strip('\n\r') # removing any unnecessary linebreaks.
  print(ircmsg) # Here we print what's coming from the server
  if ircmsg.find(' PRIVMSG ')!=-1:
     nick=ircmsg.split('!')[0][1:]
     channel=ircmsg.split(' PRIVMSG ')[-1].split(' :')[0]
     commands(nick,channel,ircmsg)
  if ircmsg.find(":Hello "+ botnick) != -1: # If we can find "Hello Mybot" it will call the function hello()
    hello()

  if ircmsg.find("PING :") != -1: # if the server pings us then we've got to respond!
    ping()
Personal tools
Namespaces

Variants
Actions
Navigation
Indexes
SHellium Sites
Toolbox