diff --git a/modules/8ball.py b/modules/8ball.py index a289a2b..c050bea 100644 --- a/modules/8ball.py +++ b/modules/8ball.py @@ -49,4 +49,3 @@ eightball.commands = ['8ball'] if __name__ == '__main__': print(__doc__.strip()) - diff --git a/modules/archwiki.py b/modules/archwiki.py index 69502de..3526d2b 100644 --- a/modules/archwiki.py +++ b/modules/archwiki.py @@ -7,7 +7,7 @@ Licensed under the Eiffel Forum License 2. http://inamidst.com/phenny/ modified from Wikipedia module -author: mutantmonkey +author: mutantmonkey """ import re, urllib.request, urllib.parse, urllib.error diff --git a/modules/botfun.py b/modules/botfun.py index 2b25f0a..aef2027 100644 --- a/modules/botfun.py +++ b/modules/botfun.py @@ -1,7 +1,7 @@ #!/usr/bin/python2 """ botfight.py - .botfight module -author: mutantmonkey +author: mutantmonkey """ import random @@ -9,18 +9,17 @@ import random otherbot = "truncatedcone" def botfight(phenny, input): - messages = ["hits %s", "punches %s", "kicks %s", "hits %s with a rubber hose", "stabs %s with a clean kitchen knife"] - response = random.choice(messages) + messages = ["hits %s", "punches %s", "kicks %s", "hits %s with a rubber hose", "stabs %s with a clean kitchen knife"] + response = random.choice(messages) - phenny.do(response % otherbot) + phenny.do(response % otherbot) botfight.commands = ['botfight'] botfight.priority = 'low' def bothug(phenny, input): - phenny.do("hugs %s" % otherbot) + phenny.do("hugs %s" % otherbot) bothug.commands = ['bothug'] bothug.priority = 'low' if __name__ == '__main__': - print(__doc__.strip()) - + print(__doc__.strip()) diff --git a/modules/botsnack.py b/modules/botsnack.py index 43aaa24..bc9eeb7 100644 --- a/modules/botsnack.py +++ b/modules/botsnack.py @@ -1,7 +1,7 @@ #!/usr/bin/python2 """ botsnack.py - .botsnack module (aka simulated hunger 1.0) -author: mutantmonkey +author: mutantmonkey author: Casey Link This module simulates bot hunger and provides a mechanism @@ -106,5 +106,4 @@ botsnack.last_tick = time.time() botsnack.coolingdown = False if __name__ == '__main__': - print(__doc__.strip()) - + print(__doc__.strip()) diff --git a/modules/calc.py b/modules/calc.py index 58b59e3..3ad8013 100644 --- a/modules/calc.py +++ b/modules/calc.py @@ -15,100 +15,100 @@ r_result = re.compile(r'(?i)(.*?)') r_tag = re.compile(r'<\S+.*?>') subs = [ - (' in ', ' -> '), - (' over ', ' / '), - ('£', 'GBP '), - ('€', 'EUR '), - ('\$', 'USD '), - (r'\bKB\b', 'kilobytes'), - (r'\bMB\b', 'megabytes'), - (r'\bGB\b', 'kilobytes'), - ('kbps', '(kilobits / second)'), - ('mbps', '(megabits / second)') + (' in ', ' -> '), + (' over ', ' / '), + ('£', 'GBP '), + ('€', 'EUR '), + ('\$', 'USD '), + (r'\bKB\b', 'kilobytes'), + (r'\bMB\b', 'megabytes'), + (r'\bGB\b', 'kilobytes'), + ('kbps', '(kilobits / second)'), + ('mbps', '(megabits / second)') ] def calc(phenny, input): - """Use the Frink online calculator.""" - q = input.group(2) - if not q: - return phenny.say('0?') + """Use the Frink online calculator.""" + q = input.group(2) + if not q: + return phenny.say('0?') - query = q[:] - for a, b in subs: - query = re.sub(a, b, query) - query = query.rstrip(' \t') + query = q[:] + for a, b in subs: + query = re.sub(a, b, query) + query = query.rstrip(' \t') - precision = 5 - if query[-3:] in ('GBP', 'USD', 'EUR', 'NOK'): - precision = 2 - query = web.quote(query) + precision = 5 + if query[-3:] in ('GBP', 'USD', 'EUR', 'NOK'): + precision = 2 + query = web.quote(query) - uri = 'http://futureboy.us/fsp/frink.fsp?fromVal=' - bytes = web.get(uri + query) - m = r_result.search(bytes) - if m: - result = m.group(1) - result = r_tag.sub('', result) # strip span.warning tags - result = result.replace('>', '>') - result = result.replace('(undefined symbol)', '(?) ') + uri = 'http://futureboy.us/fsp/frink.fsp?fromVal=' + bytes = web.get(uri + query) + m = r_result.search(bytes) + if m: + result = m.group(1) + result = r_tag.sub('', result) # strip span.warning tags + result = result.replace('>', '>') + result = result.replace('(undefined symbol)', '(?) ') - if '.' in result: - try: result = str(round(float(result), precision)) - except ValueError: pass + if '.' in result: + try: result = str(round(float(result), precision)) + except ValueError: pass - if not result.strip(): - result = '?' - elif ' in ' in q: - result += ' ' + q.split(' in ', 1)[1] + if not result.strip(): + result = '?' + elif ' in ' in q: + result += ' ' + q.split(' in ', 1)[1] - phenny.say(q + ' = ' + result[:350]) - else: phenny.reply("Sorry, can't calculate that.") - phenny.say('Note that .calc is deprecated, consider using .c') + phenny.say(q + ' = ' + result[:350]) + else: phenny.reply("Sorry, can't calculate that.") + phenny.say('Note that .calc is deprecated, consider using .c') calc.commands = ['calc'] calc.example = '.calc 5 + 3' def c(phenny, input): - """Google calculator.""" - if not input.group(2): - return phenny.reply("Nothing to calculate.") - q = input.group(2) - q = q.replace('\xcf\x95', 'phi') # utf-8 U+03D5 - q = q.replace('\xcf\x80', 'pi') # utf-8 U+03C0 - uri = 'http://www.google.com/ig/calculator?q=' - bytes = web.get(uri + web.quote(q)) - parts = bytes.split('",') - answer = [p for p in parts if p.startswith('rhs: "')][0][6:] - if answer: - #answer = ''.join(chr(ord(c)) for c in answer) - #answer = answer.decode('utf-8') - answer = answer.replace('\xc2\xa0', ',') - answer = answer.replace('', '^(') - answer = answer.replace('', ')') - answer = web.decode(answer) - phenny.say(answer) - else: phenny.say('Sorry, no result.') + """Google calculator.""" + if not input.group(2): + return phenny.reply("Nothing to calculate.") + q = input.group(2) + q = q.replace('\xcf\x95', 'phi') # utf-8 U+03D5 + q = q.replace('\xcf\x80', 'pi') # utf-8 U+03C0 + uri = 'http://www.google.com/ig/calculator?q=' + bytes = web.get(uri + web.quote(q)) + parts = bytes.split('",') + answer = [p for p in parts if p.startswith('rhs: "')][0][6:] + if answer: + #answer = ''.join(chr(ord(c)) for c in answer) + #answer = answer.decode('utf-8') + answer = answer.replace('\xc2\xa0', ',') + answer = answer.replace('', '^(') + answer = answer.replace('', ')') + answer = web.decode(answer) + phenny.say(answer) + else: phenny.say('Sorry, no result.') c.commands = ['c'] c.example = '.c 5 + 3' def py(phenny, input): - query = input.group(2) - uri = 'http://tumbolia.appspot.com/py/' - answer = web.get(uri + web.quote(query)) - if answer: - phenny.say(answer) - else: phenny.reply('Sorry, no result.') + query = input.group(2) + uri = 'http://tumbolia.appspot.com/py/' + answer = web.get(uri + web.quote(query)) + if answer: + phenny.say(answer) + else: phenny.reply('Sorry, no result.') py.commands = ['py'] def wa(phenny, input): - if not input.group(2): - return phenny.reply("No search term.") - query = input.group(2) - uri = 'http://tumbolia.appspot.com/wa/' - answer = web.get(uri + web.quote(query.replace('+', '%2B'))) - if answer: - phenny.say(answer) - else: phenny.reply('Sorry, no result.') + if not input.group(2): + return phenny.reply("No search term.") + query = input.group(2) + uri = 'http://tumbolia.appspot.com/wa/' + answer = web.get(uri + web.quote(query.replace('+', '%2B'))) + if answer: + phenny.say(answer) + else: phenny.reply('Sorry, no result.') wa.commands = ['wa'] if __name__ == '__main__': - print(__doc__.strip()) + print(__doc__.strip()) diff --git a/modules/chillmeter.py b/modules/chillmeter.py index 88305f5..9732b33 100644 --- a/modules/chillmeter.py +++ b/modules/chillmeter.py @@ -143,4 +143,4 @@ chill.commands = ['chill'] chill.priority = 'low' if __name__ == '__main__': - print(__doc__.strip()) + print(__doc__.strip()) diff --git a/modules/clock.py b/modules/clock.py index 7b27c0c..b29842e 100644 --- a/modules/clock.py +++ b/modules/clock.py @@ -12,20 +12,20 @@ from decimal import Decimal as dec from tools import deprecated TimeZones = {'KST': 9, 'CADT': 10.5, 'EETDST': 3, 'MESZ': 2, 'WADT': 9, - 'EET': 2, 'MST': -7, 'WAST': 8, 'IST': 5.5, 'B': 2, - 'MSK': 3, 'X': -11, 'MSD': 4, 'CETDST': 2, 'AST': -4, - 'HKT': 8, 'JST': 9, 'CAST': 9.5, 'CET': 1, 'CEST': 2, - 'EEST': 3, 'EAST': 10, 'METDST': 2, 'MDT': -6, 'A': 1, - 'UTC': 0, 'ADT': -3, 'EST': -5, 'E': 5, 'D': 4, 'G': 7, - 'F': 6, 'I': 9, 'H': 8, 'K': 10, 'PDT': -7, 'M': 12, - 'L': 11, 'O': -2, 'MEST': 2, 'Q': -4, 'P': -3, 'S': -6, - 'R': -5, 'U': -8, 'T': -7, 'W': -10, 'WET': 0, 'Y': -12, - 'CST': -6, 'EADT': 11, 'Z': 0, 'GMT': 0, 'WETDST': 1, - 'C': 3, 'WEST': 1, 'CDT': -5, 'MET': 1, 'N': -1, 'V': -9, - 'EDT': -4, 'UT': 0, 'PST': -8, 'MEZ': 1, 'BST': 1, - 'ACS': 9.5, 'ATL': -4, 'ALA': -9, 'HAW': -10, 'AKDT': -8, - 'AKST': -9, - 'BDST': 2} + 'EET': 2, 'MST': -7, 'WAST': 8, 'IST': 5.5, 'B': 2, + 'MSK': 3, 'X': -11, 'MSD': 4, 'CETDST': 2, 'AST': -4, + 'HKT': 8, 'JST': 9, 'CAST': 9.5, 'CET': 1, 'CEST': 2, + 'EEST': 3, 'EAST': 10, 'METDST': 2, 'MDT': -6, 'A': 1, + 'UTC': 0, 'ADT': -3, 'EST': -5, 'E': 5, 'D': 4, 'G': 7, + 'F': 6, 'I': 9, 'H': 8, 'K': 10, 'PDT': -7, 'M': 12, + 'L': 11, 'O': -2, 'MEST': 2, 'Q': -4, 'P': -3, 'S': -6, + 'R': -5, 'U': -8, 'T': -7, 'W': -10, 'WET': 0, 'Y': -12, + 'CST': -6, 'EADT': 11, 'Z': 0, 'GMT': 0, 'WETDST': 1, + 'C': 3, 'WEST': 1, 'CDT': -5, 'MET': 1, 'N': -1, 'V': -9, + 'EDT': -4, 'UT': 0, 'PST': -8, 'MEZ': 1, 'BST': 1, + 'ACS': 9.5, 'ATL': -4, 'ALA': -9, 'HAW': -10, 'AKDT': -8, + 'AKST': -9, + 'BDST': 2} TZ1 = { 'NDT': -2.5, @@ -183,8 +183,8 @@ TZ2 = { } TZ3 = { - 'AEST': 10, - 'AEDT': 11 + 'AEST': 10, + 'AEDT': 11 } # TimeZones.update(TZ2) # do these have to be negated? @@ -195,109 +195,109 @@ r_local = re.compile(r'\([a-z]+_[A-Z]+\)') @deprecated def f_time(self, origin, match, args): - """Returns the current time.""" - tz = match.group(2) or 'GMT' + """Returns the current time.""" + tz = match.group(2) or 'GMT' - # Personal time zones, because they're rad - if hasattr(self.config, 'timezones'): - People = self.config.timezones - else: People = {} + # Personal time zones, because they're rad + if hasattr(self.config, 'timezones'): + People = self.config.timezones + else: People = {} - if tz in People: - tz = People[tz] - elif (not match.group(2)) and origin.nick in People: - tz = People[origin.nick] + if tz in People: + tz = People[tz] + elif (not match.group(2)) and origin.nick in People: + tz = People[origin.nick] - TZ = tz.upper() - if len(tz) > 30: return + TZ = tz.upper() + if len(tz) > 30: return - if (TZ == 'UTC') or (TZ == 'Z'): - msg = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()) - self.msg(origin.sender, msg) - elif r_local.match(tz): # thanks to Mark Shoulsdon (clsn) - locale.setlocale(locale.LC_TIME, (tz[1:-1], 'UTF-8')) - msg = time.strftime("%A, %d %B %Y %H:%M:%SZ", time.gmtime()) - self.msg(origin.sender, msg) - elif TZ in TimeZones: - offset = TimeZones[TZ] * 3600 - timenow = time.gmtime(time.time() + offset) - msg = time.strftime("%a, %d %b %Y %H:%M:%S " + str(TZ), timenow) - self.msg(origin.sender, msg) - elif tz and tz[0] in ('+', '-') and 4 <= len(tz) <= 6: - timenow = time.gmtime(time.time() + (int(tz[:3]) * 3600)) - msg = time.strftime("%a, %d %b %Y %H:%M:%S " + str(tz), timenow) - self.msg(origin.sender, msg) - else: - try: t = float(tz) - except ValueError: - import os, re, subprocess - r_tz = re.compile(r'^[A-Za-z]+(?:/[A-Za-z_]+)*$') - if r_tz.match(tz) and os.path.isfile('/usr/share/zoneinfo/' + tz): - cmd, PIPE = 'TZ=%s date' % tz, subprocess.PIPE - proc = subprocess.Popen(cmd, shell=True, stdout=PIPE) - self.msg(origin.sender, proc.communicate()[0]) - else: - error = "Sorry, I don't know about the '%s' timezone." % tz - self.msg(origin.sender, origin.nick + ': ' + error) - else: - timenow = time.gmtime(time.time() + (t * 3600)) - msg = time.strftime("%a, %d %b %Y %H:%M:%S " + str(tz), timenow) - self.msg(origin.sender, msg) + if (TZ == 'UTC') or (TZ == 'Z'): + msg = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()) + self.msg(origin.sender, msg) + elif r_local.match(tz): # thanks to Mark Shoulsdon (clsn) + locale.setlocale(locale.LC_TIME, (tz[1:-1], 'UTF-8')) + msg = time.strftime("%A, %d %B %Y %H:%M:%SZ", time.gmtime()) + self.msg(origin.sender, msg) + elif TZ in TimeZones: + offset = TimeZones[TZ] * 3600 + timenow = time.gmtime(time.time() + offset) + msg = time.strftime("%a, %d %b %Y %H:%M:%S " + str(TZ), timenow) + self.msg(origin.sender, msg) + elif tz and tz[0] in ('+', '-') and 4 <= len(tz) <= 6: + timenow = time.gmtime(time.time() + (int(tz[:3]) * 3600)) + msg = time.strftime("%a, %d %b %Y %H:%M:%S " + str(tz), timenow) + self.msg(origin.sender, msg) + else: + try: t = float(tz) + except ValueError: + import os, re, subprocess + r_tz = re.compile(r'^[A-Za-z]+(?:/[A-Za-z_]+)*$') + if r_tz.match(tz) and os.path.isfile('/usr/share/zoneinfo/' + tz): + cmd, PIPE = 'TZ=%s date' % tz, subprocess.PIPE + proc = subprocess.Popen(cmd, shell=True, stdout=PIPE) + self.msg(origin.sender, proc.communicate()[0]) + else: + error = "Sorry, I don't know about the '%s' timezone." % tz + self.msg(origin.sender, origin.nick + ': ' + error) + else: + timenow = time.gmtime(time.time() + (t * 3600)) + msg = time.strftime("%a, %d %b %Y %H:%M:%S " + str(tz), timenow) + self.msg(origin.sender, msg) f_time.commands = ['t'] f_time.name = 't' f_time.example = '.t UTC' def beats(phenny, input): - """Shows the internet time in Swatch beats.""" - beats = ((time.time() + 3600) % 86400) / 86.4 - beats = int(math.floor(beats)) - phenny.say('@%03i' % beats) + """Shows the internet time in Swatch beats.""" + beats = ((time.time() + 3600) % 86400) / 86.4 + beats = int(math.floor(beats)) + phenny.say('@%03i' % beats) beats.commands = ['beats'] beats.priority = 'low' def divide(input, by): - return (input / by), (input % by) + return (input / by), (input % by) def yi(phenny, input): - """Shows whether it is currently yi or not.""" - quadraels, remainder = divide(int(time.time()), 1753200) - raels = quadraels * 4 - extraraels, remainder = divide(remainder, 432000) - if extraraels == 4: - return phenny.say('Yes! PARTAI!') - elif extraraels == 3: - return phenny.say('Soon...') - else: phenny.say('Not yet...') + """Shows whether it is currently yi or not.""" + quadraels, remainder = divide(int(time.time()), 1753200) + raels = quadraels * 4 + extraraels, remainder = divide(remainder, 432000) + if extraraels == 4: + return phenny.say('Yes! PARTAI!') + elif extraraels == 3: + return phenny.say('Soon...') + else: phenny.say('Not yet...') yi.commands = ['yi'] yi.priority = 'low' def tock(phenny, input): - """Shows the time from the USNO's atomic clock.""" - u = urllib.request.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') - info = u.info() - u.close() - phenny.say('"' + info['Date'] + '" - tycho.usno.navy.mil') + """Shows the time from the USNO's atomic clock.""" + u = urllib.request.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') + info = u.info() + u.close() + phenny.say('"' + info['Date'] + '" - tycho.usno.navy.mil') tock.commands = ['tock'] tock.priority = 'high' def npl(phenny, input): - """Shows the time from NPL's SNTP server.""" - client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - client.sendto('\x1b' + 47 * '\0', ('ntp1.npl.co.uk', 123)) - data, address = client.recvfrom(1024) - if data: - buf = struct.unpack('B' * 48, data) - d = dec('0.0') - for i in range(8): - d += dec(buf[32 + i]) * dec(str(math.pow(2, (3 - i) * 8))) - d -= dec(2208988800) - a, b = str(d).split('.') - f = '%Y-%m-%d %H:%M:%S' - result = datetime.datetime.fromtimestamp(d).strftime(f) + '.' + b[:6] - phenny.say(result + ' - ntp1.npl.co.uk') - else: phenny.say('No data received, sorry') + """Shows the time from NPL's SNTP server.""" + client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + client.sendto('\x1b' + 47 * '\0', ('ntp1.npl.co.uk', 123)) + data, address = client.recvfrom(1024) + if data: + buf = struct.unpack('B' * 48, data) + d = dec('0.0') + for i in range(8): + d += dec(buf[32 + i]) * dec(str(math.pow(2, (3 - i) * 8))) + d -= dec(2208988800) + a, b = str(d).split('.') + f = '%Y-%m-%d %H:%M:%S' + result = datetime.datetime.fromtimestamp(d).strftime(f) + '.' + b[:6] + phenny.say(result + ' - ntp1.npl.co.uk') + else: phenny.say('No data received, sorry') npl.commands = ['npl'] npl.priority = 'high' if __name__ == '__main__': - print(__doc__.strip()) + print(__doc__.strip()) diff --git a/modules/etymology.py b/modules/etymology.py index e78683d..47b201e 100644 --- a/modules/etymology.py +++ b/modules/etymology.py @@ -19,82 +19,82 @@ r_tag = re.compile(r'<(?!!)[^>]+>') r_whitespace = re.compile(r'[\t\r\n ]+') abbrs = [ - 'cf', 'lit', 'etc', 'Ger', 'Du', 'Skt', 'Rus', 'Eng', 'Amer.Eng', 'Sp', - 'Fr', 'N', 'E', 'S', 'W', 'L', 'Gen', 'J.C', 'dial', 'Gk', - '19c', '18c', '17c', '16c', 'St', 'Capt', 'obs', 'Jan', 'Feb', 'Mar', - 'Apr', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'c', 'tr', 'e', 'g' + 'cf', 'lit', 'etc', 'Ger', 'Du', 'Skt', 'Rus', 'Eng', 'Amer.Eng', 'Sp', + 'Fr', 'N', 'E', 'S', 'W', 'L', 'Gen', 'J.C', 'dial', 'Gk', + '19c', '18c', '17c', '16c', 'St', 'Capt', 'obs', 'Jan', 'Feb', 'Mar', + 'Apr', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'c', 'tr', 'e', 'g' ] t_sentence = r'^.*?(?') - s = s.replace('<', '<') - s = s.replace('&', '&') - return s + s = s.replace('>', '>') + s = s.replace('<', '<') + s = s.replace('&', '&') + return s def text(html): - html = r_tag.sub('', html) - html = r_whitespace.sub(' ', html) - return unescape(html).strip() + html = r_tag.sub('', html) + html = r_whitespace.sub(' ', html) + return unescape(html).strip() def etymology(word): - # @@ sbp, would it be possible to have a flag for .ety to get 2nd/etc - # entries? - http://swhack.com/logs/2006-07-19#T15-05-29 - - if len(word) > 25: - raise ValueError("Word too long: %s[...]" % word[:10]) - word = {'axe': 'ax/axe'}.get(word, word) + # @@ sbp, would it be possible to have a flag for .ety to get 2nd/etc + # entries? - http://swhack.com/logs/2006-07-19#T15-05-29 + + if len(word) > 25: + raise ValueError("Word too long: %s[...]" % word[:10]) + word = {'axe': 'ax/axe'}.get(word, word) - bytes = web.get(etyuri % web.urllib.quote(word)) - definitions = r_definition.findall(bytes) + bytes = web.get(etyuri % web.urllib.quote(word)) + definitions = r_definition.findall(bytes) - if not definitions: - return None + if not definitions: + return None - defn = text(definitions[0]) - m = r_sentence.match(defn) - if not m: - return None - sentence = m.group(0) + defn = text(definitions[0]) + m = r_sentence.match(defn) + if not m: + return None + sentence = m.group(0) - try: - sentence = str(sentence, 'iso-8859-1') - except: pass + try: + sentence = str(sentence, 'iso-8859-1') + except: pass - maxlength = 275 - if len(sentence) > maxlength: - sentence = sentence[:maxlength] - words = sentence[:-5].split(' ') - words.pop() - sentence = ' '.join(words) + ' [...]' + maxlength = 275 + if len(sentence) > maxlength: + sentence = sentence[:maxlength] + words = sentence[:-5].split(' ') + words.pop() + sentence = ' '.join(words) + ' [...]' - sentence = '"' + sentence.replace('"', "'") + '"' - return sentence + ' - ' + (etyuri % word) + sentence = '"' + sentence.replace('"', "'") + '"' + return sentence + ' - ' + (etyuri % word) @deprecated def f_etymology(self, origin, match, args): - word = match.group(2) + word = match.group(2) - try: result = etymology(word.encode('iso-8859-1')) - except IOError: - msg = "Can't connect to etymonline.com (%s)" % (etyuri % word) - self.msg(origin.sender, msg) - return - except AttributeError: - result = None + try: result = etymology(word.encode('iso-8859-1')) + except IOError: + msg = "Can't connect to etymonline.com (%s)" % (etyuri % word) + self.msg(origin.sender, msg) + return + except AttributeError: + result = None - if result is not None: - self.msg(origin.sender, result) - else: - uri = etysearch % word - msg = 'Can\'t find the etymology for "%s". Try %s' % (word, uri) - self.msg(origin.sender, msg) + if result is not None: + self.msg(origin.sender, result) + else: + uri = etysearch % word + msg = 'Can\'t find the etymology for "%s". Try %s' % (word, uri) + self.msg(origin.sender, msg) # @@ Cf. http://swhack.com/logs/2006-01-04#T01-50-22 f_etymology.rule = (['ety'], r"(.+?)$") f_etymology.thread = True f_etymology.priority = 'high' if __name__=="__main__": - import sys - print(etymology(sys.argv[1])) + import sys + print(etymology(sys.argv[1])) diff --git a/modules/fcc.py b/modules/fcc.py index f7f5a5d..6dce81a 100644 --- a/modules/fcc.py +++ b/modules/fcc.py @@ -34,4 +34,3 @@ fcc.rule = (['fcc'], r'(.*)') if __name__ == '__main__': print(__doc__.strip()) - diff --git a/modules/hs.py b/modules/hs.py index 0c29ee7..a093dc0 100644 --- a/modules/hs.py +++ b/modules/hs.py @@ -58,4 +58,3 @@ hs.rule = (['hs'], r'(.*)') if __name__ == '__main__': print(__doc__.strip()) - diff --git a/modules/lastfm.py b/modules/lastfm.py index d77ec39..5f07fc6 100644 --- a/modules/lastfm.py +++ b/modules/lastfm.py @@ -24,23 +24,23 @@ config.optionxform = str config_filename = "" def setup(self): - fn = self.nick + '-' + self.config.host + '.lastfm.db' - global config_filename - config_filename = os.path.join(os.path.expanduser('~/.phenny'), fn) - if not os.path.exists(config_filename): - try: f = open(config_filename, 'w') - except OSError: pass - else: - f.write('') - f.close() + fn = self.nick + '-' + self.config.host + '.lastfm.db' + global config_filename + config_filename = os.path.join(os.path.expanduser('~/.phenny'), fn) + if not os.path.exists(config_filename): + try: f = open(config_filename, 'w') + except OSError: pass + else: + f.write('') + f.close() - config_file = config.read(config_filename) - if not config.has_section("Nick2User"): + config_file = config.read(config_filename) + if not config.has_section("Nick2User"): config.add_section("Nick2User") - if not config.has_section("User2Nick"): - config.add_section("User2Nick") - if not config.has_section("Nick2Verb"): - config.add_section("Nick2Verb") + if not config.has_section("User2Nick"): + config.add_section("User2Nick") + if not config.has_section("Nick2Verb"): + config.add_section("Nick2Verb") def lastfm_set(phenny, input): cmd = input.group(2) diff --git a/modules/linx.py b/modules/linx.py index 8d6d1b7..a990f3b 100644 --- a/modules/linx.py +++ b/modules/linx.py @@ -9,27 +9,26 @@ import web import json def linx(phenny, input): - """.linx - Upload a URL to linx.li.""" + """.linx - Upload a URL to linx.li.""" - url = input.group(2) - if not url: - phenny.reply("No URL provided. CAN I HAS?") - return + url = input.group(2) + if not url: + phenny.reply("No URL provided. CAN I HAS?") + return - try: - req = web.post("http://linx.li/vtluug", {'url': url}) - except (HTTPError, IOError): - phenny.reply("THE INTERNET IS FUCKING BROKEN. Please try again later.") - return + try: + req = web.post("http://linx.li/vtluug", {'url': url}) + except (HTTPError, IOError): + phenny.reply("THE INTERNET IS FUCKING BROKEN. Please try again later.") + return - data = json.loads(req) - if len(data) <= 0 or not data['success']: - phenny.reply('Sorry, upload failed.') - return + data = json.loads(req) + if len(data) <= 0 or not data['success']: + phenny.reply('Sorry, upload failed.') + return - phenny.reply(data['url']) + phenny.reply(data['url']) linx.rule = (['linx'], r'(.*)') if __name__ == '__main__': - print(__doc__.strip()) - + print(__doc__.strip()) diff --git a/modules/mylife.py b/modules/mylife.py index 3f16430..0763419 100644 --- a/modules/mylife.py +++ b/modules/mylife.py @@ -149,4 +149,3 @@ mlit.commands = ['mlit'] if __name__ == '__main__': print(__doc__.strip()) - diff --git a/modules/nsfw.py b/modules/nsfw.py index abc5d87..e374070 100644 --- a/modules/nsfw.py +++ b/modules/nsfw.py @@ -10,9 +10,7 @@ def nsfw(phenny, input): phenny.say(".nsfw - for when a link isn't safe for work") return phenny.say("!!NSFW!! -> %s <- !!NSFW!!" % (link)) - nsfw.rule = (['nsfw'], r'(.*)') if __name__ == '__main__': - print(__doc__.strip()) - + print(__doc__.strip()) diff --git a/modules/oblique.py b/modules/oblique.py index 3409a4d..50ea7cf 100644 --- a/modules/oblique.py +++ b/modules/oblique.py @@ -16,102 +16,102 @@ r_item = re.compile(r'(?i)
  • (.*?)
  • ') r_tag = re.compile(r'<[^>]+>') def mappings(uri): - result = {} - bytes = web.get(uri) - for item in r_item.findall(bytes): - item = r_tag.sub('', item).strip(' \t\r\n') - if not ' ' in item: continue + result = {} + bytes = web.get(uri) + for item in r_item.findall(bytes): + item = r_tag.sub('', item).strip(' \t\r\n') + if not ' ' in item: continue - command, template = item.split(' ', 1) - if not command.isalnum(): continue - if not template.startswith('http://'): continue - result[command] = template.replace('&', '&') - return result + command, template = item.split(' ', 1) + if not command.isalnum(): continue + if not template.startswith('http://'): continue + result[command] = template.replace('&', '&') + return result def service(phenny, input, command, args): - t = o.services[command] - template = t.replace('${args}', urllib.parse.quote(args, '')) - template = template.replace('${nick}', urllib.parse.quote(input.nick, '')) - uri = template.replace('${sender}', urllib.parse.quote(input.sender, '')) + t = o.services[command] + template = t.replace('${args}', urllib.parse.quote(args, '')) + template = template.replace('${nick}', urllib.parse.quote(input.nick, '')) + uri = template.replace('${sender}', urllib.parse.quote(input.sender, '')) - info = web.head(uri) - if isinstance(info, list): - info = info[0] - if not 'text/plain' in info.get('content-type', '').lower(): - return phenny.reply("Sorry, the service didn't respond in plain text.") - bytes = web.get(uri) - lines = bytes.splitlines() - if not lines: - return phenny.reply("Sorry, the service didn't respond any output.") - phenny.say(lines[0][:350]) + info = web.head(uri) + if isinstance(info, list): + info = info[0] + if not 'text/plain' in info.get('content-type', '').lower(): + return phenny.reply("Sorry, the service didn't respond in plain text.") + bytes = web.get(uri) + lines = bytes.splitlines() + if not lines: + return phenny.reply("Sorry, the service didn't respond any output.") + phenny.say(lines[0][:350]) def refresh(phenny): - if hasattr(phenny.config, 'services'): - services = phenny.config.services - else: services = definitions + if hasattr(phenny.config, 'services'): + services = phenny.config.services + else: services = definitions - old = o.services - o.serviceURI = services - o.services = mappings(o.serviceURI) - return len(o.services), set(o.services) - set(old) + old = o.services + o.serviceURI = services + o.services = mappings(o.serviceURI) + return len(o.services), set(o.services) - set(old) def o(phenny, input): - """Call a webservice.""" - text = input.group(2) + """Call a webservice.""" + text = input.group(2) - if (not o.services) or (text == 'refresh'): - length, added = refresh(phenny) - if text == 'refresh': - msg = 'Okay, found %s services.' % length - if added: - msg += ' Added: ' + ', '.join(sorted(added)[:5]) - if len(added) > 5: msg += ', &c.' - return phenny.reply(msg) + if (not o.services) or (text == 'refresh'): + length, added = refresh(phenny) + if text == 'refresh': + msg = 'Okay, found %s services.' % length + if added: + msg += ' Added: ' + ', '.join(sorted(added)[:5]) + if len(added) > 5: msg += ', &c.' + return phenny.reply(msg) - if not text: - return phenny.reply('Try %s for details.' % o.serviceURI) + if not text: + return phenny.reply('Try %s for details.' % o.serviceURI) - if ' ' in text: - command, args = text.split(' ', 1) - else: command, args = text, '' - command = command.lower() + if ' ' in text: + command, args = text.split(' ', 1) + else: command, args = text, '' + command = command.lower() - if command == 'service': - msg = o.services.get(args, 'No such service!') - return phenny.reply(msg) + if command == 'service': + msg = o.services.get(args, 'No such service!') + return phenny.reply(msg) - if command not in o.services: - return phenny.reply('Service not found in %s' % o.serviceURI) + if command not in o.services: + return phenny.reply('Service not found in %s' % o.serviceURI) - if hasattr(phenny.config, 'external'): - default = phenny.config.external.get('*') - manifest = phenny.config.external.get(input.sender, default) - if manifest: - commands = set(manifest) - if (command not in commands) and (manifest[0] != '!'): - return phenny.reply('Sorry, %s is not whitelisted' % command) - elif (command in commands) and (manifest[0] == '!'): - return phenny.reply('Sorry, %s is blacklisted' % command) - service(phenny, input, command, args) + if hasattr(phenny.config, 'external'): + default = phenny.config.external.get('*') + manifest = phenny.config.external.get(input.sender, default) + if manifest: + commands = set(manifest) + if (command not in commands) and (manifest[0] != '!'): + return phenny.reply('Sorry, %s is not whitelisted' % command) + elif (command in commands) and (manifest[0] == '!'): + return phenny.reply('Sorry, %s is blacklisted' % command) + service(phenny, input, command, args) o.commands = ['o'] o.example = '.o servicename arg1 arg2 arg3' o.services = {} o.serviceURI = None def snippet(phenny, input): - if not o.services: - refresh(phenny) + if not o.services: + refresh(phenny) - search = urllib.parse.quote(input.group(2)) - py = "BeautifulSoup.BeautifulSoup(re.sub('<.*?>|(?<= ) +', '', " + \ - "''.join(chr(ord(c)) for c in " + \ - "eval(urllib.urlopen('http://ajax.googleapis.com/ajax/serv" + \ - "ices/search/web?v=1.0&q=" + search + "').read()" + \ - ".replace('null', 'None'))['responseData']['resul" + \ - "ts'][0]['content'].decode('unicode-escape')).replace(" + \ - "'"', '\x22')), convertEntities=True)" - service(phenny, input, 'py', py) + search = urllib.parse.quote(input.group(2)) + py = "BeautifulSoup.BeautifulSoup(re.sub('<.*?>|(?<= ) +', '', " + \ + "''.join(chr(ord(c)) for c in " + \ + "eval(urllib.urlopen('http://ajax.googleapis.com/ajax/serv" + \ + "ices/search/web?v=1.0&q=" + search + "').read()" + \ + ".replace('null', 'None'))['responseData']['resul" + \ + "ts'][0]['content'].decode('unicode-escape')).replace(" + \ + "'"', '\x22')), convertEntities=True)" + service(phenny, input, 'py', py) snippet.commands = ['snippet'] if __name__ == '__main__': - print(__doc__.strip()) + print(__doc__.strip()) diff --git a/modules/ping.py b/modules/ping.py index 3e963a0..e6272d9 100644 --- a/modules/ping.py +++ b/modules/ping.py @@ -8,16 +8,16 @@ About: http://inamidst.com/phenny/ import random def hello(phenny, input): - greeting = random.choice(('Hi', 'Hey', 'Hello')) - punctuation = random.choice(('', '!')) - phenny.say(greeting + ' ' + input.nick + punctuation) + greeting = random.choice(('Hi', 'Hey', 'Hello')) + punctuation = random.choice(('', '!')) + phenny.say(greeting + ' ' + input.nick + punctuation) hello.rule = r'(?i)(hi|hello|hey) $nickname[ \t]*$' def interjection(phenny, input): - phenny.say(input.nick + '!') + phenny.say(input.nick + '!') interjection.rule = r'$nickname!' interjection.priority = 'high' interjection.thread = False if __name__ == '__main__': - print(__doc__.strip()) + print(__doc__.strip()) diff --git a/modules/reload.py b/modules/reload.py index e270863..0723d61 100644 --- a/modules/reload.py +++ b/modules/reload.py @@ -11,45 +11,45 @@ import sys, os.path, time, imp import irc def f_reload(phenny, input): - """Reloads a module, for use by admins only.""" - if not input.admin: return + """Reloads a module, for use by admins only.""" + if not input.admin: return - name = input.group(2) - if name == phenny.config.owner: - return phenny.reply('What?') + name = input.group(2) + if name == phenny.config.owner: + return phenny.reply('What?') - if (not name) or (name == '*'): - phenny.variables = None - phenny.commands = None - phenny.setup() - return phenny.reply('done') + if (not name) or (name == '*'): + phenny.variables = None + phenny.commands = None + phenny.setup() + return phenny.reply('done') - if name not in sys.modules: - return phenny.reply('%s: no such module!' % name) + if name not in sys.modules: + return phenny.reply('%s: no such module!' % name) - # Thanks to moot for prodding me on this - path = sys.modules[name].__file__ - if path.endswith('.pyc') or path.endswith('.pyo'): - path = path[:-1] - if not os.path.isfile(path): - return phenny.reply('Found %s, but not the source file' % name) + # Thanks to moot for prodding me on this + path = sys.modules[name].__file__ + if path.endswith('.pyc') or path.endswith('.pyo'): + path = path[:-1] + if not os.path.isfile(path): + return phenny.reply('Found %s, but not the source file' % name) - module = imp.load_source(name, path) - sys.modules[name] = module - if hasattr(module, 'setup'): - module.setup(phenny) + module = imp.load_source(name, path) + sys.modules[name] = module + if hasattr(module, 'setup'): + module.setup(phenny) - mtime = os.path.getmtime(module.__file__) - modified = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(mtime)) + mtime = os.path.getmtime(module.__file__) + modified = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(mtime)) - phenny.register(vars(module)) - phenny.bind_commands() + phenny.register(vars(module)) + phenny.bind_commands() - phenny.reply('%r (version: %s)' % (module, modified)) + phenny.reply('%r (version: %s)' % (module, modified)) f_reload.name = 'reload' f_reload.rule = ('$nick', ['reload'], r'(\S+)?') f_reload.priority = 'low' f_reload.thread = False if __name__ == '__main__': - print(__doc__.strip()) + print(__doc__.strip()) diff --git a/modules/remind.py b/modules/remind.py index e9559c5..1067461 100644 --- a/modules/remind.py +++ b/modules/remind.py @@ -10,91 +10,91 @@ http://inamidst.com/phenny/ import os, re, time, threading def filename(self): - name = self.nick + '-' + self.config.host + '.reminders.db' - return os.path.join(os.path.expanduser('~/.phenny'), name) + name = self.nick + '-' + self.config.host + '.reminders.db' + return os.path.join(os.path.expanduser('~/.phenny'), name) def load_database(name): - data = {} - if os.path.isfile(name): - f = open(name, 'r') - for line in f: - unixtime, channel, nick, message = line.split('\t') - message = message.rstrip('\n') - t = int(unixtime) - reminder = (channel, nick, message) - try: data[t].append(reminder) - except KeyError: data[t] = [reminder] - f.close() - return data + data = {} + if os.path.isfile(name): + f = open(name, 'r') + for line in f: + unixtime, channel, nick, message = line.split('\t') + message = message.rstrip('\n') + t = int(unixtime) + reminder = (channel, nick, message) + try: data[t].append(reminder) + except KeyError: data[t] = [reminder] + f.close() + return data def dump_database(name, data): - f = open(name, 'w') - for unixtime, reminders in data.items(): - for channel, nick, message in reminders: - f.write('%s\t%s\t%s\t%s\n' % (unixtime, channel, nick, message)) - f.close() + f = open(name, 'w') + for unixtime, reminders in data.items(): + for channel, nick, message in reminders: + f.write('%s\t%s\t%s\t%s\n' % (unixtime, channel, nick, message)) + f.close() def setup(phenny): - phenny.rfn = filename(phenny) - phenny.rdb = load_database(phenny.rfn) + phenny.rfn = filename(phenny) + phenny.rdb = load_database(phenny.rfn) - def monitor(phenny): - time.sleep(5) - while True: - now = int(time.time()) - unixtimes = [int(key) for key in phenny.rdb] - oldtimes = [t for t in unixtimes if t <= now] - if oldtimes: - for oldtime in oldtimes: - for (channel, nick, message) in phenny.rdb[oldtime]: - if message: - phenny.msg(channel, nick + ': ' + message) - else: phenny.msg(channel, nick + '!') - del phenny.rdb[oldtime] - dump_database(phenny.rfn, phenny.rdb) - time.sleep(2.5) + def monitor(phenny): + time.sleep(5) + while True: + now = int(time.time()) + unixtimes = [int(key) for key in phenny.rdb] + oldtimes = [t for t in unixtimes if t <= now] + if oldtimes: + for oldtime in oldtimes: + for (channel, nick, message) in phenny.rdb[oldtime]: + if message: + phenny.msg(channel, nick + ': ' + message) + else: phenny.msg(channel, nick + '!') + del phenny.rdb[oldtime] + dump_database(phenny.rfn, phenny.rdb) + time.sleep(2.5) - targs = (phenny,) - t = threading.Thread(target=monitor, args=targs) - t.start() + targs = (phenny,) + t = threading.Thread(target=monitor, args=targs) + t.start() scaling = { - 'years': 365.25 * 24 * 3600, - 'year': 365.25 * 24 * 3600, - 'yrs': 365.25 * 24 * 3600, - 'y': 365.25 * 24 * 3600, + 'years': 365.25 * 24 * 3600, + 'year': 365.25 * 24 * 3600, + 'yrs': 365.25 * 24 * 3600, + 'y': 365.25 * 24 * 3600, - 'months': 29.53059 * 24 * 3600, - 'month': 29.53059 * 24 * 3600, - 'mo': 29.53059 * 24 * 3600, + 'months': 29.53059 * 24 * 3600, + 'month': 29.53059 * 24 * 3600, + 'mo': 29.53059 * 24 * 3600, - 'weeks': 7 * 24 * 3600, - 'week': 7 * 24 * 3600, - 'wks': 7 * 24 * 3600, - 'wk': 7 * 24 * 3600, - 'w': 7 * 24 * 3600, + 'weeks': 7 * 24 * 3600, + 'week': 7 * 24 * 3600, + 'wks': 7 * 24 * 3600, + 'wk': 7 * 24 * 3600, + 'w': 7 * 24 * 3600, - 'days': 24 * 3600, - 'day': 24 * 3600, - 'd': 24 * 3600, + 'days': 24 * 3600, + 'day': 24 * 3600, + 'd': 24 * 3600, - 'hours': 3600, - 'hour': 3600, - 'hrs': 3600, - 'hr': 3600, - 'h': 3600, + 'hours': 3600, + 'hour': 3600, + 'hrs': 3600, + 'hr': 3600, + 'h': 3600, - 'minutes': 60, - 'minute': 60, - 'mins': 60, - 'min': 60, - 'm': 60, + 'minutes': 60, + 'minute': 60, + 'mins': 60, + 'min': 60, + 'm': 60, - 'seconds': 1, - 'second': 1, - 'secs': 1, - 'sec': 1, - 's': 1 + 'seconds': 1, + 'second': 1, + 'secs': 1, + 'sec': 1, + 's': 1 } periods = '|'.join(list(scaling.keys())) @@ -102,35 +102,35 @@ p_command = r'\.in ([0-9]+(?:\.[0-9]+)?)\s?((?:%s)\b)?:?\s?(.*)' % periods r_command = re.compile(p_command) def remind(phenny, input): - m = r_command.match(input.bytes) - if not m: - return phenny.reply("Sorry, didn't understand the input.") - length, scale, message = m.groups() + m = r_command.match(input.bytes) + if not m: + return phenny.reply("Sorry, didn't understand the input.") + length, scale, message = m.groups() - length = float(length) - factor = scaling.get(scale, 60) - duration = length * factor + length = float(length) + factor = scaling.get(scale, 60) + duration = length * factor - if duration % 1: - duration = int(duration) + 1 - else: duration = int(duration) + if duration % 1: + duration = int(duration) + 1 + else: duration = int(duration) - t = int(time.time()) + duration - reminder = (input.sender, input.nick, message) + t = int(time.time()) + duration + reminder = (input.sender, input.nick, message) - try: phenny.rdb[t].append(reminder) - except KeyError: phenny.rdb[t] = [reminder] + try: phenny.rdb[t].append(reminder) + except KeyError: phenny.rdb[t] = [reminder] - dump_database(phenny.rfn, phenny.rdb) + dump_database(phenny.rfn, phenny.rdb) - if duration >= 60: - w = '' - if duration >= 3600 * 12: - w += time.strftime(' on %d %b %Y', time.gmtime(t)) - w += time.strftime(' at %H:%MZ', time.gmtime(t)) - phenny.reply('Okay, will remind%s' % w) - else: phenny.reply('Okay, will remind in %s secs' % duration) + if duration >= 60: + w = '' + if duration >= 3600 * 12: + w += time.strftime(' on %d %b %Y', time.gmtime(t)) + w += time.strftime(' at %H:%MZ', time.gmtime(t)) + phenny.reply('Okay, will remind%s' % w) + else: phenny.reply('Okay, will remind in %s secs' % duration) remind.commands = ['in'] if __name__ == '__main__': - print(__doc__.strip()) + print(__doc__.strip()) diff --git a/modules/search.py b/modules/search.py index 47b5c85..0b780ff 100644 --- a/modules/search.py +++ b/modules/search.py @@ -11,185 +11,185 @@ import re import web class Grab(web.urllib.request.URLopener): - def __init__(self, *args): - self.version = 'Mozilla/5.0 (Phenny)' - web.urllib.request.URLopener.__init__(self, *args) - self.addheader('Referer', 'https://github.com/sbp/phenny') - def http_error_default(self, url, fp, errcode, errmsg, headers): - return web.urllib.addinfourl(fp, [headers, errcode], "http:" + url) + def __init__(self, *args): + self.version = 'Mozilla/5.0 (Phenny)' + web.urllib.request.URLopener.__init__(self, *args) + self.addheader('Referer', 'https://github.com/sbp/phenny') + def http_error_default(self, url, fp, errcode, errmsg, headers): + return web.urllib.addinfourl(fp, [headers, errcode], "http:" + url) def google_ajax(query): - """Search using AjaxSearch, and return its JSON.""" - uri = 'http://ajax.googleapis.com/ajax/services/search/web' - args = '?v=1.0&safe=off&q=' + web.quote(query) - handler = web.urllib.request._urlopener - web.urllib.request._urlopener = Grab() - bytes = web.get(uri + args) - web.urllib.request._urlopener = handler - return web.json(bytes) + """Search using AjaxSearch, and return its JSON.""" + uri = 'http://ajax.googleapis.com/ajax/services/search/web' + args = '?v=1.0&safe=off&q=' + web.quote(query) + handler = web.urllib.request._urlopener + web.urllib.request._urlopener = Grab() + bytes = web.get(uri + args) + web.urllib.request._urlopener = handler + return web.json(bytes) def google_search(query): - results = google_ajax(query) - try: return results['responseData']['results'][0]['unescapedUrl'] - except IndexError: return None - except TypeError: - print(results) - return False + results = google_ajax(query) + try: return results['responseData']['results'][0]['unescapedUrl'] + except IndexError: return None + except TypeError: + print(results) + return False def google_count(query): - results = google_ajax(query) - if 'responseData' not in results: return '0' - if 'cursor' not in results['responseData']: return '0' - if 'estimatedResultCount' not in results['responseData']['cursor']: - return '0' - return results['responseData']['cursor']['estimatedResultCount'] + results = google_ajax(query) + if 'responseData' not in results: return '0' + if 'cursor' not in results['responseData']: return '0' + if 'estimatedResultCount' not in results['responseData']['cursor']: + return '0' + return results['responseData']['cursor']['estimatedResultCount'] def formatnumber(n): - """Format a number with beautiful commas.""" - parts = list(str(n)) - for i in range((len(parts) - 3), 0, -3): - parts.insert(i, ',') - return ''.join(parts) + """Format a number with beautiful commas.""" + parts = list(str(n)) + for i in range((len(parts) - 3), 0, -3): + parts.insert(i, ',') + return ''.join(parts) def g(phenny, input): - """Queries Google for the specified input.""" - query = input.group(2) - if not query: - return phenny.reply('.g what?') - uri = google_search(query) - if uri: - phenny.reply(uri) - if not hasattr(phenny.bot, 'last_seen_uri'): - phenny.bot.last_seen_uri = {} - phenny.bot.last_seen_uri[input.sender] = uri - elif uri is False: phenny.reply("Problem getting data from Google.") - else: phenny.reply("No results found for '%s'." % query) + """Queries Google for the specified input.""" + query = input.group(2) + if not query: + return phenny.reply('.g what?') + uri = google_search(query) + if uri: + phenny.reply(uri) + if not hasattr(phenny.bot, 'last_seen_uri'): + phenny.bot.last_seen_uri = {} + phenny.bot.last_seen_uri[input.sender] = uri + elif uri is False: phenny.reply("Problem getting data from Google.") + else: phenny.reply("No results found for '%s'." % query) g.commands = ['g'] g.priority = 'high' g.example = '.g swhack' def gc(phenny, input): - """Returns the number of Google results for the specified input.""" - query = input.group(2) - if not query: - return phenny.reply('.gc what?') - num = formatnumber(google_count(query)) - phenny.say(query + ': ' + num) + """Returns the number of Google results for the specified input.""" + query = input.group(2) + if not query: + return phenny.reply('.gc what?') + num = formatnumber(google_count(query)) + phenny.say(query + ': ' + num) gc.commands = ['gc'] gc.priority = 'high' gc.example = '.gc extrapolate' r_query = re.compile( - r'\+?"[^"\\]*(?:\\.[^"\\]*)*"|\[[^]\\]*(?:\\.[^]\\]*)*\]|\S+' + r'\+?"[^"\\]*(?:\\.[^"\\]*)*"|\[[^]\\]*(?:\\.[^]\\]*)*\]|\S+' ) def gcs(phenny, input): - if not input.group(2): - return phenny.reply("Nothing to compare.") - queries = r_query.findall(input.group(2)) - if len(queries) > 6: - return phenny.reply('Sorry, can only compare up to six things.') + if not input.group(2): + return phenny.reply("Nothing to compare.") + queries = r_query.findall(input.group(2)) + if len(queries) > 6: + return phenny.reply('Sorry, can only compare up to six things.') - results = [] - for i, query in enumerate(queries): - query = query.strip('[]') - n = int((formatnumber(google_count(query)) or '0').replace(',', '')) - results.append((n, query)) - if i >= 2: __import__('time').sleep(0.25) - if i >= 4: __import__('time').sleep(0.25) + results = [] + for i, query in enumerate(queries): + query = query.strip('[]') + n = int((formatnumber(google_count(query)) or '0').replace(',', '')) + results.append((n, query)) + if i >= 2: __import__('time').sleep(0.25) + if i >= 4: __import__('time').sleep(0.25) - results = [(term, n) for (n, term) in reversed(sorted(results))] - reply = ', '.join('%s (%s)' % (t, formatnumber(n)) for (t, n) in results) - phenny.say(reply) + results = [(term, n) for (n, term) in reversed(sorted(results))] + reply = ', '.join('%s (%s)' % (t, formatnumber(n)) for (t, n) in results) + phenny.say(reply) gcs.commands = ['gcs', 'comp'] r_bing = re.compile(r'

    ') def duck_search(query): - query = query.replace('!', '') - query = web.quote(query) - uri = 'http://duckduckgo.com/html/?q=%s&kl=uk-en' % query - bytes = web.get(uri) - m = r_duck.search(bytes) - if m: return web.decode(m.group(1)) + query = query.replace('!', '') + query = web.quote(query) + uri = 'http://duckduckgo.com/html/?q=%s&kl=uk-en' % query + bytes = web.get(uri) + m = r_duck.search(bytes) + if m: return web.decode(m.group(1)) def duck(phenny, input): - query = input.group(2) - if not query: return phenny.reply('.ddg what?') + query = input.group(2) + if not query: return phenny.reply('.ddg what?') - uri = duck_search(query) - if uri: - phenny.reply(uri) - if not hasattr(phenny.bot, 'last_seen_uri'): - phenny.bot.last_seen_uri = {} - phenny.bot.last_seen_uri[input.sender] = uri - else: phenny.reply("No results found for '%s'." % query) + uri = duck_search(query) + if uri: + phenny.reply(uri) + if not hasattr(phenny.bot, 'last_seen_uri'): + phenny.bot.last_seen_uri = {} + phenny.bot.last_seen_uri[input.sender] = uri + else: phenny.reply("No results found for '%s'." % query) duck.commands = ['duck', 'ddg'] def search(phenny, input): - if not input.group(2): - return phenny.reply('.search for what?') - query = input.group(2) - gu = google_search(query) or '-' - bu = bing_search(query) or '-' - du = duck_search(query) or '-' + if not input.group(2): + return phenny.reply('.search for what?') + query = input.group(2) + gu = google_search(query) or '-' + bu = bing_search(query) or '-' + du = duck_search(query) or '-' - if (gu == bu) and (bu == du): - result = '%s (g, b, d)' % gu - elif (gu == bu): - result = '%s (g, b), %s (d)' % (gu, du) - elif (bu == du): - result = '%s (b, d), %s (g)' % (bu, gu) - elif (gu == du): - result = '%s (g, d), %s (b)' % (gu, bu) - else: - if len(gu) > 250: gu = '(extremely long link)' - if len(bu) > 150: bu = '(extremely long link)' - if len(du) > 150: du = '(extremely long link)' - result = '%s (g), %s (b), %s (d)' % (gu, bu, du) + if (gu == bu) and (bu == du): + result = '%s (g, b, d)' % gu + elif (gu == bu): + result = '%s (g, b), %s (d)' % (gu, du) + elif (bu == du): + result = '%s (b, d), %s (g)' % (bu, gu) + elif (gu == du): + result = '%s (g, d), %s (b)' % (gu, bu) + else: + if len(gu) > 250: gu = '(extremely long link)' + if len(bu) > 150: bu = '(extremely long link)' + if len(du) > 150: du = '(extremely long link)' + result = '%s (g), %s (b), %s (d)' % (gu, bu, du) - phenny.reply(result) + phenny.reply(result) search.commands = ['search'] def suggest(phenny, input): - if not input.group(2): - return phenny.reply("No query term.") - query = input.group(2) - uri = 'http://websitedev.de/temp-bin/suggest.pl?q=' - answer = web.get(uri + web.quote(query).replace('+', '%2B')) - if answer: - phenny.say(answer) - else: phenny.reply('Sorry, no result.') + if not input.group(2): + return phenny.reply("No query term.") + query = input.group(2) + uri = 'http://websitedev.de/temp-bin/suggest.pl?q=' + answer = web.get(uri + web.quote(query).replace('+', '%2B')) + if answer: + phenny.say(answer) + else: phenny.reply('Sorry, no result.') suggest.commands = ['suggest'] if __name__ == '__main__': - print(__doc__.strip()) + print(__doc__.strip()) diff --git a/modules/seen.py b/modules/seen.py index 34d8551..3778a5a 100644 --- a/modules/seen.py +++ b/modules/seen.py @@ -12,38 +12,38 @@ from tools import deprecated @deprecated def f_seen(self, origin, match, args): - """.seen - Reports when was last seen.""" - if origin.sender == '#talis': return - nick = match.group(2).lower() - if not hasattr(self, 'seen'): - return self.msg(origin.sender, '?') - if nick in self.seen: - channel, t = self.seen[nick] - t = time.strftime('%Y-%m-%d %H:%M:%S UTC', time.gmtime(t)) + """.seen - Reports when was last seen.""" + if origin.sender == '#talis': return + nick = match.group(2).lower() + if not hasattr(self, 'seen'): + return self.msg(origin.sender, '?') + if nick in self.seen: + channel, t = self.seen[nick] + t = time.strftime('%Y-%m-%d %H:%M:%S UTC', time.gmtime(t)) - msg = "I last saw %s at %s on %s" % (nick, t, channel) - self.msg(origin.sender, str(origin.nick) + ': ' + msg) - else: self.msg(origin.sender, "Sorry, I haven't seen %s around." % nick) + msg = "I last saw %s at %s on %s" % (nick, t, channel) + self.msg(origin.sender, str(origin.nick) + ': ' + msg) + else: self.msg(origin.sender, "Sorry, I haven't seen %s around." % nick) f_seen.rule = (['seen'], r'(\S+)') @deprecated def f_note(self, origin, match, args): - def note(self, origin, match, args): - if not hasattr(self.bot, 'seen'): - self.bot.seen = {} - if origin.sender.startswith('#'): - # if origin.sender == '#inamidst': return - self.seen[origin.nick.lower()] = (origin.sender, time.time()) + def note(self, origin, match, args): + if not hasattr(self.bot, 'seen'): + self.bot.seen = {} + if origin.sender.startswith('#'): + # if origin.sender == '#inamidst': return + self.seen[origin.nick.lower()] = (origin.sender, time.time()) - # if not hasattr(self, 'chanspeak'): - # self.chanspeak = {} - # if (len(args) > 2) and args[2].startswith('#'): - # self.chanspeak[args[2]] = args[0] + # if not hasattr(self, 'chanspeak'): + # self.chanspeak = {} + # if (len(args) > 2) and args[2].startswith('#'): + # self.chanspeak[args[2]] = args[0] - try: note(self, origin, match, args) - except Exception as e: print(e) + try: note(self, origin, match, args) + except Exception as e: print(e) f_note.rule = r'(.*)' f_note.priority = 'low' if __name__ == '__main__': - print(__doc__.strip()) + print(__doc__.strip()) diff --git a/modules/slogan.py b/modules/slogan.py index 469f1ce..4c07e44 100644 --- a/modules/slogan.py +++ b/modules/slogan.py @@ -37,4 +37,4 @@ slogan.commands = ['slogan'] slogan.example = '.slogan Granola' if __name__ == '__main__': - print(__doc__.strip()) + print(__doc__.strip()) diff --git a/modules/startup.py b/modules/startup.py index d69c3a1..8ac5b41 100644 --- a/modules/startup.py +++ b/modules/startup.py @@ -8,19 +8,19 @@ http://inamidst.com/phenny/ """ def startup(phenny, input): - if hasattr(phenny.config, 'serverpass'): - phenny.write(('PASS', phenny.config.serverpass)) + if hasattr(phenny.config, 'serverpass'): + phenny.write(('PASS', phenny.config.serverpass)) - if hasattr(phenny.config, 'password'): - phenny.msg('NickServ', 'IDENTIFY %s' % phenny.config.password) - __import__('time').sleep(5) + if hasattr(phenny.config, 'password'): + phenny.msg('NickServ', 'IDENTIFY %s' % phenny.config.password) + __import__('time').sleep(5) - # Cf. http://swhack.com/logs/2005-12-05#T19-32-36 - for channel in phenny.channels: - phenny.write(('JOIN', channel)) + # Cf. http://swhack.com/logs/2005-12-05#T19-32-36 + for channel in phenny.channels: + phenny.write(('JOIN', channel)) startup.rule = r'(.*)' startup.event = '251' startup.priority = 'low' if __name__ == '__main__': - print(__doc__.strip()) + print(__doc__.strip()) diff --git a/modules/tell.py b/modules/tell.py index 0b6c60b..74ead97 100644 --- a/modules/tell.py +++ b/modules/tell.py @@ -24,139 +24,139 @@ lispchannels = frozenset([ '#lisp', '#scheme', '#opendarwin', '#macdev', '#programmering', '#maxima', '#robin', '##concurrency', '#paredit' ]) def loadReminders(fn): - result = {} - f = open(fn) - for line in f: - line = line.strip() - if line: - try: tellee, teller, verb, timenow, msg = line.split('\t', 4) - except ValueError: continue # @@ hmm - result.setdefault(tellee, []).append((teller, verb, timenow, msg)) - f.close() - return result + result = {} + f = open(fn) + for line in f: + line = line.strip() + if line: + try: tellee, teller, verb, timenow, msg = line.split('\t', 4) + except ValueError: continue # @@ hmm + result.setdefault(tellee, []).append((teller, verb, timenow, msg)) + f.close() + return result def dumpReminders(fn, data): - f = open(fn, 'w') - for tellee in data.keys(): - for remindon in data[tellee]: - line = '\t'.join((tellee,) + remindon) - try: f.write(line + '\n') - except IOError: break - try: f.close() - except IOError: pass - return True + f = open(fn, 'w') + for tellee in data.keys(): + for remindon in data[tellee]: + line = '\t'.join((tellee,) + remindon) + try: f.write(line + '\n') + except IOError: break + try: f.close() + except IOError: pass + return True def setup(self): - fn = self.nick + '-' + self.config.host + '.tell.db' - self.tell_filename = os.path.join(os.path.expanduser('~/.phenny'), fn) - if not os.path.exists(self.tell_filename): - try: f = open(self.tell_filename, 'w') - except OSError: pass - else: - f.write('') - f.close() - self.reminders = loadReminders(self.tell_filename) # @@ tell + fn = self.nick + '-' + self.config.host + '.tell.db' + self.tell_filename = os.path.join(os.path.expanduser('~/.phenny'), fn) + if not os.path.exists(self.tell_filename): + try: f = open(self.tell_filename, 'w') + except OSError: pass + else: + f.write('') + f.close() + self.reminders = loadReminders(self.tell_filename) # @@ tell def f_remind(phenny, input): - teller = input.nick + teller = input.nick - # @@ Multiple comma-separated tellees? Cf. Terje, #swhack, 2006-04-15 - verb, tellee, msg = input.groups() - verb = verb - tellee = tellee - msg = msg + # @@ Multiple comma-separated tellees? Cf. Terje, #swhack, 2006-04-15 + verb, tellee, msg = input.groups() + verb = verb + tellee = tellee + msg = msg - tellee_original = tellee.rstrip('.,:;') - tellee = tellee_original.lower() + tellee_original = tellee.rstrip('.,:;') + tellee = tellee_original.lower() - if not os.path.exists(phenny.tell_filename): - return + if not os.path.exists(phenny.tell_filename): + return - if len(tellee) > 20: - return phenny.reply('That nickname is too long.') + if len(tellee) > 20: + return phenny.reply('That nickname is too long.') - timenow = time.strftime('%d %b %H:%MZ', time.gmtime()) - if not tellee in (teller.lower(), phenny.nick, 'me'): # @@ - # @@ and year, if necessary - warn = False - if tellee not in phenny.reminders: - phenny.reminders[tellee] = [(teller, verb, timenow, msg)] - else: - # if len(phenny.reminders[tellee]) >= maximum: - # warn = True - phenny.reminders[tellee].append((teller, verb, timenow, msg)) - # @@ Stephanie's augmentation - response = "I'll pass that on when %s is around." % tellee_original - # if warn: response += (" I'll have to use a pastebin, though, so " + - # "your message may get lost.") + timenow = time.strftime('%d %b %H:%MZ', time.gmtime()) + if not tellee in (teller.lower(), phenny.nick, 'me'): # @@ + # @@ and year, if necessary + warn = False + if tellee not in phenny.reminders: + phenny.reminders[tellee] = [(teller, verb, timenow, msg)] + else: + # if len(phenny.reminders[tellee]) >= maximum: + # warn = True + phenny.reminders[tellee].append((teller, verb, timenow, msg)) + # @@ Stephanie's augmentation + response = "I'll pass that on when %s is around." % tellee_original + # if warn: response += (" I'll have to use a pastebin, though, so " + + # "your message may get lost.") - rand = random.random() - if rand > 0.9999: response = "yeah, yeah" - elif rand > 0.999: response = "yeah, sure, whatever" + rand = random.random() + if rand > 0.9999: response = "yeah, yeah" + elif rand > 0.999: response = "yeah, sure, whatever" - phenny.reply(response) - elif teller.lower() == tellee: - phenny.say('You can %s yourself that.' % verb) - else: phenny.say("Hey, I'm not as stupid as Monty you know!") + phenny.reply(response) + elif teller.lower() == tellee: + phenny.say('You can %s yourself that.' % verb) + else: phenny.say("Hey, I'm not as stupid as Monty you know!") - dumpReminders(phenny.tell_filename, phenny.reminders) # @@ tell + dumpReminders(phenny.tell_filename, phenny.reminders) # @@ tell f_remind.rule = ('$nick', ['tell', 'ask'], r'(\S+) (.*)') f_remind.thread = False def getReminders(phenny, channel, key, tellee): - lines = [] - template = "%s: %s <%s> %s %s %s" - today = time.strftime('%d %b', time.gmtime()) + lines = [] + template = "%s: %s <%s> %s %s %s" + today = time.strftime('%d %b', time.gmtime()) - for (teller, verb, datetime, msg) in phenny.reminders[key]: - if datetime.startswith(today): - datetime = datetime[len(today)+1:] - lines.append(template % (tellee, datetime, teller, verb, tellee, msg)) + for (teller, verb, datetime, msg) in phenny.reminders[key]: + if datetime.startswith(today): + datetime = datetime[len(today)+1:] + lines.append(template % (tellee, datetime, teller, verb, tellee, msg)) - try: del phenny.reminders[key] - except KeyError: phenny.msg(channel, 'Er...') - return lines + try: del phenny.reminders[key] + except KeyError: phenny.msg(channel, 'Er...') + return lines def message(phenny, input): - if not input.sender.startswith('#'): return + if not input.sender.startswith('#'): return - tellee = input.nick - channel = input.sender + tellee = input.nick + channel = input.sender - if not os: return - if not os.path.exists(phenny.tell_filename): - return + if not os: return + if not os.path.exists(phenny.tell_filename): + return - reminders = [] - remkeys = list(reversed(sorted(phenny.reminders.keys()))) - for remkey in remkeys: - if not remkey.endswith('*') or remkey.endswith(':'): - if tellee.lower() == remkey: + reminders = [] + remkeys = list(reversed(sorted(phenny.reminders.keys()))) + for remkey in remkeys: + if not remkey.endswith('*') or remkey.endswith(':'): + if tellee.lower() == remkey: + reminders.extend(getReminders(phenny, channel, remkey, tellee)) + elif tellee.lower().startswith(remkey.rstrip('*:')): reminders.extend(getReminders(phenny, channel, remkey, tellee)) - elif tellee.lower().startswith(remkey.rstrip('*:')): - reminders.extend(getReminders(phenny, channel, remkey, tellee)) - for line in reminders[:maximum]: - phenny.say(line) + for line in reminders[:maximum]: + phenny.say(line) - if reminders[maximum:]: - phenny.say('Further messages sent privately') - for line in reminders[maximum:]: - phenny.msg(tellee, line) + if reminders[maximum:]: + phenny.say('Further messages sent privately') + for line in reminders[maximum:]: + phenny.msg(tellee, line) - if len(list(phenny.reminders.keys())) != remkeys: - dumpReminders(phenny.tell_filename, phenny.reminders) # @@ tell + if len(list(phenny.reminders.keys())) != remkeys: + dumpReminders(phenny.tell_filename, phenny.reminders) # @@ tell message.rule = r'(.*)' message.priority = 'low' message.thread = False def messageAlert(phenny, input): - if (input.nick.lower() in list(phenny.reminders.keys())): - phenny.say(input.nick + ': You have messages.') + if (input.nick.lower() in list(phenny.reminders.keys())): + phenny.say(input.nick + ': You have messages.') messageAlert.event = 'JOIN' messageAlert.rule = r'.*' messageAlert.priority = 'low' messageAlert.thread = False if __name__ == '__main__': - print(__doc__.strip()) + print(__doc__.strip()) diff --git a/modules/tfw.py b/modules/tfw.py index 5ba0903..5ecf108 100644 --- a/modules/tfw.py +++ b/modules/tfw.py @@ -1,7 +1,7 @@ #!/usr/bin/python3 """ tfw.py - the fucking weather module -author: mutantmonkey +author: mutantmonkey """ from urllib.parse import quote as urlquote @@ -82,4 +82,3 @@ tfwc.rule = (['tfwc'], r'(.*)') if __name__ == '__main__': print(__doc__.strip()) - diff --git a/modules/translate.py b/modules/translate.py index 98dada7..1014561 100644 --- a/modules/translate.py +++ b/modules/translate.py @@ -13,77 +13,77 @@ import json import web def translate(text, input='auto', output='en'): - opener = urllib.request.build_opener() - opener.addheaders = [( - 'User-Agent', 'Mozilla/5.0' + - '(X11; U; Linux i686)' + - 'Gecko/20071127 Firefox/2.0.0.11' - )] + opener = urllib.request.build_opener() + opener.addheaders = [( + 'User-Agent', 'Mozilla/5.0' + + '(X11; U; Linux i686)' + + 'Gecko/20071127 Firefox/2.0.0.11' + )] - input, output = urllib.parse.quote(input), urllib.parse.quote(output) - text = urllib.parse.quote(text) + input, output = urllib.parse.quote(input), urllib.parse.quote(output) + text = urllib.parse.quote(text) - result = opener.open('http://translate.google.com/translate_a/t?' + - ('client=t&hl=en&sl=%s&tl=%s&multires=1' % (input, output)) + - ('&otf=1&ssel=0&tsel=0&uptl=en&sc=1&text=%s' % text)).read() - result = result.decode('utf-8') + result = opener.open('http://translate.google.com/translate_a/t?' + + ('client=t&hl=en&sl=%s&tl=%s&multires=1' % (input, output)) + + ('&otf=1&ssel=0&tsel=0&uptl=en&sc=1&text=%s' % text)).read() + result = result.decode('utf-8') - while ',,' in result: - result = result.replace(',,', ',null,') - data = json.loads(result) + while ',,' in result: + result = result.replace(',,', ',null,') + data = json.loads(result) - try: language = data[-2][0][0] - except: language = '?' + try: language = data[-2][0][0] + except: language = '?' - return ''.join(x[0] for x in data[0]), language + return ''.join(x[0] for x in data[0]), language def tr(phenny, context): - """Translates a phrase, with an optional language hint.""" - input, output, phrase = context.groups() + """Translates a phrase, with an optional language hint.""" + input, output, phrase = context.groups() - phrase = phrase + phrase = phrase - if (len(phrase) > 350) and (not context.admin): - return phenny.reply('Phrase must be under 350 characters.') + if (len(phrase) > 350) and (not context.admin): + return phenny.reply('Phrase must be under 350 characters.') - input = input or 'auto' - input = input.encode('utf-8') - output = (output or 'en').encode('utf-8') + input = input or 'auto' + input = input.encode('utf-8') + output = (output or 'en').encode('utf-8') - if input != output: - msg, input = translate(phrase, input, output) - output = output.decode('utf-8') - if msg: - msg = web.decode(msg) # msg.replace(''', "'") - msg = '"%s" (%s to %s, translate.google.com)' % (msg, input, output) - else: msg = 'The %s to %s translation failed, sorry!' % (input, output) + if input != output: + msg, input = translate(phrase, input, output) + output = output.decode('utf-8') + if msg: + msg = web.decode(msg) # msg.replace(''', "'") + msg = '"%s" (%s to %s, translate.google.com)' % (msg, input, output) + else: msg = 'The %s to %s translation failed, sorry!' % (input, output) - phenny.reply(msg) - else: phenny.reply('Language guessing failed, so try suggesting one!') + phenny.reply(msg) + else: phenny.reply('Language guessing failed, so try suggesting one!') tr.rule = ('$nick', r'(?:([a-z]{2}) +)?(?:([a-z]{2}) +)?["“](.+?)["”]\? *$') tr.example = '$nickname: "mon chien"? or $nickname: fr "mon chien"?' tr.priority = 'low' def mangle(phenny, input): - phrase = input.group(2) - for lang in ['fr', 'de', 'es', 'it', 'ja']: - backup = phrase - phrase = translate(phrase, 'en', lang) - if not phrase: - phrase = backup - break - __import__('time').sleep(0.5) + phrase = input.group(2) + for lang in ['fr', 'de', 'es', 'it', 'ja']: + backup = phrase + phrase = translate(phrase, 'en', lang) + if not phrase: + phrase = backup + break + __import__('time').sleep(0.5) - backup = phrase - phrase = translate(phrase, lang, 'en') - if not phrase: - phrase = backup - break - __import__('time').sleep(0.5) + backup = phrase + phrase = translate(phrase, lang, 'en') + if not phrase: + phrase = backup + break + __import__('time').sleep(0.5) - phenny.reply(phrase or 'ERRORS SRY') + phenny.reply(phrase or 'ERRORS SRY') mangle.commands = ['mangle'] if __name__ == '__main__': - print(__doc__.strip()) + print(__doc__.strip()) diff --git a/modules/uncyclopedia.py b/modules/uncyclopedia.py index 32a0fdb..3b8927d 100644 --- a/modules/uncyclopedia.py +++ b/modules/uncyclopedia.py @@ -7,7 +7,7 @@ Licensed under the Eiffel Forum License 2. http://inamidst.com/phenny/ modified from Wikipedia module -author: mutantmonkey +author: mutantmonkey """ import re, urllib.request, urllib.parse, urllib.error @@ -15,151 +15,151 @@ import web wikiuri = 'http://uncyclopedia.wikia.com/wiki/%s' wikisearch = 'http://uncyclopedia.wikia.com/wiki/Special:Search?' \ - + 'search=%s&fulltext=Search' + + 'search=%s&fulltext=Search' r_tr = re.compile(r'(?ims)]*>.*?') r_paragraph = re.compile(r'(?ims)]*>.*?

    |]*>.*?') r_tag = re.compile(r'<(?!!)[^>]+>') r_whitespace = re.compile(r'[\t\r\n ]+') r_redirect = re.compile( - r'(?ims)class=.redirectText.>\s*\s*') - s = s.replace('<', '<') - s = s.replace('&', '&') - s = s.replace(' ', ' ') - return s + s = s.replace('>', '>') + s = s.replace('<', '<') + s = s.replace('&', '&') + s = s.replace(' ', ' ') + return s def text(html): - html = r_tag.sub('', html) - html = r_whitespace.sub(' ', html) - return unescape(html).strip() + html = r_tag.sub('', html) + html = r_whitespace.sub(' ', html) + return unescape(html).strip() def search(term): - try: from . import search - except ImportError as e: - print(e) - return term + try: from . import search + except ImportError as e: + print(e) + return term - if not isinstance(term, str): - term = term.decode('utf-8') + if not isinstance(term, str): + term = term.decode('utf-8') - term = term.replace('_', ' ') - try: uri = search.result('site:uncyclopedia.wikia.com %s' % term) - except IndexError: return term - if uri: - return uri[len('http://uncyclopedia.wikia.com/wiki/'):] - else: return term + term = term.replace('_', ' ') + try: uri = search.result('site:uncyclopedia.wikia.com %s' % term) + except IndexError: return term + if uri: + return uri[len('http://uncyclopedia.wikia.com/wiki/'):] + else: return term def uncyclopedia(term, last=False): - global wikiuri - if not '%' in term: - if isinstance(term, str): - t = term - else: t = term - q = urllib.parse.quote(t) - u = wikiuri % q - bytes = web.get(u) - else: bytes = web.get(wikiuri % term) - bytes = r_tr.sub('', bytes) + global wikiuri + if not '%' in term: + if isinstance(term, str): + t = term + else: t = term + q = urllib.parse.quote(t) + u = wikiuri % q + bytes = web.get(u) + else: bytes = web.get(wikiuri % term) + bytes = r_tr.sub('', bytes) - if not last: - r = r_redirect.search(bytes[:4096]) - if r: - term = urllib.parse.unquote(r.group(1)) - return uncyclopedia(term, last=True) + if not last: + r = r_redirect.search(bytes[:4096]) + if r: + term = urllib.parse.unquote(r.group(1)) + return uncyclopedia(term, last=True) - paragraphs = r_paragraph.findall(bytes) + paragraphs = r_paragraph.findall(bytes) - if not paragraphs: - if not last: - term = search(term) - return uncyclopedia(term, last=True) - return None + if not paragraphs: + if not last: + term = search(term) + return uncyclopedia(term, last=True) + return None - # Pre-process - paragraphs = [para for para in paragraphs - if (para and 'technical limitations' not in para - and 'window.showTocToggle' not in para - and 'Deletion_policy' not in para - and 'Template:AfD_footer' not in para - and not (para.startswith('

    ') and - para.endswith('

    ')) - and not 'disambiguation)"' in para) - and not '(images and media)' in para - and not 'This article contains a' in para - and not 'id="coordinates"' in para - and not 'class="thumb' in para - and not 'There is currently no text in this page.' in para] - # and not 'style="display:none"' in para] + # Pre-process + paragraphs = [para for para in paragraphs + if (para and 'technical limitations' not in para + and 'window.showTocToggle' not in para + and 'Deletion_policy' not in para + and 'Template:AfD_footer' not in para + and not (para.startswith('

    ') and + para.endswith('

    ')) + and not 'disambiguation)"' in para) + and not '(images and media)' in para + and not 'This article contains a' in para + and not 'id="coordinates"' in para + and not 'class="thumb' in para + and not 'There is currently no text in this page.' in para] + # and not 'style="display:none"' in para] - for i, para in enumerate(paragraphs): - para = para.replace('', '|') - para = para.replace('', '|') - paragraphs[i] = text(para).strip() + for i, para in enumerate(paragraphs): + para = para.replace('', '|') + para = para.replace('', '|') + paragraphs[i] = text(para).strip() - # Post-process - paragraphs = [para for para in paragraphs if - (para and not (para.endswith(':') and len(para) < 150))] + # Post-process + paragraphs = [para for para in paragraphs if + (para and not (para.endswith(':') and len(para) < 150))] - para = text(paragraphs[0]) - m = r_sentence.match(para) + para = text(paragraphs[0]) + m = r_sentence.match(para) - if not m: - if not last: - term = search(term) - return uncyclopedia(term, last=True) - return None - sentence = m.group(0) + if not m: + if not last: + term = search(term) + return uncyclopedia(term, last=True) + return None + sentence = m.group(0) - maxlength = 275 - if len(sentence) > maxlength: - sentence = sentence[:maxlength] - words = sentence[:-5].split(' ') - words.pop() - sentence = ' '.join(words) + ' [...]' + maxlength = 275 + if len(sentence) > maxlength: + sentence = sentence[:maxlength] + words = sentence[:-5].split(' ') + words.pop() + sentence = ' '.join(words) + ' [...]' - if (('using the Article Wizard if you wish' in sentence) - or ('or add a request for it' in sentence)): - if not last: - term = search(term) - return uncyclopedia(term, last=True) - return None + if (('using the Article Wizard if you wish' in sentence) + or ('or add a request for it' in sentence)): + if not last: + term = search(term) + return uncyclopedia(term, last=True) + return None - sentence = '"' + sentence.replace('"', "'") + '"' - return sentence + ' - ' + (wikiuri % term) + sentence = '"' + sentence.replace('"', "'") + '"' + return sentence + ' - ' + (wikiuri % term) def uncyc(phenny, input): - origterm = input.groups()[1] - if not origterm: - return phenny.say('Perhaps you meant ".uncyc Zen"?') - origterm = origterm + origterm = input.groups()[1] + if not origterm: + return phenny.say('Perhaps you meant ".uncyc Zen"?') + origterm = origterm - term = urllib.parse.unquote(origterm) - term = term[0].upper() + term[1:] - term = term.replace(' ', '_') + term = urllib.parse.unquote(origterm) + term = term[0].upper() + term[1:] + term = term.replace(' ', '_') - try: result = uncyclopedia(term) - except IOError: - error = "Can't connect to uncyclopedia.wikia.com (%s)" % (wikiuri % term) - return phenny.say(error) + try: result = uncyclopedia(term) + except IOError: + error = "Can't connect to uncyclopedia.wikia.com (%s)" % (wikiuri % term) + return phenny.say(error) - if result is not None: - phenny.say(result) - else: phenny.say('Can\'t find anything in Uncyclopedia for "%s".' % origterm) + if result is not None: + phenny.say(result) + else: phenny.say('Can\'t find anything in Uncyclopedia for "%s".' % origterm) uncyc.commands = ['uncyc'] uncyc.priority = 'high' if __name__ == '__main__': - print(__doc__.strip()) + print(__doc__.strip()) diff --git a/modules/urbandict.py b/modules/urbandict.py index d70889e..b74c0e6 100644 --- a/modules/urbandict.py +++ b/modules/urbandict.py @@ -37,4 +37,3 @@ urbandict.rule = (['urb'], r'(.*)') if __name__ == '__main__': print(__doc__.strip()) - diff --git a/modules/validate.py b/modules/validate.py index 3b2fef3..624b51d 100644 --- a/modules/validate.py +++ b/modules/validate.py @@ -10,34 +10,34 @@ http://inamidst.com/phenny/ import web def val(phenny, input): - """Check a webpage using the W3C Markup Validator.""" - if not input.group(2): - return phenny.reply("Nothing to validate.") - uri = input.group(2) - if not uri.startswith('http://'): - uri = 'http://' + uri + """Check a webpage using the W3C Markup Validator.""" + if not input.group(2): + return phenny.reply("Nothing to validate.") + uri = input.group(2) + if not uri.startswith('http://'): + uri = 'http://' + uri - path = '/check?uri=%s;output=xml' % web.urllib.quote(uri) - info = web.head('http://validator.w3.org' + path) + path = '/check?uri=%s;output=xml' % web.urllib.quote(uri) + info = web.head('http://validator.w3.org' + path) - result = uri + ' is ' + result = uri + ' is ' - if isinstance(info, list): - return phenny.say('Got HTTP response %s' % info[1]) + if isinstance(info, list): + return phenny.say('Got HTTP response %s' % info[1]) - if 'X-W3C-Validator-Status' in info: - result += str(info['X-W3C-Validator-Status']) - if info['X-W3C-Validator-Status'] != 'Valid': - if 'X-W3C-Validator-Errors' in info: - n = int(info['X-W3C-Validator-Errors'].split(' ')[0]) - if n != 1: - result += ' (%s errors)' % n - else: result += ' (%s error)' % n - else: result += 'Unvalidatable: no X-W3C-Validator-Status' + if 'X-W3C-Validator-Status' in info: + result += str(info['X-W3C-Validator-Status']) + if info['X-W3C-Validator-Status'] != 'Valid': + if 'X-W3C-Validator-Errors' in info: + n = int(info['X-W3C-Validator-Errors'].split(' ')[0]) + if n != 1: + result += ' (%s errors)' % n + else: result += ' (%s error)' % n + else: result += 'Unvalidatable: no X-W3C-Validator-Status' - phenny.reply(result) + phenny.reply(result) val.rule = (['val'], r'(?i)(\S+)') val.example = '.val http://www.w3.org/' if __name__ == '__main__': - print(__doc__.strip()) + print(__doc__.strip()) diff --git a/modules/vtluugwiki.py b/modules/vtluugwiki.py index 27efd14..2979113 100644 --- a/modules/vtluugwiki.py +++ b/modules/vtluugwiki.py @@ -7,7 +7,7 @@ Licensed under the Eiffel Forum License 2. http://inamidst.com/phenny/ modified from Wikipedia module -author: mutantmonkey +author: mutantmonkey """ import re, urllib.request, urllib.parse, urllib.error diff --git a/modules/wargame.py b/modules/wargame.py deleted file mode 100644 index 8296b97..0000000 --- a/modules/wargame.py +++ /dev/null @@ -1,116 +0,0 @@ -#!/usr/bin/python2 -# -*- coding: utf-8 -*- -""" -wargame.py - wargame module for the vtluug wargame -http://wargame.vtluug.org -author: Casey Link -""" - -import random - -import configparser, os -from urllib.parse import quote as urlquote -from urllib.request import urlopen -from urllib.error import HTTPError -from lxml import etree -from lxml import objectify -from datetime import datetime -import re - - -APIURL = "http://wargame.vtluug.org/scoreboard.xml" - -class server(object): - def __init__(self, name): - self.name = name - self.players = [] - def __str__(self): - s = "%s - %d players: " %(self.name, len(self.players)) - s += ", ".join([str(p) for p in self.players]) - return s - -class player(object): - def __init__(self, name): - self.name = name - self.score = "-1" - self.isOwner = False - def __str__(self): - return "%s%s: %s points" %(self.name, " (Current King)" if self.isOwner else "", self.score) - def __cmp__(self, other): - if int(self.score) < int(other.score): - return -1 - elif int(self.score) == int(other.score): - return 0 - else: - return 1 - - -def parse_player(player_element): - p = player( player_element.attrib.get("name") ) - p.score = player_element.attrib.get("score") - p.isOwner = player_element.attrib.get("isOwner") == "True" - return p - -def parse_server(server_element): - s = server( server_element.name.text ) - for player_e in server_element.players.player: - s.players.append( parse_player( player_e ) ) - s.players.sort() - s.players.reverse() - return s - -def wargame(phenny, input): - - if input.group(2) is not None: - rest = input.group(2) - m = re.match("^scores\s+(\S+)\s*$",rest) - if m is not None and len( m.groups() ) == 1: - return wargame_scores(phenny, m.group(1)) - m = re.match("^scores\s*$",rest) - if m is not None: - return wargame_scores(phenny, "Total") - m = re.match("^help\s*$",rest) - if m is not None: - phenny.say("VTLUUG King of the Root - http://wargame.vtluug.org'") - phenny.say("syntax: '.wargame' to see network status and target list'") - phenny.say("syntax: '.wargame scores ' to get current scores for a target'") - return - else: - phenny.say("hmm.. I don't know what you mean. try '.wargame help'") - return - try: - req = urlopen(APIURL) - except HTTPError as e: - phenny.say("uhoh. try again later, mmkay?") - return - root = objectify.parse(req).getroot() - online = root.attrib.get("online") == "True" - updated = root.attrib.get("updated") - - servers = [] - for server_e in root.servers.server: - servers.append( parse_server( server_e ) ) - - phenny.say( "wargame network is %s. last updated %s. available targets: %s" % ( "ONLINE" if online else "OFFLINE", updated, ", ".join([s.name for s in servers])) ) -def wargame_scores(phenny, s_name): - try: - req = urlopen(APIURL) - except HTTPError as e: - phenny.say("uhoh. try again later, mmkay?") - return - root = objectify.parse(req).getroot() - online = root.attrib.get("online") == "True" - updated = root.attrib.get("updated") - - servers = {} - for server_e in root.servers.server: - s = parse_server( server_e ) - servers[s.name] = s - if not s_name in servers: - phenny.say("sorry, i couldn't find %s" % ( s_name )) - return - - phenny.say( str(servers[s_name]) ) - - -wargame.commands = ['wargame'] \ No newline at end of file diff --git a/modules/weather.py b/modules/weather.py index 4ecadcb..cf5cd08 100644 --- a/modules/weather.py +++ b/modules/weather.py @@ -14,397 +14,397 @@ from tools import deprecated r_from = re.compile(r'(?i)([+-]\d+):00 from') def location(name): - name = urllib.parse.quote(name) - uri = 'http://ws.geonames.org/searchJSON?q=%s&maxRows=1' % name - for i in range(10): - bytes = web.get(uri) - if bytes is not None: break + name = urllib.parse.quote(name) + uri = 'http://ws.geonames.org/searchJSON?q=%s&maxRows=1' % name + for i in range(10): + bytes = web.get(uri) + if bytes is not None: break - results = web.json(bytes) - try: name = results['geonames'][0]['name'] - except IndexError: - return '?', '?', '0', '0' - countryName = results['geonames'][0]['countryName'] - lat = results['geonames'][0]['lat'] - lng = results['geonames'][0]['lng'] - return name, countryName, lat, lng + results = web.json(bytes) + try: name = results['geonames'][0]['name'] + except IndexError: + return '?', '?', '0', '0' + countryName = results['geonames'][0]['countryName'] + lat = results['geonames'][0]['lat'] + lng = results['geonames'][0]['lng'] + return name, countryName, lat, lng class GrumbleError(object): - pass + pass def local(icao, hour, minute): - uri = ('http://www.flightstats.com/' + - 'go/Airport/airportDetails.do?airportCode=%s') - try: bytes = web.get(uri % icao) - except AttributeError: - raise GrumbleError('A WEBSITE HAS GONE DOWN WTF STUPID WEB') - m = r_from.search(bytes) - if m: - offset = m.group(1) - lhour = int(hour) + int(offset) - lhour = lhour % 24 - return (str(lhour) + ':' + str(minute) + ', ' + str(hour) + - str(minute) + 'Z') - # return (str(lhour) + ':' + str(minute) + ' (' + str(hour) + - # ':' + str(minute) + 'Z)') - return str(hour) + ':' + str(minute) + 'Z' + uri = ('http://www.flightstats.com/' + + 'go/Airport/airportDetails.do?airportCode=%s') + try: bytes = web.get(uri % icao) + except AttributeError: + raise GrumbleError('A WEBSITE HAS GONE DOWN WTF STUPID WEB') + m = r_from.search(bytes) + if m: + offset = m.group(1) + lhour = int(hour) + int(offset) + lhour = lhour % 24 + return (str(lhour) + ':' + str(minute) + ', ' + str(hour) + + str(minute) + 'Z') + # return (str(lhour) + ':' + str(minute) + ' (' + str(hour) + + # ':' + str(minute) + 'Z)') + return str(hour) + ':' + str(minute) + 'Z' def code(phenny, search): - from icao import data - - if search.upper() in [loc[0] for loc in data]: - return search.upper() - else: - name, country, latitude, longitude = location(search) - if name == '?': return False - sumOfSquares = (99999999999999999999999999999, 'ICAO') - for icao_code, lat, lon in data: - latDiff = abs(latitude - lat) - lonDiff = abs(longitude - lon) - diff = (latDiff * latDiff) + (lonDiff * lonDiff) - if diff < sumOfSquares[0]: - sumOfSquares = (diff, icao_code) - return sumOfSquares[1] + from icao import data + + if search.upper() in [loc[0] for loc in data]: + return search.upper() + else: + name, country, latitude, longitude = location(search) + if name == '?': return False + sumOfSquares = (99999999999999999999999999999, 'ICAO') + for icao_code, lat, lon in data: + latDiff = abs(latitude - lat) + lonDiff = abs(longitude - lon) + diff = (latDiff * latDiff) + (lonDiff * lonDiff) + if diff < sumOfSquares[0]: + sumOfSquares = (diff, icao_code) + return sumOfSquares[1] @deprecated def f_weather(self, origin, match, args): - """.weather - Show the weather at airport with the code .""" - if origin.sender == '#talis': - if args[0].startswith('.weather '): return + """.weather - Show the weather at airport with the code .""" + if origin.sender == '#talis': + if args[0].startswith('.weather '): return - icao_code = match.group(2) - if not icao_code: - return self.msg(origin.sender, 'Try .weather London, for example?') + icao_code = match.group(2) + if not icao_code: + return self.msg(origin.sender, 'Try .weather London, for example?') - icao_code = code(self, icao_code) + icao_code = code(self, icao_code) - if not icao_code: - self.msg(origin.sender, 'No ICAO code found, sorry') - return + if not icao_code: + self.msg(origin.sender, 'No ICAO code found, sorry') + return - uri = 'http://weather.noaa.gov/pub/data/observations/metar/stations/%s.TXT' - try: bytes = web.get(uri % icao_code) - except AttributeError: - raise GrumbleError('OH CRAP NOAA HAS GONE DOWN THE WEB IS BROKEN') - if 'Not Found' in bytes: - self.msg(origin.sender, icao_code+': no such ICAO code, or no NOAA data') - return + uri = 'http://weather.noaa.gov/pub/data/observations/metar/stations/%s.TXT' + try: bytes = web.get(uri % icao_code) + except AttributeError: + raise GrumbleError('OH CRAP NOAA HAS GONE DOWN THE WEB IS BROKEN') + if 'Not Found' in bytes: + self.msg(origin.sender, icao_code+': no such ICAO code, or no NOAA data') + return - metar = bytes.splitlines().pop() - metar = metar.split(' ') + metar = bytes.splitlines().pop() + metar = metar.split(' ') - if len(metar[0]) == 4: - metar = metar[1:] + if len(metar[0]) == 4: + metar = metar[1:] - if metar[0].endswith('Z'): - time = metar[0] - metar = metar[1:] - else: time = None + if metar[0].endswith('Z'): + time = metar[0] + metar = metar[1:] + else: time = None - if metar[0] == 'AUTO': - metar = metar[1:] - if metar[0] == 'VCU': - self.msg(origin.sender, icao_code + ': no data provided') - return + if metar[0] == 'AUTO': + metar = metar[1:] + if metar[0] == 'VCU': + self.msg(origin.sender, icao_code + ': no data provided') + return - if metar[0].endswith('KT'): - wind = metar[0] - metar = metar[1:] - else: wind = None + if metar[0].endswith('KT'): + wind = metar[0] + metar = metar[1:] + else: wind = None - if ('V' in metar[0]) and (metar[0] != 'CAVOK'): - vari = metar[0] - metar = metar[1:] - else: vari = None + if ('V' in metar[0]) and (metar[0] != 'CAVOK'): + vari = metar[0] + metar = metar[1:] + else: vari = None - if ((len(metar[0]) == 4) or - metar[0].endswith('SM')): - visibility = metar[0] - metar = metar[1:] - else: visibility = None + if ((len(metar[0]) == 4) or + metar[0].endswith('SM')): + visibility = metar[0] + metar = metar[1:] + else: visibility = None - while metar[0].startswith('R') and (metar[0].endswith('L') - or 'L/' in metar[0]): - metar = metar[1:] + while metar[0].startswith('R') and (metar[0].endswith('L') + or 'L/' in metar[0]): + metar = metar[1:] - if len(metar[0]) == 6 and (metar[0].endswith('N') or - metar[0].endswith('E') or - metar[0].endswith('S') or - metar[0].endswith('W')): - metar = metar[1:] # 7000SE? + if len(metar[0]) == 6 and (metar[0].endswith('N') or + metar[0].endswith('E') or + metar[0].endswith('S') or + metar[0].endswith('W')): + metar = metar[1:] # 7000SE? - cond = [] - while (((len(metar[0]) < 5) or - metar[0].startswith('+') or - metar[0].startswith('-')) and (not (metar[0].startswith('VV') or - metar[0].startswith('SKC') or metar[0].startswith('CLR') or - metar[0].startswith('FEW') or metar[0].startswith('SCT') or - metar[0].startswith('BKN') or metar[0].startswith('OVC')))): - cond.append(metar[0]) - metar = metar[1:] + cond = [] + while (((len(metar[0]) < 5) or + metar[0].startswith('+') or + metar[0].startswith('-')) and (not (metar[0].startswith('VV') or + metar[0].startswith('SKC') or metar[0].startswith('CLR') or + metar[0].startswith('FEW') or metar[0].startswith('SCT') or + metar[0].startswith('BKN') or metar[0].startswith('OVC')))): + cond.append(metar[0]) + metar = metar[1:] - while '/P' in metar[0]: - metar = metar[1:] + while '/P' in metar[0]: + metar = metar[1:] - if not metar: - self.msg(origin.sender, icao_code + ': no data provided') - return + if not metar: + self.msg(origin.sender, icao_code + ': no data provided') + return - cover = [] - while (metar[0].startswith('VV') or metar[0].startswith('SKC') or - metar[0].startswith('CLR') or metar[0].startswith('FEW') or - metar[0].startswith('SCT') or metar[0].startswith('BKN') or - metar[0].startswith('OVC')): - cover.append(metar[0]) - metar = metar[1:] - if not metar: - self.msg(origin.sender, icao_code + ': no data provided') - return + cover = [] + while (metar[0].startswith('VV') or metar[0].startswith('SKC') or + metar[0].startswith('CLR') or metar[0].startswith('FEW') or + metar[0].startswith('SCT') or metar[0].startswith('BKN') or + metar[0].startswith('OVC')): + cover.append(metar[0]) + metar = metar[1:] + if not metar: + self.msg(origin.sender, icao_code + ': no data provided') + return - if metar[0] == 'CAVOK': - cover.append('CLR') - metar = metar[1:] + if metar[0] == 'CAVOK': + cover.append('CLR') + metar = metar[1:] - if metar[0] == 'PRFG': - cover.append('CLR') # @@? - metar = metar[1:] + if metar[0] == 'PRFG': + cover.append('CLR') # @@? + metar = metar[1:] - if metar[0] == 'NSC': - cover.append('CLR') - metar = metar[1:] + if metar[0] == 'NSC': + cover.append('CLR') + metar = metar[1:] - if ('/' in metar[0]) or (len(metar[0]) == 5 and metar[0][2] == '.'): - temp = metar[0] - metar = metar[1:] - else: temp = None + if ('/' in metar[0]) or (len(metar[0]) == 5 and metar[0][2] == '.'): + temp = metar[0] + metar = metar[1:] + else: temp = None - if metar[0].startswith('QFE'): - metar = metar[1:] + if metar[0].startswith('QFE'): + metar = metar[1:] - if metar[0].startswith('Q') or metar[0].startswith('A'): - pressure = metar[0] - metar = metar[1:] - else: pressure = None + if metar[0].startswith('Q') or metar[0].startswith('A'): + pressure = metar[0] + metar = metar[1:] + else: pressure = None - if time: - hour = time[2:4] - minute = time[4:6] - time = local(icao_code, hour, minute) - else: time = '(time unknown)' + if time: + hour = time[2:4] + minute = time[4:6] + time = local(icao_code, hour, minute) + else: time = '(time unknown)' - if wind: - speed = int(wind[3:5]) - if speed < 1: - description = 'Calm' - elif speed < 4: - description = 'Light air' - elif speed < 7: - description = 'Light breeze' - elif speed < 11: - description = 'Gentle breeze' - elif speed < 16: - description = 'Moderate breeze' - elif speed < 22: - description = 'Fresh breeze' - elif speed < 28: - description = 'Strong breeze' - elif speed < 34: - description = 'Near gale' - elif speed < 41: - description = 'Gale' - elif speed < 48: - description = 'Strong gale' - elif speed < 56: - description = 'Storm' - elif speed < 64: - description = 'Violent storm' - else: description = 'Hurricane' + if wind: + speed = int(wind[3:5]) + if speed < 1: + description = 'Calm' + elif speed < 4: + description = 'Light air' + elif speed < 7: + description = 'Light breeze' + elif speed < 11: + description = 'Gentle breeze' + elif speed < 16: + description = 'Moderate breeze' + elif speed < 22: + description = 'Fresh breeze' + elif speed < 28: + description = 'Strong breeze' + elif speed < 34: + description = 'Near gale' + elif speed < 41: + description = 'Gale' + elif speed < 48: + description = 'Strong gale' + elif speed < 56: + description = 'Storm' + elif speed < 64: + description = 'Violent storm' + else: description = 'Hurricane' - degrees = float(wind[0:3]) - #if degrees == 'VRB': - # degrees = '\u21BB' - if (degrees <= 22.5) or (degrees > 337.5): - degrees = '\u2191' - elif (degrees > 22.5) and (degrees <= 67.5): - degrees = '\u2197' - elif (degrees > 67.5) and (degrees <= 112.5): - degrees = '\u2192' - elif (degrees > 112.5) and (degrees <= 157.5): - degrees = '\u2198' - elif (degrees > 157.5) and (degrees <= 202.5): - degrees = '\u2193' - elif (degrees > 202.5) and (degrees <= 247.5): - degrees = '\u2199' - elif (degrees > 247.5) and (degrees <= 292.5): - degrees = '\u2190' - elif (degrees > 292.5) and (degrees <= 337.5): - degrees = '\u2196' + degrees = float(wind[0:3]) + #if degrees == 'VRB': + # degrees = '\u21BB' + if (degrees <= 22.5) or (degrees > 337.5): + degrees = '\u2191' + elif (degrees > 22.5) and (degrees <= 67.5): + degrees = '\u2197' + elif (degrees > 67.5) and (degrees <= 112.5): + degrees = '\u2192' + elif (degrees > 112.5) and (degrees <= 157.5): + degrees = '\u2198' + elif (degrees > 157.5) and (degrees <= 202.5): + degrees = '\u2193' + elif (degrees > 202.5) and (degrees <= 247.5): + degrees = '\u2199' + elif (degrees > 247.5) and (degrees <= 292.5): + degrees = '\u2190' + elif (degrees > 292.5) and (degrees <= 337.5): + degrees = '\u2196' - if not icao_code.startswith('EN') and not icao_code.startswith('ED'): - wind = '%s %skt (%s)' % (description, speed, degrees) - elif icao_code.startswith('ED'): - kmh = int(round(speed * 1.852, 0)) - wind = '%s %skm/h (%skt) (%s)' % (description, kmh, speed, degrees) - elif icao_code.startswith('EN'): - ms = int(round(speed * 0.514444444, 0)) - wind = '%s %sm/s (%skt) (%s)' % (description, ms, speed, degrees) - else: wind = '(wind unknown)' + if not icao_code.startswith('EN') and not icao_code.startswith('ED'): + wind = '%s %skt (%s)' % (description, speed, degrees) + elif icao_code.startswith('ED'): + kmh = int(round(speed * 1.852, 0)) + wind = '%s %skm/h (%skt) (%s)' % (description, kmh, speed, degrees) + elif icao_code.startswith('EN'): + ms = int(round(speed * 0.514444444, 0)) + wind = '%s %sm/s (%skt) (%s)' % (description, ms, speed, degrees) + else: wind = '(wind unknown)' - if visibility: - visibility = visibility + 'm' - else: visibility = '(visibility unknown)' + if visibility: + visibility = visibility + 'm' + else: visibility = '(visibility unknown)' - if cover: - level = None - for c in cover: - if c.startswith('OVC') or c.startswith('VV'): - if (level is None) or (level < 8): - level = 8 - elif c.startswith('BKN'): - if (level is None) or (level < 5): - level = 5 - elif c.startswith('SCT'): - if (level is None) or (level < 3): - level = 3 - elif c.startswith('FEW'): - if (level is None) or (level < 1): - level = 1 - elif c.startswith('SKC') or c.startswith('CLR'): - if level is None: - level = 0 + if cover: + level = None + for c in cover: + if c.startswith('OVC') or c.startswith('VV'): + if (level is None) or (level < 8): + level = 8 + elif c.startswith('BKN'): + if (level is None) or (level < 5): + level = 5 + elif c.startswith('SCT'): + if (level is None) or (level < 3): + level = 3 + elif c.startswith('FEW'): + if (level is None) or (level < 1): + level = 1 + elif c.startswith('SKC') or c.startswith('CLR'): + if level is None: + level = 0 - if level == 8: - cover = 'Overcast \u2601' - elif level == 5: - cover = 'Cloudy' - elif level == 3: - cover = 'Scattered' - elif (level == 1) or (level == 0): - cover = 'Clear \u263C' - else: cover = 'Cover Unknown' - else: cover = 'Cover Unknown' + if level == 8: + cover = 'Overcast \u2601' + elif level == 5: + cover = 'Cloudy' + elif level == 3: + cover = 'Scattered' + elif (level == 1) or (level == 0): + cover = 'Clear \u263C' + else: cover = 'Cover Unknown' + else: cover = 'Cover Unknown' - if temp: - if '/' in temp: - temp = temp.split('/')[0] - else: temp = temp.split('.')[0] - if temp.startswith('M'): - temp = '-' + temp[1:] - try: temp = int(temp) - except ValueError: temp = '?' - else: temp = '?' + if temp: + if '/' in temp: + temp = temp.split('/')[0] + else: temp = temp.split('.')[0] + if temp.startswith('M'): + temp = '-' + temp[1:] + try: temp = int(temp) + except ValueError: temp = '?' + else: temp = '?' - if pressure: - if pressure.startswith('Q'): - pressure = pressure.lstrip('Q') - if pressure != 'NIL': - pressure = str(int(pressure)) + 'mb' - else: pressure = '?mb' - elif pressure.startswith('A'): - pressure = pressure.lstrip('A') - if pressure != 'NIL': - inches = pressure[:2] + '.' + pressure[2:] - mb = int(float(inches) * 33.7685) - pressure = '%sin (%smb)' % (inches, mb) - else: pressure = '?mb' + if pressure: + if pressure.startswith('Q'): + pressure = pressure.lstrip('Q') + if pressure != 'NIL': + pressure = str(int(pressure)) + 'mb' + else: pressure = '?mb' + elif pressure.startswith('A'): + pressure = pressure.lstrip('A') + if pressure != 'NIL': + inches = pressure[:2] + '.' + pressure[2:] + mb = int(float(inches) * 33.7685) + pressure = '%sin (%smb)' % (inches, mb) + else: pressure = '?mb' - if isinstance(temp, int): - f = round((temp * 1.8) + 32, 2) - temp = '%s\u2109 (%s\u2103)' % (f, temp) - else: pressure = '?mb' - if isinstance(temp, int): - temp = '%s\u2103' % temp + if isinstance(temp, int): + f = round((temp * 1.8) + 32, 2) + temp = '%s\u2109 (%s\u2103)' % (f, temp) + else: pressure = '?mb' + if isinstance(temp, int): + temp = '%s\u2103' % temp - if cond: - conds = cond - cond = '' + if cond: + conds = cond + cond = '' - intensities = { - '-': 'Light', - '+': 'Heavy' - } + intensities = { + '-': 'Light', + '+': 'Heavy' + } - descriptors = { - 'MI': 'Shallow', - 'PR': 'Partial', - 'BC': 'Patches', - 'DR': 'Drifting', - 'BL': 'Blowing', - 'SH': 'Showers of', - 'TS': 'Thundery', - 'FZ': 'Freezing', - 'VC': 'In the vicinity:' - } + descriptors = { + 'MI': 'Shallow', + 'PR': 'Partial', + 'BC': 'Patches', + 'DR': 'Drifting', + 'BL': 'Blowing', + 'SH': 'Showers of', + 'TS': 'Thundery', + 'FZ': 'Freezing', + 'VC': 'In the vicinity:' + } - phenomena = { - 'DZ': 'Drizzle', - 'RA': 'Rain', - 'SN': 'Snow', - 'SG': 'Snow Grains', - 'IC': 'Ice Crystals', - 'PL': 'Ice Pellets', - 'GR': 'Hail', - 'GS': 'Small Hail', - 'UP': 'Unknown Precipitation', - 'BR': 'Mist', - 'FG': 'Fog', - 'FU': 'Smoke', - 'VA': 'Volcanic Ash', - 'DU': 'Dust', - 'SA': 'Sand', - 'HZ': 'Haze', - 'PY': 'Spray', - 'PO': 'Whirls', - 'SQ': 'Squalls', - 'FC': 'Tornado', - 'SS': 'Sandstorm', - 'DS': 'Duststorm', - # ? Cf. http://swhack.com/logs/2007-10-05#T07-58-56 - 'TS': 'Thunderstorm', - 'SH': 'Showers' - } + phenomena = { + 'DZ': 'Drizzle', + 'RA': 'Rain', + 'SN': 'Snow', + 'SG': 'Snow Grains', + 'IC': 'Ice Crystals', + 'PL': 'Ice Pellets', + 'GR': 'Hail', + 'GS': 'Small Hail', + 'UP': 'Unknown Precipitation', + 'BR': 'Mist', + 'FG': 'Fog', + 'FU': 'Smoke', + 'VA': 'Volcanic Ash', + 'DU': 'Dust', + 'SA': 'Sand', + 'HZ': 'Haze', + 'PY': 'Spray', + 'PO': 'Whirls', + 'SQ': 'Squalls', + 'FC': 'Tornado', + 'SS': 'Sandstorm', + 'DS': 'Duststorm', + # ? Cf. http://swhack.com/logs/2007-10-05#T07-58-56 + 'TS': 'Thunderstorm', + 'SH': 'Showers' + } - for c in conds: - if c.endswith('//'): - if cond: cond += ', ' - cond += 'Some Precipitation' - elif len(c) == 5: - intensity = intensities[c[0]] - descriptor = descriptors[c[1:3]] - phenomenon = phenomena.get(c[3:], c[3:]) - if cond: cond += ', ' - cond += intensity + ' ' + descriptor + ' ' + phenomenon - elif len(c) == 4: - descriptor = descriptors.get(c[:2], c[:2]) - phenomenon = phenomena.get(c[2:], c[2:]) - if cond: cond += ', ' - cond += descriptor + ' ' + phenomenon - elif len(c) == 3: - intensity = intensities.get(c[0], c[0]) - phenomenon = phenomena.get(c[1:], c[1:]) - if cond: cond += ', ' - cond += intensity + ' ' + phenomenon - elif len(c) == 2: - phenomenon = phenomena.get(c, c) - if cond: cond += ', ' - cond += phenomenon + for c in conds: + if c.endswith('//'): + if cond: cond += ', ' + cond += 'Some Precipitation' + elif len(c) == 5: + intensity = intensities[c[0]] + descriptor = descriptors[c[1:3]] + phenomenon = phenomena.get(c[3:], c[3:]) + if cond: cond += ', ' + cond += intensity + ' ' + descriptor + ' ' + phenomenon + elif len(c) == 4: + descriptor = descriptors.get(c[:2], c[:2]) + phenomenon = phenomena.get(c[2:], c[2:]) + if cond: cond += ', ' + cond += descriptor + ' ' + phenomenon + elif len(c) == 3: + intensity = intensities.get(c[0], c[0]) + phenomenon = phenomena.get(c[1:], c[1:]) + if cond: cond += ', ' + cond += intensity + ' ' + phenomenon + elif len(c) == 2: + phenomenon = phenomena.get(c, c) + if cond: cond += ', ' + cond += phenomenon - # if not cond: - # format = u'%s at %s: %s, %s, %s, %s' - # args = (icao, time, cover, temp, pressure, wind) - # else: - # format = u'%s at %s: %s, %s, %s, %s, %s' - # args = (icao, time, cover, temp, pressure, cond, wind) + # if not cond: + # format = u'%s at %s: %s, %s, %s, %s' + # args = (icao, time, cover, temp, pressure, wind) + # else: + # format = u'%s at %s: %s, %s, %s, %s, %s' + # args = (icao, time, cover, temp, pressure, cond, wind) - if not cond: - format = '%s, %s, %s, %s - %s %s' - args = (cover, temp, pressure, wind, str(icao_code), time) - else: - format = '%s, %s, %s, %s, %s - %s, %s' - args = (cover, temp, pressure, cond, wind, str(icao_code), time) + if not cond: + format = '%s, %s, %s, %s - %s %s' + args = (cover, temp, pressure, wind, str(icao_code), time) + else: + format = '%s, %s, %s, %s, %s - %s, %s' + args = (cover, temp, pressure, cond, wind, str(icao_code), time) - self.msg(origin.sender, format % args) + self.msg(origin.sender, format % args) f_weather.rule = (['weather'], r'(.*)') if __name__ == '__main__': - print(__doc__.strip()) + print(__doc__.strip()) diff --git a/modules/wiktionary.py b/modules/wiktionary.py index cae160b..fb066f8 100644 --- a/modules/wiktionary.py +++ b/modules/wiktionary.py @@ -15,86 +15,86 @@ r_tag = re.compile(r'<[^>]+>') r_ul = re.compile(r'(?ims)
      .*?
    ') def text(html): - text = r_tag.sub('', html).strip() - text = text.replace('\n', ' ') - text = text.replace('\r', '') - text = text.replace('(intransitive', '(intr.') - text = text.replace('(transitive', '(trans.') - return text + text = r_tag.sub('', html).strip() + text = text.replace('\n', ' ') + text = text.replace('\r', '') + text = text.replace('(intransitive', '(intr.') + text = text.replace('(transitive', '(trans.') + return text def wiktionary(word): - bytes = web.get(uri % web.quote(word)) - bytes = r_ul.sub('', bytes) + bytes = web.get(uri % web.quote(word)) + bytes = r_ul.sub('', bytes) - mode = None - etymology = None - definitions = {} - for line in bytes.splitlines(): - if 'id="Etymology"' in line: - mode = 'etymology' - elif 'id="Noun"' in line: - mode = 'noun' - elif 'id="Verb"' in line: - mode = 'verb' - elif 'id="Adjective"' in line: - mode = 'adjective' - elif 'id="Adverb"' in line: - mode = 'adverb' - elif 'id="Interjection"' in line: - mode = 'interjection' - elif 'id="Particle"' in line: - mode = 'particle' - elif 'id="Preposition"' in line: - mode = 'preposition' - elif 'id="' in line: - mode = None + mode = None + etymology = None + definitions = {} + for line in bytes.splitlines(): + if 'id="Etymology"' in line: + mode = 'etymology' + elif 'id="Noun"' in line: + mode = 'noun' + elif 'id="Verb"' in line: + mode = 'verb' + elif 'id="Adjective"' in line: + mode = 'adjective' + elif 'id="Adverb"' in line: + mode = 'adverb' + elif 'id="Interjection"' in line: + mode = 'interjection' + elif 'id="Particle"' in line: + mode = 'particle' + elif 'id="Preposition"' in line: + mode = 'preposition' + elif 'id="' in line: + mode = None - elif (mode == 'etmyology') and ('

    ' in line): - etymology = text(line) - elif (mode is not None) and ('

  • ' in line): - definitions.setdefault(mode, []).append(text(line)) + elif (mode == 'etmyology') and ('

    ' in line): + etymology = text(line) + elif (mode is not None) and ('

  • ' in line): + definitions.setdefault(mode, []).append(text(line)) - if ' 300: - result = result[:295] + '[...]' - phenny.say(result) + if len(result) > 300: + result = result[:295] + '[...]' + phenny.say(result) w.commands = ['w'] w.example = '.w bailiwick' def encarta(phenny, input): - return phenny.reply('Microsoft removed Encarta, try .w instead!') + return phenny.reply('Microsoft removed Encarta, try .w instead!') encarta.commands = ['dict'] if __name__ == '__main__': - print(__doc__.strip()) + print(__doc__.strip())