]> jfr.im git - z_archive/twitter.git/blobdiff - twitter/ircbot.py
Merge branch 'master' into py3-2
[z_archive/twitter.git] / twitter / ircbot.py
index 1c2a6490a56c82284af336fc94653a05888aec78..ee6adee58cedb33ea97a2417811587cb9ac74d0c 100644 (file)
@@ -46,27 +46,28 @@ IRC_REGULAR = chr(0x0f)
 
 import sys
 import time
-from dateutil.parser import parse
+from datetime import datetime, timedelta
+from email.utils import parsedate
 from ConfigParser import SafeConfigParser
 from heapq import heappop, heappush
 import traceback
 import os
 import os.path
 
-from api import Twitter, TwitterError
-from oauth import OAuth, read_token_file
-from oauth_dance import oauth_dance
-from util import htmlentitydecode
+from .api import Twitter, TwitterError
+from .oauth import OAuth, read_token_file
+from .oauth_dance import oauth_dance
+from .util import htmlentitydecode
 
 PREFIXES = dict(
     cats=dict(
         new_tweet="=^_^= ",
         error="=O_o= ",
         inform="=o_o= "
-        )
+        ),
     none=dict(
         new_tweet=""
-        )
+        ),
     )
 ACTIVE_PREFIXES=dict()
 
@@ -96,10 +97,10 @@ class SchedTask(object):
 
     def __repr__(self):
         return "<SchedTask %s next:%i delta:%i>" %(
-            self.task.__name__, self.next, self.delta)
+            self.task.__name__, self.__next__, self.delta)
 
     def __cmp__(self, other):
-        return cmp(self.next, other.next)
+        return cmp(self.__next__, other.__next__)
 
     def __call__(self):
         return self.task()
@@ -113,13 +114,13 @@ class Scheduler(object):
     def next_task(self):
         now = time.time()
         task = heappop(self.task_heap)
-        wait = task.next - now
+        wait = task.__next__ - now
         task.next = now + task.delta
         heappush(self.task_heap, task)
         if (wait > 0):
             time.sleep(wait)
         task()
-        debug("tasks: " + str(self.task_heap))
+        #debug("tasks: " + str(self.task_heap))
 
     def run_forever(self):
         while True:
@@ -131,6 +132,9 @@ class TwitterBot(object):
         self.configFilename = configFilename
         self.config = load_config(self.configFilename)
 
+        global ACTIVE_PREFIXES
+        ACTIVE_PREFIXES = PREFIXES[self.config.get('irc', 'prefixes')]
+
         oauth_file = self.config.get('twitter', 'oauth_token_file')
         if not os.path.exists(oauth_file):
             oauth_dance("IRC Bot", CONSUMER_KEY, CONSUMER_SECRET, oauth_file)
@@ -150,21 +154,22 @@ class TwitterBot(object):
         self.sched = Scheduler(
             (SchedTask(self.process_events, 1),
              SchedTask(self.check_statuses, 120)))
-        self.lastUpdate = time.gmtime()
+        self.lastUpdate = (datetime.now() - timedelta(minutes=10)).utctimetuple()
 
     def check_statuses(self):
         debug("In check_statuses")
         try:
-            updates = self.twitter.statuses.friends_timeline()
-        except Exception, e:
-            print >> sys.stderr, "Exception while querying twitter:"
+            updates = reversed(self.twitter.statuses.friends_timeline())
+        except Exception as e:
+            print("Exception while querying twitter:", file=sys.stderr)
             traceback.print_exc(file=sys.stderr)
             return
 
         nextLastUpdate = self.lastUpdate
+        debug("self.lastUpdate is %s" % self.lastUpdate)
         for update in updates:
-            crt = parse(update['created_at']).utctimetuple()
-            if (crt > self.lastUpdate):
+            crt = parsedate(update['created_at'])
+            if (crt > nextLastUpdate):
                 text = (htmlentitydecode(
                     update['text'].replace('\n', ' '))
                     .encode('utf-8', 'replace'))
@@ -174,18 +179,20 @@ class TwitterBot(object):
                 #   to people who are not on our following list.
                 if not text.startswith("@"):
                     self.privmsg_channels(
-                        u"%s  %s%s%s %s" %(
+                        "%s %s%s%s %s" %(
                             get_prefix(),
                             IRC_BOLD, update['user']['screen_name'],
                             IRC_BOLD, text.decode('utf-8')))
 
+                debug("tweet has crt %s, updating nextLastUpdate (was %s)" %(
+                        crt, nextLastUpdate,
+                        ))
                 nextLastUpdate = crt
-            else:
-                break
+
+        debug("setting self.lastUpdate to %s" % nextLastUpdate)
         self.lastUpdate = nextLastUpdate
 
     def process_events(self):
-        debug("In process_events")
         self.irc.process_once()
 
     def handle_privmsg(self, conn, evt):
@@ -331,14 +338,12 @@ def main():
         if not os.path.exists(configFilename):
             raise Exception()
         load_config(configFilename)
-    except Exception, e:
-        print >> sys.stderr, "Error while loading ini file %s" %(
-            configFilename)
-        print >> sys.stderr, e
-        print >> sys.stderr, __doc__
+    except Exception as e:
+        print("Error while loading ini file %s" %(
+            configFilename), file=sys.stderr)
+        print(e, file=sys.stderr)
+        print(__doc__, file=sys.stderr)
         sys.exit(1)
 
-    global ACTIVE_PREFIXES
-    ACTIVE_PREFIXES = PREFIXES[cp.get('irc', 'prefixes')]
     bot = TwitterBot(configFilename)
     return bot.run()