PEP8 compliance + clean dotnetpad

This commit is contained in:
Ryan Hitchman 2010-02-28 19:32:41 -07:00
parent ab8f316eb9
commit 253881f4b4
35 changed files with 223 additions and 174 deletions

10
bot.py
View File

@ -7,7 +7,7 @@ import time
sys.path += ['plugins'] # so 'import hook' works without duplication
sys.path += ['lib']
os.chdir(sys.path[0] or '.') # do stuff relative to the installation directory
os.chdir(sys.path[0] or '.') # do stuff relative to the install directory
class Bot(object):
@ -30,12 +30,12 @@ bot.conns = {}
try:
for name, conf in bot.config['connections'].iteritems():
if conf.get('ssl'):
bot.conns[name] = SSLIRC(conf['server'], conf['nick'],
port=conf.get('port', 6667), channels=conf['channels'], conf=conf,
bot.conns[name] = SSLIRC(conf['server'], conf['nick'], conf=conf,
port=conf.get('port', 6667), channels=conf['channels'],
ignore_certificate_errors=conf.get('ignore_cert', True))
else:
bot.conns[name] = IRC(conf['server'], conf['nick'],
port=conf.get('port', 6667), channels=conf['channels'], conf=conf)
bot.conns[name] = IRC(conf['server'], conf['nick'], conf=conf,
port=conf.get('port', 6667), channels=conf['channels'])
except Exception, e:
print 'ERROR: malformed config file', Exception, e
sys.exit()

View File

@ -2,9 +2,11 @@ import inspect
import json
import os
def load():
return
def save(conf):
json.dump(conf, open('config', 'w'), sort_keys=True, indent=2)
@ -26,6 +28,7 @@ if not os.path.exists('config'):
bot.config = json.load(open('config'))
bot._config_mtime = os.stat('config').st_mtime
def config():
# reload config from file if file has changed
if bot._config_mtime != os.stat('config').st_mtime:

View File

@ -1,6 +1,7 @@
import os
import sqlite3
def get_db_connection(server, name='skybot.%s.db'):
"returns an sqlite3 connection to a persistent database"
filename = os.path.join(bot.persist_dir, name % server)

View File

@ -7,6 +7,7 @@ import Queue
from ssl import wrap_socket, CERT_NONE, CERT_REQUIRED, SSLError
def decode(txt):
for codec in ('utf-8', 'iso-8859-1', 'shift_jis', 'cp1252'):
try:
@ -15,6 +16,7 @@ def decode(txt):
continue
return txt.decode('utf-8', 'ignore')
class crlf_tcp(object):
"Handles tcp connections that consist of utf-8 lines ending with crlf"
@ -81,6 +83,7 @@ class crlf_tcp(object):
sent = self.socket.send(self.obuffer)
self.obuffer = self.obuffer[sent:]
class crlf_ssl_tcp(crlf_tcp):
"Handles ssl tcp connetions that consist of utf-8 lines ending with crlf"
def __init__(self, host, port, ignore_cert_errors, timeout=300):
@ -89,7 +92,8 @@ class crlf_ssl_tcp(crlf_tcp):
def create_socket(self):
return wrap_socket(crlf_tcp.create_socket(self), server_side=False,
cert_reqs = [CERT_REQUIRED, CERT_NONE][self.ignore_cert_errors])
cert_reqs=CERT_NONE if self.ignore_cert_errors else
CERT_REQUIRED)
def recv_from_socket(self, nbytes):
return self.socket.read(nbytes)
@ -119,7 +123,7 @@ class IRC(object):
self.port = port
self.nick = nick
self.out = Queue.Queue() #responses from the server are placed here
self.out = Queue.Queue() # responses from the server are placed here
# format: [rawline, prefix, command, params,
# nick, user, host, paramlist, msg]
self.connect()
@ -146,7 +150,7 @@ class IRC(object):
self.connect()
continue
if msg.startswith(":"): #has a prefix
if msg.startswith(":"): # has a prefix
prefix, command, params = irc_prefix_rem(msg).groups()
else:
prefix, command, params = irc_noprefix_rem(msg).groups()
@ -178,13 +182,14 @@ class IRC(object):
def cmd(self, command, params=None):
if params:
params[-1] = ':' + params[-1]
self.send(command+' '+' '.join(params))
self.send(command + ' ' + ' '.join(params))
else:
self.send(command)
def send(self, str):
self.conn.oqueue.put(str)
class FakeIRC(IRC):
def __init__(self, server, nick, port=6667, channels=[], conf={}, fn=""):
self.channels = channels
@ -193,7 +198,7 @@ class FakeIRC(IRC):
self.port = port
self.nick = nick
self.out = Queue.Queue() #responses from the server are placed here
self.out = Queue.Queue() # responses from the server are placed here
self.f = open(fn, 'rb')
@ -207,7 +212,7 @@ class FakeIRC(IRC):
print "!!!!DONE READING FILE!!!!"
return
if msg.startswith(":"): #has a prefix
if msg.startswith(":"): # has a prefix
prefix, command, params = irc_prefix_rem(msg).groups()
else:
prefix, command, params = irc_noprefix_rem(msg).groups()
@ -226,6 +231,7 @@ class FakeIRC(IRC):
def cmd(self, command, params=None):
pass
class SSLIRC(IRC):
def __init__(self, server, nick, port=6667, channels=[], conf={},
ignore_certificate_errors=True):

