Commits

Marc-Alexandre Chan committed 169b6fd

Event fixes/changes.

+ Continuous event interval changed to directly access config value.
- Offset for the initial events queued adjusted.
- Various code errors fixed.
- Bugfixes on CheckMessageCommand.

  • Participants
  • Parent commits bfd13fa

Comments (0)

Files changed (2)

minibot/__init__.py

         now = time.time()
 
         ev_msg = CheckMessageEvent()
-        ev_msg.interval = config.minibot.msg_rate
-        ev_msg.start_time = time.time() + 1
+        ev_msg.start_time = time.time() + 5
         self.scheduler.queue_event(ev_msg)
 
         ev_post = CheckPostQueueEvent()
-        ev_post.interval = config.minibot.queue_rate
-        ev_post.start_time = time.time() + 5
+        ev_post.start_time = time.time() + 8
         self.scheduler.queue_event(ev_post)
 
         ev_sugg = CheckSuggestionQueueEvent()
-        ev_sugg.interval = config.minibot.queue_rate
-        ev_post.start_time = time.time() + 7
+        ev_post.start_time = time.time() + 13
         self.scheduler.queue_event(ev_sugg)
 
         ev_sugg_maint = SuggestionThreadQueueMaintainer()
         ev_sugg_maint.interval =\
             self.THREAD_MAINTAINER_INTERVAL_FACTOR * config.minibot.queue_rate
-        ev_post.start_time = time.time() + 9
+        ev_post.start_time = time.time() + 21
         self.scheduler.queue_event(ev_sugg)
 
     def sigterm_handler(self, signum, frame):

minibot/events.py

 from datetime import timedelta
 from calendar import timegm
 from urlparse import urlparse
-from time     import strftime
+from time     import strftime, localtime
 import re
 
