My IRC bot

This is an irc bot I wrote. I first started out with a BotNet for my security class, but decided to make more commands and turn it into something useful. It was interesting and fun to learn about the protocol. It’s an easy protocol pick up on, and can be very useful.

There are 5 irc commands needed to make a connection, set up user info, and navigate the channels. These commands are:

  • NICK your_nickname
  • USER your_nickname user info :Your “real” name here
  • JOIN #Channel_name
  • PART #current_channel_name
  • PONG :sender
  • PRIVMSG #Channel_name :message

NICK is for your nick name obviously. USER is the user information; I’m not fully sure what is supposed to be in the arguments. I always use random words. I do know your name should be there. JOIN is to join a channel, the # is needed to denote the name of the channel. PART is to leave the specified channel. PRIVMSG is to send messages to the channel your on. The code gives example how to privet message a user in a channel; found in ^translate command.

My bots features/commands:

  • Translate between 91 different languages; uses xgoogle lib
  • Pull quotes from a website; that website is hellboundhackers
  • Google search, returns first 5 links; also xgoogle
  • Time
  • Random sentence; something I wrote for my wife a while back
  • Crude immature humor; why not?
  • Have the bot say what I tell it to say; pretty standard for an IRC bot
  • About the bot; intentions and whatnot
  • Text message a cellphone (requires Gmail account); NEW! Google helps me out once again. This time I use my gmail account to send SMS messages to cell phones. I know AT&T works; Ntelos also works. I tried Verizon with no success… I’ve yet to try all the other carriers found http://www.mutube.com/projects/open-email-to-sms/gateway-list/

This bot doesn’t use RegEx to parse for things, so all the splitting and stripping is kinda messy. I user the re module in one command, but that was because I pulled it from script I wrote to solve the programming challenges on http://www.hellboundhackers.org/ The rest uses command denotation. I denote mine with a “^'” right before the command to make a place to split from. Some commands have arguments that need to be passed,such as the phone number and carrier to send the text to, or the term to be searched by google. These are denoted using “:” or “#”.

Even if you’re not after writing an IRC bot, it show some examples on interacting with the web. The ^quote command shows cookie handling and user-agent management. The text message command could be used in other code to send you a text when you get in email. Or maybe just text you the email you received.

Requirements:

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

os.system("color 0a")
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"
"NTELOS" : "@pcs.ntelos.com"}

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

def sendText(body, to = "3045553333@txt.att.net", username = "user_name@gmail.com", password = "userpass123"):
    """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():
    """generates a random sentence"""
    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', 'panty', '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','vomited','fell','burned',
    'smiled','spied','slept','drove','fucked','skipped','ran','walked',
    'died','laughed','sang','tripped','frowned','slipped','committed murder']

    adjective = ['beautiful','black','old','ugly','wet','red','loud','blue','dry',
    'quiet','purple','hairy','mediocre','yellow','bald','melancholy',
    'white','smooth','bright','clear','rough','dark','round','sexual',
    'heavy','square','sexy','smelly','triangular','angry','disgusting',
    '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 = 'TechBotV3'
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 who 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 :\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"
    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%;'>(.*)",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 "^sentence" in readbuffer:
        """calls random sentence"""
        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 , sentance, test, whoareyou, boobs, google :, quote,\r\n" % chan)
        irc.send("PRIVMSG #%s :translate : : **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)
Advertisements

About Tech B.

I am currently employed as a tech support rep for Frontier DSL internet and Dail-Up service. If you live on the East Coast and have Frontier or the old Verizon, you may have spoken with me at one point. I do side jobs programming and building things for people. I know Python better than any language in my toolbox. I can also develop Android Apps, which are Java based. Other languages include C , VB/VB.NET, some C#, PBASIC, Batch, Javascript, and some PHP. I love microcontrollers and interfacing with the outside world. I am currently working with Arduinos, which are amazing. Also I can work with the Basic Stamp family of microcontrollers; future development includes FPGA and embedded Linux. I was going to school, but have financial issues at the moment that are keeping me from the books. I plan on going back in the next couple semesters and finishing up my Associates in IT, then perusing a BS in computer science.
This entry was posted in Programming Python. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s