27749 total geeks with 3539 solutions
Recent challengers:
 Welcome, you are an anonymous user! [register] [login] Get a yourname@osix.net email address 



User's box

Forgot password?
New account

<strong><a href="http:/ /www.shoeslo ver.net/">ne w balance mens shoes sale</a></st rong> <br> <strong><a href="http:/ /www.shoeslo ver.net/">On line New Balance Shoes Outlet</a></ strong> <br> <strong><a href="http:/ /www.shoeslo ver.net/">Ne w Balance Outlet Sale<
[b][url=http ://www.nbspo rtsshoes.com /]buy cheap <strong><a href="http:/ /www.nbsport sshoes.com/" >buy cheap new balance shoes</a></s trong> <br> <strong><a href="http:/ /www.nbsport sshoes.com/" >new balance shoes</a></s trong> <br>
[b][url=http ://www.repli cawatchesfam ily.com/]ome ga w<strong><a href="http:/ /www.replica watchesfamil y.com/">omeg a watches on sale</a></st rong> <br> <strong><a href="http:/ /www.replica watchesfamil y.com/">omeg a watches replica</a>< /strong> <br >
<strong><a href="http:/ /www.replica watchesfamil y.com/">omeg a watches replica brand watches</a>< /strong> | <strong><a href="http:/ /www.replica watchesfamil y.com/">watc hes</a></str ong> | <strong><a href="http:/ /www.replica watchesfamil y.com/">watc h</a></str
<strong><a href="http:/ /www.dresses fashion.org/ ">Bridal Factory Outlet Limited</a>< /strong> <br > <strong><a href="http:/ /www.dresses fashion.org/ ">Wedding Dress Factory Outlet</a></ strong> <br> <strong><a href="http:/ /www.dresses fashion.org/ ">wedding dress

Donate and help us fund new challenges
Due Date: Nov 30
November Goal: $40.00
Gross: $0.00
Net Balance: $0.00
Left to go: $40.00

News Feeds
The Register
Doctor Who:
The Hybrid finally
reveals itself in
the epic Heaven
Meet ARM1,
grandfather of
today"s mobe,
tablet CPUs ? watch
it crunch code live
in a
Court: Swedish ISPs
can"t be forced to
block Sweden"s
Pirate Bay
Final countdown ?
NSA says it really
will end blanket
phone spying on US
citizens this
VW"s Audi suspends
two engineers in
air pollution
cheatware probe
Millions of
families hit in
toymaker VTech hack
? including
200,000+ kids
What a bum note:
Violin"s shares
perform financial
Research: Microsoft
the fastest growing
maker of tablet OSs
... by 2019
IT manager jailed
for 5 years for
attempting dark web
gun buy
German ex-pat
jailed for smearing
own pat all over
Cork apartment
2 Planets Can Share
the Same Orbit, In
3 Different Ways
Pwned Barbies
Spying On Children?
Toytalk CEO
Downplays Hacking
Swarm Robotics
Breakthrough Brings
Communication To AI
Creator of Relay On
BITNET, Predecessor
of IRC, Dies
NASA Prepares To
Launch an Orion and
3 Cubesats To Deep
Space: 3 Years To
Bill Gates To
Headline Paris
Climate Talks
What USB Has
Replaced (And What
it Hasn"t)
How Bad of a World
Are We Really
Living In Right
nfinite Ransomware
Decrypted, No Need
To Pay Ransom
Ask Slashdot: Buy
Or Build a High End
Gaming PC?
Article viewer

A simple IRC BOT written in Python

Written by:ne0
Published by:Nightscript
Published on:2006-02-12 05:32:37
Search OSI about Python.More articles by ne0.
 viewed 113906 times send this article printer friendly

Digg this!
    Rate this article :
This article shows you how to make a simple IRC bot in python.

First question: why the hell not eggdrop? Answer: I don't know TCL, and I like to customize my scripts; plus it's a heavy program, and I hardly need 1% of the features it provides. I have been using python for a few months now and absoulutely love it. Creating bots in python is quite a simple job really. So lets start making it.

Importing the libraries:

import sys
import socket
import string
import os #not necassary but later on I am going to use a few features from this

With that done, now we need to give a configuration:

HOST='mesa.az.us.undernet.org' #The server we want to connect to
PORT=6667 #The connection port which is usually 6667
NICK='pybotv000' #The bot's nickname
OWNER='ne0n-' #The bot owner's nick
CHANNELINIT='#test198' #The default channel for the bot
readbuffer='' #Here we store all the messages from server

Warning:Keep the nickname quite unique because then you'll have to use a method to change the nick if it is already taken.

Connecting to the server:

s=socket.socket( ) #Create the socket
s.connect((HOST, PORT)) #Connect to server
s.send('NICK '+NICK+'n') #Send the nick to server
s.send('USER '+IDENT+' '+HOST+' bla :'+REALNAME+'n') #Identify to server

The main part of the bot:

Now, we are sitting on the server but not doing anything. To do stuff we setup an infinite loop that listens to the messages and handles them appropriately.

while 1:

        line=s.recv(500) #recieve server messages
    print line #server message is output
    if line.find('Welcome to the UnderNet IRC Network')!=-1: #This is Crap(I wasn't sure about it but it works)
        s.send('JOIN '+CHANNELINIT+'n') #Join a channel
    if line.find('PRIVMSG')!=-1: #Call a parsing function
        line=line.rstrip() #remove trailing 'rn'
        if(line[0]=='PING'): #If server pings then pong
            s.send('PONG '+line[1]+'n')

We recieve the server input in a variable line; if you want to see the servers messages, use print line. Once we connect to the server, we join a channel. Now whenever we recieve any PRIVMSG, we call a function which does the appropriate action. The next few lines are used to reply to a servers PING. Until this point, the bot just sits idle in a channel.
To make it active we use the parsemsg function.

The parsemsg function:

def parsemsg(msg):
    complete=msg[1:].split(':',1) #Parse the message into useful data
    info=complete[0].split(' ')
    if msgpart[0]=='`' and sender[0]==OWNER: #Treat all messages starting with '`' as command
        cmd=msgpart[1:].split(' ')
        if cmd[0]=='op':
            s.send('MODE '+info[2]+' +o '+cmd[1]+'n')
        if cmd[0]=='deop':
            s.send('MODE '+info[2]+' -o '+cmd[1]+'n')
        if cmd[0]=='voice':
            s.send('MODE '+info[2]+' +v '+cmd[1]+'n')
        if cmd[0]=='devoice':
            s.send('MODE '+info[2]+' -v '+cmd[1]+'n')
        if cmd[0]=='sys':
    if msgpart[0]=='-' and sender[0]==OWNER : #Treat msgs with - as explicit command to send to server
        print 'cmd='+cmd

This is the most interesting part, PRIVMSG are usually of this form:

:nick!username@host PRIVMSG channel/nick :Message

First, we seperate out all the data and nick part. The actual message is stored in variable msgpart.
If a message starts with ` it is trated as a user commands these can be used as public op/deop/ voice/devoice
commands. One spesial command is sysproc which is a special command that executes a command on the
bot's system and also displays the output(That's where os comes in).If we use a '-' we instruct the bot to send
RAW data to server, this is quite a handy feature using this you can almost use the bot as an IRC client
well not really.

The syscmd function:

def syscmd(commandline,channel):
    cmd=commandline.replace('sys ','')
    os.system(cmd+' >temp.txt')
    s.send('PRIVMSG '+channel+' :'+ot+'n')
    return 0

This piece of code takes the command and executes it printing the output to ot.txt. Then ot.txt is
read and displayed to the given channel.Multiline output is shown by using '|'.

You can easily add features to this bot and also CTCP replies but that's upto you.
I know the code is very ugly. The complete listing is on my osi drive :

Did you like this article? There are hundreds more.

2006-02-12 17:39:55
Very cool, nice job! n0k
2006-06-22 09:41:00
Laugh out out out loud?

Read this, its funnier
2006-06-27 08:20:03
really cool, but i cant get it to work properly. i also really like python. If i knew more about irc i could probably find what im doing wrong... thats what happens when you use mirc, it does everything for you and you learn nothing.

2006-10-08 10:33:10
so u connect the shell to the server after u made the bot mine is just a help questionaire bot how to do things like

hello= "my name is Legion"


just making it respond to text so it can give a answer to help user out on the server
2007-01-20 08:16:43
Hope you're not claiming this as your own...

2007-01-20 09:29:23
Can you read? That's quite different...
2007-01-20 14:59:08
As a matter of fact, it's not so different. The core is obviously the same, see the unused "readbuffer" variable in the code published here for example.

Since TCP is a stream and not based on datagrams, the code in this article fails but the one at oreilly.com works. So, the author who modified the simplebot.py broke it. The bot here will fail to process messages under lag or flooding as a result of these undesirable changes.

Funny enough, backslashes have died during submitting, and even the security check in place (testing owner name) will fail under flood. Just send enough data and the lack of buffering will cause the bot to eventually process PRIVMSG contents as a raw irc protocol message...

The original source should've definitely been credited.
2007-05-19 17:21:19
This piece of code is horribly mangled and ill-conceived, not to mention sloppily lifted from an O'Reilly example.

If you got here from google looking for help crafting an IRC bot, see http://python-irclib.sourceforge.net/. This is a robust implementation of the IRC protocol in an event-driven model like perl's Net::IRC.
2007-07-30 23:47:20
it doesnt work. the program says 'line' isnt defined and when you assign it something... it gets stuck in a while loop
2008-05-12 15:29:55
Allthough it probably is obvious to most readers, I still felt to comment on the security issues in this code.This bot is _not_ secure and should not be used for anything else than studying/experimenting with elementary socket programming.

For one thing, since it does no true buffering, one might get the bot to _execute a system command_ by flooding it with constructed PRIVMSG's, as pointed out by muzzy.
2008-08-10 17:29:50
damn I tried making auto op but it doens't op me :C
2009-03-07 03:43:10
For some reason this article doesn't have the escape characters in it. Instead of showing "\n" it just shows "n." That could confuse people. =)
2009-03-09 07:04:29
i wrote better one >_>
2009-03-09 16:08:03
lemme paste it ^^^^
2009-04-22 14:23:33
I still felt to comment on the security issues in this code.This bot is _not_ secure and should not be used for anything else than studying/experimenting with elementary socket programming. flash games
2009-06-04 03:51:17
I think you should all stop bitching and understand that even though it's not the "best" code, it's still a WORKING piece of code. Why rely on other librabries or modules when you can simply use built in socket?
2009-06-07 20:55:32
I dont get why this would even stay connected, the ping:pong looks wrong to me. he is checking for 'PRIVMSG' in the line, then in the if block the PONG reply line hecks for the presence of 'PING' in line[0] but the ping request is

PING :server.name.net

so as there is no 'PRIVMSG' in that, I doubt it would get noticed.

I strongly urge people to use this code only as a basic base structure, do not copy it, you will be disappointed later. Instead check out the latest RFC http://www.kvirc.de/docu/doc_rfc2812.html and build off of that.
2009-07-23 15:30:10
To customize my web scripts, I use Python as it has more useful features than TCL and is easy to load. Another advantage it provides is that creating bots in Python is like a breeze! Thanks to the author for sharing the creation process. <a href="http://www.sidgilreath.com/firm-overview/">nashville truck accident law firm</a>
2009-08-03 18:32:41
The ping:pong in that code is wrong, it won't work. Anyone know of a code that works?<a href="http://www.keeperskit.com/product/categories/goalkeeper_gloves/puma_goalkeeper_gloves/index.html">Puma Goalkeeper Gloves</a>
2009-08-26 23:31:56
From the looks of it, it's just that his indentation is wrong. There should be two separate if statements; after parsemsg(line), the next four lines should jump back an indentation level.
2009-09-07 21:27:33
How do I know what socket to create?
2009-09-08 03:37:04
the socket family is AF_INET and the type is SOCK_STREAM (which is TCP), but these are all defaults so you don't have to enter them, so both lines below are the same
1:  s = socket.socket()
2:  s = socket.socket(socket.AF_INET,socket.SOCK_STREAM,0)
2009-09-08 18:17:35
NOTICE AUTH :*** Looking up your hostname

NOTICE AUTH :*** Checking Ident

NOTICE AUTH :*** Found your hostname

NOTICE AUTH :*** No ident response

this is what i get.
2009-09-08 20:33:25
it might be a proxy causing a problem and it might not happen on certain networks
2009-09-23 06:57:22
No it is not a proxy problem. It is a problem in the code.
The line:
s.send('USER '+IDENT+' '+HOST+' bla :'+REALNAME+'n') #Identify to server
should look like this
s.send('USER '+IDENT+' '+HOST+' bla :'+REALNAME+'\r\n') #Identify to server
2009-10-05 22:14:12
Thanks for this tutorial, as I'm still newbie, articles like this is very useful for me.
download pc games
2009-10-25 15:45:17
Since TCP is a stream and not based on datagrams, the code in this article fails but the one at oreilly.com works. So, the author who modified the simplebot.py broke it. The bot here will fail to process messages under lag or flooding as a result of these undesirable changes.
Matt - Luxury Car Seats
2009-11-18 07:51:30
Thanks for sharing.
Jonny cleaner reviews
2010-01-05 16:02:48
Great sample, thanks! Vera @ <a href="http://www.yourloan.ca/">Student Loans Canada</a>
2010-01-05 16:04:20
Great sample, thanks! Student Loans Canada
2010-01-27 03:38:34
<a href="http://www.made-in-china.com/products-search/hot-china-products/Aluminium_Doors.html">Aluminium Door</a>

<a href="http://www.made-in-china.com/products-search/hot-china-products/Aluminum_Profile.html">Aluminum Profile</a>

<a href="http://www.made-in-china.com/products-search/hot-china-products/Lock_Body.html">Lock Body</a>

<a href="http://www.made-in-china.com/products-search/hot-china-products/Food_Additive.html">Food Additive</a>

<a href="http://www.made-in-china.com/products-search/hot-china-products/Amusement_Park.html">Amusement Park</a>

<a href="http://www.made-in-china.com/products-search/hot-china-products/Dog_Collar.html">Dog Collar</a>
2010-01-27 03:39:38

china agriculture
office items
recreation time
construction hardware
2010-02-13 10:35:12
RegCure Review is the best way to get a lot of information about your PC and Python
2010-03-11 05:15:46
spectacular post.thanks a lot for showing this here
frequent anxiety attacks
2011-02-12 06:39:03
No offense personally and thanks for trying, but how the fuck is this piece of shit at the top of google! How can "python irc bot tutorial" not turn up ANYTHING better - maybe even OOP since it is fucking python for fuck's sake! Don't mind me - I haven't smoked weed in 2 days!
2011-04-18 15:57:00
Shopping is more popular in recent year especially for women. Women want to do more and more shopping and look different to others. Today, online shopping is also so popular and most of the people like it.http://toobby.com
2011-04-22 23:13:39
Shopping is more popular in recent year especially for women. Women want to do more and more shopping and look different to others. Today, online shopping is also so popular and most of the people like it. http://toobby.com
2011-05-05 12:14:33
Always excited for the movie in the weekend. thanks for sharing. <a href="http://www.affordablehealthinsurancez.com/">affordable health insurance</a>
2011-05-05 12:15:40
This is totally an awesome. I like what you have in here. thanks.
affordable health insurance
2011-05-08 11:34:24
Great information. thanks.
puppies for sale
2011-05-13 03:54:07
Really interesting. thanks. slim fast diet plan
2011-05-16 19:54:37
You've got to make thing happen as plan. <a href="http://www.makemymtg.com/">mortgage loan refinance</a>
2011-05-16 19:56:06
Nice page. THanks.
home mortgage lender
2011-07-02 18:36:28
This is only at the top of google because the captcha is too easy for automated reading, so all these "Made in China" comments are spam increasing the pagerank. Unfortunately the comments telling people to ignore this page are way down at the bottom.
Anonymously add a comment: (or register here)
(registration is really fast and we send you no spam)
BB Code is enabled.
Captcha Number:

Test Yourself: (why not try testing your skill on this subject? Clicking the link will start the test.)
Beginning Python by byteCode

Test your knowledge of basic python

Your Ad Here
Copyright Open Source Institute, 2006