PEP8, lots of tweaks/fixes

This commit is contained in:
neersighted 2012-04-02 09:17:55 -07:00
parent 641b770dc3
commit 508fec8ae8
29 changed files with 165 additions and 111 deletions

View file

@ -33,6 +33,7 @@ def admin(inp, notice=None, bot=None, config=None):
json.dump(bot.config, open('config', 'w'), sort_keys=True, indent=2) json.dump(bot.config, open('config', 'w'), sort_keys=True, indent=2)
return return
@hook.command(adminonly=True) @hook.command(adminonly=True)
def unadmin(inp, notice=None, bot=None, config=None): def unadmin(inp, notice=None, bot=None, config=None):
".unadmin <nick|host> -- Make <nick|host> a non-admin." ".unadmin <nick|host> -- Make <nick|host> a non-admin."
@ -47,6 +48,7 @@ def unadmin(inp, notice=None, bot=None, config=None):
notice("%s is not an admin." % target) notice("%s is not an admin." % target)
return return
@hook.command(autohelp=False) @hook.command(autohelp=False)
def channels(inp, conn=None): def channels(inp, conn=None):
".channels -- Lists the channels that the bot is in." ".channels -- Lists the channels that the bot is in."
@ -64,6 +66,7 @@ def stop(inp, nick=None, conn=None):
time.sleep(5) time.sleep(5)
os.execl("./cloudbot", "stop") os.execl("./cloudbot", "stop")
@hook.command(autohelp=False, adminonly=True) @hook.command(autohelp=False, adminonly=True)
def restart(inp, nick=None, conn=None): def restart(inp, nick=None, conn=None):
".restart [reason] -- Restarts the bot with [reason] as its quit message." ".restart [reason] -- Restarts the bot with [reason] as its quit message."

View file

@ -1,7 +1,5 @@
""" # Written by Scaevolus, updated by Lukeroge
dice.py: written by Scaevolus 2008, updated 2009
simulates dicerolls
"""
import re import re
import random import random
@ -30,7 +28,8 @@ def nrolls(count, n):
return [random.randint(1, n) for x in xrange(count)] return [random.randint(1, n) for x in xrange(count)]
else: # fake it else: # fake it
return [int(random.normalvariate(.5 * (1 + n) * count, return [int(random.normalvariate(.5 * (1 + n) * count,
(((n+1)*(2*n+1)/6.-(.5*(1+n))**2)*count)**.5))] (((n + 1) * (2 * n + 1) / 6. -
(.5 * (1 + n)) ** 2) * count) ** .5))]
@hook.command('roll') @hook.command('roll')

View file

@ -1,13 +1,14 @@
# Plugin by GhettoWizard and Scaevolus
import re import re
from util import hook
from util import hook, http from util import http
@hook.command('u') @hook.command('u')
@hook.command @hook.command
def urban(inp): def urban(inp):
".urban <phrase> [id] -- Looks up <phrase> on urbandictionary.com." ".urban <phrase> [id] -- Looks up <phrase> on urbandictionary.com."
# set a default definition number # set a default definition number
id = 1 id = 1
@ -27,11 +28,12 @@ def urban(inp):
if page['result_type'] == 'no_results': if page['result_type'] == 'no_results':
return 'Not found.' return 'Not found.'
# try getting the requested definition # try getting the requested definition
try: try:
out = "[%s/%s] %s: %s" % \ out = "[%s/%s] %s: %s" % \
(str(id), str(len(defs)), defs[id-1]['word'], defs[id-1]['definition']) (str(id), str(len(defs)), defs[id - 1]['word'],
defs[id - 1]['definition'])
except IndexError: except IndexError:
return 'Not found.' return 'Not found.'
@ -41,7 +43,6 @@ def urban(inp):
return out return out
# define plugin by GhettoWizard & Scaevolus
@hook.command('dictionary') @hook.command('dictionary')
@hook.command @hook.command
def define(inp): def define(inp):

View file

@ -7,7 +7,8 @@ ed_url = "http://encyclopediadramatica.ch/"
@hook.command('ed') @hook.command('ed')
@hook.command @hook.command
def drama(inp): def drama(inp):
".drama <phrase> -- Gets the first paragraph of Encyclopedia Dramatica article on <phrase>." ".drama <phrase> -- Gets the first paragraph of"\
"the Encyclopedia Dramatica article on <phrase>."
j = http.get_json(api_url, search=inp) j = http.get_json(api_url, search=inp)
if not j[1]: if not j[1]:

View file

@ -1,7 +1,10 @@
import re import re
from util import hook, http, misc from util import hook
from util import http
from util import misc
from BeautifulSoup import BeautifulSoup from BeautifulSoup import BeautifulSoup
@hook.command(autohelp=False) @hook.command(autohelp=False)
def fact(inp, say=False, nick=False): def fact(inp, say=False, nick=False):
".fact -- Gets a random fact from OMGFACTS." ".fact -- Gets a random fact from OMGFACTS."
@ -15,10 +18,11 @@ def fact(inp, say=False, nick=False):
return u"%s [ %s ]" % (fact, link) return u"%s [ %s ]" % (fact, link)
def get_fact(): def get_fact():
page = http.get('http://www.omg-facts.com/random') page = http.get('http://www.omg-facts.com/random')
soup = BeautifulSoup(page) soup = BeautifulSoup(page)
container = soup.find('a', {'class' : 'surprise'}) container = soup.find('a', {'class': 'surprise'})
link = container['href'] link = container['href']
fact = misc.strip_html(container.renderContents()) fact = misc.strip_html(container.renderContents())

View file

@ -112,11 +112,10 @@ def forget(inp, db=None, input=None, notice=None):
def factoid(inp, say=None, db=None, bot=None): def factoid(inp, say=None, db=None, bot=None):
"?<word> -- Shows what data is associated with <word>." "?<word> -- Shows what data is associated with <word>."
try: try:
prefix_on = bot.config["plugins"]["factoids"].get("prefix", False) prefix_on = bot.config["plugins"]["factoids"].get("prefix", False)
except KeyError: except KeyError:
prefix_on = False prefix_on = False
db_init(db) db_init(db)
data = get_memory(db, inp.group(1).strip()) data = get_memory(db, inp.group(1).strip())

