717d7fb5e82b — Steve Fink tip 3 years ago
Fixup for running on laptop
4 files changed, 41 insertions(+), 30 deletions(-)

M mrgiggles.py
M plugins/knowledge/__init__.py
M plugins/map/__init__.py
M plugins/pun/__init__.py
M mrgiggles.py +10 -11
@@ 5,6 5,7 @@ VERSION = "1.0"
 import argparse
 import sys
 import re
+import importlib
 import json
 import os
 import requests

          
@@ 17,7 18,7 @@ from collections import defaultdict
 
 def include(filename):
     path = os.path.join(os.path.dirname(os.path.abspath(__file__)), filename)
-    execfile(path, data)
+    exec(open(path).read(), data)
 
 data = { 'include': include }
 

          
@@ 207,7 208,7 @@ class CustomIRCBotProtocol(irc.IRCClient
 
     def msg(self, message, *args, **kwargs):
         # Fix unicode BS
-        return irc.IRCClient.msg(self, message.encode('utf-8'), *args, **kwargs)
+        return irc.IRCClient.msg(self, message, *args, **kwargs)
 
     def process_batchlines(self, infh, outfh):
         for line in infh:

          
@@ 297,7 298,7 @@ class CustomIRCBotProtocol(irc.IRCClient
 
         if 'nick_passwd' in config:
             log.msg("DEBUG: attempting to identify with NickServ")
-            self.msg('NickServ', ('identify ' + config['nick_passwd']).encode('utf8'))
+            self.msg('NickServ', ('identify ' + config['nick_passwd']))
 
         plugins.startup(self)
 

          
@@ 431,7 432,7 @@ class CustomIRCBotProtocol(irc.IRCClient
         nick, _, host = user.partition('!')
         if nick == channel:
             return # my own message
-        message = message.strip().decode('utf-8')
+        message = message.strip()
         addressee = None
         if channel == self.bot.nickname:
             addressee = self.bot.nickname

          
@@ 510,7 511,7 @@ class CustomIRCBotProtocol(irc.IRCClient
                 command = str(command)
                 func = self.resolve_command(command, source=nick)
                 if func is None and addressee == self.bot.nickname:
-                    self.debug(u"Unknown direct command '{command}' in channel {channel} from {source}".format(command=message, channel=channel, source=nick).encode('utf-8'))
+                    self.debug(u"Unknown direct command '{command}' in channel {channel} from {source}".format(command=message, channel=channel, source=nick))
 
         if not func:
             return

          
@@ 543,8 544,6 @@ class CustomIRCBotProtocol(irc.IRCClient
 
     @defer.inlineCallbacks
     def _send_message(self, msg, target, nick=None):
-        target = target.encode('utf8', errors='ignore')
-
         if msg is None:
             defer.returnValue(None)
             yield None

          
@@ 561,11 560,11 @@ class CustomIRCBotProtocol(irc.IRCClient
                 text = pieces.pop(0)
                 if len(text) > 0:
                     if text.startswith("/me "):
-                        self.describe(target, text.replace("/me ", "").encode('utf8'))
+                        self.describe(target, text.replace("/me ", ""))
                     else:
                         if nick:
                             text = '%s: %s' % (nick, text)
-                        self.msg(target, text.encode('utf8'))
+                        self.msg(target, text)
 
                 if pieces:
                     text = pieces.pop(0)

          
@@ 665,7 664,7 @@ class CustomIRCBotProtocol(irc.IRCClient
         self.msg(sendback, "reloading %s" % (rest,))
         try:
             oldplugin = self.plugins[rest]
-            module = reload(sys.modules[oldplugin.__module__])
+            module = importlib.reload(sys.modules[oldplugin.__module__])
             plugin = getattr(module, oldplugin.__class__.__name__)(self, rest)
             self.plugins[rest] = plugin
             oldplugin.unload()

          
@@ 715,7 714,7 @@ class CustomIRCBotProtocol(irc.IRCClient
         return self.leave_channel(rest)
 
     def pastebin(self, lines, style='text'):
-        body = '\n'.join(lines).encode('utf8')
+        body = '\n'.join(lines)
         maxlen = 20000
         if style == 'text' and len(body) > maxlen:
             body = body[0:maxlen] + "...(truncated)"

          
M plugins/knowledge/__init__.py +13 -6
@@ 260,8 260,14 @@ def punbox64_to_string(number_str):
     return typeStr
 
 random_questions = {
-    'what have I done now': 'only that which had to be done',
-    'botsnack': 'I am above such things<...10sec...>/me furtively gobbles up the botsnack',
+    'what have I done now': {
+        'response': 'only that which had to be done',
+        'direct': False
+    },
+    'botsnack': {
+        'response': 'I am above such things<...10sec...>/me furtively gobbles up the botsnack',
+        'direct': True
+    }
 }
 
 class KnowledgePlugin(plugins.Plugin):

          
@@ 575,9 581,10 @@ it is the symptom when you mark a Cell (
 
     def command_response(self, rest, channel, **kwargs):
         '''Various canned responses'''
-        if kwargs.get('addressee') != self.proto.bot.nickname:
-            return
-
         query = kwargs.get('query', rest)
         if query in random_questions:
-            return random_questions[query]
+            info = random_questions[query]
+            if info.get('direct'):
+                if kwargs.get('addressee') != self.proto.bot.nickname:
+                    return
+            return info['response']

          
M plugins/map/__init__.py +11 -12
@@ 3,7 3,6 @@ from plugins import MatchGroup
 
 import re
 import json
-import urllib2
 
 from collections import namedtuple
 from twisted.web.client import getPage

          
@@ 49,17 48,19 @@ class MapPlugin(plugins.Plugin):
     def find_location(self, location):
         url = self.plugin_config['geocode-url']
         url = url.replace('<key>', self.plugin_config['api-key'])
-        url = url.replace('<query>', urllib2.quote(location))
-        url = url.encode('utf-8')
+        #url = url.replace('<query>', urllib2.quote(location))
+        # FIXME
+        url = url.replace('<query>', location.replace(" ", "+"))  # FIXME!
 
         try:
-            data = yield getPage(url)
+            data = yield getPage(url.encode())
+            data = data.decode()
         except Exception as e:
             log.msg("Error fetching url %s: %s" % (url, e))
             raise(e)
 
         try:
-            file("/tmp/last-geo.json", "w").write(url + "\n" + data)
+            open("/tmp/last-geo.json", "w").write(url + "\n" + data)
             info = json.loads(data)
         except Exception as e:
             log.msg("Error parsing JSON response: " + data)

          
@@ 91,8 92,8 @@ class MapPlugin(plugins.Plugin):
         url = self.plugin_config['time-url']
         url = url.replace('<lat>', str(where.latitude))
         url = url.replace('<long>', str(where.longitude))
-        url = url.encode('utf-8')
-        data = yield getPage(url)
+        data = yield getPage(url.encode())
+        data = data.decode()
 
         span = where.bbox[3] - where.bbox[1]
         log.msg("%s spans %s degrees of longitude, bbox %r" % (location or rest, span, where.bbox))

          
@@ 103,17 104,15 @@ class MapPlugin(plugins.Plugin):
             url = self.plugin_config['time-url']
             url = url.replace('<lat>', str(where.bbox[0]))
             url = url.replace('<long>', str(where.bbox[1]))
-            url = url.encode('utf-8')
-            data0 = yield getPage(url)
+            data0 = yield getPage(url.encode())
 
             url = self.plugin_config['time-url']
             url = url.replace('<lat>', str(where.bbox[2]))
             url = url.replace('<long>', str(where.bbox[3]))
-            url = url.encode('utf-8')
-            data1 = yield getPage(url)
+            data1 = yield getPage(url.encode())
 
         try:
-            file("/tmp/last-tz.json", "w").write(url + "\n" + data)
+            open("/tmp/last-tz.json", "w").write(url + "\n" + data)
             info = json.loads(data)
             now = info['time']
             info0 = json.loads(data0)

          
M plugins/pun/__init__.py +7 -1
@@ 329,6 329,8 @@ Freezing rain might not be made of ice, 
 My job at the concrete plant seems to get harder and harder.
 
 Why did Joe quit his job at the doughnut factory?<...2sec...>He probably got tired of the hole business.
+
+Light travels faster than sound.<...4sec...>That's why some people appear bright until you hear them speak.
 """.split("\n\n")
 
 class PunPlugin(plugins.Plugin):

          
@@ 336,6 338,10 @@ class PunPlugin(plugins.Plugin):
 
     def command_pun(self, filename, channel, **kwargs):
         '''tell a randomly chosen pun'''
-        pun = random.sample(PUNS, 1)[0]
+        if filename == '':
+            pun = random.sample(PUNS, 1)[0]
+        else:
+            matches = [p for p in PUNS if filename in p]
+            pun = random.sample(matches, 1)[0]
         pun = re.sub(r'^\d+\. ', '', pun)
         return pun