Start New Discussion within our Software Development Community

This bot has some common functions, along with some not so common. I've been using this code to text my wife from work when my phone dies.


  • Gmail account (for texting)
  • xgoogle (for lang translation)

I know it is messy, and the variables are named poorly; sorry. I swear they made since at the time of initial coding :$

Once the bot is in the channel you send it commands denoted with '^'.

Some commands require more than one argument like the texting command; they are seporated by '*' or ':'. Just take a look at the code to see where it splits the data.
^textMessage *ATT *3045555555 *This is a test message

I want to add DCC file transfer, but don't know the raw IRC commands to do it. I know its something like "PRIVMSG #ChtRm DCC"

I've googled with no good result; maybe I'm stupid...
I found plenty on doing it with a client program like mIRC, but not the raw protocol commands. Anyone have an idea?

# Name:        PyIRC
# Purpose:     Python based IRC bot
# Author:      K.B. Carte (techb)
# Created:     04/27/2010
# -->updated:   07/19/2010
# Copyright:   (c) K.B. Carte (techb) 2010
#!/usr/bin/env python

import socket, string, time, random, re, xgoogle, urllib2, cookielib, smtplib
from import GoogleSearch, SearchError
from xgoogle.translate import Translator

carriers = {"Alltel":"",

chan = 'PyIRC'
ircsite = ''
port = 6667
lang = Translator().lang
translate = Translator().translate

def sendText(body, to = "", username = "", password = "Your pass"):
    """Sends a text via Gmail"""
    mail_server = smtplib.SMTP("", 587)
    mail_server.login(username, password)
    mail_server.sendmail(username, to, body)

def sentance():
    """Genorates a random sentance"""
    noun = ['school', 'yard', 'house', 'ball', 'shoes', 'shirt',
        'fan', 'purse', 'bag', 'pants', 'toaster', 'lamp', 'floor',
        'door', 'table', 'bread', 'dresser', 'cup', 'salt', 'pepper',
        'plate', 'dog', 'cat', 'wood', 'stool', 'suitcase', 'plane',
        'bus', 'car', 'bike', 'phone', 'pillow', 'wall', 'window',
        'bed', 'blanket', 'hand', 'head', 'bra', 'eyes', 'sock',
        'plastic', 'card board', 'pantys', 'oven', 'bow', 'hair',
        'person', 'clock', 'foot', 'boy', 'book', 'ear', 'girl',
        'park', 'basket', 'woman', 'street', 'box', 'man']

    verb = ['bounced', 'cried', 'jumped', 'yelled', 'flew', 'screamed',
        'died','laughed','sang','tripped','frowned','slipped','committed murder']

    adjective = ['beautiful','black','old','ugly','wet','red','loud','blue','dry',

    ending = ['?', '.', '...', '!']

    s = "The %s %s %s %s" % (random.choice(adjective),

irc = socket.socket()
irc.connect((ircsite, port))
print irc.recv(1024)
n = 'PyIRCV3'
irc.send('NICK %s\r\n' %  n)
irc.send("USER %s %s bla :%s\r\n" % ("Ohlook", 'itsnotmy', 'Realname'))
irc.send("JOIN #%s\r\n" % chan)

readbuffer = ''
while True:
    readbuffer= irc.recv(1024)
    temp=string.split(readbuffer, "\n")
    Check = readbuffer.split(':')
    print readbuffer

    if 'PING' in readbuffer:
        """PIN/PONG connection echo response"""
        irc.send("PONG :%s" % Check[1])

    if 'JOIN' in readbuffer:
        """Greet people that join the channel"""
        na = Check[1].split('!')
        irc.send("PRIVMSG #%s :Hello %s\r\n" % (chan, str(na[0])))

    if "^translate" in readbuffer:
        """Translate command"""
        if "^translate lang" in readbuffer:
            na = readbuffer.split('!')
            for i in lang:
                """send privet message to who wants to know
                   the languages supported, it is a big list"""
                irc.send("PRIVMSG %s :%s = %s\r\n" % (na[0].strip(':'),lang[i],i))
            tran = readbuffer.split(':')
            na = readbuffer.split('!')
            tran = tran[2:]
            if not tran:
                irc.send("PRIVMSG #%s :syntax'^translate :search term :<lang>\r\n'" % chan)
                tr = tran[1].strip()
                    l = translate(tr, lang_to=tran[2].strip())
                    l= l.encode('ascii','ignore')
                    print l
                    irc.send("PRIVMSG #%s :%s\r\n" % (chan, l))
                except xgoogle.translate.TranslationError:
                    irc.send("PRIVMSG #%s :not a valid language\r\n" % chan)

    if "^quote" in readbuffer:
        """Pulls a quote from HBH"""
        cj = cookielib.CookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        opener.addheaders.append(('User-agent', 'Mozilla/4.0'))
        opener.addheaders.append( ('Referer', '') )
        resp ='')
        r =
        del cj, opener
        da = re.findall("nter; width:70%;'>(.*)</div>",r)
        irc.send("PRIVMSG #%s :%s\r\n" % (chan, da[0]))

    if "^google" in readbuffer:
        """googles the search term and displays the first 5 results"""
            fin = readbuffer.split(':')
            if not fin:
                irc.send("PRIVMSG #%s :syntax'^google :search term\r\n'" % chan)
                fin = fin[3].strip()
                gs = GoogleSearch(fin)
                gs.results_per_page = 10
                results = gs.get_results()
                for results in results:
                    irc.send("PRIVMSG #%s :%s\r\n" % (chan, results.url.encode("utf8")))
        except IndexError:
            irc.send("PRIVMSG #%s :syntax ^+google :search term\r\n" % chan)
        except SearchError, e:
            irc.send("PRIVMAS #%s :Search failed: %s" % (chan, e))

    if "^time" in readbuffer:
        """displays time"""
        irc.send("PRIVMSG #%s :%s\r\n" % (chan, time.strftime('%I')+':'+time.strftime('%M')))

    if "^sentance" in readbuffer:
        """calls random sentance"""
        sen = sentance()
        irc.send("PRIVMSG #%s :%s\r\n" % (chan, sen))

    if "^boobs" in readbuffer:
        """crude perverted humor lol"""
        irc.send("PRIVMSG #%s :(.Y.)\r\n" % chan)

    if "^say" in readbuffer:
        """make the bot say the given word/phrase"""
        th = readbuffer.split('^say')
        th = th[-1].split('\r\n')
        irc.send("PRIVMSG #%s :%s\r\n" % (chan, th[0].strip()))

    if "^test" in readbuffer:
        """test bot, see if its listening"""
        irc.send("PRIVMSG #%s :I'm still alive...\r\n" % chan)

    if "^commands" in readbuffer:
        """shows a list of supported commands"""
        irc.send("PRIVMSG #%s :^ + (commands, carr, say <term/phrase>, sentance, test, whoareyou, boobs, google :<search term>, quote,\r\n" % chan)
        irc.send("PRIVMSG #%s :translate :<term/phrase> :<lang code> **type trans lang for list of available languages**)\r\n" % chan)
        irc.send("PRIVMSG #%s :^ + textMessage *carr *10 digit number *The message\r\n")

    if "^whoareyou" in readbuffer:
        """Shows who/what the bot is and written in"""
        irc.send("PRIVMSG #%s :I am %s, I was created By: TechB\r\n" % (chan, n))
        irc.send("PRIVMSG #%s :I was written in Python 2.6, and edited with PyScripter\r\n" % chan)
        irc.send("PRIVMSG #%s :The Classes used are socket, string, time, random, re, xgoogle, urllib2, cookielib, smtplib\r\n" % chan)
        irc.send("PRIVMSG #%s :As well as some functions from TechB\r\n" % chan)
        irc.send("PRIVMSG #%s :type ^commands for a list of things I can do\r\n" % chan)

    if "^carr" in readbuffer:
        """list of carrier codes used in ^textMessage"""
        irc.send("PRIVMSG #%s :%s\r\n" % (chan,carriers.keys()))

    if "^textMessage" in readbuffer:
        """Send text to a cellphone"""
            text = readbuffer.split('^textMessage')
            text = text[-1].split('\r\n')
            text = text[0].strip()
            text = text.split('*')
            carr = text[1].strip()
            numb = text[2].strip()
            bdy = text[3]
            sendText(bdy, to=numb+carriers[carr])
            irc.send("PRIVMSG #%s :^+carr for carrier codes\r\n" % chan)
The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.