PEP8 compliance (only whitespace changes)
This commit is contained in:
parent
94d9fd22f0
commit
5ea26b8ff7
7
bot.py
7
bot.py
|
@ -20,7 +20,9 @@ import yaml
|
|||
|
||||
os.chdir(sys.path[0]) # do stuff relative to the installation directory
|
||||
|
||||
|
||||
class Bot(object):
|
||||
|
||||
def __init__(self, nick, channel, network):
|
||||
self.nick = nick
|
||||
self.channel = channel
|
||||
|
@ -32,6 +34,7 @@ print 'Loading plugins'
|
|||
|
||||
plugin_mtimes = {}
|
||||
|
||||
|
||||
def reload_plugins():
|
||||
|
||||
if not hasattr(bot, 'plugs'):
|
||||
|
@ -79,7 +82,9 @@ bot.persist_dir = os.path.abspath('persist')
|
|||
|
||||
print 'Running main loop'
|
||||
|
||||
|
||||
class Input(object):
|
||||
|
||||
def __init__(self, raw, prefix, command,
|
||||
params, nick, user, host, paraml, msg):
|
||||
self.raw = raw
|
||||
|
@ -99,7 +104,9 @@ class Input(object):
|
|||
else:
|
||||
self.chan = ""
|
||||
|
||||
|
||||
class FakeBot(object):
|
||||
|
||||
def __init__(self, bot, input, func):
|
||||
self.bot = bot
|
||||
self.persist_dir = bot.persist_dir
|
||||
|
|
|
@ -2,6 +2,7 @@ import re
|
|||
|
||||
import hook
|
||||
|
||||
|
||||
@hook.sieve
|
||||
def sieve_suite(bot, input, func, args):
|
||||
events = args.get('events', ['PRIVMSG'])
|
||||
|
@ -16,7 +17,8 @@ def sieve_suite(bot, input, func, args):
|
|||
args.setdefault('prefix', True)
|
||||
|
||||
if args.get('prefix', True):
|
||||
hook = (r'^(?:[.!]|' if input.chan != input.nick else r'^(?:[.!]?|') + bot.nick +r'[:,]*\s*)' + hook
|
||||
hook = (r'^(?:[.!]|' if input.chan != input.nick else r'^(?:[.!]?|') \
|
||||
+ bot.nick +r'[:,]*\s*)' + hook
|
||||
|
||||
input.re = re.match(hook, input.msg, flags=re.I)
|
||||
if input.re is None:
|
||||
|
|
12
irc.py
12
irc.py
|
@ -8,6 +8,7 @@ import Queue
|
|||
|
||||
queue = Queue.Queue
|
||||
|
||||
|
||||
def decode(txt):
|
||||
for codec in ('utf-8', 'iso-8859-1', 'shift_jis', 'cp1252'):
|
||||
try:
|
||||
|
@ -16,8 +17,10 @@ def decode(txt):
|
|||
continue
|
||||
return txt.decode('utf-8', 'ignore')
|
||||
|
||||
|
||||
class crlf_tcp(asynchat.async_chat):
|
||||
"Handles tcp connections that consist of utf-8 lines ending with crlf"
|
||||
|
||||
def __init__(self, host, port):
|
||||
asynchat.async_chat.__init__(self)
|
||||
self.set_terminator('\r\n')
|
||||
|
@ -35,13 +38,13 @@ class crlf_tcp(asynchat.async_chat):
|
|||
asyncore.loop()
|
||||
|
||||
def handle_connect(self):
|
||||
thread.start_new_thread(self.queue_read_loop,())
|
||||
thread.start_new_thread(self.queue_read_loop, ())
|
||||
|
||||
def queue_read_loop(self):
|
||||
while True:
|
||||
line = self.oqueue.get().splitlines()[0][:500]
|
||||
print ">>> %r" % line
|
||||
self.push(line.encode('utf-8','replace')+'\r\n')
|
||||
self.push(line.encode('utf-8', 'replace') + '\r\n')
|
||||
|
||||
def collect_incoming_data(self, data):
|
||||
self.buffer += data
|
||||
|
@ -56,19 +59,20 @@ irc_noprefix_re = re.compile(r'()(.*?) (.*)')
|
|||
irc_param_re = re.compile(r'(?:^|(?<= ))(:.*|[^ ]+)')
|
||||
irc_netmask_re = re.compile(r':?([^!@]*)!?([^@]*)@?(.*)')
|
||||
|
||||
|
||||
class irc(object):
|
||||
"handles the IRC protocol"
|
||||
#see the docs/ folder for more information on the protocol
|
||||
|
||||
def __init__(self, network, nick, port=6667):
|
||||
self.conn = crlf_tcp(network, port)
|
||||
thread.start_new_thread(self.conn.run,())
|
||||
thread.start_new_thread(self.conn.run, ())
|
||||
self.out = queue() #responses from the server are placed here
|
||||
# format: [rawline, prefix, command, params,
|
||||
# nick, user, host, paramlist, msg]
|
||||
self.nick(nick)
|
||||
self.cmd("USER", ["skybot v0.01", "0", "bot"])
|
||||
thread.start_new_thread(self.parse_loop,())
|
||||
thread.start_new_thread(self.parse_loop, ())
|
||||
|
||||
def parse_loop(self):
|
||||
while True:
|
||||
|
|
|
@ -4,8 +4,13 @@ import htmlentitydefs
|
|||
import re
|
||||
|
||||
import hook
|
||||
|
||||
|
||||
########### from http://effbot.org/zone/re-sub.htm#unescape-html #############
|
||||
|
||||
|
||||
def unescape(text):
|
||||
|
||||
def fixup(m):
|
||||
text = m.group(0)
|
||||
if text[:2] == "&#":
|
||||
|
@ -24,12 +29,15 @@ def unescape(text):
|
|||
except KeyError:
|
||||
pass
|
||||
return text # leave as is
|
||||
|
||||
return re.sub("&#?\w+;", fixup, text)
|
||||
|
||||
##############################################################################
|
||||
|
||||
languages = 'ja fr de ko ru zh'.split();
|
||||
languages = 'ja fr de ko ru zh'.split()
|
||||
language_pairs = zip(languages[:-1], languages[1:])
|
||||
|
||||
|
||||
def goog_trans(text, slang, tlang):
|
||||
req_url = 'http://ajax.googleapis.com/ajax/services/language/translate' \
|
||||
'?v=1.0&q=%s&langpair=%s'
|
||||
|
@ -38,10 +46,11 @@ def goog_trans(text, slang, tlang):
|
|||
parsed = yaml.load(json)
|
||||
if not 200 <= parsed['responseStatus'] < 300:
|
||||
print parsed
|
||||
raise IOError, 'error with the translation server: %d: %s' % (
|
||||
parsed['responseStatus'], '')
|
||||
raise IOError('error with the translation server: %d: %s' % (
|
||||
parsed['responseStatus'], ''))
|
||||
return unescape(parsed['responseData']['translatedText'])
|
||||
|
||||
|
||||
def babel_gen(inp):
|
||||
for language in languages:
|
||||
inp = inp.encode('utf8')
|
||||
|
@ -50,6 +59,7 @@ def babel_gen(inp):
|
|||
print language, trans, inp
|
||||
yield language, trans, inp
|
||||
|
||||
|
||||
@hook.command
|
||||
def babel(inp):
|
||||
try:
|
||||
|
@ -57,6 +67,7 @@ def babel(inp):
|
|||
except IOError, e:
|
||||
return e
|
||||
|
||||
|
||||
@hook.command
|
||||
def babelext(inp):
|
||||
try:
|
||||
|
|
|
@ -9,6 +9,7 @@ import hook
|
|||
BUFFER_SIZE = 5000
|
||||
MAX_STEPS = 1000000
|
||||
|
||||
|
||||
@hook.command
|
||||
def bf(input):
|
||||
"""Runs a Brainfuck program."""
|
||||
|
@ -37,7 +38,6 @@ def bf(input):
|
|||
steps = 0
|
||||
memory = [0] * BUFFER_SIZE #initial memory area
|
||||
rightmost = 0
|
||||
|
||||
output = "" #we'll save the output here
|
||||
|
||||
# the main program loop:
|
||||
|
@ -61,7 +61,7 @@ def bf(input):
|
|||
if len(output) > 500:
|
||||
break
|
||||
elif c == ',':
|
||||
memory[mp] = random.randint(1,255)
|
||||
memory[mp] = random.randint(1, 255)
|
||||
elif c == '[':
|
||||
if memory[mp] == 0:
|
||||
ip = brackets[ip]
|
||||
|
|
|
@ -2,6 +2,7 @@ import urllib
|
|||
|
||||
import hook
|
||||
|
||||
|
||||
@hook.command('god')
|
||||
@hook.command
|
||||
def bible(inp):
|
||||
|
|
|
@ -12,20 +12,22 @@ valid_diceroll_re = re.compile(r'^[+-]?(\d+|\d*d\d+)([+-](\d+|\d*d\d+))*$')
|
|||
sign_re = re.compile(r'[+-]?(?:\d*d)?\d+')
|
||||
split_re = re.compile(r'([\d+-]*)d?(\d*)')
|
||||
|
||||
|
||||
def nrolls(count, n):
|
||||
"roll an n-sided die count times"
|
||||
if n < 2: #it's a coin
|
||||
if count < 5000:
|
||||
return sum(random.randint(0,1) for x in xrange(count))
|
||||
return sum(random.randint(0, 1) for x in xrange(count))
|
||||
else: #fake it
|
||||
return int(random.normalvariate(.5*count,(.75*count)**.5))
|
||||
return int(random.normalvariate(.5*count, (.75*count)**.5))
|
||||
else:
|
||||
if count < 5000:
|
||||
return sum(random.randint(1,n) for x in xrange(count))
|
||||
return sum(random.randint(1, n) for x in xrange(count))
|
||||
else: #fake it
|
||||
return int(random.normalvariate(.5*(1+n)*count,
|
||||
(((n+1)*(2*n+1)/6.-(.5*(1+n))**2)*count)**.5))
|
||||
|
||||
|
||||
@hook.command
|
||||
def dice(input):
|
||||
".dice <diceroll> - simulates dicerolls, e.g. .dice 2d20-d5+4 roll 2 " \
|
||||
|
@ -43,7 +45,7 @@ def dice(input):
|
|||
if side == "":
|
||||
sum += int(count)
|
||||
else:
|
||||
count = int(count) if count not in " +-" else 1
|
||||
count = int(count) if count not in" +-" else 1
|
||||
side = int(side)
|
||||
try:
|
||||
if count > 0:
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
import hook
|
||||
|
||||
|
||||
#@hook.command
|
||||
def goonsay(bot, input):
|
||||
bot.say(' __________ /')
|
||||
|
|
|
@ -2,14 +2,17 @@ import hashlib
|
|||
|
||||
import hook
|
||||
|
||||
|
||||
@hook.command
|
||||
def md5(input):
|
||||
return hashlib.md5(input).hexdigest()
|
||||
|
||||
|
||||
@hook.command
|
||||
def sha1(input):
|
||||
return hashlib.sha1(input).hexdigest()
|
||||
|
||||
|
||||
@hook.command
|
||||
def hash(input):
|
||||
return ', '.join(x + ": " + getattr(hashlib, x)(input).hexdigest()
|
||||
|
|
|
@ -3,27 +3,32 @@ def _isfunc(x):
|
|||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _hook_add(func, add):
|
||||
if not hasattr(func, '_skybot_hook'):
|
||||
func._skybot_hook = []
|
||||
func._skybot_hook.append(add)
|
||||
|
||||
|
||||
def _make_sig(f):
|
||||
return f.func_code.co_filename, f.func_name, f.func_code.co_firstlineno
|
||||
|
||||
|
||||
def sieve(func):
|
||||
if func.func_code.co_argcount != 4:
|
||||
raise ValueError, \
|
||||
'sieves must take 4 arguments: (bot, input, func, args)'
|
||||
raise ValueError(
|
||||
'sieves must take 4 arguments: (bot, input, func, args)')
|
||||
_hook_add(func, ['sieve', (_make_sig(func), func)])
|
||||
return func
|
||||
|
||||
|
||||
def command(func=None, hook=None, **kwargs):
|
||||
args = {}
|
||||
|
||||
def command_wrapper(func):
|
||||
if func.func_code.co_argcount not in (1, 2):
|
||||
raise ValueError, \
|
||||
'commands must take 1 or 2 arguments: (inp) or (bot, input)'
|
||||
raise ValueError(
|
||||
'commands must take 1 or 2 arguments: (inp) or (bot, input)')
|
||||
args.setdefault('name', func.func_name)
|
||||
args.setdefault('hook', args['name'] + r'(?:\s+|$)(.*)')
|
||||
_hook_add(func, ['command', (_make_sig(func), func, args)])
|
||||
|
@ -39,12 +44,13 @@ def command(func=None, hook=None, **kwargs):
|
|||
else:
|
||||
return command_wrapper(func)
|
||||
|
||||
|
||||
def event(arg=None, **kwargs):
|
||||
args = kwargs
|
||||
|
||||
def event_wrapper(func):
|
||||
if func.func_code.co_argcount != 2:
|
||||
raise ValueError, \
|
||||
'events must take 2 arguments: (bot, input)'
|
||||
raise ValueError('events must take 2 arguments: (bot, input)')
|
||||
args['name'] = func.func_name
|
||||
args['prefix'] = False
|
||||
args.setdefault('events', '*')
|
||||
|
|
|
@ -6,6 +6,7 @@ posts everything buttbot says to the iambuttbot twitter account
|
|||
import urllib
|
||||
import hook
|
||||
|
||||
|
||||
@hook.command(hook=r'(.*)', prefix=False, ignorebots=False)
|
||||
def iambuttbot(bot, input):
|
||||
if input.nick.lower() != 'buttbot':
|
||||
|
|
|
@ -16,13 +16,16 @@ log_fds = {} # '%(net)s %(chan)s' : (filename, fd)
|
|||
|
||||
timestamp_format = '%H:%M:%S'
|
||||
|
||||
|
||||
def get_log_filename(dir, network, chan):
|
||||
return os.path.join(dir, 'log', gmtime('%Y'), network,
|
||||
gmtime('%%s.%m-%d.log') % chan).lower()
|
||||
|
||||
|
||||
def gmtime(format):
|
||||
return time.strftime(format, time.gmtime())
|
||||
|
||||
|
||||
def get_log_fd(dir, network, chan):
|
||||
fn = get_log_filename(dir, network, chan)
|
||||
cache_key = '%s %s' % (network, chan)
|
||||
|
@ -40,6 +43,7 @@ def get_log_fd(dir, network, chan):
|
|||
|
||||
return fd
|
||||
|
||||
|
||||
@hook.event(ignorebots=False)
|
||||
def log(bot, input):
|
||||
".remember <word> <data> -- maps word to data in the memory"
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
import hook
|
||||
|
||||
|
||||
@hook.event('KICK INVITE')
|
||||
def rejoin(bot, input):
|
||||
print input.command, input.inp
|
||||
|
|
|
@ -5,10 +5,11 @@ import hook
|
|||
|
||||
re_lineends = re.compile(r'[\r\n]*')
|
||||
|
||||
|
||||
@hook.command
|
||||
def py(input):
|
||||
res = urllib.urlopen("http://eval.appspot.com/eval?statement=%s" %
|
||||
urllib.quote(input.strip(),safe='')).readlines()
|
||||
urllib.quote(input.strip(), safe='')).readlines()
|
||||
if len(res) == 0:
|
||||
return
|
||||
res[0] = re_lineends.split(res[0])[0]
|
||||
|
|
|
@ -13,6 +13,7 @@ import hook
|
|||
lock = thread.allocate_lock()
|
||||
memory = {}
|
||||
|
||||
|
||||
def load_memory(filename, mtimes={}):
|
||||
if not os.path.exists(filename):
|
||||
return {}
|
||||
|
@ -22,15 +23,18 @@ def load_memory(filename, mtimes={}):
|
|||
return dict((x.split(None, 1)[0].lower(), x.strip()) for x in
|
||||
codecs.open(filename, 'r', 'utf-8'))
|
||||
|
||||
|
||||
def save_memory(filename, memory):
|
||||
out = codecs.open(filename, 'w', 'utf-8')
|
||||
out.write('\n'.join(sorted(memory.itervalues())))
|
||||
out.flush()
|
||||
out.close()
|
||||
|
||||
|
||||
def make_filename(dir, chan):
|
||||
return os.path.join(dir, 'memory')
|
||||
|
||||
|
||||
@hook.command
|
||||
def remember(bot, input):
|
||||
".remember <word> <data> -- maps word to data in the memory"
|
||||
|
@ -53,6 +57,7 @@ def remember(bot, input):
|
|||
memory[filename][low] = input.inp.strip()
|
||||
save_memory(filename, memory[filename])
|
||||
|
||||
|
||||
@hook.command
|
||||
def forget(bot, input):
|
||||
".forget <word> -- forgets the mapping that word had"
|
||||
|
@ -74,6 +79,7 @@ def forget(bot, input):
|
|||
del memory[filename][low]
|
||||
save_memory(filename, memory[filename])
|
||||
|
||||
|
||||
@hook.command(hook='\?(.+)', prefix=False)
|
||||
def question(bot, input):
|
||||
"?<word> -- shows what data is associated with word"
|
||||
|
|
|
@ -8,6 +8,7 @@ from lxml import etree
|
|||
|
||||
import hook
|
||||
|
||||
|
||||
@hook.command
|
||||
def twitter(bot, input):
|
||||
".twitter <user> - gets most recent tweet from <user>"
|
||||
|
|
|
@ -3,6 +3,7 @@ import urllib
|
|||
|
||||
import hook
|
||||
|
||||
|
||||
@hook.command('u')
|
||||
@hook.command
|
||||
def urban(inp):
|
||||
|
|
|
@ -13,6 +13,7 @@ import hook
|
|||
lock = thread.allocate_lock()
|
||||
stalk = {}
|
||||
|
||||
|
||||
def load_stalk(filename, mtimes={}):
|
||||
if not os.path.exists(filename):
|
||||
return {}
|
||||
|
@ -22,12 +23,14 @@ def load_stalk(filename, mtimes={}):
|
|||
return dict(x.strip().split(None, 1) for x in
|
||||
codecs.open(filename, 'r', 'utf-8'))
|
||||
|
||||
|
||||
def save_stalk(filename, houses):
|
||||
out = codecs.open(filename, 'w', 'utf-8')
|
||||
out.write('\n'.join('%s %s' % x for x in sorted(houses.iteritems()))) #_heh_
|
||||
out.write('\n'.join('%s %s' % x for x in sorted(houses.iteritems()))) #heh
|
||||
out.flush()
|
||||
out.close()
|
||||
|
||||
|
||||
@hook.command
|
||||
def weather(bot, input):
|
||||
".weather <location> -- queries the google weather API for weather data"
|
||||
|
@ -45,7 +48,7 @@ def weather(bot, input):
|
|||
if not loc:
|
||||
return weather.__doc__
|
||||
|
||||
data = urllib.urlencode({'weather':loc.encode('utf-8')})
|
||||
data = urllib.urlencode({'weather': loc.encode('utf-8')})
|
||||
url = 'http://www.google.com/ig/api?' + data
|
||||
w = etree.parse(url).find('weather')
|
||||
|
||||
|
|
|
@ -12,10 +12,12 @@ search_url = api_prefix + "?action=opensearch&search=%s&format=xml"
|
|||
|
||||
paren_re = re.compile('\s*\(.*\)$')
|
||||
|
||||
|
||||
@hook.command(hook='w(\s+.*|$)')
|
||||
@hook.command
|
||||
def wiki(query):
|
||||
'''.w/.wiki <phrase> -- gets first sentence of wikipedia article on <phrase>'''
|
||||
'''.w/.wiki <phrase> -- gets first sentence of wikipedia ''' \
|
||||
'''article on <phrase>'''
|
||||
|
||||
if not query.strip():
|
||||
return wiki.__doc__
|
||||
|
|
|
@ -6,6 +6,7 @@ import hook
|
|||
|
||||
locale.setlocale(locale.LC_ALL, "")
|
||||
|
||||
|
||||
def ytdata(id):
|
||||
url = 'http://gdata.youtube.com/feeds/api/videos/' + id
|
||||
x = etree.parse(url)
|
||||
|
@ -31,6 +32,7 @@ def ytdata(id):
|
|||
|
||||
youtube_re = re.compile(r'.*youtube.*v=([-_a-z0-9]+)', flags=re.IGNORECASE)
|
||||
|
||||
|
||||
#@hook.command(hook=r'(.*)', prefix=False)
|
||||
def youtube(inp):
|
||||
m = youtube_re.match(inp)
|
||||
|
|
Loading…
Reference in New Issue