27089 total geeks with 3528 solutions
Recent challengers:
 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
timsattemme
<ul><li><str ong><a href="http:/ /www.ywjx8.c om/">cheap wedding dresses</a>< /strong> </l i><li><stron g><a href="http:/ /www.ywjx8.c om/">Sexy Beach Wedding Dresses Sale</a></st rong> </li>< li><strong>< a href="http:/ /www.ywjx8.c om/">cheap wedding dresses</a>< /st
timsattemme
[b][url=http ://www.watch esiphone5.co m/]replica o<strong><a href="http:/ /www.watches iphone5.com/ ">replica omega watches</a>< /strong> <br > <strong><a href="http:/ /www.watches iphone5.com/ ">replica cartier watches</a>< /strong> <br >
timsattemme
<strong><a href="http:/ /www.watches iphone5.com/ ">cartier watches</a>< /strong> | <strong><a href="http:/ /www.watches iphone5.com/ ">rolex watches</a>< /strong> | <strong><a href="http:/ /www.watches iphone5.com/ ">omega watches</a>< /strong> <br > <title>Longi
timsattemme
[b][url=http ://www.copyr olexdaytona. com/]rolex new 2013[/url][/ b] [b][url=h ttp://www.co pyrolexdayto na.com/]role x basel[/url][ /b] [b][url=http ://www.copyr olexdaytona. com/]rolex Y<br><strong ><a href="http:/ /www.copyrol exdaytona.co m/">rolex new 2013</a></st
timsattemme
<br><strong> <a href="http:/ /www.copyrol exdaytona.co m/">rolex new 2013</a></st rong> <stron g><a href="http:/ /www.copyrol exdaytona.co m/">rolex basel</a></s trong> <br>< strong><a href="http:/ /www.copyrol exdaytona.co m/">rolex Yacht-Master II</a></stro ng> <br><b

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


News Feeds
The Register
SKYPE has the HOTS
for my NAKED WIFE
Time to test your
sarcasm detectors:
It"s the UN"s
global comms
shakeup
extravaganza!
Wanna see how
Russia et al hope
to shape the
internet? ITU opens
up (a little more)
t
Google CEO Larry
Page gives Sundar
Pichai keys to the
kingdom
Cheapo telcos fined
for their cheapo
security: Financial
records on 305,000
people spill
LG taps TSMC to
bake its first-ever
mobile chip
FCC: You"ll have to
wait even longer
for faster wireless
broadband
Breaking news:
Google exec in
terrifying SKY
PLUNGE DRAMA
Revealed: The
amazing magical
innovation in the
iPad Mini 3 ? a
lick of paint
Silicon Valley
scrooges paid staff
$1.21 an hour in a
122-hour week
Slashdot
Peter Kuran:Visual
Effects Artist and
Atomic Bomb
Archivist
OwnCloud Dev
Requests Removal
From Ubuntu Repos
Over Security Holes
Microsoft Now Makes
Money From Surface
Line, Q1 Sales
Reach Almost $1
Billion
Days After
Shooting, Canada
Proposes New
Restrictions On and
Offline
AT&T Locks
Apple SIM Cards On
New iPads
Passwords: Too Much
and Not Enough
Verizon Injects
Unique IDs Into
HTTP Traffic
Secretive Funding
Fuels Ongoing Net
Neutrality
Astroturfing
Controversy
A Low Cost, Open
Source Geiger
Counter (Video)
Computer Scientist
Parachutes From
135,908 Feet,
Breaking Record
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 103889 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-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-03-11 05:15:46
spectacular post.thanks a lot for showing this here
frequent anxiety attacks
Anonymous
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!
Anonymous
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
Anonymous
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
Anonymous
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>
Anonymous
2011-05-05 12:15:40
This is totally an awesome. I like what you have in here. thanks.
affordable health insurance
Anonymous
2011-05-08 11:34:24
Great information. thanks.
puppies for sale
Anonymous
2011-05-13 03:54:07
Really interesting. thanks. slim fast diet plan
Anonymous
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>
Anonymous
2011-05-16 19:56:06
Nice page. THanks.
home mortgage lender
Anonymous
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