Commits

Josh VanderLinden committed c1ac750

Fixed a problem that made it impossible to post from your IM program. Added the trends command. Fixed some other problems relating to the creation of the User class

Comments (0)

Files changed (1)

 from wx import wizard
 from wx.lib.agw.hyperlink import HyperLinkCtrl
 from wx.lib.embeddedimage import PyEmbeddedImage
+import base64
 import cgi
 import ConfigParser
 import logging
 
         # update any previously existing users
         for user in self._users.values():
-            if not user.id:
+            if user.id == None:
                 log.info('%s has not been saved yet...' % user.username)
                 unsorted.append(user)
             else:
         Retrieves any scheduled tweets that we have
         """
         try:
-            schedule = pickle.loads(self.scheduled_tweets)
+            schedule = pickle.loads(base64.b64decode(self.scheduled_tweets))
         except:
             schedule = []
         self._scheduled_tweets = schedule
         """
         Pickles the scheduled tweets
         """
-        self.scheduled_tweets = pickle.dumps(self._scheduled_tweets)
+        dump = pickle.dumps(self._scheduled_tweets)
+        self.scheduled_tweets = base64.b64encode(dump)
 
     def Persist(self):
         """
             'search': self.OnSearchCommand,
             'favorite': None,
             'unfavorite': None,
-            'schedule': self.OnScheduleCommand
+            'schedule': self.OnScheduleCommand,
+            'trends': self.OnTrendsCommand,
         }
         if len(self.users) > 1:
             self._commands['as'] = self.OnAsCommand
         args = re.search('^([^ $]+)', remaining)
         if args:
             username = args.group(1)
-            api = user.get('api', None)
-            if api:
-                try:
-                    api.CreateFriendship(username)
-                    self.TellUser('You are now following %s' % username)
-                except urllib2.HTTPError:
-                    self.TellUser('You are already following %s!' % username)
+            try:
+                user.api.CreateFriendship(username)
+                self.TellUser('You are now following %s' % username)
+            except urllib2.HTTPError:
+                self.TellUser('You are already following %s!' % username)
         else:
             self.TellUser('Incomplete command!')
 
         args = re.search('^([^ $]+)', remaining)
         if args:
             username = args.group(1)
-            api = user.get('api', None)
-            if api:
-                try:
-                    api.DestroyFriendship(username)
-                    self.TellUser('You are no longer following %s' % username)
-                except urllib2.HTTPError:
-                    self.TellUser('You are not following %s!' % username)
+            try:
+                user.api.DestroyFriendship(username)
+                self.TellUser('You are no longer following %s' % username)
+            except urllib2.HTTPError:
+                self.TellUser('You are not following %s!' % username)
         else:
             self.TellUser('Incomplete command!')
             
         args = re.search('^([^ $]+)', remaining)
         if args:
             username = args.group(1)
-            api = user.get('api', None)
-            if api:
-                try:
-                    info = api.GetUser(username)
-                    
-                    init = ('location', 'description', 'url', 'utc_offset', 
-                            'time_zone', 'name')
-                    info_dict = dict((k, 'not specified') for k in init)
-                    info_dict['profile'] = 'http://twitter.com/%s' % username
-                    info_dict['status_text'] = info.status.text
+            try:
+                info = user.api.GetUser(username)
+                
+                init = ('location', 'description', 'url', 'utc_offset', 
+                        'time_zone', 'name')
+                info_dict = dict((k, 'not specified') for k in init)
+                info_dict['profile'] = 'http://twitter.com/%s' % username
+                info_dict['status_text'] = info.status.text
 
-                    info_dict.update(info.AsDict())
-                    
-                    # clean up any unicode
-                    for key, val in info_dict.items():
-                        info_dict[key] = cgi.escape(clean(val))
+                info_dict.update(info.AsDict())
+                
+                # clean up any unicode
+                for key, val in info_dict.items():
+                    info_dict[key] = cgi.escape(clean(val))
 
-                    log.debug(info_dict)
-                    self.TellUser('WhoIs: %(screen_name)s\n'
-                        'Name: %(name)s\n'
-                        'Profile: %(profile)s\n'
-                        'Location: %(location)s\n'
-                        'Description: %(description)s\n'
-                        'Homepage: %(url)s\n'
-                        'Status Updates: %(statuses_count)s\n'
-                        'Followers: %(followers_count)s\n'
-                        'Friends: %(friends_count)s\n'
-                        'Protected: %(protected)s\n'
-                        'UTC Offset: %(utc_offset)s\n'
-                        'Timezone: %(time_zone)s\n'
-                        'Status: %(status_text)s\n' % info_dict)
-                except urllib2.HTTPError:
-                    self.TellUser('Invalid Twitter user: %s!' % username)
+                log.debug(info_dict)
+                self.TellUser('WhoIs: %(screen_name)s\n'
+                    'Name: %(name)s\n'
+                    'Profile: %(profile)s\n'
+                    'Location: %(location)s\n'
+                    'Description: %(description)s\n'
+                    'Homepage: %(url)s\n'
+                    'Status Updates: %(statuses_count)s\n'
+                    'Followers: %(followers_count)s\n'
+                    'Friends: %(friends_count)s\n'
+                    'Protected: %(protected)s\n'
+                    'UTC Offset: %(utc_offset)s\n'
+                    'Timezone: %(time_zone)s\n'
+                    'Status: %(status_text)s\n' % info_dict)
+            except urllib2.HTTPError:
+                self.TellUser('Invalid Twitter user: %s!' % username)
         else:
             self.TellUser('Incomplete command!')
     
         """
         if len(self._history):
             last_tweet = self._history.pop()
-            api = user.get('api', None)
-            if api:
-                try:
-                    self.TellUser('Attempting to remove: %s' % last_tweet.text)
-                    api.DestroyStatus(last_tweet.id)
-                    self.TellUser('The tweet has been removed.')
-                except:
-                    self.TellUser('Something went wrong when I tried to remove'
-                        ' the tweet.  Please try again.')
-                    
-                    # add the tweet back to the stack
-                    self._history.append(last_tweet)
+            try:
+                self.TellUser('Attempting to remove: %s' % last_tweet.text)
+                user.api.DestroyStatus(last_tweet.id)
+                self.TellUser('The tweet has been removed.')
+            except:
+                self.TellUser('Something went wrong when I tried to remove'
+                    ' the tweet.  Please try again.')
+                
+                # add the tweet back to the stack
+                self._history.append(last_tweet)
         else:
             self.TellUser('There is nothing left for you to undo right now.')
     
     
     def OnScheduleCommand(self, user, body, remaining):
         """