View file

@ -33,7 +33,7 @@ def insult(inp, nick=None, me=None, conn=None):
target = nick target = nick
else: else:
target = inp target = inp
out = 'insults %s... "%s"' % (target, random.choice(insults)) out = 'insults %s... "%s"' % (target, random.choice(insults))
me(out) me(out)
@ -51,6 +51,6 @@ def flirt(inp, nick=None, me=None, conn=None):
target = 'itself' target = 'itself'
else: else:
target = inp target = inp
out = 'insults %s... "%s"' % (target, random.choice(flirts)) out = 'insults %s... "%s"' % (target, random.choice(flirts))
me(out) me(out)

View file

@ -1,6 +1,7 @@
from util import hook from util import hook
import random import random
@hook.command @hook.command
def flip(inp, flip_count=0, say=None): def flip(inp, flip_count=0, say=None):
".flip <text> -- Flips <text> over." ".flip <text> -- Flips <text> over."

View file

@ -1,5 +1,4 @@
# Plugin by Lukeroge # Plugin by Lukeroge
# <lukeroge@gmail.com> <https://github.com/lukeroge/CloudBot/>
from util import hook, http from util import hook, http
from urlparse import urljoin from urlparse import urljoin
@ -12,7 +11,7 @@ fml_cache = defaultdict()
def refresh_cache(): def refresh_cache():
""" gets a page of random fmls and puts them into a dictionary """ """Gets a page of random FMLs and puts them into a dictionary"""
page = http.get(urljoin(base_url, 'random')) page = http.get(urljoin(base_url, 'random'))
soup = BeautifulSoup(page) soup = BeautifulSoup(page)

View file

@ -36,8 +36,10 @@ def geoip(inp, say=None, bot=None):
localstring = give["city"] localstring = give["city"]
else: else:
localstring = give["city"] + ", " + give["state"] localstring = give["city"] + ", " + give["state"]
say("That IP comes from " + give["country"] + " (" + give["country_short"] + ")") say("That IP comes from " + give["country"] +
say("I think it's in " + localstring + " with a timezone of " + give["timezone"] + "GMT") " (" + give["country_short"] + ")")
say("I think it's in " + localstring +
" with a timezone of " + give["timezone"] + "GMT")
else: else:
say("Either that wasn't an IP or I cannot locate it in my database. :(") say("Either that wasn't an IP or I cannot locate it in my database.")
return return

View file

@ -1,4 +1,4 @@
# plugin created by neersighted and lukeroge # Plugin by neersighted and Lukeroge
from util import hook from util import hook
import urllib2 import urllib2

View file

@ -1,9 +1,10 @@
import random import random
from util import hook
from util import hook, http from util import http
def api_get(kind, query): def api_get(kind, query):
"""Use the RESTful Google Search API"""
url = 'http://ajax.googleapis.com/ajax/services/search/%s?' \ url = 'http://ajax.googleapis.com/ajax/services/search/%s?' \
'v=1.0&safe=off' 'v=1.0&safe=off'
return http.get_json(url % kind, q=query) return http.get_json(url % kind, q=query)
@ -21,8 +22,9 @@ def googleimage(inp):
parsed['responseStatus'], '')) 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'] # squares is dumb + ['unescapedUrl']
@hook.command('search') @hook.command('search')
@hook.command('g') @hook.command('g')

View file

@ -1,26 +1,31 @@
import hashlib import hashlib
from util import hook from util import hook
@hook.command @hook.command
def md5(inp): def md5(inp):
".hash <text> -- Returns a md5 hash of <text>." ".hash <text> -- Returns a md5 hash of <text>."
return hashlib.md5(inp).hexdigest() return hashlib.md5(inp).hexdigest()
@hook.command @hook.command
def sha1(inp): def sha1(inp):
".hash <text> -- Returns a sha1 hash of <text>." ".hash <text> -- Returns a sha1 hash of <text>."
return hashlib.sha1(inp).hexdigest() return hashlib.sha1(inp).hexdigest()
@hook.command @hook.command
def sha256(inp): def sha256(inp):
".hash <text> -- Returns a sha256 hash of <text>." ".hash <text> -- Returns a sha256 hash of <text>."
return hashlib.sha256(inp).hexdigest() return hashlib.sha256(inp).hexdigest()
@hook.command @hook.command
def sha512(inp): def sha512(inp):
".hash <text> -- Returns a sha512 hash of <text>." ".hash <text> -- Returns a sha512 hash of <text>."
return hashlib.sha512(inp).hexdigest() return hashlib.sha512(inp).hexdigest()
@hook.command @hook.command
def hash(inp): def hash(inp):
".hash <text> -- Returns hashes of <text>." ".hash <text> -- Returns hashes of <text>."

View file

@ -1,7 +1,7 @@
import re import re
from util import hook from util import hook
@hook.command(autohelp=False) @hook.command(autohelp=False)
def help(inp, input=None, bot=None, say=None, notice=None): def help(inp, input=None, bot=None, say=None, notice=None):
".help -- Gives a list of commands/help for a command." ".help -- Gives a list of commands/help for a command."
@ -12,7 +12,9 @@ def help(inp, input=None, bot=None, say=None, notice=None):
for command, (func, args) in bot.commands.iteritems(): for command, (func, args) in bot.commands.iteritems():
fn = re.match(r'^plugins.(.+).py$', func._filename) fn = re.match(r'^plugins.(.+).py$', func._filename)
if fn.group(1).lower() not in disabled: if fn.group(1).lower() not in disabled:
if not args.get('adminonly', False) or input.mask in input.bot.config["admins"]: if not args.get('adminonly', False) or\
input.nick in bot.config["admins"] or\
input.mask in bot.config["admins"]:
if command not in disabled_comm: if command not in disabled_comm:
if func.__doc__ is not None: if func.__doc__ is not None:
if func in funcs: if func in funcs:
@ -35,13 +37,13 @@ def help(inp, input=None, bot=None, say=None, notice=None):
out[1] += " " + str(x) out[1] += " " + str(x)
else: else:
out[0] += " " + str(x) out[0] += " " + str(x)
notice("Commands I recognise: " + out[0][1:]) notice("Commands I recognise: " + out[0][1:])
if out[1]: if out[1]:
notice(out[1][1:]) notice(out[1][1:])
notice("For detailed help, do '.help <example>' where <example> is the " + notice("For detailed help, do '.help <example>' where <example> "\
"name of the command you want help for.") "is the name of the command you want help for.")
else: else:
if inp in commands: if inp in commands:
notice(commands[inp].__doc__) notice(commands[inp].__doc__)

View file

@ -1,6 +1,7 @@
import json import json
from util import hook from util import hook
@hook.sieve @hook.sieve
def ignoresieve(bot, input, func, type, args): def ignoresieve(bot, input, func, type, args):
""" blocks input from ignored channels/nicks """ """ blocks input from ignored channels/nicks """
@ -8,7 +9,10 @@ def ignoresieve(bot, input, func, type, args):
# don't block input to event hooks # don't block input to event hooks
if type == "event": if type == "event":
return input return input
if input.chan in ignorelist or input.nick in ignorelist or input.host in ignorelist or input.mask in ignorelist: if input.chan in ignorelist or\
input.nick in ignorelist or\
input.host in ignorelist or\
input.mask in ignorelist:
if input.command == "PRIVMSG" and input.lastparam[1:] == "unignore": if input.command == "PRIVMSG" and input.lastparam[1:] == "unignore":
return input return input
else: else:
@ -41,9 +45,11 @@ def ignore(inp, notice=None, bot=None, config=None):
json.dump(bot.config, open('config', 'w'), sort_keys=True, indent=2) json.dump(bot.config, open('config', 'w'), sort_keys=True, indent=2)
return return
@hook.command(adminonly=True) @hook.command(adminonly=True)
def unignore(inp, notice=None, bot=None, config=None): def unignore(inp, notice=None, bot=None, config=None):
".unignore <channel|nick|host> -- Makes the bot listen to <channel|nick|host>." ".unignore <channel|nick|host> -- Makes the bot listen to"\
" <channel|nick|host>."
target = inp.lower() target = inp.lower()
ignorelist = bot.config["plugins"]["ignore"]["ignored"] ignorelist = bot.config["plugins"]["ignore"]["ignored"]
if target in ignorelist: if target in ignorelist:
@ -54,4 +60,3 @@ def unignore(inp, notice=None, bot=None, config=None):
else: else:
notice("%s is not ignored." % target) notice("%s is not ignored." % target)
return return

View file

@ -1,11 +1,12 @@
# Upgraded with tables/caching by ChauffeR of #freebnc on irc.esper.net # Upgraded with tables/caching by ChauffeR of #freebnc on irc.esper.net
from util import hook, http from util import hook, http
@hook.command('l', autohelp=False) @hook.command('l', autohelp=False)
@hook.command('lfm', autohelp=False)
@hook.command(autohelp=False) @hook.command(autohelp=False)
def lastfm(inp, nick='', say=None, db=None, bot=None): def lastfm(inp, nick='', say=None, db=None, bot=None):
".lastfm [user] -- Displays the now playing (or last played) track of LastFM user [user]." ".lastfm [user] -- Displays the now playing (or last played) "\
"track of LastFM user [user]."
if inp: if inp:
user = inp user = inp
else: else:

View file