View File

@ -1,6 +1,7 @@
import thread
import traceback
class Input(dict):
def __init__(self, conn, raw, prefix, command, params,
nick, user, host, paraml, msg):

View File

@ -10,12 +10,14 @@ if 'mtimes' not in globals():
if 'lastfiles' not in globals():
lastfiles = set()
def format_plug(plug, lpad=0, width=40):
out = ' ' * lpad + '%s:%s:%s' % (plug[0])
if len(plug) == 3 and 'hook' in plug[2]:
out += '%s%s' % (' ' * (width - len(out)), plug[2]['hook'])
return out
def reload(init=False):
if init:
bot.plugs = collections.defaultdict(lambda: [])
@ -64,7 +66,7 @@ def reload(init=False):
bot.plugs[name] = filter(lambda x: x[0][0] != filename, data)
for obj in namespace.itervalues():
if hasattr(obj, '_skybot_hook'): #check for magic
if hasattr(obj, '_skybot_hook'): # check for magic
for type, data in obj._skybot_hook:
bot.plugs[type] += [data]

View File

@ -7,8 +7,8 @@ from util import hook
########### from http://effbot.org/zone/re-sub.htm#unescape-html #############
def unescape(text):
def unescape(text):
def fixup(m):
text = m.group(0)
if text[:2] == "&#":

View File

@ -21,8 +21,8 @@ def bf(inp):
program = re.sub('[^][<>+-.,]', '', inp)
# create a dict of brackets pairs, for speed later on
brackets={}
open_brackets=[]
brackets = {}
open_brackets = []
for pos in range(len(program)):
if program[pos] == '[':
open_brackets.append(pos)
@ -40,9 +40,9 @@ def bf(inp):
ip = 0 # instruction pointer
mp = 0 # memory pointer
steps = 0
memory = [0] * BUFFER_SIZE #initial memory area
memory = [0] * BUFFER_SIZE # initial memory area
rightmost = 0
output = "" #we'll save the output here
output = "" # we'll save the output here
# the main program loop:
while ip < len(program):
@ -57,7 +57,7 @@ def bf(inp):
rightmost = mp
if mp >= len(memory):
# no restriction on memory growth!
memory.extend([0]*BUFFER_SIZE)
memory.extend([0] * BUFFER_SIZE)
elif c == '<':
mp = mp - 1 % len(memory)
elif c == '.':

View File

@ -3,6 +3,7 @@ import random
from util import hook
@hook.command
def choose(inp):
".choose <choice1>, <choice2>, ... <choicen> -- makes a decision"

View File

@ -17,15 +17,15 @@ split_re = re.compile(r'([\d+-]*)d?(\d*)', re.I)
def nrolls(count, n):
"roll an n-sided die count times"
if n < 2: #it's a coin
if n < 2: # it's a coin
if count < 5000:
return sum(random.randint(0, 1) for x in xrange(count))
else: #fake it
else: # fake it
return int(random.normalvariate(.5*count, (.75*count)**.5))
else:
if count < 5000:
return sum(random.randint(1, n) for x in xrange(count))
else: #fake it
else: # fake it
return int(random.normalvariate(.5*(1+n)*count,
(((n+1)*(2*n+1)/6.-(.5*(1+n))**2)*count)**.5))

View File

