Format everything to pep8 guidelines

This commit is contained in:
Dabo Ross 2013-11-12 07:06:06 +01:00
parent cd4b65de3d
commit 99fe34a0b1
33 changed files with 142 additions and 107 deletions

View file

@ -1,5 +1,6 @@
from util import hook
import os, sys
import os
import sys
import re
import json
import time
@ -127,6 +128,7 @@ def restart(inp, nick=None, conn=None, bot=None):
args.insert(0, sys.executable)
os.execv(sys.executable, args)
@hook.command(autohelp=False, permissions=["botcontrol"])
def clearlogs(inp, input=None):
"""clearlogs -- Clears the bots log(s)."""

View file

@ -13,6 +13,7 @@ with open("plugins/data/flirts.txt") as f:
flirts = [line.strip() for line in f.readlines()
if not line.startswith("//")]
@hook.command
def lart(inp, action=None, nick=None, conn=None, notice=None):
"""lart <user> -- LARTs <user>."""

View file

@ -7,10 +7,10 @@ def bitcoin(inp, message=None):
data = http.get_json("https://data.mtgox.com/api/2/BTCUSD/money/ticker")
data = data['data']
ticker = {
'buy': data['buy']['display_short'].encode('ascii','ignore'),
'high': data['high']['display_short'].encode('ascii','ignore'),
'low': data['low']['display_short'].encode('ascii','ignore'),
'vol': data['vol']['display_short'].encode('ascii','ignore'),
'buy': data['buy']['display_short'].encode('ascii', 'ignore'),
'high': data['high']['display_short'].encode('ascii', 'ignore'),
'low': data['low']['display_short'].encode('ascii', 'ignore'),
'vol': data['vol']['display_short'].encode('ascii', 'ignore'),
}
message("Current: \x0307{!s}\x0f - High: \x0307{!s}\x0f"
" - Low: \x0307{!s}\x0f - Volume: {!s}".format(ticker['buy'],ticker['high'],ticker['low'],ticker['vol']))
" - Low: \x0307{!s}\x0f - Volume: {!s}".format(ticker['buy'], ticker['high'], ticker['low'], ticker['vol']))

View file

@ -10,9 +10,10 @@ def encode(key, clear):
enc.append(enc_c)
return base64.urlsafe_b64encode("".join(enc))
def decode(key, enc):
dec = []
enc = base64.urlsafe_b64decode(enc.encode('ascii','ignore'))
enc = base64.urlsafe_b64decode(enc.encode('ascii', 'ignore'))
for i in range(len(enc)):
key_c = key[i % len(key)]
dec_c = chr((256 + ord(enc[i]) - ord(key_c)) % 256)
@ -26,7 +27,7 @@ def cypher(inp):
passwd = inp.split(" ")[0]
inp = " ".join(inp.split(" ")[1:])
return encode(passwd,inp)
return encode(passwd, inp)
@hook.command
@ -34,4 +35,4 @@ def decypher(inp):
"""decypher <pass> <string> -- Decyphers <string> with <password>."""
passwd = inp.split(" ")[0]
inp = " ".join(inp.split(" ")[1:])
return decode(passwd,inp)
return decode(passwd, inp)

View file

@ -12,7 +12,7 @@ import hashlib
# <http://stackoverflow.com/questions/12524994/encrypt-decrypt-using-pycrypto-aes-256>
BS = AES.block_size
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[0:-ord(s[-1])]
unpad = lambda s: s[0:-ord(s[-1])]
# helper functions to encrypt and encode a string with AES and base64
encode_aes = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
@ -56,7 +56,7 @@ def encrypt(inp, bot=None, db=None, notice=None):
key = PBKDF2(password, salt)
# generate the IV and encode it to store in the database
iv = Random.new().read(AES.block_size);
iv = Random.new().read(AES.block_size)
iv_encoded = base64.b64encode(iv)
# create the AES cipher and encrypt/encode the text with it

View file

@ -20,8 +20,7 @@ def googleimage(inp):
raise IOError('error searching for images: {}: {}'.format(parsed['responseStatus'], ''))
if not parsed['responseData']['results']:
return 'no images found'
return random.choice(parsed['responseData']['results'][:10]) \
['unescapedUrl']
return random.choice(parsed['responseData']['results'][:10])['unescapedUrl']
@hook.command('search')

View file

