__module_name__ = "Phoney"
__module_author__ = "NovaSquirrel"
__module_description__ = "Misc phenny/skybot theft module"
__module_version__ = "0.05"
import xchat
import random
import re, urllib, urllib2, httplib, urlparse, gzip, StringIO, socket, hashlib
from htmlentitydefs import name2codepoint
#######################################################################################
class Grab(urllib.URLopener):
def __init__(self, *args):
self.version = 'Mozilla/5.0 (Phenny)'
urllib.URLopener.__init__(self, *args)
self.addheader('Referer', 'https://github.com/sbp/phenny')
def http_error_default(self, url, fp, errcode, errmsg, headers):
return urllib.addinfourl(fp, [headers, errcode], "http:" + url)
urllib._urlopener = Grab()
def webget(uri):
if not uri.startswith('http'):
return
u = urllib.urlopen(uri)
bytes = u.read()
u.close()
return bytes
def webhead(uri):
if not uri.startswith('http'):
return
u = urllib.urlopen(uri)
info = u.info()
u.close()
return info
def webpost(uri, query):
if not uri.startswith('http'):
return
data = urllib.urlencode(query)
u = urllib.urlopen(uri, data)
bytes = u.read()
u.close()
return bytes
r_entity = re.compile(r'&([^;\s]+);')
def webentity(match):
value = match.group(1).lower()
if value.startswith('#x'):
return unichr(int(value[2:], 16))
elif value.startswith('#'):
return unichr(int(value[1:]))
elif name2codepoint.has_key(value):
return unichr(name2codepoint[value])
return '[' + value + ']'
def webdecode(html):
return r_entity.sub(entity, html)
r_string = re.compile(r'("(\\.|[^"\\])*")')
r_json = re.compile(r'^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]+$')
env = {'__builtins__': None, 'null': None, 'true': True, 'false': False}
def webjson(text):
"""Evaluate JSON text safely (we hope)."""
if r_json.match(r_string.sub('', text)):
text = r_string.sub(lambda m: 'u' + m.group(1), text)
return eval(text.strip(' \t\r\n'), env, {})
raise ValueError('Input must be serialised JSON.')
#######################################################################################
r_title = re.compile(r'(?ims)
]*>(.*?)')
r_entity = re.compile(r'&[A-Za-z0-9#]+;')
def WebTitle(uri):
if not uri:
return 'I need a URI to give the title of...'
if not ':' in uri:
uri = 'http://' + uri
uri = uri.replace('#!', '?_escaped_fragment_=')
try:
redirects = 0
while True:
headers = {
'Accept': 'text/html',
'User-Agent': 'Mozilla/5.0 (Phoney)'
}
req = urllib2.Request(uri, headers=headers)
u = urllib2.urlopen(req)
info = u.info()
u.close()
if not isinstance(info, list):
status = '200'
else:
status = str(info[1])
info = info[0]
if status.startswith('3'):
uri = urlparse.urljoin(uri, info['Location'])
else: break
redirects += 1
if redirects >= 25:
return 'Too many redirects'
try: mtype = info['content-type']
except:
return "Couldn't get the Content-Type, sorry"
if not (('/html' in mtype) or ('/xhtml' in mtype)):
return "Document isn't HTML"
u = urllib2.urlopen(req)
bytes = u.read(262144)
u.close()
except IOError:
return "Can't connect"
m = r_title.search(bytes)
if m:
title = m.group(1)
title = title.strip()
title = title.replace('\t', ' ')
title = title.replace('\r', ' ')
title = title.replace('\n', ' ')
while ' ' in title:
title = title.replace(' ', ' ')
if len(title) > 200:
title = title[:200] + '[...]'
if title:
try: title.decode('utf-8')
except:
try: title = title.decode('iso-8859-1').encode('utf-8')
except: title = title.decode('cp1252').encode('utf-8')
else: pass
else: title = '[The title is empty.]'
title = title.replace('\n', '')
title = title.replace('\r', '')
return title
else: return 'No title found';
#######################################################################################
def SafeAnswer(answer):
answer = (answer[:420] + '..') if len(answer) > 420 else answer
return answer.replace('\n', '').replace('\r', '')
def Suggest(query):
uri = 'http://websitedev.de/temp-bin/suggest.pl?q='
answer = webget(uri + urllib.quote(query).replace('+', '%2B'))
if answer:
return SafeAnswer(answer)
else:
return 'Sorry, no result.'
def google_ajax(query):
if isinstance(query, unicode):
query = query.encode('utf-8')
uri = 'http://ajax.googleapis.com/ajax/services/search/web'
args = '?v=1.0&safe=off&q=' + urllib.quote(query)
bytes = webget(uri + args)
return webjson(bytes)
def google_search(query, number):
results = google_ajax(query)
try:
result = results['responseData']['results'][number]['unescapedUrl']
try:
result = result + ' "' + WebTitle(result) + '"'
except:
result = result + ' ?'
return result
except IndexError: return None
except TypeError:
print results
return False
def Google4(query, ReplyCmd):
results = google_ajax(query)
try:
xchat.command(ReplyCmd + "1. " + results['responseData']['results'][0]['unescapedUrl']);
xchat.command(ReplyCmd + "2. " + results['responseData']['results'][1]['unescapedUrl']);
xchat.command(ReplyCmd + "3. " + results['responseData']['results'][2]['unescapedUrl']);
xchat.command(ReplyCmd + "4. " + results['responseData']['results'][3]['unescapedUrl']);
except IndexError: return None
except TypeError:
print results
return False
def GoogleSearch(query, number):
uri = google_search(query, number)
if uri:
return uri
elif uri is False: return "Problem getting data from Google."
else: return "No results found for '" + query + "'"
def Python(query):
uri = 'http://tumbolia.appspot.com/py/'
answer = webget(uri + urllib.quote(query))
if answer:
return SafeAnswer(answer)
else: return "Sorry, no result"
def ExtCmdHandler(word, word_eol, userdata):
ReplyCmd = word[1] + " "
NBCmd = word[2]
Nick = word[3]
ArgStart = 0
ArgString = ""
for i in range(4,len(word)):
if word[i] == "-A":
if len(word) >= i+2:
ArgStart = i+1
ArgString = word_eol[i+1]
break
takes_string = ["py","suggest","g","g4","dns","md5","sha1"]
if NBCmd in takes_string:
if ArgStart == 0:
xchat.command(ReplyCmd + "Oops, that command needs parameters after the command name to work")
return xchat.EAT_ALL
if NBCmd == "py": xchat.command(ReplyCmd + Python(ArgString)); return xchat.EAT_ALL
if NBCmd == "suggest": xchat.command(ReplyCmd + Suggest(ArgString)); return xchat.EAT_ALL
if NBCmd == "g": xchat.command(ReplyCmd + GoogleSearch(ArgString, 0)); return xchat.EAT_ALL
if NBCmd == "yt": xchat.command(ReplyCmd + GoogleSearch(ArgString + " site:youtube.com", 0)); return xchat.EAT_ALL
if NBCmd == "title":
try: xchat.command(ReplyCmd + WebTitle(ArgString)); return xchat.EAT_ALL
except: xchat.command(ReplyCmd + "No title?"); return xchat.EAT_ALL
if NBCmd == "g4": Google4(ArgString, ReplyCmd); return xchat.EAT_ALL
if NBCmd == "dns":
try: xchat.command(ReplyCmd + socket.gethostbyname(ArgString)); return xchat.EAT_ALL
except: xchat.command(ReplyCmd + "No IP returned?"); return xchat.EAT_ALL
if NBCmd == "md5": xchat.command(ReplyCmd + hashlib.md5(ArgString).hexdigest()); return xchat.EAT_ALL
if NBCmd == "sha1": xchat.command(ReplyCmd + hashlib.sha1(ArgString).hexdigest()); return xchat.EAT_ALL
return xchat.EAT_NONE
xchat.hook_command("NB_ExtCmd", ExtCmdHandler)