@ -10,11 +10,12 @@ import re
from util import hook from util import hook
log_fds = {} # '%(net)s %(chan)s' : (filename, fd) log_fds = {} # '%(net)s %(chan)s': (filename, fd)
timestamp_format = '%H:%M:%S' timestamp_format = '%H:%M:%S'
formats = {'PRIVMSG': '<%(nick)s> %(msg)s', formats = {
'PRIVMSG': '<%(nick)s> %(msg)s',
'PART': '-!- %(nick)s [%(user)s@%(host)s] has left %(chan)s', 'PART': '-!- %(nick)s [%(user)s@%(host)s] has left %(chan)s',
'JOIN': '-!- %(nick)s [%(user)s@%(host)s] has joined %(param0)s', 'JOIN': '-!- %(nick)s [%(user)s@%(host)s] has joined %(param0)s',
'MODE': '-!- mode/%(chan)s [%(param_tail)s] by %(nick)s', 'MODE': '-!- mode/%(chan)s [%(param_tail)s] by %(nick)s',
@ -22,16 +23,22 @@ formats = {'PRIVMSG': '<%(nick)s> %(msg)s',
'TOPIC': '-!- %(nick)s changed the topic of %(chan)s to: %(msg)s', 'TOPIC': '-!- %(nick)s changed the topic of %(chan)s to: %(msg)s',
'QUIT': '-!- %(nick)s has quit [%(msg)s]', 'QUIT': '-!- %(nick)s has quit [%(msg)s]',
'PING': '', 'PING': '',
'NOTICE': '' 'NOTICE': '-%(nick)s- %(msg)s'
} }
ctcp_formats = {'ACTION': '* %(nick)s %(ctcpmsg)s'} ctcp_formats = {
'ACTION': '* %(nick)s %(ctcpmsg)s'
'VERSION': '%(nick)s has requested CTCP %(ctcpcmd)s from %(chan)s: %(ctcpmsg)s'
'PING': '%(nick)s has requested CTCP %(ctcpcmd)s from %(chan)s: %(ctcpmsg)s'
'TIME': '%(nick)s has requested CTCP %(ctcpcmd)s from %(chan)s: %(ctcpmsg)s'
'FINGER': '%(nick)s has requested CTCP %(ctcpcmd)s from %(chan)s: %(ctcpmsg)s'
}
irc_color_re = re.compile(r'(\x03(\d+,\d+|\d)|[\x0f\x02\x16\x1f])') irc_color_re = re.compile(r'(\x03(\d+,\d+|\d)|[\x0f\x02\x16\x1f])')
def get_log_filename(dir, server, chan): def get_log_filename(dir, server, chan):
return os.path.join(dir, 'log', gmtime('%Y'), server, chan, return os.path.join(dir, 'log', gmtime('%Y'), server, chan,
(gmtime('%%s.%m-%d.log') % chan).lower()) (gmtime('%%s.%m-%d.log') % chan).lower())

View file

@ -12,13 +12,15 @@ def mcping_connect(host, port):
sock.send('\xfe') sock.send('\xfe')
response = sock.recv(1) response = sock.recv(1)
if response != '\xff': if response != '\xff':
return "Server gave invalid response: "+repr(response) return "Server gave invalid response: " + repr(response)
length = struct.unpack('!h', sock.recv(2))[0] length = struct.unpack('!h', sock.recv(2))[0]
values = sock.recv(length*2).decode('utf-16be').split(u'\xa7') values = sock.recv(length * 2).decode('utf-16be').split(u'\xa7')
sock.close() sock.close()
return "%s - %d/%d players" % (values[0], int(values[1]), int(values[2])) return "%s - %d/%d players"\
% (values[0], int(values[1]), int(values[2]))
except: except:
return "Error pinging "+host+":"+str(port)+", is it up? Double-check your address!" return "Error pinging " + host + ":" + str(port) +\
", is it up? Double-check your address!"
@hook.command(autohelp=False) @hook.command(autohelp=False)
@ -29,33 +31,42 @@ def mcstatus(inp, bot=None):
if password is None: if password is None:
return "error: no login set" return "error: no login set"
login = http.get("https://login.minecraft.net/?user="+username+"&password="+password+"&version=13") login = http.get("https://login.minecraft.net/?user="\
+ username + "&password=" + password + "&version=13")
if username.lower() in login.lower(): if username.lower() in login.lower():
return "Minecraft login servers appear to be online!" return "Minecraft login servers appear to be online!"
else: else:
return "Minecraft login servers appear to be offline!" return "Minecraft login servers appear to be offline!"
@hook.command @hook.command
def mclogin(inp, say=None): def mclogin(inp, say=None):
".mclogin <username> <password> -- Attempts to log in to Minecrat with <username> and <password> (This is NOT logged)." ".mclogin <username> <password> -- Attempts to log in to Minecraft with "\
" <username> and <password> (This is NOT logged)."
inp = inp.split(" ") inp = inp.split(" ")
username = inp[0] username = inp[0]
password = inp[1] password = inp[1]
say("Attempting to log in using " + username) say("Attempting to log in using " + username)
login = http.get("https://login.minecraft.net/?user=" + username + "&password=" + password + "&version=13") login = http.get("https://login.minecraft.net/?user="\
+ username + "&password=" + password + "&version=13")
if username.lower() in login.lower(): if username.lower() in login.lower():
return "I logged in with " + username return "I logged in with " + username
else: else:
return "I couldn't log in using " + username + ", either the password is wrong or minecraft login servers are down!" return "I couldn't log in using " + username + ", either"\
" the password is wrong or Minecraft login servers are down!"
@hook.command @hook.command
def mcpaid(inp): def mcpaid(inp):
".mcpaid <username> -- Checks if <username> has a premium Minecraft account." ".mcpaid <username> -- Checks if <username> has a "\
"premium Minecraft account."
login = http.get("http://www.minecraft.net/haspaid.jsp?user=" + inp) login = http.get("http://www.minecraft.net/haspaid.jsp?user=" + inp)
if "true" in login: if "true" in login:
return "The account \'" + inp + "\' is a premium Minecraft account!" return "The account \'" + inp + "\' is a "\
"premium Minecraft account!"
else: else:
return "The account \'" + inp + "\' is not a premium Minecraft account!" return "The account \'" + inp + "\' is not a "\
"premium Minecraft account!"
from util import hook from util import hook

View file

@ -1,9 +1,9 @@
# Plugin by Lukeroge # Plugin by Lukeroge
# <lukeroge@gmail.com> <https://github.com/lukeroge/CloudBot/> from util import hook
from util import molecular
from util import hook, molecular
import unicodedata import unicodedata
@hook.command() @hook.command()
def namegen(inp, say=None, nick=None, input=None, notice=None): def namegen(inp, say=None, nick=None, input=None, notice=None):
".namegen [modules] -- Generates some names using the chosen modules. '.namegen list' will display a list of all modules." ".namegen [modules] -- Generates some names using the chosen modules. '.namegen list' will display a list of all modules."

View file

@ -2,6 +2,17 @@
from util import hook from util import hook
@hook.command(adminonly=True)
def topic(inp, conn=None, chan=None, notice=None):
".topic [channel] <topic> -- Change the topic of a channel."
inp = inp.split(" ")
if inp[0][0] == "#":
out = "PRIVMSG %s :%s" % (inp[0], message)
else:
out = "TOPIC %s :%s" % (chan, message)
conn.send(out)
@hook.command(adminonly=True) @hook.command(adminonly=True)
def kick(inp, chan=None, conn=None, notice=None): def kick(inp, chan=None, conn=None, notice=None):
".kick [channel] <user> [reason] -- Makes the bot kick <user> in [channel] "\ ".kick [channel] <user> [reason] -- Makes the bot kick <user> in [channel] "\
@ -65,6 +76,7 @@ def unban(inp, conn=None, chan=None, notice=None):
notice("Attempting to unban %s from %s..." % (user, chan)) notice("Attempting to unban %s from %s..." % (user, chan))
conn.send(out) conn.send(out)
@hook.command(adminonly=True) @hook.command(adminonly=True)
def kickban(inp, chan=None, conn=None, notice=None): def kickban(inp, chan=None, conn=None, notice=None):
".kickban [channel] <user> [reason] -- Makes the bot kickban <user> in [channel] "\ ".kickban [channel] <user> [reason] -- Makes the bot kickban <user> in [channel] "\
@ -96,13 +108,3 @@ def kickban(inp, chan=None, conn=None, notice=None):
notice("Attempting to kickban %s from %s..." % (user, chan)) notice("Attempting to kickban %s from %s..." % (user, chan))
conn.send(out1) conn.send(out1)
conn.send(out2) conn.send(out2)
@hook.command(adminonly=True)
def topic(inp, conn=None, chan=None, notice=None):
".topic [channel] <topic> -- Change the topic of a channel."
inp = inp.split(" ")
if inp[0][0] == "#":
out = "PRIVMSG %s :%s" % (inp[0], message)
else:
out = "TOPIC %s :%s" % (chan, message)
conn.send(out)

View file

@ -4,6 +4,7 @@ import random
potatoes = ['AC Belmont', 'AC Blue Pride', 'AC Brador', 'AC Chaleur', 'AC Domino', 'AC Dubuc', 'AC Glacier Chip', 'AC Maple Gold', 'AC Novachip', 'AC Peregrine Red', 'AC Ptarmigan', 'AC Red Island', 'AC Saguenor', 'AC Stampede Russet', 'AC Sunbury', 'Abeille', 'Abnaki', 'Acadia', 'Acadia Russet', 'Accent', 'Adirondack Blue', 'Adirondack Red', 'Adora', 'Agria', 'All Blue', 'All Red', 'Alpha', 'Alta Russet', 'Alturas Russet', 'Amandine', 'Amisk', 'Andover', 'Anoka', 'Anson', 'Aquilon', 'Arran Consul', 'Asterix', 'Atlantic', 'Austrian Crescent', 'Avalanche', 'Banana', 'Bannock Russet', 'Batoche', 'BeRus', 'Belle De Fonteney', 'Belleisle', 'Bintje', 'Blossom', 'Blue Christie', 'Blue Mac', 'Brigus', 'Brise du Nord', 'Butte', 'Butterfinger', 'Caesar', 'CalWhite', 'CalRed', 'Caribe', 'Carlingford', 'Carlton', 'Carola', 'Cascade', 'Castile', 'Centennial Russet', 'Century Russet', 'Charlotte', 'Cherie', 'Cherokee', 'Cherry Red', 'Chieftain', 'Chipeta', 'Coastal Russet', 'Colorado Rose', 'Concurrent', 'Conestoga', 'Cowhorn', 'Crestone Russet', 'Crispin', 'Cupids', 'Daisy Gold', 'Dakota Pearl', 'Defender', 'Delikat', 'Denali', 'Desiree', 'Divina', 'Dundrod', 'Durango Red', 'Early Rose', 'Elba', 'Envol', 'Epicure', 'Eramosa', 'Estima', 'Eva', 'Fabula', 'Fambo', 'Fremont Russet', 'French Fingerling', 'Frontier Russet', 'Fundy', 'Garnet Chile', 'Gem Russet', 'GemStar Russet', 'Gemchip', 'German Butterball', 'Gigant', 'Goldrush', 'Granola', 'Green Mountain', 'Haida', 'Hertha', 'Hilite Russet', 'Huckleberry', 'Hunter', 'Huron', 'IdaRose', 'Innovator', 'Irish Cobbler', 'Island Sunshine', 'Ivory Crisp', 'Jacqueline Lee', 'Jemseg', 'Kanona', 'Katahdin', 'Kennebec', "Kerr's Pink", 'Keswick', 'Keuka Gold', 'Keystone Russet', 'King Edward VII', 'Kipfel', 'Klamath Russet', 'Krantz', 'LaRatte', 'Lady Rosetta', 'Latona', 'Lemhi Russet', 'Liberator', 'Lili', 'MaineChip', 'Marfona', 'Maris Bard', 'Maris Piper', 'Matilda', 'Mazama', 'McIntyre', 'Michigan Purple', 'Millenium Russet', 'Mirton Pearl', 'Modoc', 'Mondial', 'Monona', 'Morene', 'Morning Gold', 'Mouraska', 'Navan', 'Nicola', 'Nipigon', 'Niska', 'Nooksack', 'NorValley', 'Norchip', 'Nordonna', 'Norgold Russet', 'Norking Russet', 'Norland', 'Norwis', 'Obelix', 'Ozette', 'Peanut', 'Penta', 'Peribonka', 'Peruvian Purple', 'Pike', 'Pink Pearl', 'Prospect', 'Pungo', 'Purple Majesty', 'Purple Viking', 'Ranger Russet', 'Reba', 'Red Cloud', 'Red Gold', 'Red La Soda', 'Red Pontiac', 'Red Ruby', 'Red Thumb', 'Redsen', 'Rocket', 'Rose Finn Apple', 'Rose Gold', 'Roselys', 'Rote Erstling', 'Ruby Crescent', 'Russet Burbank', 'Russet Legend', 'Russet Norkotah', 'Russet Nugget', 'Russian Banana', 'Saginaw Gold', 'Sangre', 'Sant<EFBFBD>', 'Satina', 'Saxon', 'Sebago', 'Shepody', 'Sierra', 'Silverton Russet', 'Simcoe', 'Snowden', 'Spunta', "St. John's", 'Summit Russet', 'Sunrise', 'Superior', 'Symfonia', 'Tolaas', 'Trent', 'True Blue', 'Ulla', 'Umatilla Russet', 'Valisa', 'Van Gogh', 'Viking', 'Wallowa Russet', 'Warba', 'Western Russet', 'White Rose', 'Willamette', 'Winema', 'Yellow Finn', 'Yukon Gold'] potatoes = ['AC Belmont', 'AC Blue Pride', 'AC Brador', 'AC Chaleur', 'AC Domino', 'AC Dubuc', 'AC Glacier Chip', 'AC Maple Gold', 'AC Novachip', 'AC Peregrine Red', 'AC Ptarmigan', 'AC Red Island', 'AC Saguenor', 'AC Stampede Russet', 'AC Sunbury', 'Abeille', 'Abnaki', 'Acadia', 'Acadia Russet', 'Accent', 'Adirondack Blue', 'Adirondack Red', 'Adora', 'Agria', 'All Blue', 'All Red', 'Alpha', 'Alta Russet', 'Alturas Russet', 'Amandine', 'Amisk', 'Andover', 'Anoka', 'Anson', 'Aquilon', 'Arran Consul', 'Asterix', 'Atlantic', 'Austrian Crescent', 'Avalanche', 'Banana', 'Bannock Russet', 'Batoche', 'BeRus', 'Belle De Fonteney', 'Belleisle', 'Bintje', 'Blossom', 'Blue Christie', 'Blue Mac', 'Brigus', 'Brise du Nord', 'Butte', 'Butterfinger', 'Caesar', 'CalWhite', 'CalRed', 'Caribe', 'Carlingford', 'Carlton', 'Carola', 'Cascade', 'Castile', 'Centennial Russet', 'Century Russet', 'Charlotte', 'Cherie', 'Cherokee', 'Cherry Red', 'Chieftain', 'Chipeta', 'Coastal Russet', 'Colorado Rose', 'Concurrent', 'Conestoga', 'Cowhorn', 'Crestone Russet', 'Crispin', 'Cupids', 'Daisy Gold', 'Dakota Pearl', 'Defender', 'Delikat', 'Denali', 'Desiree', 'Divina', 'Dundrod', 'Durango Red', 'Early Rose', 'Elba', 'Envol', 'Epicure', 'Eramosa', 'Estima', 'Eva', 'Fabula', 'Fambo', 'Fremont Russet', 'French Fingerling', 'Frontier Russet', 'Fundy', 'Garnet Chile', 'Gem Russet', 'GemStar Russet', 'Gemchip', 'German Butterball', 'Gigant', 'Goldrush', 'Granola', 'Green Mountain', 'Haida', 'Hertha', 'Hilite Russet', 'Huckleberry', 'Hunter', 'Huron', 'IdaRose', 'Innovator', 'Irish Cobbler', 'Island Sunshine', 'Ivory Crisp', 'Jacqueline Lee', 'Jemseg', 'Kanona', 'Katahdin', 'Kennebec', "Kerr's Pink", 'Keswick', 'Keuka Gold', 'Keystone Russet', 'King Edward VII', 'Kipfel', 'Klamath Russet', 'Krantz', 'LaRatte', 'Lady Rosetta', 'Latona', 'Lemhi Russet', 'Liberator', 'Lili', 'MaineChip', 'Marfona', 'Maris Bard', 'Maris Piper', 'Matilda', 'Mazama', 'McIntyre', 'Michigan Purple', 'Millenium Russet', 'Mirton Pearl', 'Modoc', 'Mondial', 'Monona', 'Morene', 'Morning Gold', 'Mouraska', 'Navan', 'Nicola', 'Nipigon', 'Niska', 'Nooksack', 'NorValley', 'Norchip', 'Nordonna', 'Norgold Russet', 'Norking Russet', 'Norland', 'Norwis', 'Obelix', 'Ozette', 'Peanut', 'Penta', 'Peribonka', 'Peruvian Purple', 'Pike', 'Pink Pearl', 'Prospect', 'Pungo', 'Purple Majesty', 'Purple Viking', 'Ranger Russet', 'Reba', 'Red Cloud', 'Red Gold', 'Red La Soda', 'Red Pontiac', 'Red Ruby', 'Red Thumb', 'Redsen', 'Rocket', 'Rose Finn Apple', 'Rose Gold', 'Roselys', 'Rote Erstling', 'Ruby Crescent', 'Russet Burbank', 'Russet Legend', 'Russet Norkotah', 'Russet Nugget', 'Russian Banana', 'Saginaw Gold', 'Sangre', 'Sant<EFBFBD>', 'Satina', 'Saxon', 'Sebago', 'Shepody', 'Sierra', 'Silverton Russet', 'Simcoe', 'Snowden', 'Spunta', "St. John's", 'Summit Russet', 'Sunrise', 'Superior', 'Symfonia', 'Tolaas', 'Trent', 'True Blue', 'Ulla', 'Umatilla Russet', 'Valisa', 'Van Gogh', 'Viking', 'Wallowa Russet', 'Warba', 'Western Russet', 'White Rose', 'Willamette', 'Winema', 'Yellow Finn', 'Yukon Gold']
@hook.command @hook.command
def potato(inp, me=None, input=None): def potato(inp, me=None, input=None):
".potato <user> - Makes <user> a tasty little potato." ".potato <user> - Makes <user> a tasty little potato."

View file

@ -4,24 +4,27 @@ import time
from util import hook from util import hook
def format_quote(q, num, n_quotes): def format_quote(q, num, n_quotes):
"Returns a formatted string of a quote" """Returns a formatted string of a quote"""
ctime, nick, msg = q ctime, nick, msg = q
return "[%d/%d] <%s> %s" % (num, n_quotes, return "[%d/%d] <%s> %s" % (num, n_quotes,
nick, msg) nick, msg)
def create_table_if_not_exists(db): def create_table_if_not_exists(db):
"Creates an empty quote table if one does not already exist" """Creates an empty quote table if one does not already exist"""
db.execute("create table if not exists quote" db.execute("create table if not exists quote"
"(chan, nick, add_nick, msg, time real, deleted default 0, " "(chan, nick, add_nick, msg, time real, deleted default 0, "
"primary key (chan, nick, msg))") "primary key (chan, nick, msg))")
db.commit() db.commit()
def add_quote(db, chan, nick, add_nick, msg): def add_quote(db, chan, nick, add_nick, msg):
"Adds a quote to a nick, returns message string" """Adds a quote to a nick, returns message string"""
try: try:
db.execute('''INSERT OR FAIL INTO quote db.execute('''INSERT OR FAIL INTO quote
(chan, nick, add_nick, msg, time) (chan, nick, add_nick, msg, time)
VALUES(?,?,?,?,?)''', VALUES(?,?,?,?,?)''',
(chan, nick, add_nick, msg, time.time())) (chan, nick, add_nick, msg, time.time()))
db.commit() db.commit()
@ -29,30 +32,34 @@ def add_quote(db, chan, nick, add_nick, msg):
return "Message already stored, doing nothing." return "Message already stored, doing nothing."
return "Quote added." return "Quote added."
def del_quote(db, chan, nick, add_nick, msg): def del_quote(db, chan, nick, add_nick, msg):
"Deletes a quote from a nick" """Deletes a quote from a nick"""
db.execute('''UPDATE quote SET deleted = 1 WHERE db.execute('''UPDATE quote SET deleted = 1 WHERE
chan=? AND lower(nick)=lower(?) AND msg=msg''') chan=? AND lower(nick)=lower(?) AND msg=msg''')
db.commit() db.commit()
def get_quote_num(num, count, name): def get_quote_num(num, count, name):
"Returns the quote number to fetch from the DB" """Returns the quote number to fetch from the DB"""
if num: # Make sure num is a number if it isn't false if num: # Make sure num is a number if it isn't false
num = int(num) num = int(num)
if count == 0: # If there are no quotes in the database, raise an Exception. if count == 0: # Error on no quotes
raise Exception("No quotes found for %s." % name) raise Exception("No quotes found for %s." % name)
if num and num < 0: # If the selected quote is less than 0, count back if possible. if num and num < 0: # Count back if possible
num = count + num + 1 if num + count > -1 else count + 1 num = count + num + 1 if num + count > -1 else count + 1
if num and num > count: # If a number is given and and there are not enough quotes, raise an Exception. if num and num > count: # If there are not enough quotes, raise an error
raise Exception("I only have %d quote%s for %s." % (count, ('s', '')[count == 1], name)) raise Exception("I only have %d quote%s for %s."\
% (count, ('s', '')[count == 1], name))
if num and num == 0: # If the number is zero, set it to one if num and num == 0: # If the number is zero, set it to one
num = 1 num = 1
if not num: # If a number is not given, select a random one if not num: # If a number is not given, select a random one
num = random.randint(1, count) num = random.randint(1, count)
return num return num
def get_quote_by_nick(db, nick, num=False): def get_quote_by_nick(db, nick, num=False):
"Returns a formatted quote from a nick, random or selected by number" """Returns a formatted quote from a nick, random or selected by number"""
count = db.execute('''SELECT COUNT(*) FROM quote WHERE deleted != 1 count = db.execute('''SELECT COUNT(*) FROM quote WHERE deleted != 1
AND lower(nick) = lower(?)''', [nick]).fetchall()[0][0] AND lower(nick) = lower(?)''', [nick]).fetchall()[0][0]
@ -60,17 +67,18 @@ def get_quote_by_nick(db, nick, num=False):
num = get_quote_num(num, count, nick) num = get_quote_num(num, count, nick)
except Exception as error_message: except Exception as error_message:
return error_message return error_message
quote = db.execute('''SELECT time, nick, msg quote = db.execute('''SELECT time, nick, msg
FROM quote FROM quote
WHERE deleted != 1 WHERE deleted != 1
AND lower(nick) = lower(?) AND lower(nick) = lower(?)
ORDER BY time ORDER BY time
LIMIT ?, 1''', (nick, (num-1))).fetchall()[0] LIMIT ?, 1''', (nick, (num - 1))).fetchall()[0]
return format_quote(quote, num, count) return format_quote(quote, num, count)
def get_quote_by_nick_chan(db, chan, nick, num=False): def get_quote_by_nick_chan(db, chan, nick, num=False):
"Returns a formatted quote from a nick in a channel, random or selected by number" """Returns a formatted quote from a nick in a channel, random or selected by number"""
count = db.execute('''SELECT COUNT(*) count = db.execute('''SELECT COUNT(*)
FROM quote FROM quote
WHERE deleted != 1 WHERE deleted != 1
@ -88,11 +96,12 @@ def get_quote_by_nick_chan(db, chan, nick, num=False):
AND chan = ? AND chan = ?
AND lower(nick) = lower(?) AND lower(nick) = lower(?)
ORDER BY time ORDER BY time
LIMIT ?, 1''', (chan, nick, (num-1))).fetchall()[0] LIMIT ?, 1''', (chan, nick, (num - 1))).fetchall()[0]
return format_quote(quote, num, count) return format_quote(quote, num, count)
def get_quote_by_chan(db, chan, num=False):
"Returns a formatted quote from a channel, random or selected by number" def get_quote_by_chan(db, chan, num=False):
"""Returns a formatted quote from a channel, random or selected by number"""
count = db.execute('''SELECT COUNT(*) count = db.execute('''SELECT COUNT(*)
FROM quote FROM quote
WHERE deleted != 1 WHERE deleted != 1
@ -103,14 +112,15 @@ def get_quote_by_chan(db, chan, num=False):
except Exception as error_message: except Exception as error_message:
return error_message return error_message
quote = db.execute('''SELECT time, nick, msg quote = db.execute('''SELECT time, nick, msg
FROM quote FROM quote
WHERE deleted != 1 WHERE deleted != 1
AND chan = ? AND chan = ?
ORDER BY time ORDER BY time
LIMIT ?, 1''', (chan, (num -1))).fetchall()[0] LIMIT ?, 1''', (chan, (num - 1))).fetchall()[0]
return format_quote(quote, num, count) return format_quote(quote, num, count)
@hook.command('q') @hook.command('q')
@hook.command @hook.command
def quote(inp, nick='', chan='', db=None, notice=None): def quote(inp, nick='', chan='', db=None, notice=None):
@ -128,12 +138,12 @@ def quote(inp, nick='', chan='', db=None, notice=None):
elif retrieve: elif retrieve:
select, num = retrieve.groups() select, num = retrieve.groups()
by_chan = True if select.startswith('#') else False by_chan = True if select.startswith('#') else False
if by_chan: if by_chan:
return get_quote_by_chan(db, select, num) return get_quote_by_chan(db, select, num)
else: else:
return get_quote_by_nick(db, select, num) return get_quote_by_nick(db, select, num)
elif retrieve_chan: elif retrieve_chan:
chan, nick, num = retrieve_chan.groups() chan, nick, num = retrieve_chan.groups()
return get_quote_by_nick_chan(db, chan, nick, num) return get_quote_by_nick_chan(db, chan, nick, num)
notice(quote.__doc__) notice(quote.__doc__)

View file

@ -1,5 +1,4 @@
# Plugin by Lukeroge # Plugin by Lukeroge
# <lukeroge@gmail.com> <https://github.com/lukeroge/CloudBot/>
from util import hook, http from util import hook, http
from re import match from re import match

View file

@ -5,7 +5,7 @@ from util import hook
@hook.sieve @hook.sieve
def sieve_suite(bot, input, func, kind, args): def sieve_suite(bot, input, func, kind, args):
if input.command == 'PRIVMSG' and \ if input.command == 'PRIVMSG' and\
input.nick.endswith('bot') and args.get('ignorebots', True): input.nick.endswith('bot') and args.get('ignorebots', True):
return None return None
@ -32,7 +32,7 @@ def sieve_suite(bot, input, func, kind, args):
if args.get('adminonly', False): if args.get('adminonly', False):
admins = bot.config.get('admins', []) admins = bot.config.get('admins', [])
if input.mask not in admins and input.nick not in admins: if input.nick not in admins and input.mask not in admins:
input.notice("Sorry, you are not allowed to use this command.") input.notice("Sorry, you are not allowed to use this command.")
return None return None

View file

@ -1,5 +1,4 @@
# Plugin by Lukeroge with some code from Phenny # Plugin by Lukeroge with some code from Phenny
# <lukeroge@gmail.com> <http://www.dempltr.com/>
from util import hook from util import hook
from util import http from util import http

View file

@ -1,4 +1,4 @@
# BING translation plugin by lukeroge and neersighted # BING translation plugin by Lukeroge and neersighted
from util import hook from util import hook
from util import http from util import http
import re import re

View file

@ -1,17 +1,17 @@
""" # written by Scaevolus, modified by Lukeroge
twitter.py: written by Scaevolus 2009, modified by Lukeroge 2012
retrieves most recent tweets
"""
import random import random
import re import re
from time import strptime, strftime from time import strftime
from time import strptime
from datetime import datetime from datetime import datetime
from util import hook
from util import hook, http, timesince from util import http
from util import timesince
def unescape_xml(string): def unescape_xml(string):
"""Unescapes XML"""
return string.replace('&gt;', '>').replace('&lt;', '<').replace('&apos;', return string.replace('&gt;', '>').replace('&lt;', '<').replace('&apos;',
"'").replace('&quote;', '"').replace('&amp;', '&') "'").replace('&quote;', '"').replace('&amp;', '&')
@ -20,6 +20,7 @@ history_max_size = 250
def parseDateTime(s): def parseDateTime(s):
"""Parses the date from a string"""
if s is None: if s is None:
return None return None
m = re.match(r'(.*?)(?:\.(\d+))?(([-+]\d{1,2}):(\d{2}))?$', m = re.match(r'(.*?)(?:\.(\d+))?(([-+]\d{1,2}):(\d{2}))?$',

View file

@ -46,7 +46,7 @@ with open("plugins/data/kill_bodyparts.txt") as f:
def slap(inp, me=None, nick=None, conn=None, notice=None): def slap(inp, me=None, nick=None, conn=None, notice=None):
".slap <user> -- Makes the bot slap <user>." ".slap <user> -- Makes the bot slap <user>."
target = inp.lower() target = inp.lower()
if not re.match(nick_re, target): if not re.match(nick_re, target):
notice("Invalid username!") notice("Invalid username!")
return return
@ -56,11 +56,11 @@ def slap(inp, me=None, nick=None, conn=None, notice=None):
target = nick target = nick
else: else:
target = inp target = inp
out = random.choice(slaps) out = random.choice(slaps)
out = out.replace('<who>', target) out = out.replace('<who>', target)
out = out.replace('<item>', random.choice(slap_items)) out = out.replace('<item>', random.choice(slap_items))
# act out the message # act out the message
me(out) me(out)
@ -78,7 +78,7 @@ def lart(inp, me=None, nick=None, conn=None, notice=None):
target = nick target = nick
else: else:
target = inp target = inp
out = random.choice(larts) out = random.choice(larts)
out = out.replace('<who>', target) out = out.replace('<who>', target)
out = out.replace('<item>', random.choice(slap_items)) out = out.replace('<item>', random.choice(slap_items))
@ -98,7 +98,7 @@ def kill(inp, me=None, nick=None, conn=None, notice=None):
target = nick target = nick
else: else:
target = inp target = inp
out = random.choice(kills) out = random.choice(kills)
out = out.replace('<who>', target) out = out.replace('<who>', target)
out = out.replace('<body>', random.choice(kill_bodyparts)) out = out.replace('<body>', random.choice(kill_bodyparts))

View file

@ -10,8 +10,8 @@ def word(inp, say=False, nick=False):
soup = BeautifulSoup(page) soup = BeautifulSoup(page)
word = soup.find('strong', {'class' : 'main_entry_word'}).renderContents() word = soup.find('strong', {'class': 'main_entry_word'}).renderContents()
function = soup.find('p', {'class' : 'word_function'}).renderContents() function = soup.find('p', {'class': 'word_function'}).renderContents()
#definitions = re.findall(r'<span class="ssens"><strong>:</strong>' #definitions = re.findall(r'<span class="ssens"><strong>:</strong>'
# r' *([^<]+)</span>', content) # r' *([^<]+)</span>', content)