Advertisement
NovaYoshi

Phoney

Jul 17th, 2013
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.63 KB | None | 0 0
  1. __module_name__ = "Phoney"
  2. __module_author__ = "NovaSquirrel"
  3. __module_description__ = "Misc phenny/skybot theft module"
  4. __module_version__ = "0.05"
  5.  
  6. import xchat
  7. import random
  8. import re, urllib, urllib2, httplib, urlparse, gzip, StringIO, socket, hashlib
  9. from htmlentitydefs import name2codepoint
  10.  
  11. #######################################################################################
  12.  
  13. class Grab(urllib.URLopener):
  14.    def __init__(self, *args):
  15.       self.version = 'Mozilla/5.0 (Phenny)'
  16.       urllib.URLopener.__init__(self, *args)
  17.       self.addheader('Referer', 'https://github.com/sbp/phenny')
  18.    def http_error_default(self, url, fp, errcode, errmsg, headers):
  19.       return urllib.addinfourl(fp, [headers, errcode], "http:" + url)
  20. urllib._urlopener = Grab()
  21.  
  22. def webget(uri):
  23.    if not uri.startswith('http'):
  24.       return
  25.    u = urllib.urlopen(uri)
  26.    bytes = u.read()
  27.    u.close()
  28.    return bytes
  29.  
  30. def webhead(uri):
  31.    if not uri.startswith('http'):
  32.       return
  33.    u = urllib.urlopen(uri)
  34.    info = u.info()
  35.    u.close()
  36.    return info
  37.  
  38. def webpost(uri, query):
  39.    if not uri.startswith('http'):
  40.       return
  41.    data = urllib.urlencode(query)
  42.    u = urllib.urlopen(uri, data)
  43.    bytes = u.read()
  44.    u.close()
  45.    return bytes
  46.  
  47. r_entity = re.compile(r'&([^;\s]+);')
  48.  
  49. def webentity(match):
  50.    value = match.group(1).lower()
  51.    if value.startswith('#x'):
  52.       return unichr(int(value[2:], 16))
  53.    elif value.startswith('#'):
  54.       return unichr(int(value[1:]))
  55.    elif name2codepoint.has_key(value):
  56.       return unichr(name2codepoint[value])
  57.    return '[' + value + ']'
  58.  
  59. def webdecode(html):
  60.    return r_entity.sub(entity, html)
  61.  
  62. r_string = re.compile(r'("(\\.|[^"\\])*")')
  63. r_json = re.compile(r'^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]+$')
  64. env = {'__builtins__': None, 'null': None, 'true': True, 'false': False}
  65.  
  66. def webjson(text):
  67.    """Evaluate JSON text safely (we hope)."""
  68.    if r_json.match(r_string.sub('', text)):
  69.       text = r_string.sub(lambda m: 'u' + m.group(1), text)
  70.       return eval(text.strip(' \t\r\n'), env, {})
  71.    raise ValueError('Input must be serialised JSON.')
  72. #######################################################################################
  73. r_title = re.compile(r'(?ims)<title[^>]*>(.*?)</title\s*>')
  74. r_entity = re.compile(r'&[A-Za-z0-9#]+;')
  75.  
  76. def WebTitle(uri):
  77.    if not uri:
  78.       return 'I need a URI to give the title of...'
  79.  
  80.    if not ':' in uri:
  81.       uri = 'http://' + uri
  82.    uri = uri.replace('#!', '?_escaped_fragment_=')
  83.  
  84.    try:
  85.       redirects = 0
  86.       while True:
  87.          headers = {
  88.             'Accept': 'text/html',
  89.             'User-Agent': 'Mozilla/5.0 (Phoney)'
  90.          }
  91.          req = urllib2.Request(uri, headers=headers)
  92.          u = urllib2.urlopen(req)
  93.          info = u.info()
  94.          u.close()
  95.  
  96.          if not isinstance(info, list):
  97.             status = '200'
  98.          else:
  99.             status = str(info[1])
  100.             info = info[0]
  101.          if status.startswith('3'):
  102.             uri = urlparse.urljoin(uri, info['Location'])
  103.          else: break
  104.  
  105.          redirects += 1
  106.          if redirects >= 25:
  107.             return 'Too many redirects'
  108.  
  109.       try: mtype = info['content-type']
  110.       except:
  111.          return "Couldn't get the Content-Type, sorry"
  112.       if not (('/html' in mtype) or ('/xhtml' in mtype)):
  113.          return "Document isn't HTML"
  114.  
  115.       u = urllib2.urlopen(req)
  116.       bytes = u.read(262144)
  117.       u.close()
  118.  
  119.    except IOError:
  120.       return "Can't connect"
  121.  
  122.    m = r_title.search(bytes)
  123.    if m:
  124.       title = m.group(1)
  125.       title = title.strip()
  126.       title = title.replace('\t', ' ')
  127.       title = title.replace('\r', ' ')
  128.       title = title.replace('\n', ' ')
  129.       while '  ' in title:
  130.          title = title.replace('  ', ' ')
  131.       if len(title) > 200:
  132.          title = title[:200] + '[...]'
  133.  
  134.       if title:
  135.          try: title.decode('utf-8')
  136.          except:
  137.             try: title = title.decode('iso-8859-1').encode('utf-8')
  138.             except: title = title.decode('cp1252').encode('utf-8')
  139.          else: pass
  140.       else: title = '[The title is empty.]'
  141.  
  142.       title = title.replace('\n', '')
  143.       title = title.replace('\r', '')
  144.       return title
  145.    else: return 'No title found';
  146.  
  147. #######################################################################################
  148.  
  149. def SafeAnswer(answer):
  150.     answer = (answer[:420] + '..') if len(answer) > 420 else answer
  151.     return answer.replace('\n', '').replace('\r', '')
  152.  
  153. def Suggest(query):
  154.     uri = 'http://websitedev.de/temp-bin/suggest.pl?q='
  155.     answer = webget(uri + urllib.quote(query).replace('+', '%2B'))
  156.     if answer:
  157.         return SafeAnswer(answer)
  158.     else:
  159.         return 'Sorry, no result.'
  160.  
  161. def google_ajax(query):
  162.    if isinstance(query, unicode):
  163.       query = query.encode('utf-8')
  164.    uri = 'http://ajax.googleapis.com/ajax/services/search/web'
  165.    args = '?v=1.0&safe=off&q=' + urllib.quote(query)
  166.    bytes = webget(uri + args)
  167.    return webjson(bytes)
  168.  
  169. def google_search(query, number):
  170.    results = google_ajax(query)
  171.    try:
  172.      result = results['responseData']['results'][number]['unescapedUrl']
  173.      try:
  174.        result = result + ' "' + WebTitle(result) + '"'
  175.      except:
  176.        result = result + ' ?'
  177.      return result
  178.    except IndexError: return None
  179.    except TypeError:
  180.       print results
  181.       return False
  182.  
  183. def Google4(query, ReplyCmd):
  184.    results = google_ajax(query)
  185.    try:
  186.      xchat.command(ReplyCmd + "1. " + results['responseData']['results'][0]['unescapedUrl']);
  187.      xchat.command(ReplyCmd + "2. " + results['responseData']['results'][1]['unescapedUrl']);
  188.      xchat.command(ReplyCmd + "3. " + results['responseData']['results'][2]['unescapedUrl']);
  189.      xchat.command(ReplyCmd + "4. " + results['responseData']['results'][3]['unescapedUrl']);
  190.    except IndexError: return None
  191.    except TypeError:
  192.       print results
  193.       return False
  194.  
  195. def GoogleSearch(query, number):
  196.    uri = google_search(query, number)
  197.    if uri:
  198.       return uri
  199.    elif uri is False: return "Problem getting data from Google."
  200.    else: return "No results found for '" + query + "'"
  201.  
  202. def Python(query):
  203.    uri = 'http://tumbolia.appspot.com/py/'
  204.    answer = webget(uri + urllib.quote(query))
  205.    if answer:
  206.      return SafeAnswer(answer)
  207.    else: return "Sorry, no result"
  208.  
  209. def ExtCmdHandler(word, word_eol, userdata):
  210.     ReplyCmd = word[1] + " "
  211.     NBCmd = word[2]
  212.     Nick = word[3]
  213.  
  214.     ArgStart = 0
  215.     ArgString = ""
  216.     for i in range(4,len(word)):
  217.         if word[i] == "-A":
  218.             if len(word) >= i+2:
  219.                 ArgStart = i+1
  220.                 ArgString = word_eol[i+1]
  221.                 break
  222.  
  223.     takes_string = ["py","suggest","g","g4","dns","md5","sha1"]
  224.     if NBCmd in takes_string:
  225.         if ArgStart == 0:
  226.             xchat.command(ReplyCmd + "Oops, that command needs parameters after the command name to work")
  227.             return xchat.EAT_ALL
  228.     if NBCmd == "py": xchat.command(ReplyCmd + Python(ArgString)); return xchat.EAT_ALL
  229.     if NBCmd == "suggest": xchat.command(ReplyCmd + Suggest(ArgString)); return xchat.EAT_ALL
  230.     if NBCmd == "g": xchat.command(ReplyCmd + GoogleSearch(ArgString, 0)); return xchat.EAT_ALL
  231.     if NBCmd == "title": xchat.command(ReplyCmd + WebTitle(ArgString)); return xchat.EAT_ALL
  232.     if NBCmd == "g4": Google4(ArgString, ReplyCmd); return xchat.EAT_ALL
  233.     if NBCmd == "dns": xchat.command(ReplyCmd + socket.gethostbyname(ArgString)); return xchat.EAT_ALL
  234.     if NBCmd == "md5": xchat.command(ReplyCmd + hashlib.md5(ArgString).hexdigest()); return xchat.EAT_ALL
  235.     if NBCmd == "sha1": xchat.command(ReplyCmd + hashlib.sha1(ArgString).hexdigest()); return xchat.EAT_ALL
  236.  
  237.     return xchat.EAT_NONE
  238.  
  239. xchat.hook_command("NB_ExtCmd", ExtCmdHandler)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement