PyIRC

Tech B 0 Tallied Votes 464 Views Share

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.

Requirements:

  • 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 '^'.
Example:
^whoareyou

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.
Example:
^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 file.zip"

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 xgoogle.search import GoogleSearch, SearchError
from xgoogle.translate import Translator

carriers = {"Alltel":"@message.alltel.com",
"ATT":"@txt.att.net",
"NEXTEL":"@messaging.nextel.com",
"SPRI":"@messaging.sprintpcs.com",
"TMOBILE":"@tmomail.net",
"VERIS":"@vtext.com",
"VERGIN":"@vmobl.com"}

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

def sendText(body, to = "5555555555@txt.att.net", username = "yourAccount@gmail.com", password = "Your pass"):
    """Sends a text via Gmail"""
    mail_server = smtplib.SMTP("smtp.gmail.com", 587)
    mail_server.ehlo()
    mail_server.starttls()
    mail_server.ehlo()
    mail_server.login(username, password)
    mail_server.sendmail(username, to, body)
    mail_server.close()

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',
        'coughed','smoked','sneezed','exploded','puked','fell','burned',
        'smiled','spied','slept','drove','####ed','skipped','ran','walked',
        'died','laughed','sang','tripped','frowned','slipped','committed murder']

    adjective = ['beautiful','black','old','ugly','wet','red','loud','blue','dry',
             'quiet','purple','hairy','medicore','yellow','bald','meloncholy',
             'white','smooth','bright','clear','rough','dark','round','sexual',
             'heavy','square','sexy','smelly','triangular','angry','discusting',
             'octagon','sad','delicious','precious','happy','fat','distinguished',
             'scared','skinny','burnt','brown','new']

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

    s = "The %s %s %s %s" % (random.choice(adjective),
                                 random.choice(noun),
                                 random.choice(verb),
                                 random.choice(ending))
    return(s)

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'))
time.sleep(4)
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))
        else:
            tran = readbuffer.split(':')
            na = readbuffer.split('!')
            tran = tran[2:]
            if not tran:
                irc.send("PRIVMSG #%s :syntax'^translate :search term :<lang>\r\n'" % chan)
            else:
                tr = tran[1].strip()
                try:
                    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', 'http://www.hellboundhackers.org/index.php') )
        resp = opener.open('http://www.hellboundhackers.org/index.php')
        r = resp.read()
        resp.close()
        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"""
        try:
            fin = readbuffer.split(':')
            if not fin:
                irc.send("PRIVMSG #%s :syntax'^google :search term\r\n'" % chan)
            else:
                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"""
        try:
            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])
        except:
            irc.send("PRIVMSG #%s :^+carr for carrier codes\r\n" % chan)