 #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""SET @rownum := 0;
SELECT @rownum := @rownum + 1 AS rank, score, id
FROM score WHERE `id`='1' ORDER BY score DESC LIMIT 0, 1;"""
from __future__ import division
import string
import time
from ircbot import SingleServerIRCBot
from irclib import nm_to_n, irc_lower
from math import ceil, degrees, exp, fabs, floor, fmod, frexp, hypot, ldexp, log, log10, modf, pow, radians, sqrt, pi, e
import math
import datetime
from random import random, randint
import re
import socket
import MySQLdb
import popen2
strip_html_pattern = re.compile(r'<[^>]*>')
password="dcs"
owner="dotcommie"
db = 0
allowfunct="x, b, acos, asin, atan, atan2, ceil, cos, cosh, degrees, exp, fabs, floor, fmod, frexp, hypot, ldexp, log, log10, modf, pow, radians, sin, sinh, sqrt, tan, tanh, pi, int, random, randint, abs, float, e, rsin, rcos, rtan, rasim, racos, ratan"
allowfunct=allowfunct.split(", ")

def sin(num):
    return math.sin(radians(num))
def cos(num):
    return math.cos(radians(num))
def tan(num):
    return math.tan(radians(num))

def asin(num):
    return degrees(math.asin(num))
def acos(num):
    return degrees(math.acos(num))
def atan(num):
    return degrees(math.atan(num))

def rsin(num):
    return math.sin(num)
def rcos(num):
    return math.cos(num)
def rtan(num):
    return math.tan(num)

def rasin(num):
    return math.asin(num)
def racos(num):
    return math.acos(num)
def ratan(num):
    return math.atan(num)



#server="teardrop.ca"
server="irc.mystica.cx"
#server="teardrop.ca"
#server="irc.anduin.net"
#server="ircd.networkessence.net"
#server="irc.ethereal.cc"
#server="irc.celduin.net"
#server="irc.netpratique.fr"

channel="#287"
nickname="dotbot"

def connectMySQL():
    #if globals()['db']:
    #    return globals()['db'].cursor()
    #else:
    #    globals()['db'] = MySQLdb.connect(host='localhost', user='dotbot', passwd='dcs', db='dotbot')
    #    return globals()['db'].cursor()
    globals()['db'] = MySQLdb.connect(host='localhost', user='dotbot', passwd='dcs', db='dotbot')
    return globals()['db'].cursor()

def readMySQL(query):
    cursor = connectMySQL()
    cursor.execute(query)
    print query
    return cursor.fetchall()

def writeMySQL(query):
    cursor = connectMySQL()
    print query
    cursor.execute(query)

def list():
    list=readMySQL("SELECT  `name`, `url` FROM  `streams` WHERE 1 ORDER BY `name`")
    i=0
    output="Current memorized streams: "
    while len(list)>i:
        if len(list[i])>0:
            output=output+list[i][0]+", "
            i+=1
    return output[:-2]+"."

def longUrl(data):
	http="http://"
	http_len=len(http)
	https="https://"
	https_len=len(https)
	ftp="ftp://"
	ftp_len=len(ftp)
	ln="\n"
	space=" "
	allUrls=""
	something=1
	startChar=0
	while something:
		http_char=string.rfind(string.lower(data), http)
		https_char=string.rfind(string.lower(data), https)
		ftp_char=string.rfind(string.lower(data), ftp)
		if http_char>=0 and http_char>https_char and http_char>ftp_char:
			fm=http_char
			ln_char=string.find(string.lower(data), ln, fm)
			space_char=string.find(string.lower(data), space, fm)
			if (ln_char>=0 and space_char<0) or (ln_char>=0 and space_char>=0 and ln_char>space_char):
				sm=ln_char
			elif (space_char>=0 and ln_char<0) or (space_char>=0 and ln_char>=0 and space_char>ln_char):
				sm=space_char
			else:
				sm=len(data)
			if sm-fm>40:
				currentUrl=data[fm:sm]
				currentUrl=tinyUrl(currentUrl)
				if allUrls!="":
					allUrls=currentUrl+", "+allUrls
				else:
					allUrls=currentUrl
			data=data[:fm]
		elif https_char>=0 and https_char>http_char and https_char>ftp_char:
			fm=https_char
			ln_char=string.find(string.lower(data), ln, fm)
			space_char=string.find(string.lower(data), space, fm)
			if (ln_char>=0 and space_char<0) or (ln_char>=0 and space_char>=0 and ln_char>space_char):
				sm=ln_char
			elif (space_char>=0 and ln_char<0) or (space_char>=0 and ln_char>=0 and space_char>ln_char):
				sm=space_char
			else:
				sm=len(data)
			if sm-fm>40:
				currentUrl=data[fm:sm]
				currentUrl=tinyUrl(currentUrl)
				if allUrls!="":
					allUrls=currentUrl+", "+allUrls
				else:
					allUrls=currentUrl
			data=data[:fm]
		elif ftp_char>=0 and ftp_char>http_char and ftp_char>https_char:
			fm=ftp_char
			ln_char=string.find(string.lower(data), ln, fm)
			space_char=string.find(string.lower(data), space, fm)
			if (ln_char>=0 and space_char<0) or (ln_char>=0 and space_char>=0 and ln_char>space_char):
				sm=ln_char
			elif (space_char>=0 and ln_char<0) or (space_char>=0 and ln_char>=0 and space_char>ln_char):
				sm=space_char
			else:
				sm=len(data)
			if sm-fm>40:
				currentUrl=data[fm:sm]
				currentUrl=tinyUrl(currentUrl)
				if allUrls!="":
					allUrls=currentUrl+", "+allUrls
				else:
					allUrls=currentUrl
			data=data[:fm]
		else:
			something=0
	return allUrls




	firstMartchLen=len(firstMatch)
	fc_def_one=string.find(string.lower(alldata), firstMatch)
        lc_def_one=string.find(string.lower(alldata), secondMatch, fc_def_one+firstMartchLen)

def tinyUrl(url):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    ok=1
    try:
        s.connect(("tinyurl.com", 80))
    except:
        ok=0
    if ok==1:
        alldata=""
        data=""
        s.send('GET /create.php?url='+url+' HTTP/1.0\r\n')
        s.send('Accept: */*\r\n')
        s.send('User-Agent: dotBot/0.0.1\r\n')
        s.send('Host: tinyurl.com\r\n')
        s.send('Connection: keep-alive\r\n')
        s.send('Accept-encoding: gzip, deflate\r\n')
        s.send('\r\n')
	data=s.recv(1000)
        while data!="":
            alldata=alldata+data
            data=s.recv(1000)
        s.close()

	firstMatch="characters:\n<blockquote><b>"
	secondMatch="</b><p>"
	firstMatchLen=len(firstMatch)
	fc_def_one=string.find(string.lower(alldata), firstMatch)
        lc_def_one=string.find(string.lower(alldata), secondMatch, fc_def_one+firstMatchLen)
        if fc_def_one!=-1 and fc_def_one!=-1:
            return alldata[fc_def_one+firstMatchLen:lc_def_one]

def lucky(find):
    find=string.replace(find, " ", "+")
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    ok=1
    try:
        s.connect(("www.google.com", 80))
    except:
        ok=0
    if ok==1:
        s.send('GET /search?hl=en&ie=UTF-8&oe=UTF-8&q='+find+'&btnI=I%27m+Feeling+Lucky HTTP/1.0\r\n')
        s.send('Accept: */*\r\n')
        s.send('Referer: http://www.google.com/search?hl=en&ie=UTF-8&oe=UTF-8&q='+find+'&btnI=I%27m+Feeling+Lucky\r\n')
        s.send('User-Agent: dotBot/0.0.1\r\n')
        s.send('Host: www.google.com\r\n')
        s.send('Connection: keep-alive\r\n')
        s.send('Accept-encoding: gzip, deflate\r\n')
        s.send('\r\n')
        data=s.recv(1000)
        s.close()
        data=data.split("\r\n\r\n")
        data=data[0]
        #print data

        sloc_location=string.find(data, "Location: ")+len("Location: ")
        eloc_location=string.find(data, "\r\n", sloc_location)
        if sloc_location-len("Location: ")>0:
            return data[sloc_location:eloc_location]
        else:
            return "No results have been found."
    else:
        return "Cant connect to server"

def url(name):
    name=string.lower(name)
    list=readMySQL("SELECT  `url` FROM  `streams` WHERE 1 AND `name`='"+name+"' LIMIT 0,1")
    if len(list)>0:
        url=list[0][0]
    else:
        url=name

    sloc_http=string.find(url, "http://")
    if sloc_http>=0:
        url=url[len("http://"):]

    sloc_colen=string.find(url, ":")
    sloc_slash=string.find(url, "/")

    if sloc_slash>0:
        path=url[sloc_slash:]
        url=url[:sloc_slash]
    else:
        path="/"

    url=url.split(":", 1)
    if len(url)>1:
        host=url[0]
        port=int(url[1])
    else:
        host=url[0]
        port=80

    return [host, port, path]


def add(name, url, nick):
    name=string.lower(name)
    url=string.lower(url)
    list=readMySQL("SELECT  `name` FROM  `streams` WHERE 1 AND `name`='"+name+"' ORDER BY `name`")
    if len(list)>0:
        writeMySQL("UPDATE `streams` SET `url` = '"+url+"', `nick`= '"+nick+"' WHERE `name` = '"+name+"' LIMIT 1")
    else:
        writeMySQL("INSERT INTO `streams` ( `name` , `url` , `nick` )VALUES ('"+name+"', '"+url+"', '"+nick+"')")

def rem(name):
    name=string.lower(name)
    writeMySQL("DELETE FROM `streams` where `name`='"+name+"' LIMIT 1")

def define(word):
    find=string.replace(word, " ", "+")
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    ok=1
    try:
        s.connect(("dictionary.reference.com", 80))
    except:
        ok=0
    if ok==1:
        alldata=""
        data=""
        s.send('GET //search?q='+word+' HTTP/1.0\r\n')
        s.send('Accept: */*\r\n')
        s.send('Referer: http://dictionary.reference.com/search?q='+word+'\r\n')
        s.send('User-Agent: dotBot/0.0.1\r\n')
        s.send('Host: dictionary.reference.com\r\n')
        s.send('Connection: keep-alive\r\n')
        s.send('Accept-encoding: gzip, deflate\r\n')
        s.send('\r\n')
        data=s.recv(1000)
        while data!="":
            alldata=alldata+data
            data=s.recv(1000)
        s.close()
        print alldata

        fc_def_one=string.find(string.lower(alldata), "<ol><li>")
        lc_def_one=string.find(string.lower(alldata), "</li>", fc_def_one)
        return strip_html_pattern.sub('', alldata[fc_def_one:lc_def_one])
    else:
        return "Cant connect to server"

def resolve(host):
    if string.lower(host[2][-4:])==".pls":
        print "its a .pls"
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        ok=1
        try:
            s.connect((host[0], host[1]))
        except:
            ok=0
        if ok==1:
            s.send('GET '+host[2]+' HTTP/1.0\r\n')
            s.send('Accept: */*\r\n')
            s.send('Accept-Language: en-us\r\n')
            s.send('User-Agent: dotBot/0.0.1\r\n')
            s.send('Connection: keep-alive\r\n')
            s.send('Accept-encoding: gzip, deflate\r\n')
            s.send('\r\n')
            data = s.recv(1000)
            s.send('GET / HTTP/1.0\r\n\r\n')
            data = data+s.recv(1000)
            data=data.split("\r\n\r\n", 1)
            #save data to tuples
            data_tupl=data[0].split("\r\n")
            i=0
            data_dict={}
            while len(data_tupl)>i:
                tmp_tupl=data_tupl[i].split(":", 1)
                if len(tmp_tupl)>1:
                    data_dict[string.lower(tmp_tupl[0])]=string.rstrip(string.lstrip(tmp_tupl[1]))
                else:
                    data_dict[string.lower(tmp_tupl[0])]="null"
                i+=1
            #print data_dict
            data=data[1]
            while len(data) < int(data_dict["content-length"]):
                    data = data+s.recv(100)
            #print len(data)
            s.close()
            data=data.split("\r\n")
            #print data
            i=0
            files=[]
            while i<len(data):
                if string.lower(data[i][0:4])=="file":
                    try:
                        files=files+[data[i].split("=")[1]]
                    except:
                        print "bad format"
                i+=1
            return files
        else:
            return None
    else:
        host="http://"+host[0]+":"+`host[1]`+""+host[2]
        return host

def whatsplaying(host):
    if string.lower(host[2][-4:])==".pls":
        files=resolve(host)
        i=0
        while i<len(files):
            output=icemeta(url(files[i]))
            if output!="Can't connect to host" or output!="Are you sure thats an icy/ice mp3 stream?":
                break
            i+=1
        return output
    else:
        print "its not a pls"
        return icemeta(host)



def icemeta(host):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    ok=1
    try:
        s.connect((host[0], host[1]))
    except:
        ok=0
    if ok==1:
        #send request
        s.send('GET '+host[2]+' HTTP/1.0\r\n')
        s.send('Host: localhost')
        s.send('Accept: */*\r\n')
        s.send('Icy-MetaData: 1\r\n')
        s.send('User-Agent: dotBot/0.0.1\r\n')
        s.send('Connection: keep-alive\r\n')
        s.send('Accept-encoding: gzip, deflate\r\n')
        s.send('\r\n')
        data = s.recv(1000)
        s.send('GET / HTTP/1.0\r\n\r\n')
        data = data+s.recv(1000)
        data=data.split("\r\n\r\n", 1)
        #print data[0]

        #save data to tuples
        data_tupl=data[0].split("\r\n")
        i=0
        data_dict={}
        while len(data_tupl)>i:
            tmp_tupl=data_tupl[i].split(":", 1)
            if len(tmp_tupl)>1:
                data_dict[string.lower(tmp_tupl[0])]=string.rstrip(string.lstrip(tmp_tupl[1]))
            else:
                data_dict[string.lower(tmp_tupl[0])]="null"
            i+=1
        print data_dict

        if data_dict.has_key("icy 200 ok"):
            data=data[1]
            i=0
            while len(data) < int(data_dict["icy-metaint"])*20 and (string.find(data, "';", string.find(data, "StreamTitle='"))<0) and i<100:
                data = data+s.recv(2000)
                i+=1
            print data
            #print len(data)
            sloc_strm_ttl=string.find(data, "StreamTitle='")+len("StreamTitle='")
            eloc_strm_ttl=string.find(data, "'", sloc_strm_ttl)
            sloc_strm_url=string.find(data, "StreamUrl='")+len("StreamUrl='")
            eloc_strm_url=string.find(data, "'", sloc_strm_url)
            if sloc_strm_ttl-len("StreamTitle='")>=0:
                data_dict["streamtitle"]=string.rstrip(string.lstrip(data[sloc_strm_ttl:eloc_strm_ttl]))
            else:
                data_dict["streamtitle"]="title unknown"
            if sloc_strm_url-len("StreamUrl='")>=0:
                data_dict["streamurl"]=string.rstrip(string.lstrip(data[sloc_strm_url:eloc_strm_url]))
            else:
                data_dict["streamurl"]="streamurl unknown"
            if not data_dict.has_key("icy-url"):
                data_dict["icy-url"]="N/A"
            if not data_dict.has_key("icy-name"):
                data_dict["icy-name"]="N/A"
            if not data_dict.has_key("icy-br"):
                data_dict["icy-br"]="N/A"
            #print data_dict
            s.close()
            print data_dict["icy-name"]+"("+data_dict["icy-url"]+"). Currently playing "+data_dict["streamtitle"]+" at "+data_dict["icy-br"]+"Kbps."
            return data_dict["icy-name"]+"("+data_dict["icy-url"]+"). Currently playing "+data_dict["streamtitle"]+" at "+data_dict["icy-br"]+"Kbps."
            #print data
            data=None
        elif data_dict.has_key("http/1.0 200 ok"):
            data=data[1]
            i=0
            while len(data)<1000 and i<100:
                data=data+s.recv(1000)
		i+=1
            print data
            #print len(data)
            sloc_strm_ttl=string.find(data, "TITLE=")+len("TITLE=")
            eloc_strm_ttl=string.find(data, "\x00\x00\x00", sloc_strm_ttl)-1
            sloc_strm_art=string.find(data, "ARTIST=")+len("ARTIST=")
            eloc_strm_art=string.find(data, "\x00\x00\x00", sloc_strm_art)-1
            #print "sloc_strm_ttl:", sloc_strm_ttl, "eloc_strm_art:", eloc_strm_art
            if sloc_strm_ttl-len("TITLE=")>=0:
                data_dict["streamtitle"]=string.rstrip(string.lstrip(data[sloc_strm_ttl:eloc_strm_ttl]))
            else:
                data_dict["streamtitle"]="title unknown"
            if sloc_strm_art-len("ARTIST=")>=0:
                data_dict["artist"]=string.rstrip(string.lstrip(data[sloc_strm_art:eloc_strm_art]))
            else:
                data_dict["artist"]="artist unknown"
            if not data_dict.has_key("ice-url"):
                data_dict["ice-url"]="N/A"
            if not data_dict.has_key("ice-name"):
                data_dict["ice-name"]="N/A"
            if not data_dict.has_key("ice-bitrate"):
                data_dict["ice-bitrate"]="N/A"
            print data_dict
            s.close
            print data_dict["ice-name"]+"("+data_dict["ice-url"]+"). Currently playing "+data_dict["artist"]+" - "+data_dict["streamtitle"]+" at "+data_dict["ice-bitrate"]
            return data_dict["ice-name"]+"("+data_dict["ice-url"]+"). Currently playing "+data_dict["artist"]+" - "+data_dict["streamtitle"]+" at "+data_dict["ice-bitrate"]
            #print data
            data=None
        else:
            s.close()
            return "Are you sure thats an icy/ice mp3 stream?"
            print "Are you sure thats an icy/ice mp3 stream?"
    else:
        return "Can't connect to host"
        print "Can't connect to host"

def eval_math(exp):
    striphex=re.compile('0x[a-fA-F0-9]*')
    exp_exam=striphex.sub('', exp)
    stripbin=re.compile('0b[a-fA-F0-9]*')
    exp_exam=stripbin.sub('', exp)
    exp_exam=re.split('[^a-zA-Z]', exp_exam)
    illigal=0
    i=0
    while len(exp_exam)>i:
        if exp_exam[i]!='':
            ii=0
            while len(allowfunct)>ii:
                if exp_exam[i]==allowfunct[ii]:
                    break
                ii+=1
            if ii==len(allowfunct):
                illigal=1
                break
        i+=1
    if illigal==0:
        error=0
        try:
            output=eval(exp)
        except:
            error=1
        try:
            flooroutput=floor(output)
        except:
            error=1
        if error==0:
            if flooroutput==output:
                return int(output)
            else:
                return output

def scramble(text):
    text=text.split(" ")
    output=""
    i=0
    while i<len(text):
        if len(text[i])<4:
            output=output+" "+text[i]
        else:
            f_char=text[i][0]
            l_char=text[i][-1]
            f_cnt=1
            l_cnt=1
            while len(text[i])-len(f_char)-len(l_char)>0 and not(90>=ord(f_char[0])>=65 or 122>=ord(f_char[0])>=97):
                f_char=text[i][0:f_cnt]
                f_cnt+=1
            while len(text[i])-len(f_char)-len(l_char)>0 and not(90>=ord(l_char[0])>=65 or 122>=ord(l_char[0])>=97):
                l_char=text[i][-l_cnt:]
                l_cnt+=1
            if l_cnt>1:
                l_cnt=l_cnt-1
            middle=text[i][f_cnt:-l_cnt]
            junk=""
            while len(middle)>0:
                remove_char=randint(0, len(middle)-1)
                junk=junk+middle[remove_char]
                if middle[remove_char+1:]>1:
                    middle=middle[0:remove_char]+middle[remove_char+1:]
                else:
                    middle=""
            output=output+" "+f_char+junk+l_char
        i+=1
    return output

def mySQLtoUnix(mysql):
    #mysql=mysql.split(" ", 2)
    #mysql=mysql[0].split("-", 3)+mysql[1].split(":", 3)
    #mysql=[int(mysql[0]), int(mysql[1]), int(mysql[2]), int(mysql[3]), int(mysql[4]), int(mysql[5]), 0, 0, -1]
    #unix=time.mktime(mysql)
    #return int(unix)
    return time.mktime(mysql.utctimetuple())

def UnixtomySQL(unix):
    return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(unix)))


def readscore(nick):
    score=readMySQL("SELECT `score` , `date`, `id` FROM `score` WHERE 1 AND `nick` LIKE '"+nick+"' LIMIT 0 , 1")
    if len(score)>0:
        date=mySQLtoUnix(score[0][1])
        id=int(score[0][2])
        score=int(score[0][0])
        return [nick+"'s score is "+`score`, score, date, id]
    else:
        return ["No such user"]

def score(nick, score):
    data=readscore(nick)
    if len(data)>1:
        if int(time.time())-data[2]>600:
            score=data[1]+score
            writeMySQL("UPDATE `score` SET `score` = '"+`score`+"',`date` = NOW() WHERE `id`='"+`data[3]`+"'  LIMIT 1")
        else:
            return 0
    else:
        score=`0+score`
        writeMySQL("INSERT INTO `score` ( `id` , `nick` , `score` , `date` ) VALUES ( '', '"+nick+"', '"+score+"', NOW() )")
    return 1

def scoreregardless(nick, score):
    data=readscore(nick)
    if len(data)>1:
        score=data[1]+score
        writeMySQL("UPDATE `score` SET `score` = '"+`score`+"',`date` = NOW() WHERE `id`='"+`data[3]`+"'  LIMIT 1")
    else:
        score=`0+score`
        writeMySQL("INSERT INTO `score` ( `id` , `nick` , `score` , `date` ) VALUES ( '', '"+nick+"', '"+score+"', NOW() )")

def greeting(nick):
    greeting=readMySQL("SELECT `greeting` FROM `greetings` WHERE 1 AND `name` LIKE '"+nick+"' ORDER BY RAND( ) LIMIT 0 , 10")
    if len(greeting)>0:
        return greeting[randint(0, len(greeting)-1)][0]
    else:
        return ""
def slashes(inStr):
    inStr=inStr.replace("'", "\\'");
    inStr=inStr.replace("\"", "\\\"");
    inStr=inStr.replace("`", "\\`");
    return inStr

def spell(phrase, l=0):
    outd, ind=popen2.popen2("aspell -a")
    ind.write(phrase+"\n")
    ind.flush()
    data=outd.readline()
    datacomb=""

    while data!="\n":
        datacomb=datacomb+data
        data=outd.readline()
    ind.close()
    outd.close()
    datacomb=datacomb.split("\n")
    i=0
    if l==0:
        addlen=0
        while i<len(datacomb):
            if datacomb[i][0:1]=="&":
                correction=datacomb[i].split(":", 1)[1].split(", ")
                original=datacomb[i].split(":", 1)[0][2:].split(" ")
                phrase=phrase[:int(string.strip(original[2]))+addlen] + string.strip(correction[0]) + phrase[int(string.strip(original[2]))+addlen+len(string.strip(original[0])):]
                addlen=addlen+len(string.strip(correction[0]))-len(string.strip(original[0]))
            i+=1
    else:
        addlen=0
        while i<=len(phrase) and i<len(datacomb):
            if datacomb[i][0:1]=="&":
                correction="["+datacomb[i].split(":", 1)[1][1:]+"]"
                original=datacomb[i].split(":", 1)[0][2:].split(" ")
                phrase=phrase[:int(string.strip(original[2]))+addlen] + original[0]+"-"+ correction + phrase[int(string.strip(original[2]))+addlen+len(string.strip(original[0])):]
                addlen=addlen+len(original[0]+"-"+ correction)-len(string.strip(original[0]))
            i+=1
    return phrase


#MAIN CLASS
class TestBot(SingleServerIRCBot):
    def __init__(self, channel, nickname, server, port=6667):
        SingleServerIRCBot.__init__(self, [(server, port)], nickname, nickname)
        self.channel = channel
        self.start()

    def on_welcome(self, c, e):
        c.join(self.channel)
        print e

    def on_join (self, c, e):
        nick=nm_to_n(e.source())
        greet=greeting(nick)
        if greet!="":
            c.privmsg(channel, greet)


    def on_privmsg(self, c, e):
        nick=nm_to_n(e.source())
        if string.lower(nick)==owner:
            if e.arguments()[0].split(" ", 1)[0]==password:
                c.privmsg(channel, e.arguments()[0].split(" ", 1)[1])
            else:
                c.privmsg(channel, "<"+nick+">"+scramble(e.arguments()[0].split(" ", 1)[1]))
        else:
            c.privmsg(channel, "<"+nick+">"+scramble(e.arguments()[0]))
    def on_privnotice(self, c, e):
        print e
    def on_numeric_events(self, c, e):
        print e

    def on_pubmsg(self, c, e):
        nick=nm_to_n(e.source())
        print "<"+nick+"> "+`e.arguments()[0]`
        cmdin=e.arguments()[0].split(" ", 1)
        if string.lower(nick)=="kaiobot":
            scoreregardless("kaiobot", -1)
        elif string.lower(nick)=="mina":
            if (string.find(string.lower(e.arguments()[0]), "love")>=0) and (string.find(string.lower(e.arguments()[0]), "dotbot")>=0):
                c.privmsg(channel, "Mina! I love you.")



        if cmdin[0]=="playing?":
            if len(cmdin)>1:
                if cmdin[1]=="yourmom" or cmdin[1]=="yourm0m":
                    c.privmsg(channel, "I am playing your fucking mom mother fucker")
                else:
                    c.privmsg(channel, whatsplaying(url(slashes(cmdin[1]))))
            else:
                c.privmsg(channel, list())
        elif cmdin[0]=="add?":
            if len(cmdin)>1:
                args=cmdin[1].split(" ",1)
                if len(args)==2:
                    add(slashes(args[0]), slashes(args[1]), nick)
                else:
                    c.privmsg(channel, "Improper syntax! add? streamName Url")
            else:
                c.privmsg(channel, "Improper syntax! add? streamName Url")
        elif cmdin[0]=="rem?" or cmdin[0]=="del?" or cmdin[0]=="remove?" or cmdin[0]=="delete?" or cmdin[0]=="rm?":
            if len(cmdin)>1:
                args=cmdin[1].split(" ",1)
                if len(args)==1:
                    rem(slashes(args[0]))
                else:
                    c.privmsg(channel, "Improper syntax! del? streamName")
            else:
                c.privmsg(channel, "Improper syntax! del? streamName")
        elif cmdin[0]=="find?":
            if len(cmdin)>1:
                c.privmsg(channel, lucky(e.arguments()[0][string.find(e.arguments()[0], " ")+1:]))
            else:
                c.privmsg(channel, "Improper syntax! find? key word")
        elif cmdin[0]=="spell?":
            if len(cmdin)>1:
                c.privmsg(channel, spell(e.arguments()[0][7:]))
            else:
                c.privmsg(channel, "Improper syntax! spell? phrase")
        elif cmdin[0]=="espell?":
            if len(cmdin)>1:
                c.privmsg(channel, spell(e.arguments()[0][8:], 1))
            else:
                c.privmsg(channel, "Improper syntax! espell? phrase")
        elif cmdin[0]=="define?":
            if len(cmdin)>1:
                c.privmsg(channel, define(e.arguments()[0][8:]))
            else:
                c.privmsg(channel, "Improper syntax! define? word")
        elif cmdin[0]=="score?":
            if len(cmdin)>1:
                param=cmdin[1].split(" ")
                if len(param)>1:
                    if param[1]=="+":
                        if score(slashes(param[0]), +1)==0:
                            c.privmsg(channel, "Adding too soon.")
                    elif param[1]=="-":
                        if score(slashes(param[0]), -1)==0:
                            c.privmsg(channel, "Subtracting too soon.")
                else:
                    c.privmsg(channel, readscore(slashes(param[0]))[0] )
            else:
                c.privmsg(channel, "Improper syntax! score? nickname || score? nickname + || score? nickname -")
        elif cmdin[0]=="url?":
            if len(cmdin)>1:
                c.privmsg(channel, "The url for stream "+cmdin[1]+" is "+`resolve(url(slashes(cmdin[1])))`)
            else:
                c.privmsg(channel, "Url look-up usage: resolve? streamname or resolve? http://whatever.com/playlist.pls")
        elif cmdin[0]=="scramble?":
            if len(cmdin)>1:
                c.privmsg(channel, scramble(e.arguments()[0][10:])[1:])
            else:
                c.privmsg(channel, "Improper syntax! scramble? phrase")
        elif cmdin[0]=="help?":
            c.privmsg(channel, "The following commands are avalible: url?, add?, del?, playing?, find?, scramble?, score?, spell?, espell?.")
        else:
            math_out=eval_math(e.arguments()[0])
            if math_out!=None:
                c.privmsg(channel, math_out)
            url_out=longUrl(e.arguments()[0])
            if url_out!="":
                c.privmsg(channel, url_out)



def main():
    bot = TestBot(channel, nickname, server, 6667)
    bot.start()

if __name__ == "__main__":
    main()