-# TODO: error handling
-# TODO: repr
-
 # this is in all superscript (renders equiv. small text) ^(syntax is like this)
 _BOT_MSG = ("^(Having a problem with DailyPromptBot? Want to comment? You can "
 "contact [Laogeodritt](http://www.reddit.com/u/Laogeodritt) or leave us a note "
     Defaults:
         * ``start_time`` = 0
         * ``duration`` = -1
-        * ``interval`` = 10
+        * ``interval`` = config.minibot.msg_rate (unless set before start())
         * ``priority`` = 90
 
     """
     required_res = ['reddit', 'approved', 'config.minibot', 'logger']
     start_time = 0
     duration = -1
-    interval = 10
+    interval = None
     priority = 90
 
     def __init__(self):
         self.msg_chunk = self.res['config.minibot'].msg_chunk
         self.log = self.res['logger']
 
+        if self.interval is None:
+            self.interval = self.res['config.minibot'].msg_rate
+
         self.run()
 
     def run(self):
                     CommandParameterError, MissingParameterError) as e:
                 self.log.info("%s: %s", classname(self), e.args[0])
 
-                self.log.info("%s: Replying to invalid command PM from %s (%d)",
+                self.log.info("%s: Replying to invalid command PM from %s (%s)",
                     classname(self), msg.author.name, msg.id)
                 err_cmd = SendErrorMessageCommand.command_parameter(e, msg)
                 self.owner.queue_event(err_cmd)
 
                 msg.mark_as_read()
-            else: # bad message, ignore it
+            except BadCommandError: # bad message, ignore it
                 # if bad PM, log; but don't care about replies/comments
                 if msg.subreddit is None:
                     self.log.info(
-                        "%s: Ignoring bad private message from %s (%d)",
+                        "%s: Ignoring bad private message from %s (%s)",
                         classname(self), msg.author.name, msg.id)
                 msg.mark_as_read()
 
 
     def _process_message(self, msg):
         """ Process a message. May throw CommandParseError, CommandNameError,
-        CommandParameterError, MissingParameterError BadCommandError. """
+        CommandParameterError, MissingParameterError, BadCommandError. """
         if not self._is_valid_message(msg):
             raise BadCommandError('CheckMessageEvent: bad command message', msg)
         # raises CommandParseError
         (is a PM sent to the bot (not modmail) from an approved user). """
         return (msg.subreddit is None and
                 msg.dest == self.reddit.user.name and
-                msg.author.name in self.approved)
+                msg.author.name in self.users)
 
     # command message parsing variables
     PARSE_FIELD = 0
         No validation of the data is performed.
 
         """
-        self.log.debug('%s: Parsing message %d from %s.',
+        self.log.debug('%s: Parsing message %s from %s.',
             classname(self), msg.id, msg.author.name)
         msg_data = {}
         text_data = []
         # set up parsing line-by-line
         lineno = 0
         lines = msg.body.splitlines()
-        state = PARSE_FIELD
+        state = self.PARSE_FIELD
 
         for line in lines:
             if state == self.PARSE_ERROR:
         eq_pos  = line.find('=')
         col_pos = line.find(':')
 
-        if eq_pos < 1:
-            sep_pos = col_pos
-        elif col_pos < 1:
-            sep_pos = eq_pos
-        else:
+        if eq_pos >= 0 and col_pos >= 0: # both are present - take first occurr.
             sep_pos = min(eq_pos, col_pos)
+        else: # one isn't present - take the one that is present
+            sep_pos = max(eq_pos, col_pos)
 
-        field_data = (line[0:sep_pos].strip(), line[sep_pos:].strip())
+        field_data = (line[0:sep_pos].strip(), line[sep_pos+1:].strip())
 
         # check for valid data extracted
         if not field_data[0]:
                     ''.join(["Unknown command '", data['action'], "' in ",
                              self._exc_msg_data(msg)]))
 
-
     def _make_command(self, msg, data):
         """ Build a bot command object from ``_parse_message()``'s message
         data. If the command name is invalid, raises a CommandNameError. If the
         command parameters are invalid or incomplete, raises a
         CommandParametersError (from the command constructor). """
-        self.log.info('%s: message %d: building command: %s',
-            classname(self), msg.id, '; '.join(data))
-        if data['action'] in self.cmd_actions.keys():
+        self.log.info('%s: message %s: building command: %s',
+            classname(self), msg.id,
+            '; '.join(['='.join(x, y) for x, y in data.iteritems()]))
+        if data.has_key('action') and data['action'] in self.cmd_actions.keys():
             CommandClass = self.cmd_actions[data.pop('action')]
             cmd_obj = CommandClass(msg, **data)
             cmd_obj.start_time = 0
     def _exc_msg_data(self, msg):
         """ Return info string on a message for use in exceptions. """
         return 'message "{subject}" from {author} at {time}'.format(
-            txt=msg.subject, author=msg.author.name,
+            subject=msg.subject, author=msg.author.name,
             time=strftime('%Y-%m-%d %H:%M:%S',
                 localtime(msg.created_utc)))
 
     Defaults:
         * ``start_time`` = 0
         * ``duration`` = -1
-        * ``interval`` = 5
+        * ``interval`` = config.minibot.queue_rate (unless set before start())
         * ``priority`` = 80
 
     """
     required_res = ['dbsession', 'config.minibot', 'logger']
     start_time = 0
-    interval = 60
+    interval = None
     duration = -1
     priority = 80
 
 
     def start(self):
         self.log = self.res['logger']
+
+        if self.interval is None:
+            self.interval = self.res['config.minibot'].queue_rate
+
         self.run()
         return
 
     Defaults:
         * ``start_time`` = 0
         * ``duration`` = -1
-        * ``interval`` = 5
+        * ``interval`` = config.minibot.queue_rate (unless set before start())
         * ``priority`` = 75
 
     """
     required_res = ['dbsession', 'config.minibot', 'logger']
     start_time = 0
-    interval = 60
+    interval = None
     duration = -1
     priority = 75
 
 
     def start(self):
         self.log = self.res['logger']
+
+        if self.interval is None:
+            self.interval = self.res['config.minibot'].queue_rate
+
         self.run()
         return
 
             cls=classname(self), to=self.user, title=self.title, msg=excerpt)
 
 
-
 class SendReplyCommand(CommandBase):
     """ Command to send a private message reply to a user and then mark the
     original message read.
         else:
             excerpt = self.text
         return "<{cls}: msgid={id_}, to={to}, title={title}, message={msg}>".\
-            format(cls=classname(self), msgid=self.msg.id,
+            format(cls=classname(self), id_=self.msg.id,
             to=self.msg.author.name, msg=excerpt)