diff --git a/plugins/admin.py b/plugins/admin.py index 2190101..65673e2 100755 --- a/plugins/admin.py +++ b/plugins/admin.py @@ -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) return + @hook.command(adminonly=True) def unadmin(inp, notice=None, bot=None, config=None): ".unadmin -- Make a non-admin." @@ -47,6 +48,7 @@ def unadmin(inp, notice=None, bot=None, config=None): notice("%s is not an admin." % target) return + @hook.command(autohelp=False) def channels(inp, conn=None): ".channels -- Lists the channels that the bot is in." @@ -64,6 +66,7 @@ def stop(inp, nick=None, conn=None): time.sleep(5) os.execl("./cloudbot", "stop") + @hook.command(autohelp=False, adminonly=True) def restart(inp, nick=None, conn=None): ".restart [reason] -- Restarts the bot with [reason] as its quit message." diff --git a/plugins/dice.py b/plugins/dice.py index dd2ee2f..2e688bd 100755 --- a/plugins/dice.py +++ b/plugins/dice.py @@ -1,7 +1,5 @@ -""" -dice.py: written by Scaevolus 2008, updated 2009 -simulates dicerolls -""" +# Written by Scaevolus, updated by Lukeroge + import re import random @@ -30,7 +28,8 @@ def nrolls(count, n): return [random.randint(1, n) for x in xrange(count)] else: # fake it return [int(random.normalvariate(.5 * (1 + n) * count, - (((n+1)*(2*n+1)/6.-(.5*(1+n))**2)*count)**.5))] + (((n + 1) * (2 * n + 1) / 6. - + (.5 * (1 + n)) ** 2) * count) ** .5))] @hook.command('roll') diff --git a/plugins/dictionary.py b/plugins/dictionary.py index 5efbf9c..934a8b8 100755 --- a/plugins/dictionary.py +++ b/plugins/dictionary.py @@ -1,13 +1,14 @@ +# Plugin by GhettoWizard and Scaevolus import re - -from util import hook, http +from util import hook +from util import http @hook.command('u') @hook.command def urban(inp): ".urban [id] -- Looks up on urbandictionary.com." - + # set a default definition number id = 1 @@ -27,11 +28,12 @@ def urban(inp): if page['result_type'] == 'no_results': return 'Not found.' - + # try getting the requested definition try: 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: return 'Not found.' @@ -41,7 +43,6 @@ def urban(inp): return out -# define plugin by GhettoWizard & Scaevolus @hook.command('dictionary') @hook.command def define(inp): diff --git a/plugins/drama.py b/plugins/drama.py index 67008bf..db586bc 100755 --- a/plugins/drama.py +++ b/plugins/drama.py @@ -7,7 +7,8 @@ ed_url = "http://encyclopediadramatica.ch/" @hook.command('ed') @hook.command def drama(inp): - ".drama -- Gets the first paragraph of Encyclopedia Dramatica article on ." + ".drama -- Gets the first paragraph of"\ + "the Encyclopedia Dramatica article on ." j = http.get_json(api_url, search=inp) if not j[1]: diff --git a/plugins/fact.py b/plugins/fact.py index 3a4ee55..82bec4e 100755 --- a/plugins/fact.py +++ b/plugins/fact.py @@ -1,7 +1,10 @@ import re -from util import hook, http, misc +from util import hook +from util import http +from util import misc from BeautifulSoup import BeautifulSoup + @hook.command(autohelp=False) def fact(inp, say=False, nick=False): ".fact -- Gets a random fact from OMGFACTS." @@ -15,10 +18,11 @@ def fact(inp, say=False, nick=False): return u"%s [ %s ]" % (fact, link) + def get_fact(): page = http.get('http://www.omg-facts.com/random') soup = BeautifulSoup(page) - container = soup.find('a', {'class' : 'surprise'}) + container = soup.find('a', {'class': 'surprise'}) link = container['href'] fact = misc.strip_html(container.renderContents()) diff --git a/plugins/factoids.py b/plugins/factoids.py index c52a736..706cc06 100755 --- a/plugins/factoids.py +++ b/plugins/factoids.py @@ -112,11 +112,10 @@ def forget(inp, db=None, input=None, notice=None): def factoid(inp, say=None, db=None, bot=None): "? -- Shows what data is associated with ." try: - prefix_on = bot.config["plugins"]["factoids"].get("prefix", False) + prefix_on = bot.config["plugins"]["factoids"].get("prefix", False) except KeyError: prefix_on = False - db_init(db) data = get_memory(db, inp.group(1).strip()) diff --git a/plugins/feelings.py b/plugins/feelings.py index 184d8e1..3141ceb 100755 --- a/plugins/feelings.py +++ b/plugins/feelings.py @@ -33,7 +33,7 @@ def insult(inp, nick=None, me=None, conn=None): target = nick else: target = inp - + out = 'insults %s... "%s"' % (target, random.choice(insults)) me(out) @@ -51,6 +51,6 @@ def flirt(inp, nick=None, me=None, conn=None): target = 'itself' else: target = inp - + out = 'insults %s... "%s"' % (target, random.choice(flirts)) me(out) diff --git a/plugins/flip.py b/plugins/flip.py index d613e48..14ad83e 100755 --- a/plugins/flip.py +++ b/plugins/flip.py @@ -1,6 +1,7 @@ from util import hook import random + @hook.command def flip(inp, flip_count=0, say=None): ".flip -- Flips over." diff --git a/plugins/fmylife.py b/plugins/fmylife.py index 27ca639..7c67b15 100755 --- a/plugins/fmylife.py +++ b/plugins/fmylife.py @@ -1,5 +1,4 @@ # Plugin by Lukeroge -# from util import hook, http from urlparse import urljoin @@ -12,7 +11,7 @@ fml_cache = defaultdict() 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')) soup = BeautifulSoup(page) diff --git a/plugins/geoip.py b/plugins/geoip.py index b8d540c..7912b1a 100755 --- a/plugins/geoip.py +++ b/plugins/geoip.py @@ -36,8 +36,10 @@ def geoip(inp, say=None, bot=None): localstring = give["city"] else: localstring = give["city"] + ", " + give["state"] - say("That IP comes from " + give["country"] + " (" + give["country_short"] + ")") - say("I think it's in " + localstring + " with a timezone of " + give["timezone"] + "GMT") + say("That IP comes from " + give["country"] + + " (" + give["country_short"] + ")") + say("I think it's in " + localstring + + " with a timezone of " + give["timezone"] + "GMT") 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 diff --git a/plugins/gitio.py b/plugins/gitio.py index 6c5c8fa..99d4e41 100755 --- a/plugins/gitio.py +++ b/plugins/gitio.py @@ -1,4 +1,4 @@ -# plugin created by neersighted and lukeroge +# Plugin by neersighted and Lukeroge from util import hook import urllib2 diff --git a/plugins/google.py b/plugins/google.py index bf2a81c..282649a 100755 --- a/plugins/google.py +++ b/plugins/google.py @@ -1,9 +1,10 @@ import random - -from util import hook, http +from util import hook +from util import http def api_get(kind, query): + """Use the RESTful Google Search API""" url = 'http://ajax.googleapis.com/ajax/services/search/%s?' \ 'v=1.0&safe=off' return http.get_json(url % kind, q=query) @@ -21,8 +22,9 @@ def googleimage(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'] + @hook.command('search') @hook.command('g') diff --git a/plugins/hash.py b/plugins/hash.py index 48d291f..d00731c 100755 --- a/plugins/hash.py +++ b/plugins/hash.py @@ -1,26 +1,31 @@ import hashlib from util import hook + @hook.command def md5(inp): ".hash -- Returns a md5 hash of ." return hashlib.md5(inp).hexdigest() + @hook.command def sha1(inp): ".hash -- Returns a sha1 hash of ." return hashlib.sha1(inp).hexdigest() + @hook.command def sha256(inp): ".hash -- Returns a sha256 hash of ." return hashlib.sha256(inp).hexdigest() + @hook.command def sha512(inp): ".hash -- Returns a sha512 hash of ." return hashlib.sha512(inp).hexdigest() + @hook.command def hash(inp): ".hash -- Returns hashes of ." diff --git a/plugins/help.py b/plugins/help.py index 70ac3be..ceb67c3 100755 --- a/plugins/help.py +++ b/plugins/help.py @@ -1,7 +1,7 @@ import re - from util import hook + @hook.command(autohelp=False) def help(inp, input=None, bot=None, say=None, notice=None): ".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(): fn = re.match(r'^plugins.(.+).py$', func._filename) 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 func.__doc__ is not None: if func in funcs: @@ -35,13 +37,13 @@ def help(inp, input=None, bot=None, say=None, notice=None): out[1] += " " + str(x) else: out[0] += " " + str(x) - + notice("Commands I recognise: " + out[0][1:]) if out[1]: notice(out[1][1:]) - notice("For detailed help, do '.help ' where is the " + - "name of the command you want help for.") - + notice("For detailed help, do '.help ' where "\ + "is the name of the command you want help for.") + else: if inp in commands: notice(commands[inp].__doc__) diff --git a/plugins/ignore.py b/plugins/ignore.py index b6b2110..662531f 100755 --- a/plugins/ignore.py +++ b/plugins/ignore.py @@ -1,6 +1,7 @@ import json from util import hook + @hook.sieve def ignoresieve(bot, input, func, type, args): """ blocks input from ignored channels/nicks """ @@ -8,7 +9,10 @@ def ignoresieve(bot, input, func, type, args): # don't block input to event hooks if type == "event": 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": return input 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) return + @hook.command(adminonly=True) def unignore(inp, notice=None, bot=None, config=None): - ".unignore -- Makes the bot listen to ." + ".unignore -- Makes the bot listen to"\ + " ." target = inp.lower() ignorelist = bot.config["plugins"]["ignore"]["ignored"] if target in ignorelist: @@ -54,4 +60,3 @@ def unignore(inp, notice=None, bot=None, config=None): else: notice("%s is not ignored." % target) return - diff --git a/plugins/lastfm.py b/plugins/lastfm.py index a1616aa..d910ea7 100755 --- a/plugins/lastfm.py +++ b/plugins/lastfm.py @@ -1,11 +1,12 @@ # Upgraded with tables/caching by ChauffeR of #freebnc on irc.esper.net from util import hook, http + @hook.command('l', autohelp=False) -@hook.command('lfm', autohelp=False) @hook.command(autohelp=False) 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: user = inp else: diff --git a/plugins/log.py b/plugins/log.py index f05129e..4b761a9 100755 --- a/plugins/log.py +++ b/plugins/log.py @@ -10,11 +10,12 @@ import re 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' -formats = {'PRIVMSG': '<%(nick)s> %(msg)s', +formats = { + 'PRIVMSG': '<%(nick)s> %(msg)s', 'PART': '-!- %(nick)s [%(user)s@%(host)s] has left %(chan)s', 'JOIN': '-!- %(nick)s [%(user)s@%(host)s] has joined %(param0)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', 'QUIT': '-!- %(nick)s has quit [%(msg)s]', '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])') 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()) diff --git a/plugins/mctools.py b/plugins/mctools.py index 399c4fd..19f1e95 100755 --- a/plugins/mctools.py +++ b/plugins/mctools.py @@ -12,13 +12,15 @@ def mcping_connect(host, port): sock.send('\xfe') response = sock.recv(1) 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] - values = sock.recv(length*2).decode('utf-16be').split(u'\xa7') + values = sock.recv(length * 2).decode('utf-16be').split(u'\xa7') 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: - 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) @@ -29,33 +31,42 @@ def mcstatus(inp, bot=None): if password is None: 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(): return "Minecraft login servers appear to be online!" else: return "Minecraft login servers appear to be offline!" + @hook.command def mclogin(inp, say=None): - ".mclogin -- Attempts to log in to Minecrat with and (This is NOT logged)." + ".mclogin -- Attempts to log in to Minecraft with "\ + " and (This is NOT logged)." inp = inp.split(" ") username = inp[0] password = inp[1] 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(): return "I logged in with " + username 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 def mcpaid(inp): - ".mcpaid -- Checks if has a premium Minecraft account." + ".mcpaid -- Checks if has a "\ + "premium Minecraft account." login = http.get("http://www.minecraft.net/haspaid.jsp?user=" + inp) if "true" in login: - return "The account \'" + inp + "\' is a premium Minecraft account!" + return "The account \'" + inp + "\' is a "\ + "premium Minecraft account!" 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 diff --git a/plugins/namegen.py b/plugins/namegen.py index e3d5683..ba82033 100755 --- a/plugins/namegen.py +++ b/plugins/namegen.py @@ -1,9 +1,9 @@ # Plugin by Lukeroge -# - -from util import hook, molecular +from util import hook +from util import molecular import unicodedata + @hook.command() 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." diff --git a/plugins/op.py b/plugins/op.py index c11be31..28e96ad 100644 --- a/plugins/op.py +++ b/plugins/op.py @@ -2,6 +2,17 @@ from util import hook +@hook.command(adminonly=True) +def topic(inp, conn=None, chan=None, notice=None): + ".topic [channel] -- 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) def kick(inp, chan=None, conn=None, notice=None): ".kick [channel] [reason] -- Makes the bot kick in [channel] "\ @@ -65,6 +76,7 @@ def unban(inp, conn=None, chan=None, notice=None): notice("Attempting to unban %s from %s..." % (user, chan)) conn.send(out) + @hook.command(adminonly=True) def kickban(inp, chan=None, conn=None, notice=None): ".kickban [channel] [reason] -- Makes the bot kickban in [channel] "\ @@ -96,13 +108,3 @@ def kickban(inp, chan=None, conn=None, notice=None): notice("Attempting to kickban %s from %s..." % (user, chan)) conn.send(out1) conn.send(out2) - -@hook.command(adminonly=True) -def topic(inp, conn=None, chan=None, notice=None): - ".topic [channel] -- 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) diff --git a/plugins/potato.py b/plugins/potato.py index cf34686..5712a35 100755 --- a/plugins/potato.py +++ b/plugins/potato.py @@ -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�', '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 def potato(inp, me=None, input=None): ".potato - Makes a tasty little potato." diff --git a/plugins/quote.py b/plugins/quote.py index 6553018..d1a49b6 100755 --- a/plugins/quote.py +++ b/plugins/quote.py @@ -4,24 +4,27 @@ import time from util import hook + 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 return "[%d/%d] <%s> %s" % (num, n_quotes, nick, msg) + 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" "(chan, nick, add_nick, msg, time real, deleted default 0, " "primary key (chan, nick, msg))") db.commit() + 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: - db.execute('''INSERT OR FAIL INTO quote - (chan, nick, add_nick, msg, time) + db.execute('''INSERT OR FAIL INTO quote + (chan, nick, add_nick, msg, time) VALUES(?,?,?,?,?)''', (chan, nick, add_nick, msg, time.time())) db.commit() @@ -29,30 +32,34 @@ def add_quote(db, chan, nick, add_nick, msg): return "Message already stored, doing nothing." return "Quote added." + 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 chan=? AND lower(nick)=lower(?) AND msg=msg''') db.commit() + 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 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) - 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 - if num and num > count: # If a number is given and and there are not enough quotes, raise an Exception. - raise Exception("I only have %d quote%s for %s." % (count, ('s', '')[count == 1], name)) + 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)) if num and num == 0: # If the number is zero, set it to one num = 1 if not num: # If a number is not given, select a random one num = random.randint(1, count) return num + 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 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) except Exception as error_message: return error_message - + quote = db.execute('''SELECT time, nick, msg FROM quote WHERE deleted != 1 AND lower(nick) = lower(?) ORDER BY time - LIMIT ?, 1''', (nick, (num-1))).fetchall()[0] + LIMIT ?, 1''', (nick, (num - 1))).fetchall()[0] return format_quote(quote, num, count) - + + 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(*) FROM quote WHERE deleted != 1 @@ -88,11 +96,12 @@ def get_quote_by_nick_chan(db, chan, nick, num=False): AND chan = ? AND lower(nick) = lower(?) 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) -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(*) FROM quote WHERE deleted != 1 @@ -103,14 +112,15 @@ def get_quote_by_chan(db, chan, num=False): except Exception as error_message: return error_message - quote = db.execute('''SELECT time, nick, msg + quote = db.execute('''SELECT time, nick, msg FROM quote WHERE deleted != 1 - AND chan = ? + AND chan = ? ORDER BY time - LIMIT ?, 1''', (chan, (num -1))).fetchall()[0] + LIMIT ?, 1''', (chan, (num - 1))).fetchall()[0] return format_quote(quote, num, count) + @hook.command('q') @hook.command def quote(inp, nick='', chan='', db=None, notice=None): @@ -128,12 +138,12 @@ def quote(inp, nick='', chan='', db=None, notice=None): elif retrieve: select, num = retrieve.groups() by_chan = True if select.startswith('#') else False - if by_chan: + if by_chan: return get_quote_by_chan(db, select, num) else: return get_quote_by_nick(db, select, num) elif retrieve_chan: chan, nick, num = retrieve_chan.groups() return get_quote_by_nick_chan(db, chan, nick, num) - + notice(quote.__doc__) diff --git a/plugins/shorten.py b/plugins/shorten.py index 7e7daf2..7ab07e6 100755 --- a/plugins/shorten.py +++ b/plugins/shorten.py @@ -1,5 +1,4 @@ # Plugin by Lukeroge -# from util import hook, http from re import match diff --git a/plugins/sieve.py b/plugins/sieve.py index cdbeb9c..ccc4174 100755 --- a/plugins/sieve.py +++ b/plugins/sieve.py @@ -5,7 +5,7 @@ from util import hook @hook.sieve 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): return None @@ -32,7 +32,7 @@ def sieve_suite(bot, input, func, kind, args): if args.get('adminonly', False): 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.") return None diff --git a/plugins/time.py b/plugins/time.py index 1bb9f1f..d8cd9ed 100755 --- a/plugins/time.py +++ b/plugins/time.py @@ -1,5 +1,4 @@ # Plugin by Lukeroge with some code from Phenny -# from util import hook from util import http diff --git a/plugins/translate.py b/plugins/translate.py index 253e5f5..d61ab14 100755 --- a/plugins/translate.py +++ b/plugins/translate.py @@ -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 http import re diff --git a/plugins/twitter.py b/plugins/twitter.py index 9b78fef..6186823 100755 --- a/plugins/twitter.py +++ b/plugins/twitter.py @@ -1,17 +1,17 @@ -""" -twitter.py: written by Scaevolus 2009, modified by Lukeroge 2012 -retrieves most recent tweets -""" +# written by Scaevolus, modified by Lukeroge import random import re -from time import strptime, strftime +from time import strftime +from time import strptime from datetime import datetime - -from util import hook, http, timesince +from util import hook +from util import http +from util import timesince def unescape_xml(string): + """Unescapes XML""" return string.replace('>', '>').replace('<', '<').replace(''', "'").replace('"e;', '"').replace('&', '&') @@ -20,6 +20,7 @@ history_max_size = 250 def parseDateTime(s): + """Parses the date from a string""" if s is None: return None m = re.match(r'(.*?)(?:\.(\d+))?(([-+]\d{1,2}):(\d{2}))?$', diff --git a/plugins/violence.py b/plugins/violence.py index 603f7c5..9eda0e1 100755 --- a/plugins/violence.py +++ b/plugins/violence.py @@ -46,7 +46,7 @@ with open("plugins/data/kill_bodyparts.txt") as f: def slap(inp, me=None, nick=None, conn=None, notice=None): ".slap -- Makes the bot slap ." target = inp.lower() - + if not re.match(nick_re, target): notice("Invalid username!") return @@ -56,11 +56,11 @@ def slap(inp, me=None, nick=None, conn=None, notice=None): target = nick else: target = inp - + out = random.choice(slaps) out = out.replace('', target) out = out.replace('', random.choice(slap_items)) - + # act out the message me(out) @@ -78,7 +78,7 @@ def lart(inp, me=None, nick=None, conn=None, notice=None): target = nick else: target = inp - + out = random.choice(larts) out = out.replace('', target) out = out.replace('', random.choice(slap_items)) @@ -98,7 +98,7 @@ def kill(inp, me=None, nick=None, conn=None, notice=None): target = nick else: target = inp - + out = random.choice(kills) out = out.replace('', target) out = out.replace('', random.choice(kill_bodyparts)) diff --git a/plugins/wordoftheday.py b/plugins/wordoftheday.py index 3d4b631..ebf6c1c 100755 --- a/plugins/wordoftheday.py +++ b/plugins/wordoftheday.py @@ -10,8 +10,8 @@ def word(inp, say=False, nick=False): soup = BeautifulSoup(page) - word = soup.find('strong', {'class' : 'main_entry_word'}).renderContents() - function = soup.find('p', {'class' : 'word_function'}).renderContents() + word = soup.find('strong', {'class': 'main_entry_word'}).renderContents() + function = soup.find('p', {'class': 'word_function'}).renderContents() #definitions = re.findall(r':' # r' *([^<]+)', content)