-        Allows you to schedule a tweet for posting at a later time.
+        Allows you to schedule a tweet for posting at a later time.  You can 
+        use several patterns to specify when a tweet should appear.  These 
+        patterns are as follows:
+        
+        YYYY-MM-DD HH:MM
+        MM/DD HH:MM
+        HH:MM
+        
+        You also have the option of specifing a certain amount of time from 
+        the time you schedule a tweet.  For example, you could schedule a 
+        tweet to be posted in 5 seconds, or 2 minutes, or 1 hour, or 6 days.
+        These options cannot yet be combined into something like "5 minutes 
+        and 15 seconds."
+        
+        Examples:
+        
+        ./schedule 2009-6-1 5:13 This should be posted at 5:13 AM on June 1st 2009
+        ./schedule 6/1 14:23 This should be posted at 2:23 PM on June 1st (cur year)
+        ./schedule 18:30 This should be posted at 6:30 PM
+        ./schedule 15minutes This should be posted 15 minutes from now
         """
         params = (
             ('year', 'month', 'day', 'hour', 'minute', 'tweet'),
             # 18:30 This should be posted at 6:30 PM
             '^(\d{1,2}):(\d{2}) (.*)$',
             # 15minutes This should be posted 15 minutes from now
-            '^(\d+)(seconds|minutes|hours|days) (.*)$',
+            '^(\d+)(seconds?|minutes?|hours?|days?) (.*)$',
         )
 
         matched = False
             else:
                 schedule = [at.strftime('On %Y-%m-%d (%H:%M): ') + t for at,u,t in config._scheduled_tweets]
                 self.TellUser('Scheduled Tweets:\n' + '\n'.join(schedule))
+    
+    def OnTrendsCommand(self, user, body, remaining):
+        """
+        Retrieves the trends that are currently most popular on Twitter
+        """
+        
+        try:
+            url = 'http://search.twitter.com/trends/current.json'
+        
+            api = twitter.Api()
+            json = api._FetchUrl(url)
+            data = simplejson.loads(json)
+            log.debug(data)
+            results = data.get('trends', {' ': []})
+            info = results.popitem()[1]
+            
+            trends = []
+            for trend in info:
+                log.debug(trend)
+                query, name = trend.values()
+                if query == name:
+                    trends.append(query)
+                else:
+                    trends.append('%s (search for %s)' % (name, query))
+            
+            if len(trends):
+                self.TellUser('Current Trends:\n%s' % '\n'.join(trends))
+            else:
+                self.TellUser('No trends were retrieved.')
+        except Exception, ex:
+            log.error(ex)
+            self.TellUser(
+                'Something went wrong when I tried to get the current trends.')
 
     def OnMessage(self, con, evt):
         """
         while not event.isSet():
             try:
                 event.wait(interval)
+                
+                now = datetime.now()
+        
+                # run through any scheduled tweets to see if it's time to post
+                to_remove = []
+                for info in config._scheduled_tweets:
+                    at, un, tx = info
+                    if at <= now:
+                        log.info('Time to tweet "%s"' % tx)
+                        self.PostUpdate(self.users[un], tx)
+                        to_remove.append(info)
+                
+                # remove any tweets that have been posted
+                for info in to_remove:
+                    try:
+                        config._scheduled_tweets.remove(info)
+                    except ValueError:
+                        continue
+
+                if len(to_remove):
+                    config.SetScheduledTweets()
+            
                 action()
             except Exception, ex:
                 log.error(ex)
         """
         try:
             now = datetime.now()
-    
-            # run through any scheduled tweets to see if it's time to post
-            to_remove = []
-            for info in config._scheduled_tweets:
-                at, un, tx = info
-                if at <= now:
-                    log.info('Time to tweet "%s"' % tx)
-                    self.PostUpdate(self.users[un], tx)
-                    to_remove.append(info)
-            
-            # remove any tweets that have been posted
-            for info in to_remove:
-                config._scheduled_tweets.remove(info)
-            if len(to_remove):
-                config.SetScheduledTweets()
-        
             for user in self.users.values():
                 last_update = user.last_update or now - self.interval
                 next_run = last_update + self.interval
         """
         Sends a message back to the user
         """
-        msg = xmpp.Message(to=config.send_to_user, body=message)
+        msg = xmpp.Message(to=config.send_to_user, 
+                           body='===> ' + message)
         self.client.send(msg)
 
 if __name__ == '__main__':