@ -64,33 +64,34 @@ def cs(snippet):
'using System.Linq; '
'using System.Collections.Generic; '
'using System.Text; '
'%(class)s')
'%s')
class_template = ('public class Default '
'{ '
' %(main)s '
'{'
' %s '
'}')
main_template = ('public static void Main(String[] args) '
'{ '
' %(snippet)s '
'{'
' %s '
'}')
# There are probably better ways to do the following, but I'm feeling lazy
# if no main is found in the snippet, then we use the template with Main in it
# if no main is found in the snippet, use the template with Main in it
if 'public static void Main' not in snippet:
code = main_template % { 'snippet': snippet }
code = class_template % { 'main': code }
code = file_template % { 'class' : code }
code = main_template % snippet
code = class_template % code
code = file_template % code
# if Main is found, check for class and see if we need to use the classed template
# if Main is found, check for class and see if we need to use the
# classed template
elif 'class' not in snippet:
code = class_template % { 'main': snippet }
code = file_template % { 'class' : code }
code = class_template % snippet
code = file_template % code
return 'Error using dotnetpad'
# if we found class, then use the barebones template
else:
code = file_template % { 'class' : snippet }
code = file_template % snippet
return dotnetpad('csharp', code)

View File

@ -3,6 +3,7 @@ import urlparse
from util import hook
@hook.command
def down(inp):
'''.down <url> -- checks to see if the site is down'''

View File

@ -1,6 +1,7 @@
from util import hook
from pycparser.cdecl import explain_c_declaration
@hook.command
def explain(inp):
".explain <c expression> -- gives an explanation of C expression"

View File

@ -5,6 +5,7 @@ from lxml import html
from util import hook
@hook.command
def calc(inp):
'''.calc <term> -- returns Google Calculator result'''
@ -22,7 +23,7 @@ def calc(inp):
if m is None:
return "could not calculate " + inp
result = m.group(1).replace("<font size=-2> </font>",",")
result = result.replace(" &#215; 10<sup>","E").replace("</sup>","")
result = result.replace("\xa0",",")
result = m.group(1).replace("<font size=-2> </font>", ",")
result = result.replace(" &#215; 10<sup>", "E").replace("</sup>", "")
result = result.replace("\xa0", ",")
return result

View File

@ -27,8 +27,8 @@ def gis(inp):
parsed['responseStatus'], ''))
if not parsed['responseData']['results']:
return 'no images found'
return random.choice(parsed['responseData']['results'][:10]
)['unescapedUrl'] # squares is dumb
return random.choice(parsed['responseData']['results'][:10]) \
['unescapedUrl'] # squares is dumb
@hook.command

View File

@ -1,6 +1,8 @@
from util import hook
#Scaevolus: factormystic if you commit a re-enabled goonsay I'm going to revoke your commit access
#Scaevolus: factormystic if you commit a re-enabled goonsay I'm
# going to revoke your commit access
#@hook.command
def goonsay(inp, say=None):
say(' __________ /')

View File

@ -1,5 +1,6 @@
from util import hook
@hook.command
def help(inp, bot=None, pm=None):
".help [command] -- gives a list of commands/help for a command"

View File

@ -11,12 +11,14 @@ def rejoin(inp, paraml=[], conn=None):
if paraml[0].lower() in conn.channels:
conn.join(paraml[0])
#join channels when invited
@hook.event('INVITE')
def invite(inp, command='', conn=None):
if command == 'INVITE':
conn.join(inp)
#join channels when server says hello & identify bot
@hook.event('004')
def onjoin(inp, conn=None):

View File

@ -8,7 +8,7 @@ from util import hook
@hook.command
def mtg(inp):
".mtg <card> -- gets information about Magic the Gathering card <card name>"
".mtg <name> -- gets information about Magic the Gathering card <name>"
url = 'http://magiccards.info/query.php?cardname='
url += urllib2.quote(inp, safe='')
h = html.parse(url)

View File

@ -12,11 +12,13 @@ def add_quote(db, chan, nick, add_nick, msg):
(chan, nick, add_nick, msg, now))
db.commit()
def get_quotes_by_nick(db, chan, nick):
return db.execute("select time, nick, msg from quote where deleted!=1 "
"and chan=? and lower(nick)=lower(?) order by time",
(chan, nick)).fetchall()
def get_quotes_by_chan(db, chan):
return db.execute("select time, nick, msg from quote where deleted!=1 "
"and chan=? order by time", (chan,)).fetchall()
@ -27,6 +29,7 @@ def format_quote(q, num, n_quotes):
return "[%d/%d] %s <%s> %s" % (num, n_quotes,
time.strftime("%Y-%m-%d", time.gmtime(ctime)), nick, msg)
@hook.command('q')
@hook.command
def quote(inp, nick='', chan='', db=None):

View File

@ -21,4 +21,3 @@ def reg(inp):
return reg.__doc__
return '|'.join(re.findall(query[0], query[1]))

View File

@ -4,11 +4,13 @@ remember.py: written by Scaevolus 2010
from util import hook
def db_init(db):
db.execute("create table if not exists memory(chan, word, data, nick,"
" primary key(chan, word))")
db.commit()
def get_memory(db, chan, word):
row = db.execute("select data from memory where chan=? and word=lower(?)",
(chan, word)).fetchone()
@ -17,6 +19,7 @@ def get_memory(db, chan, word):
else:
return None
@hook.command
def remember(inp, nick='', chan='', db=None):
".remember <word> <data> -- maps word to data in the memory"
@ -37,6 +40,7 @@ def remember(inp, nick='', chan='', db=None):
else:
return 'done.'
@hook.command
def forget(inp, chan='', db=None):
".forget <word> -- forgets the mapping that word had"
@ -57,6 +61,7 @@ def forget(inp, chan='', db=None):
else:
return "I don't know about that."
@hook.command(hook='\?(.+)', prefix=False)
def question(inp, chan='', say=None, db=None):
"?<word> -- shows what data is associated with word"

View File

@ -6,6 +6,7 @@ import json
from util import hook
@hook.command
def suggest(inp, inp_unstripped=''):
".suggest [#n] <phrase> -- gets a random/the nth suggested google search"

View File

@ -5,6 +5,7 @@ import time
from util import hook, timesince
def get_tells(db, user_to, chan):
return db.execute("select user_from, message, time from tell where"
" user_to=lower(?) and chan=? order by time",
@ -37,6 +38,7 @@ def tellinput(bot, input):
db.commit()
input.reply(reply)
@hook.command
def showtells(inp, nick='', chan='', pm=None, db=None):
".showtells -- view all pending tell messages (sent in PM)."
@ -58,6 +60,7 @@ def showtells(inp, nick='', chan='', pm=None, db=None):
(nick, chan))
db.commit()
@hook.command
def tell(inp, nick='', chan='', db=None):
".tell <nick> <message> -- relay <message> to <nick> when <nick> is around"

View File

