Advertisement
CVSoft

pyirc_acarsdbot

Feb 22nd, 2015
240
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.05 KB | None | 0 0
  1. import msvcrt
  2. import Queue
  3. import socket
  4. import string
  5. import sys
  6. import time
  7.  
  8. ch = "#acars"
  9. server = "irc.efnet.pl"
  10. port = "6667"
  11. irc = socket.socket()
  12. event = ''
  13. nickname = "acarsdbot"
  14.  
  15. def send(arg):
  16.     irc.send(arg+"\r\n")
  17.     time.sleep(0.55)
  18.  
  19. def get_line_content(inp):
  20.     try:
  21.         if string.find(inp, ':', 2) > 0:
  22.             return inp[string.find(inp, ':', 2)+1:]
  23.         else:
  24.             return ''
  25.     except:
  26.         return "--- DEBUG Error in getLineContent"
  27.  
  28. def check_buffer(inp):
  29.     try:
  30.         return (True if inp[-1] in "\r\n" else False)
  31.     except:
  32.         return False
  33.  
  34. def strip_color(s):
  35.     k = string.split(s, '\x03')
  36.     o = ''
  37.     for x in k:
  38.         q = list(x)
  39.         l = 2
  40.         t = 0
  41.         while t < l:
  42.             if len(q) > 0:
  43.                 if q[0] == ',':
  44.                     l = 5
  45.                 if q[0] in "0123456789," and t != 3:
  46.                     q.pop(0)
  47.             t += 1
  48.         o += string.join(q, sep='')
  49.     for x in '\x02\x03\x1d\x1f\x0f':
  50.         o = string.replace(o, x, '')
  51.     return o
  52.  
  53. def split_ctcp(inp):
  54.     msgEnd = [0]
  55.     inp = string.rstrip(inp) + ' '
  56.     msgStart = string.find(inp, '\x01')
  57.     msgEnd[0] = string.find(inp, ' ', msgStart)
  58.     while msgEnd[len(msgEnd)-1] > 2:
  59.         msgEnd.append(string.find(inp, ' ', msgEnd[len(msgEnd)-1]+1))
  60.     msgEnd.pop()
  61.     msgEnd[len(msgEnd)-1] = (string.find(inp, '\x01') \
  62.                              if string.find(inp, '\x01') > msgStart + 1 \
  63.                              else msgEnd[len(msgEnd)-1]-1)
  64.     out = []
  65.     msgEnd.insert(0, msgStart)
  66.     i = 0
  67.     while msgEnd[i] > 2 and i < len(msgEnd)-1:
  68.         out.append(inp[msgEnd[i]+1:msgEnd[i+1]])
  69.         i += 1
  70.     #find sender
  71.     sender = inp[1:string.find(inp, '!', 2)]
  72.     out.insert(1, sender)
  73.     out[0] = string.upper(out[0])
  74.     for i in range(len(out)-1, 0, -1):
  75.         if out[i] == '':
  76.             out.pop(i)
  77.     return out
  78.  
  79. def reply_ctcp(target, req):
  80.     send("NOTICE "+target+" :\x01"+req+"\x01")
  81.  
  82. def send_ctcp(target, req):
  83.     send("PRIVMSG "+target+" :\x01"+req+"\x01")
  84.  
  85. def generate_lines(inp, lc):
  86.     doReset = False
  87.     inter = string.split(inp, "\r")
  88.     out = inter[lc]
  89.     lc += 1
  90.     if lc >= len(inter):
  91.         lc = 0
  92.         doReset = True
  93.     return [out, lc, doReset]
  94.  
  95. def privmsg(target, message):
  96.     send("PRIVMSG "+target+" :"+message)
  97.  
  98. def get_command(inp, command):
  99.     """boolean repr. if inp contains command"""
  100.     try:
  101.         return string.lower((getLine(inp)[2]+' '*(len(command)+3))\
  102.                             [:len(command)]) == command
  103.     except:
  104.         return False
  105.  
  106. # [channel, sender, text]
  107. def get_line(inp):
  108.     try:
  109.         out = [0,0,0,0]
  110.         out[1] = (string.split(inp, ' ')[0])[1:]
  111.         if "!" in out[1]:
  112.             out[1] = (string.split(out[1], '!'))[0]
  113.         out[0] = (string.split(inp, ' ')[2])
  114.         out[2] = inp[string.find(inp,':', 2)+1:]
  115.         out[3] = string.upper(inp[string.find(inp," ")+1:\
  116.                                   string.find(inp," ",string.find(inp," ")+1)])
  117.     except:
  118.         out = ['','error','','']
  119.     return out
  120.  
  121. def format_mode(inp):
  122.     try:
  123.         out = [0,0,0,0]
  124.         out[1] = (string.split(inp, ' ')[0])[1:]
  125.         if "!" in out[1]:
  126.             out[1] = (string.split(out[1], '!'))[0]
  127.         out[0] = (string.split(inp, ' ')[2])
  128.         out[2] = inp[string.find(inp,out[0])+len(out[0])+1:]
  129.         out[3] = string.upper(inp[string.find(inp," ")+1:\
  130.                                   string.find(inp," ",string.find(inp," ")+1)])
  131.     except:
  132.         return ['','','','']
  133.     return out
  134.  
  135. def hostmask(inp):
  136.     out = ['','--- DEBUG Error in hostmask()','']
  137.     if '!' not in inp or '@' not in inp:
  138.         return ['','--- DEBUG Error in hostmask(), missing trigger character',
  139.                 '']
  140.     out[0] = (string.split(inp,"!"))[0]
  141.     out[1] = inp[string.find(inp, '!')+1:string.find(inp, '@')]
  142.     out[2] = (inp[string.find(inp,'@')+1:]).split(' ')[0]
  143.     return out
  144.  
  145. def ping(inp):
  146.     inter = string.split(inp, ' ')
  147.     if string.lower(inter[0]) == "ping":
  148.         send(string.replace(inp, "PING", "PONG", 1))\
  149.  
  150. def connect(nick = "Python0", realname = "Real name", server = "localhost",
  151.             port = 6667):
  152.     if type(port) == str:
  153.         port = int(port)
  154.     tries = 0
  155.     while tries < 3:
  156.         try:
  157.             global irc
  158.             irc = socket.socket()
  159.             irc.setblocking(0)
  160.             irc.settimeout(0.5)
  161.             irc.connect((server, port))
  162.             time.sleep(0.5)
  163.             set_nick(nick)
  164.             send("USER "+nick+" localhost "+server+" :"+realname)
  165.             return True
  166.         except:
  167.             tries += 1
  168.             time.sleep(4)
  169.             if tries == 4:
  170.                 return False
  171.  
  172. def disconnect(partmsg = "Connection closed"):
  173.     global irc
  174.     #print "Closing..."
  175.     send("QUIT :"+partmsg)
  176.     irc.close()
  177.     msvcrt.getch()
  178.  
  179. ### general IRC features
  180.  
  181. def join(channel):
  182.     send("JOIN :"+channel)
  183.  
  184. def part(channel, message = ""):
  185.     send("PART :"+channel+" :"+message)
  186.  
  187. def set_nick(nick):
  188.     send("NICK "+nick)
  189.  
  190. def receive():
  191.     try:
  192.         return irc.recv(2048)
  193.     except:
  194.         return ''
  195.  
  196. ## END StickybotLayer
  197.    
  198. def handle_ctcp(inp):
  199.     if (string.find(inp, '\x01') > 2) and (string.find(inp, "PRIVMSG") > 2):
  200.         ctcp = splitCTCP(inp)
  201.         if "PING" in string.upper(ctcp[0]):
  202.             reply_ctcp(ctcp[1], "PING "+ctcp[2])
  203.         if "VERSION" in string.upper(ctcp[0]):
  204.             reply_ctcp(ctcp[1], "VERSION acarsd Reporter Bot")
  205.  
  206. def check_error():
  207.     if (buff+' '*19)[0:19] == "ERROR :Closing Link: "[0:19]:
  208.         doExit = True
  209.  
  210. def check_nick():
  211.     if string.find(buff, ':', 2) > 11:
  212.         i = string.find(buff, ':', 2)+1
  213.         if (buff+' '*16)[i:i+15] == "Nickname is alr":
  214.             nick = "acarsdcl"+['`','_','^'][random.randrange(3)]
  215.             set_nick(nick)
  216.    
  217. def check_verified_line():
  218.     global doExit
  219.     global buff
  220.     global event
  221.     out = hostmask(buff)
  222.     if "PRIVMSG %s :&version" in buff:
  223.         event = "&event version"
  224.     if ("CVSoft-P2" in out[1] or "CVSoft" in out[1] or "notipa" in out[1]\
  225.         or "kj6psg" in out[1]):## and (out[2] == "cpe-107-185.52.246.socal.res.rr.com" or out[2] == "withg.org"):
  226.         if "PRIVMSG %s :&killbot" % ch in buff:
  227.             doExit = True
  228.             out = get_line(buff)
  229.             privmsg(ch, "killbot initiated by authenticated user")
  230.             event = "&event kill"
  231.         if "PRIVMSG %s :&event" % ch in buff:
  232.             out = get_line(buff)
  233.             event = out[2]
  234.         #here's an example:
  235.         ##if get_command(buff, "&quit"):
  236.         ##    doExit = True
  237.         ##    out = get_line(buff)
  238.         ##    privmsg(out[1], "Exiting IRC...")
  239.  
  240. def dt(inp):
  241.     return int(time.time()-inp)
  242.  
  243. def handle_motd(inp):
  244.     """this handles the MOTD, setting flag wasMOTD to true if it has passed.
  245.       input is the line to check if it is the end of a MOTD"""
  246.     global wasMOTD
  247.     if "End of /MOTD" in inp:
  248.         wasMOTD = True
  249.         join(ch)
  250.  
  251. def build_line_buffer():
  252.     """this code translates buffull into a line"""
  253.     global buff, buffull, lineCounter, doReset
  254.     bufftemp = '\x02'
  255.     while not (check_buffer(buffull)):
  256.         bufftemp = receive()
  257.         if bufftemp == '':
  258.             break
  259.         buffull = buffull+bufftemp
  260.     temp = generate_lines(buffull, lineCounter)
  261.     # generateLines returns [a line, lineCounter, doReset]
  262.     buff = string.strip(temp[0], "\r\n")
  263.     lineCounter = temp[1]
  264.     doReset = temp[2]
  265.     return (buff, doReset)
  266.  
  267. # :irc.colosolutions.net 376 CVPython :End of /MOTD command.
  268.  
  269. def handle_buffer():
  270.     try:
  271.         commands = ["killbot", "&nickchange"]
  272.         global doExit
  273.         r = irc_queue.get(False)
  274.         irc_queue.task_done()
  275.         if len(r) > 0 and r not in commands and "&nickchange" not in r:
  276.             privmsg(ch, r)
  277.         elif r == "killbot":
  278.             doExit = True
  279.         elif "&nickchange " in r and len(r) > 13:
  280.             set_nick(r.split(' ')[1])
  281.     except Queue.Empty:
  282.         return ''
  283.     except:
  284.         return "ERROR "+sys.exc_info()[1]
  285.         raise
  286.  
  287. def handler(buff, doReset):
  288.     global buffull
  289.     handle_motd(buff)
  290.     ping(buff)
  291.     check_nick()
  292.     handle_ctcp(buff)
  293.     check_verified_line()
  294.     time.sleep(0.01)
  295.     if doReset:
  296.         buffull = ''
  297.         return False
  298.     return doReset
  299.  
  300. # connect to IRC
  301. def main():
  302.     connect(nickname, "acarsdbot", server, port)
  303.     global buff, buffull, ch, doExit, irc_queue, lineCounter, wasMOTD
  304.     buff, buffull = '', ''
  305.     doExit, doReset, wasMOTD = False, False, False
  306.     lineCounter = 0
  307.     while not (doExit):
  308.         buff, doReset = build_line_buffer()
  309.         #code goes from here to doReset's redefinition
  310.         if wasMOTD and len(buff)>0:
  311.             pass #print buff
  312.         if wasMOTD:
  313.             handle_buffer()
  314.         doReset = handler(buff, doReset)
  315.     disconnect()
  316.  
  317. irc_queue = Queue.Queue(50)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement