Merge branch 'develop' into refresh

Conflicts:
	core/config.py
	plugins/util/color.py
	plugins/util/formatting.py
This commit is contained in:
Luke Rogers 2013-11-27 16:55:04 +13:00
commit aa8ab33ccb
31 changed files with 113 additions and 86 deletions

View file

@ -1,5 +1,6 @@
from util import hook from util import hook
import os, sys import os
import sys
import re import re
import json import json
import time import time
@ -120,6 +121,7 @@ def restart(inp, bot=None):
bot.restart() bot.restart()
@hook.command(autohelp=False, permissions=["botcontrol"]) @hook.command(autohelp=False, permissions=["botcontrol"])
def clearlogs(inp, input=None): def clearlogs(inp, input=None):
"""clearlogs -- Clears the bots log(s).""" """clearlogs -- Clears the bots log(s)."""

View file

@ -13,6 +13,7 @@ with open("data/flirts.txt") as f:
flirts = [line.strip() for line in f.readlines() flirts = [line.strip() for line in f.readlines()
if not line.startswith("//")] if not line.startswith("//")]
@hook.command @hook.command
def lart(inp, action=None, nick=None, conn=None, notice=None): def lart(inp, action=None, nick=None, conn=None, notice=None):
"""lart <user> -- LARTs <user>.""" """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 = http.get_json("https://data.mtgox.com/api/2/BTCUSD/money/ticker")
data = data['data'] data = data['data']
ticker = { ticker = {
'buy': data['buy']['display_short'].encode('ascii','ignore'), 'buy': data['buy']['display_short'].encode('ascii', 'ignore'),
'high': data['high']['display_short'].encode('ascii','ignore'), 'high': data['high']['display_short'].encode('ascii', 'ignore'),
'low': data['low']['display_short'].encode('ascii','ignore'), 'low': data['low']['display_short'].encode('ascii', 'ignore'),
'vol': data['vol']['display_short'].encode('ascii','ignore'), 'vol': data['vol']['display_short'].encode('ascii', 'ignore'),
} }
message("Current: \x0307{!s}\x0f - High: \x0307{!s}\x0f" 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

@ -6,7 +6,7 @@ from util import hook
@hook.command @hook.command
def choose(inp): def choose(inp):
"""choose <choice1>, [choice2], [choice3], [choice4], ... -- """choose <choice1>, [choice2], [choice3], [choice4], ... --
Randomly picks one of the given choices.""" Randomly picks one of the given choices."""
c = re.findall(r'([^,]+)', inp) c = re.findall(r'([^,]+)', inp)
@ -15,4 +15,4 @@ def choose(inp):
if len(c) == 1: if len(c) == 1:
return 'The decision is up to you!' return 'The decision is up to you!'
return random.choice(c).strip() return random.choice(c).strip()

View file

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

View file

@ -9,10 +9,10 @@ import json
import hashlib import hashlib
# helper functions to pad and unpad a string to a specified block size # helper functions to pad and unpad a string to a specified block size
# <http://stackoverflow.com/questions/12524994/encrypt-decrypt-using-pycrypto-aes-256> # <http://stackoverflow.com/questions/12524994/encrypt-decrypt-using-pycrypto-aes-256>
BS = AES.block_size BS = AES.block_size
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS) 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 # helper functions to encrypt and encode a string with AES and base64
encode_aes = lambda c, s: base64.b64encode(c.encrypt(pad(s))) encode_aes = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
@ -48,7 +48,7 @@ def encrypt(inp, bot=None, db=None, notice=None):
# if there is only one argument, return the help message # if there is only one argument, return the help message
if len(split) == 1: if len(split) == 1:
notice(encrypt.__doc__) notice(encrypt.__doc__)
return return
# generate the key from the password and salt # generate the key from the password and salt
password = split[0] password = split[0]
@ -56,7 +56,7 @@ def encrypt(inp, bot=None, db=None, notice=None):
key = PBKDF2(password, salt) key = PBKDF2(password, salt)
# generate the IV and encode it to store in the database # 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) iv_encoded = base64.b64encode(iv)
# create the AES cipher and encrypt/encode the text with it # create the AES cipher and encrypt/encode the text with it
@ -83,9 +83,9 @@ def decrypt(inp, bot=None, db=None, notice=None):
# if there is only one argument, return the help message # if there is only one argument, return the help message
if len(split) == 1: if len(split) == 1:
notice(decrypt.__doc__) notice(decrypt.__doc__)
return return
# generate the key from the password and salt # generate the key from the password and salt
password = split[0] password = split[0]
salt = get_salt(bot) salt = get_salt(bot)
key = PBKDF2(password, salt) key = PBKDF2(password, salt)
@ -99,4 +99,4 @@ def decrypt(inp, bot=None, db=None, notice=None):
# create AES cipher, decode text, decrypt text, and unpad it # create AES cipher, decode text, decrypt text, and unpad it
cipher = AES.new(key, AES.MODE_CBC, iv) cipher = AES.new(key, AES.MODE_CBC, iv)
return decode_aes(cipher, text) return decode_aes(cipher, text)

View file

@ -6,7 +6,7 @@ shortcuts = {"cloudbot": "ClouDev/CloudBot"}
def truncate(msg): def truncate(msg):
nmsg = msg.split(" ") nmsg = msg.split()
out = None out = None
x = 0 x = 0
for i in nmsg: for i in nmsg:
@ -50,8 +50,8 @@ def ghissues(inp):
return "Repo has no open issues" return "Repo has no open issues"
except ValueError: except ValueError:
return "Invalid data returned. Check arguments (.github issues username/repo [number]" return "Invalid data returned. Check arguments (.github issues username/repo [number]"
fmt = "Issue: #{} ({}) by {}: {} | {} {}" # (number, state, user.login, title, truncate(body), gitio.gitio(data.url)) fmt = "Issue: #%s (%s) by %s: %s | %s %s" # (number, state, user.login, title, truncate(body), gitio.gitio(data.url))
fmt1 = "Issue: #{} ({}) by {}: {} {}" # (number, state, user.login, title, gitio.gitio(data.url)) fmt1 = "Issue: #%s (%s) by %s: %s %s" # (number, state, user.login, title, gitio.gitio(data.url))
number = data["number"] number = data["number"]
if data["state"] == "open": if data["state"] == "open":
state = u"\x033\x02OPEN\x02\x0f" state = u"\x033\x02OPEN\x02\x0f"

View file

@ -20,8 +20,7 @@ def googleimage(inp):
raise IOError('error searching for images: {}: {}'.format(parsed['responseStatus'], '')) raise IOError('error searching for images: {}: {}'.format(parsed['responseStatus'], ''))
if not parsed['responseData']['results']: if not parsed['responseData']['results']:
return 'no images found' return 'no images found'
return random.choice(parsed['responseData']['results'][:10]) \ return random.choice(parsed['responseData']['results'][:10])['unescapedUrl']
['unescapedUrl']
@hook.command('search') @hook.command('search')
@ -48,4 +47,4 @@ def google(inp):
content = http.html.fromstring(content).text_content() content = http.html.fromstring(content).text_content()
content = text.truncate_str(content, 150) content = text.truncate_str(content, 150)
return u'{} -- \x02{}\x02: "{}"'.format(result['unescapedUrl'], title, content) return u'{} -- \x02{}\x02: "{}"'.format(result['unescapedUrl'], title, content)

View file

@ -164,4 +164,4 @@ lang_pairs = [
("vi", "Vietnamese"), ("vi", "Vietnamese"),
("cy", "Welsh"), ("cy", "Welsh"),
("yi", "Yiddish") ("yi", "Yiddish")
] ]

View file

@ -53,4 +53,4 @@ def horoscope(inp, db=None, notice=None, nick=None):
(nick.lower(), sign)) (nick.lower(), sign))
db.commit() db.commit()
return result return result

View file

@ -77,4 +77,4 @@ def imgur(inp):
if show_nsfw: if show_nsfw:
return "{} \x02NSFW\x02".format(web.isgd("http://imgur.com/" + ','.join(items))) return "{} \x02NSFW\x02".format(web.isgd("http://imgur.com/" + ','.join(items)))
else: else:
return web.isgd("http://imgur.com/" + ','.join(items)) return web.isgd("http://imgur.com/" + ','.join(items))

View file

@ -25,4 +25,4 @@ def isup(inp):
elif "is up" in content: elif "is up" in content:
return "It's just you. {} is \x02\x033up\x02\x0f.".format(url) return "It's just you. {} is \x02\x033up\x02\x0f.".format(url)
else: else:
return "Huh? That doesn't look like a site on the interweb." return "Huh? That doesn't look like a site on the interweb."

View file

@ -53,7 +53,7 @@ def allowed(db, nick, nick_vote):
db.commit() db.commit()
return True, 0 return True, 0
else: else:
return False, timesince.timeuntil(check, now=time.time()-time_restriction) return False, timesince.timeuntil(check, now=time.time() - time_restriction)
else: else:
db.execute("""INSERT OR REPLACE INTO karma_voters( db.execute("""INSERT OR REPLACE INTO karma_voters(
voter, voter,
@ -64,10 +64,11 @@ def allowed(db, nick, nick_vote):
# TODO Make this work on multiple matches in a string, right now it'll only # TODO Make this work on multiple matches in a string, right now it'll only
# work on one match. # work on one match.
# karma_re = ('((\S+)(\+\+|\-\-))+', re.I) # karma_re = ('((\S+)(\+\+|\-\-))+', re.I)
karma_re = ('(.+)(\+\+|\-\-)$', re.I) karma_re = ('(.+)(\+\+|\-\-)$', re.I)
@hook.regex(*karma_re) @hook.regex(*karma_re)
def karma_add(match, nick='', chan='', db=None, notice=None): def karma_add(match, nick='', chan='', db=None, notice=None):
@ -79,7 +80,7 @@ def karma_add(match, nick='', chan='', db=None, notice=None):
notice("You can't vote on yourself!") notice("You can't vote on yourself!")
return return
if len(nick_vote) < 3 or " " in nick_vote: if len(nick_vote) < 3 or " " in nick_vote:
return # ignore anything below 3 chars in length or with spaces return # ignore anything below 3 chars in length or with spaces
vote_allowed, when = allowed(db, nick, nick_vote) vote_allowed, when = allowed(db, nick, nick_vote)
if vote_allowed: if vote_allowed:
@ -88,7 +89,7 @@ def karma_add(match, nick='', chan='', db=None, notice=None):
nick_vote, nick_vote,
up_karma, up_karma,
down_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) up(db, nick_vote)
notice("Gave {} 1 karma!".format(nick_vote)) notice("Gave {} 1 karma!".format(nick_vote))
if match.group(2) == '--': if match.group(2) == '--':
@ -96,7 +97,7 @@ def karma_add(match, nick='', chan='', db=None, notice=None):
nick_vote, nick_vote,
up_karma, up_karma,
down_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) down(db, nick_vote)
notice("Took away 1 karma from {}.".format(nick_vote)) notice("Took away 1 karma from {}.".format(nick_vote))
else: else:
@ -126,6 +127,6 @@ def karma(inp, nick='', chan='', db=None):
return "That user has no karma." return "That user has no karma."
else: else:
out = out[0] 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 return

View file

@ -22,11 +22,11 @@ def kill(inp, action=None, nick=None, conn=None, notice=None):
target = nick target = nick
variables = { variables = {
"user": target "user": target
} }
with open("./data/kills.json") as f: with open("./data/kills.json") as f:
generator = get_generator(f.read(), variables) generator = get_generator(f.read(), variables)
# act out the message # act out the message
action(generator.generate_string()) action(generator.generate_string())

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", 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"\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"\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: for s in colors:
lcol = s.split(",") lcol = s.split(",")
motd = motd.replace(lcol[1], lcol[0]) motd = motd.replace(lcol[1], lcol[0])
@ -50,7 +50,7 @@ def mcping_connect(host, port):
return message return message
except: 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): def srvData(domain):

View file

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

View file

@ -178,4 +178,4 @@ def unlock(inp, conn=None, chan=None, notice=None):
"""unlock [channel] -- Makes the bot unlock a channel.. """unlock [channel] -- Makes the bot unlock a channel..
If [channel] is blank the bot will mute If [channel] is blank the bot will mute
the channel the command was used in.""" the channel the command was used in."""
mode_cmd_no_target("-i", "unlock", inp, chan, conn, notice) mode_cmd_no_target("-i", "unlock", inp, chan, conn, notice)

View file

@ -19,7 +19,7 @@ def osrc(inp):
response["nick"] = user_nick response["nick"] = user_nick
soup = BeautifulSoup(response["summary"]) 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)) response["short_url"] = web.try_isgd(user_url.format(user_nick))

View file

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

View file

@ -36,14 +36,14 @@ def reddit(inp):
# find the requested post number (if any) # find the requested post number (if any)
if len(parts) > 1: if len(parts) > 1:
url = base_url.format(parts[0].strip()) url = base_url.format(parts[0].strip())
try: try:
id_num = int(parts[1]) - 1 id_num = int(parts[1]) - 1
except ValueError: except ValueError:
return "Invalid post number." return "Invalid post number."
else: else:
url = base_url.format(parts[0].strip()) url = base_url.format(parts[0].strip())
else: else:
url = "http://reddit.com/.json" url = "http://reddit.com/.json"
try: try:
data = http.get_json(url, user_agent=http.ua_chrome) data = http.get_json(url, user_agent=http.ua_chrome)
@ -51,9 +51,8 @@ def reddit(inp):
return "Error: " + str(e) return "Error: " + str(e)
data = data["data"]["children"] data = data["data"]["children"]
# get the requested/random post # get the requested/random post
if id_num: if id_num != None:
try: try:
item = data[id_num]["data"] item = data[id_num]["data"]
except IndexError: except IndexError:

View file

@ -36,4 +36,4 @@ def rottentomatoes(inp, bot=None):
rotten = review_count - fresh rotten = review_count - fresh
return u"{} - Critics Rating: \x02{}%\x02 ({} liked, {} disliked) " \ return u"{} - Critics Rating: \x02{}%\x02 ({} liked, {} disliked) " \
"Audience Rating: \x02{}%\x02 - {}".format(title, critics_score, fresh, rotten, audience_score, url) "Audience Rating: \x02{}%\x02 - {}".format(title, critics_score, fresh, rotten, audience_score, url)

View file

@ -32,7 +32,7 @@ def seen_sieve(paraml, input=None, db=None):
@hook.command @hook.command
def seen(inp, nick='', chan='', db=None, input=None): def seen(inp, nick='', chan='', db=None, input=None):
"""seen <nick> <channel> -- Tell when a nickname was last in active in one of this bot's channels.""" """seen <nick> <channel> -- Tell when a nickname was last in active in one of this bot's channels."""
if input.conn.nick.lower() == inp.lower(): if input.conn.nick.lower() == inp.lower():
return "You need to get your eyes checked." return "You need to get your eyes checked."

View file

@ -22,11 +22,11 @@ def slap(inp, action=None, nick=None, conn=None, notice=None):
target = nick target = nick
variables = { variables = {
"user": target "user": target
} }
with open("./data/slaps.json") as f: with open("./data/slaps.json") as f:
generator = get_generator(f.read(), variables) generator = get_generator(f.read(), variables)
# act out the message # act out the message
action(generator.generate_string()) action(generator.generate_string())

View file

@ -7,8 +7,13 @@ gauge_url = "http://www.mysteamgauge.com/search?username={}"
api_url = "http://mysteamgauge.com/user/{}.csv" api_url = "http://mysteamgauge.com/user/{}.csv"
steam_api_url = "http://steamcommunity.com/id/{}/?xml=1" 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): def is_number(s):
@ -45,7 +50,7 @@ def steamcalc(inp, reply=None):
except (http.HTTPError, http.URLError): except (http.HTTPError, http.URLError):
return "Could not get data for this user." return "Could not get data for this user."
csv_data = StringIO.StringIO(request) # we use StringIO because CSV can't read a string csv_data = StringIO.StringIO(request) # we use StringIO because CSV can't read a string
reader = unicode_dictreader(csv_data) reader = unicode_dictreader(csv_data)
# put the games in a list # put the games in a list
@ -63,7 +68,7 @@ def steamcalc(inp, reply=None):
except AttributeError: except AttributeError:
return "Could not get data for this user." return "Could not get data for this user."
online_state = online_state.replace("<br/>", ": ") # will make this pretty later online_state = online_state.replace("<br/>", ": ") # will make this pretty later
data["state"] = text.strip_html(online_state) data["state"] = text.strip_html(online_state)
# work out the average metascore for all games # work out the average metascore for all games
@ -91,9 +96,8 @@ def steamcalc(inp, reply=None):
data["size"] = "{0:.1f}".format(total_size) data["size"] = "{0:.1f}".format(total_size)
reply("{name} ({state}) has {games} games with a total value of ${value}"
reply("{name} ({state}) has {games} games with a total value of ${value}" \ " and a total size of {size}GB! The average metascore for these"
" and a total size of {size}GB! The average metascore for these" \
" games is {average_metascore}.".format(**data)) " games is {average_metascore}.".format(**data))
if do_refresh: if do_refresh:

View file

@ -30,4 +30,4 @@ def stock(inp):
"Day Range: %(DaysRange)s " \ "Day Range: %(DaysRange)s " \
"MCAP: %(MarketCapitalization)s" % quote "MCAP: %(MarketCapitalization)s" % quote
return ret return ret

View file

@ -131,12 +131,12 @@ def twuser(inp, bot=None):
prefix = "" prefix = ""
if user.location: if user.location:
loc_str = " is located in \x02{}\x02 and".format(user.location) loc_str = " is located in \x02{}\x02 and".format(user.location)
else: else:
loc_str = "" loc_str = ""
if user.description: if user.description:
desc_str = " The users description is \"{}\"".format(user.description) desc_str = " The users description is \"{}\"".format(user.description)
else: else:
desc_str = "" desc_str = ""

View file

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

View file

@ -24,11 +24,11 @@ def get_sound_info(game, search):
text = item["text"] text = item["text"]
items.append("{} - {} {}".format(item["who"], items.append("{} - {} {}".format(item["who"],
text if len(text) < 325 else text[:325] + "...", text if len(text) < 325 else text[:325] + "...",
item["listen"] ) ) item["listen"]))
if len(items) == 1: if len(items) == 1:
return items[0] return items[0]
else: 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 @hook.command

View file

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

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 # Expression to match some_token and some_token="with spaces" (and similarly
# for single-quoted strings). # for single-quoted strings).
split_re = re.compile(r"""((?:[^\s'"]*(?:(?:"(?:[^"\\]|\\.)*" | '(?:[""" \ split_re = re.compile(r"""((?:[^\s'"]*(?:(?:"(?:[^"\\]|\\.)*" | '(?:["""
r"""^'\\]|\\.)*')[^\s'"]*)+) | \S+)""", re.VERBOSE) r"""^'\\]|\\.)*')[^\s'"]*)+) | \S+)""", re.VERBOSE)

View file

@ -48,4 +48,4 @@ class TextGenerator(object):
return strings return strings
def get_template(self, template): def get_template(self, template):
return self.templates[template] return self.templates[template]