@ -26,10 +26,12 @@ def unescape_xml(string):
history = []
history_max_size = 250
@hook.command
def twitter(inp):
".twitter <user>/<user> <n>/<id>/#<hashtag>/@<user> -- gets last/<n>th tweet from"\
"<user>/gets tweet <id>/gets random tweet with #<hashtag>/gets replied tweet from @<user>"
".twitter <user>/<user> <n>/<id>/#<hashtag>/@<user> -- gets last/<n>th "\
"tweet from <user>/gets tweet <id>/gets random tweet with #<hashtag>/"\
"gets replied tweet from @<user>"
if not inp:
return twitter.__doc__
@ -89,7 +91,7 @@ def twitter(inp):
try:
xml = urllib2.urlopen(url).read()
except urllib2.HTTPError, e:
errors = {400 : 'bad request (ratelimited?)',
errors = {400: 'bad request (ratelimited?)',
401: 'tweet is private',
404: 'invalid user/id',
500: 'twitter is broken',
@ -125,7 +127,8 @@ def twitter(inp):
reply_name = tweet.find(reply_name).text
reply_id = tweet.find(reply_id).text
reply_user = tweet.find(reply_user).text
if reply_name is not None and (reply_id is not None or reply_user is not None):
if reply_name is not None and (reply_id is Not None or
reply_user is not None):
add_reply(reply_name, reply_id if reply_id else -1)
time = strftime('%Y-%m-%d %H:%M:%S',

View File

@ -10,6 +10,7 @@ expiration_period = 60 * 60 * 24 # 1 day
ignored_urls = [urlnorm.normalize("http://google.com")]
def db_connect(bot, server):
"check to see that our db has the the seen table and return a dbection."
db = bot.get_db_connection(server)
@ -18,18 +19,21 @@ def db_connect(bot, server):
db.commit()
return db
def insert_history(db, chan, url, nick):
now = time.time()
db.execute("insert into urlhistory(chan, url, nick, time) "
"values(?,?,?,?)", (chan, url, nick, time.time()))
db.commit()
def get_history(db, chan, url):
db.execute("delete from urlhistory where time < ?",
(time.time() - expiration_period,))
return db.execute("select nick, time from urlhistory where "
"chan=? and url=? order by time desc", (chan, url)).fetchall()
def nicklist(nicks):
nicks = sorted(dict(nicks), key=unicode.lower)
if len(nicks) <= 2:
@ -37,6 +41,7 @@ def nicklist(nicks):
else:
return ', and '.join((', '.join(nicks[:-1]), nicks[-1]))
def format_reply(history):
if not history:
return
@ -61,6 +66,7 @@ def format_reply(history):
return "that url has been posted %s in the past %s by %s (%s)." % (ordinal,
hour_span, nicklist(history), last)
@hook.command(hook=r'(.*)', prefix=False)
def urlinput(inp, nick='', chan='', server='', reply=None, bot=None):
m = url_re.search(inp.encode('utf8'))

View File

@ -3,6 +3,7 @@ import thread
import traceback
import Queue
def _isfunc(x):
if type(x) == type(_isfunc):
return True
@ -37,6 +38,7 @@ def _hook_add(func, add, name=''):
args.append(0) # means kwargs present
func._skybot_args = args
def _make_sig(f):
return f.func_code.co_filename, f.func_name, f.func_code.co_firstlineno

View File

@ -1,8 +1,8 @@
# Copyright (c) Django Software Foundation and individual contributors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
@ -15,20 +15,21 @@
# to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"AND
#ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
#WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
#DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
#ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
#(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
#LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
#ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
#(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
#SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import datetime
import time
def timesince(d, now=None):
"""
Takes two datetime objects and returns the time between d and now
@ -86,11 +87,12 @@ def timesince(d, now=None):
count2 = (since - (seconds * count)) // seconds2
if count2 != 0:
if count2 == 1:
s += ', %(number)d %(type)s' % {'number': count2, 'type': name2[0]}
s += ', %d %s' % (count2, name2[0])
else:
s += ', %(number)d %(type)s' % {'number': count2, 'type': name2[1]}
s += ', %d %s' % (count2, name2[1])
return s
def timeuntil(d, now=None):
"""
Like timesince, but returns a string measuring the time until

View File

@ -8,7 +8,7 @@ from util import hook
@hook.command
def weather(inp, nick='', server='', reply=None, db=None):
".weather <location> [dontsave] -- queries the google weather API for weather data"
".weather <location> [dontsave] -- gets weather data from Google"
loc = inp

View File

@ -26,7 +26,8 @@ def wiki(inp):
q = search_url % (urllib2.quote(inp, safe=''))
request = urllib2.Request(q)
request.add_header('User-Agent', 'Skybot/1.0 http://bitbucket.org/Scaevolus/skybot/')
request.add_header('User-Agent',
'Skybot/1.0 http://bitbucket.org/Scaevolus/skybot/')
opener = urllib2.build_opener()
xml = opener.open(request).read()
x = etree.fromstring(xml)
@ -54,7 +55,7 @@ def wiki(inp):
if title.lower() not in desc.lower():
desc = title + desc
desc = re.sub('\s+', ' ', desc).strip() #remove excess spaces
desc = re.sub('\s+', ' ', desc).strip() # remove excess spaces
if len(desc) > 300:
desc = desc[:300] + '...'

View File

@ -5,6 +5,7 @@ from lxml import html
from util import hook
@hook.command
@hook.command('wa')
def wolframalpha(inp):
@ -40,7 +41,7 @@ def wolframalpha(inp):
if results:
pod_texts.append(heading + ' ' + '|'.join(results))
ret = '. '.join(pod_texts) # first pod is the input
ret = '. '.join(pod_texts)
if not pod_texts:
return 'no results'

View File

@ -17,6 +17,7 @@ url = base_url + 'videos/%s?v=2&alt=jsonc'
search_api_url = base_url + 'videos?v=2&alt=jsonc&max-results=1&q=%s'
video_url = "http://youtube.com/watch?v=%s"
def get_video_description(vid_id):
j = json.load(urllib2.urlopen(url % vid_id))
@ -39,7 +40,6 @@ def get_video_description(vid_id):
out += ' - rated \x02%.2f/5.0\x02 (%d)' % (j['rating'],
j['ratingCount'])
if 'viewCount' in j:
out += ' - \x02%s\x02 views' % locale.format('%d',
j['viewCount'], 1)