@ -53,7 +53,7 @@ def allowed(db, nick, nick_vote):
db.commit()
return True, 0
else:
return False, timesince.timeuntil(check, now=time.time()-time_restriction)
return False, timesince.timeuntil(check, now=time.time() - time_restriction)
else:
db.execute("""INSERT OR REPLACE INTO karma_voters(
voter,
@ -68,6 +68,7 @@ def allowed(db, nick, nick_vote):
# karma_re = ('((\S+)(\+\+|\-\-))+', re.I)
karma_re = ('(.+)(\+\+|\-\-)$', re.I)
@hook.regex(*karma_re)
def karma_add(match, nick='', chan='', db=None, notice=None):
@ -88,7 +89,7 @@ def karma_add(match, nick='', chan='', db=None, notice=None):
nick_vote,
up_karma,
down_karma,
total_karma) values(?,?,?,?)""", (nick_vote.lower(),0,0,0))
total_karma) values(?,?,?,?)""", (nick_vote.lower(), 0, 0, 0))
up(db, nick_vote)
notice("Gave {} 1 karma!".format(nick_vote))
if match.group(2) == '--':
@ -96,7 +97,7 @@ def karma_add(match, nick='', chan='', db=None, notice=None):
nick_vote,
up_karma,
down_karma,
total_karma) values(?,?,?,?)""", (nick_vote.lower(),0,0,0))
total_karma) values(?,?,?,?)""", (nick_vote.lower(), 0, 0, 0))
down(db, nick_vote)
notice("Took away 1 karma from {}.".format(nick_vote))
else:
@ -126,6 +127,6 @@ def karma(inp, nick='', chan='', db=None):
return "That user has no karma."
else:
out = out[0]
return "{} has {} karma points.".format(nick_vote, out[1]-out[2])
return "{} has {} karma points.".format(nick_vote, out[1] - out[2])
return

View file

@ -15,7 +15,7 @@ def format_motd(motd):
colors = [u"\x0300,\xa7f", u"\x0301,\xa70", u"\x0302,\xa71", u"\x0303,\xa72", u"\x0304,\xa7c", u"\x0305,\xa74",
u"\x0306,\xa75", u"\x0307,\xa76", u"\x0308,\xa7e", u"\x0309,\xa7a", u"\x0310,\xa73", u"\x0311,\xa7b",
u"\x0312,\xa71", u"\x0313,\xa7d", u"\x0314,\xa78", u"\x0315,\xa77", u"\x02,\xa7l", u"\x0310,\xa79",
u"\x09,\xa7o", u"\x13,\xa7m", u"\x0f,\xa7r", u"\x15,\xa7n"];
u"\x09,\xa7o", u"\x13,\xa7m", u"\x0f,\xa7r", u"\x15,\xa7n"]
for s in colors:
lcol = s.split(",")
motd = motd.replace(lcol[1], lcol[0])
@ -50,7 +50,7 @@ def mcping_connect(host, port):
return message
except:
return "Error pinging {}:{}, is it up? Double-check your address!".format(host,str(port))
return "Error pinging {}:{}, is it up? Double-check your address!".format(host, str(port))
def srvData(domain):

View file

@ -1,6 +1,7 @@
# Plugin by Lukeroge
from util import hook, text, textgen
import json, os
import json
import os
GEN_DIR = "./plugins/data/name_files/"
@ -9,7 +10,7 @@ GEN_DIR = "./plugins/data/name_files/"
def get_generator(_json):
data = json.loads(_json)
return textgen.TextGenerator(data["templates"],
data["parts"], default_templates = data["default_templates"])
data["parts"], default_templates=data["default_templates"])
@hook.command(autohelp=False)

View file

@ -19,7 +19,7 @@ def osrc(inp):
response["nick"] = user_nick
soup = BeautifulSoup(response["summary"])
response["work_time"] = soup.find("a", {"href" : "#day"}).contents[0]
response["work_time"] = soup.find("a", {"href": "#day"}).contents[0]
response["short_url"] = web.try_isgd(user_url.format(user_nick))

View file

@ -27,18 +27,18 @@ def rdio(inp, bot=None):
except IndexError:
return "No results."
if 'name' in info:
if 'artist' in info and 'album' in info: #Track
if 'artist' in info and 'album' in info: # Track
name = info['name']
artist = info['artist']
album = info['album']
url = info['shortUrl']
return u"\x02{}\x02 by \x02{}\x02 - {} {}".format(name, artist, album, url)
elif 'artist' in info and not 'album' in info: #Album
elif 'artist' in info and not 'album' in info: # Album
name = info['name']
artist = info['artist']
url = info['shortUrl']
return u"\x02{}\x02 by \x02{}\x02 - {}".format(name, artist, url)
else: #Artist
else: # Artist
name = info['name']
url = info['shortUrl']
return u"\x02{}\x02 - {}".format(name, url)
@ -115,15 +115,15 @@ def rdio_url(match, bot=None):
data = json.loads(response[1])
info = data['result']
if 'name' in info:
if 'artist' in info and 'album' in info: #Track
if 'artist' in info and 'album' in info: # Track
name = info['name']
artist = info['artist']
album = info['album']
return u"Rdio track: \x02{}\x02 by \x02{}\x02 - {}".format(name, artist, album)
elif 'artist' in info and not 'album' in info: #Album
elif 'artist' in info and not 'album' in info: # Album
name = info['name']
artist = info['artist']
return u"Rdio album: \x02{}\x02 by \x02{}\x02".format(name, artist)
else: #Artist
else: # Artist
name = info['name']
return u"Rdio artist: \x02{}\x02".format(name)

View file

@ -51,7 +51,6 @@ def reddit(inp):
return "Error: " + str(e)
data = data["data"]["children"]
# get the requested/random post
if id_num:
try:

View file

@ -7,8 +7,13 @@ gauge_url = "http://www.mysteamgauge.com/search?username={}"
api_url = "http://mysteamgauge.com/user/{}.csv"
steam_api_url = "http://steamcommunity.com/id/{}/?xml=1"
def refresh_data(name): http.get(gauge_url.format(name), timeout=25, get_method='HEAD')
def get_data(name): return http.get(api_url.format(name))
def refresh_data(name):
http.get(gauge_url.format(name), timeout=25, get_method='HEAD')
def get_data(name):
return http.get(api_url.format(name))
def is_number(s):
@ -91,9 +96,8 @@ def steamcalc(inp, reply=None):
data["size"] = "{0:.1f}".format(total_size)
reply("{name} ({state}) has {games} games with a total value of ${value}" \
" and a total size of {size}GB! The average metascore for these" \
reply("{name} ({state}) has {games} games with a total value of ${value}"
" and a total size of {size}GB! The average metascore for these"
" games is {average_metascore}.".format(**data))
if do_refresh:

View file

@ -13,23 +13,29 @@ control = {'bold': '\x02', 'color': '\x03', 'italic': '\x09',
def color(color):
return control['color'] + colors[color]
def bold():
return control['bold']
def italic():
return control['italic']
def strike():
return control['strikethrough']
def reset():
return control['reset']
def underline(other=False):
if other:
return control['underline2']
else:
return control['underline']
def reverse():
return control['reverse']

View file

@ -1,4 +1,5 @@
import http, web
import http
import web
def eval_py(code, paste_multiline=True):

View file

@ -1,34 +1,36 @@
def raw(format_string):
"""Replace based irc formatting"""
stuff = {}
stuff['col'] = {'[white]':'\x030',
'[black]':'\x031',
'[dblue]':'\x032',
'[dgreen]':'\x033',
'[dred]':'\x034',
'[brown]':'\x035',
'[purple]':'\x036',
'[gold]':'\x037',
'[yellow]':'\x038',
'[green]':'\x039',
'[cyan]':'\x0310',
'[lblue]':'\x0311',
'[blue]':'\x0312',
'[pink]':'\x0313',
'[gray]':'\x0314',
'[lgray]':'\x0315',
'[err]':'\x034\x02'
'[/err]':'\x030\x02'}
stuff['style'] = {'[b]':'\x02',
'[clear]':'\x0f'}
stuff['sym'] = {'[point]':'\x07'}
stuff['text'] = {'[url]':'http://'}
stuff['col'] = {'[white]': '\x030',
'[black]': '\x031',
'[dblue]': '\x032',
'[dgreen]': '\x033',
'[dred]': '\x034',
'[brown]': '\x035',
'[purple]': '\x036',
'[gold]': '\x037',
'[yellow]': '\x038',
'[green]': '\x039',
'[cyan]': '\x0310',
'[lblue]': '\x0311',
'[blue]': '\x0312',
'[pink]': '\x0313',
'[gray]': '\x0314',
'[lgray]': '\x0315',
'[err]': '\x034\x02'
'[/err]': '\x030\x02'}
stuff['style'] = {'[b]': '\x02',
'[clear]': '\x0f'}
stuff['sym'] = {'[point]': '\x07'}
stuff['text'] = {'[url]': 'http://'}
final = {}
for x in stuff:
final.update(stuff[x])
for x in final:
format_string = format_string.replace(x,final[x])
format_string = format_string.replace(x, final[x])
return format_string
def err(format_string):
"""Format the string with standard error styling"""
return "\x034\x02{}\x0f".format(format_string)

View file

@ -184,7 +184,7 @@ def truncate_str(content, length=100, suffix='...'):
# Expression to match some_token and some_token="with spaces" (and similarly
# for single-quoted strings).
split_re = re.compile(r"""((?:[^\s'"]*(?:(?:"(?:[^"\\]|\\.)*" | '(?:[""" \
split_re = re.compile(r"""((?:[^\s'"]*(?:(?:"(?:[^"\\]|\\.)*" | '(?:["""
r"""^'\\]|\\.)*')[^\s'"]*)+) | \S+)""", re.VERBOSE)

View file

@ -12,9 +12,9 @@ colors = collections.OrderedDict([
('green', '\x0309'),
('cyan', '\x0303'),
('ltblue', '\x0310'),
('rylblue','\x0312'),
('rylblue', '\x0312'),
('blue', '\x0302'),
('magenta','\x0306'),
('magenta', '\x0306'),
('pink', '\x0313'),
('maroon', '\x0305')
])
@ -23,11 +23,13 @@ colors = collections.OrderedDict([
strip_re = re.compile("(\x03|\x02|\x1f)(?:,?\d{1,2}(?:,\d{1,2})?)?", re.UNICODE)
def strip(text):
return strip_re.sub('', text)
# basic text tools
## TODO: make this capitalize sentences correctly
@hook.command("capitalise")
@hook.command
@ -35,21 +37,25 @@ def capitalize(inp):
"""capitalize <string> -- Capitalizes <string>."""
return inp.capitalize()
@hook.command
def upper(inp):
"""upper <string> -- Convert string to uppercase."""
return inp.upper()
@hook.command
def lower(inp):
"""lower <string> -- Convert string to lowercase."""
return inp.lower()
@hook.command
def titlecase(inp):
"""title <string> -- Convert string to title case."""
return inp.title()
@hook.command
def swapcase(inp):
"""swapcase <string> -- Swaps the capitalization of <string>."""
@ -57,21 +63,25 @@ def swapcase(inp):
# encoding
@hook.command
def rot13(inp):
"""rot13 <string> -- Encode <string> with rot13."""
return inp.encode('rot13')
@hook.command
def base64(inp):
"""base64 <string> -- Encode <string> with base64."""
return inp.encode('base64')
@hook.command
def unbase64(inp):
"""unbase64 <string> -- Decode <string> with base64."""
return inp.decode('base64')
@hook.command
def checkbase64(inp):
try:
@ -86,6 +96,7 @@ def checkbase64(inp):
else:
return '"{}" is not base64 encoded'.format(inp)
@hook.command
def unescape(inp):
"""unescape <string> -- Unescapes <string>."""
@ -94,6 +105,7 @@ def unescape(inp):
except Exception as e:
return "Error: {}".format(e)
@hook.command
def escape(inp):
"""escape <string> -- Escapes <string>."""
@ -104,6 +116,7 @@ def escape(inp):
# length
@hook.command
def length(inp):
"""length <string> -- gets the length of <string>"""
@ -111,6 +124,7 @@ def length(inp):
# reverse
@hook.command
def reverse(inp):
"""reverse <string> -- reverses <string>."""
@ -118,6 +132,7 @@ def reverse(inp):
# hashing
@hook.command
def hash(inp):
"""hash <string> -- Returns hashes of <string>."""
@ -126,6 +141,7 @@ def hash(inp):
# novelty
@hook.command
def munge(inp):
"""munge <text> -- Munges up <text>."""
@ -133,6 +149,7 @@ def munge(inp):
# colors - based on code by Reece Selwood - <https://github.com/hitzler/homero>
@hook.command
def rainbow(inp):
inp = unicode(inp)
@ -147,6 +164,7 @@ def rainbow(inp):
out += col[i % l][1] + t
return out
@hook.command
def wrainbow(inp):
inp = unicode(inp)
@ -158,6 +176,7 @@ def wrainbow(inp):
out.append(col[i % l][1] + t)
return ' '.join(out)
@hook.command
def usa(inp):
inp = strip(inp)
@ -167,4 +186,3 @@ def usa(inp):
for i, t in enumerate(inp):
out += c[i % l] + t
return out

View file

@ -24,11 +24,11 @@ def get_sound_info(game, search):
text = item["text"]
items.append("{} - {} {}".format(item["who"],
text if len(text) < 325 else text[:325] + "...",
item["listen"] ) )
item["listen"]))
if len(items) == 1:
return items[0]
else:
return "{} (and {} others: {})".format(items[0], len(items) - 1, web.haste("\n".join(items)) )
return "{} (and {} others: {})".format(items[0], len(items) - 1, web.haste("\n".join(items)))
@hook.command