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

Articles

GEEK

User's box
Username:
Password:

Forgot password?
New account

Shoutbox
sefo
anilg, new comments are deleted automaticall y because of some abuse recently
anilg
this is plain wierd. I submitted comments twice to article 950, and they dont seem to be there. Something wrong with the comment code?
CodeX
shout-boxes in general are old + the staff thing happened to everyone after an issue 2 months ago
anilg
/me is no longer staff :(
anilg
Also, osix's shoutbox predated twitter. Heh.

Donate
Donate and help us fund new challenges
Donate!
Due Date: Jul 31
July Goal: $40.00
Gross: $0.00
Net Balance: $0.00
Left to go: $40.00
Contributors


News Feeds
The Register
UK.gov sticks to IE
6 cos it"s more
"cost effective",
innit
T-Mobile UK pumps
out the iPhone 4
Polaroid 300
instant print
camera
NatWest dumps O2
Money
YouTube ups video
time limit
Alleged expenses
fiddlers to face
justice
Nude trampolinist
bounces free from
court
Nexus One phone
rockets to 28,000ft
UK.gov drops £6m on
Google
Fake Firefox update
used to sling
scareware
Slashdot
British ISPs Favour
Well-Connected
Customers
"Bizarre"
Nanobubbles Found
In Strained
Graphene
1-in-1,000 Chance
of Asteroid Impact
In
...
2182?
2 Chinese ISPs
Serve 20% of World
Broadband Users
World"s Fastest
Hybrid OK"d For
Production
Sometimes It"s OK
To Steal My Games
Thermoelectrics
Could Let You Feel
the Heat In Games
KDE SC 4.7 May Use
OpenGL 3 For
Compositing
Perl 6, Early, With
Rakudo Star
Internal Costs Per
Gigabyte —
What Do You Pay?
Article viewer

A simple IRC BOT written in Python



Written by:ne0
Published by:Nightscript
Published on:2006-02-12 05:32:37
Topic:Python
Search OSI about Python.More articles by ne0.
 viewed 43614 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
IDENT='pybot'
REALNAME='s1ash'
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
        parsemsg(line)
        line=line.rstrip() #remove trailing 'rn'
        line=line.split()
        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(' ')
    msgpart=complete[1]
    sender=info[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':
            syscmd(msgpart[1:],info[2])
        
    if msgpart[0]=='-' and sender[0]==OWNER : #Treat msgs with - as explicit command to send to server
        cmd=msgpart[1:]
        s.send(cmd+'n')
        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 ','')
    cmd=cmd.rstrip()
    os.system(cmd+' >temp.txt')
    a=open('temp.txt')
    ot=a.read()
    ot.replace('n','|')
    a.close()
    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 :
http://www.osix.net:80/modules/folder/index.php?tid=10807&action=vf

Did you like this article? There are hundreds more.

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

Read this, its funnier
Anonymous
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.

cheers
Anonymous
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"

print

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

http://www.oreilly.com/pub/h/1968
Anonymous
2007-01-20 09:29:23
Can you read? That's quite different...
muzzy
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.
Anonymous
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.
Anonymous
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
Anonymous
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.
Anonymous
2008-08-10 17:29:50
damn I tried making auto op but it doens't op me :C
Anonymous
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. =)
Anonymous
2009-03-09 07:04:29
i wrote better one >_>
Anonymous
2009-03-09 16:08:03
lemme paste it ^^^^
Anonymous
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
Anonymous
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?
Anonymous
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.
Anonymous
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>
Anonymous
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>
Anonymous
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.
Anonymous
2009-09-07 21:27:33
How do I know what socket to create?
CodeX
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)
Anonymous
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.
CodeX
2009-09-08 20:33:25
it might be a proxy causing a problem and it might not happen on certain networks
Anonymous
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
Anonymous
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
Anonymous
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
Anonymous
2009-11-18 07:51:30
Thanks for sharing.
Jonny cleaner reviews
Anonymous
2010-01-05 16:02:48
Great sample, thanks! Vera @ <a href="http://www.yourloan.ca/">Student Loans Canada</a>
Anonymous
2010-01-05 16:04:20
Great sample, thanks! Student Loans Canada
Anonymous
2010-01-19 07:33:05
http://www.bagscabin.com/mulberry bags
Anonymous
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>
Anonymous
2010-01-27 03:39:38

china agriculture
office items
recreation time
construction hardware
Anonymous
2010-02-13 10:35:12
RegCure Review is the best way to get a lot of information about your PC and Python
Anonymous
2010-02-27 17:44:16
All the world's latest and most authoritative website with all kinds of uniforms. We are recognized worldwide network of sales jersey website. Here you can choose a variety of uniforms such as MLB jerseys, NFL jerseys, NHL jerseys and NBA jerseys. Professional security identification products with credit guarantee, first-class quality and reasonable prices!
--Lin Guowang
Anonymous
2010-03-11 05:15:46
spectacular post.thanks a lot for showing this here
frequent anxiety attacks
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