Commits

Anonymous committed 832cabe

Added the concept of jobs and a simple job to dm new followers

  • Participants
  • Parent commits b3f2c38

Comments (0)

Files changed (4)

 from paver.easy import *
 from paver.setuputils import setup
 
+from twitterbot.config import load
+from twitterbot.bot import TwitterBot
+
+
 setup(
     name='TwitterBot',
     version='0.1',
     author_email='eric@ionrock.org',
     packages=['twitterbot'],
 )
+
+
+@task
+def run():
+    conf = load('basic.conf')
+    bot = TwitterBot(conf['username'], conf['password'], conf)
+    bot.listen()

File twitterbot/bot.py

 
     def handle_tweet(self, tweet):
         if tweet.user.screen_name in self.conf['users']:
-            for handler, conf in self.conf['handlers']:
+            for handler, conf in self.conf.get('handlers'):
                 try:
                     handler(tweet, self.api, conf)
                 except Exception, e:
+                    print 'exception in: ', handler
                     print e
                     pass
         self.seen.add(tweet.id)
                 for r in replies:
                     if r.id not in self.seen:
                         self.handle_tweet(r)
-                time.sleep(3)
+
+                for job, conf in self.conf.get('jobs'):
+                    job(self.api, conf)
+
+                time.sleep(self.conf.get('interval', 10))
         except KeyboardInterrupt, e:
             pass
 
 
-if __name__ == '__main__':
-    u, p = 'twtrview', 'f00bar'
-    from delicious import delicious
-    conf = {
-        'users' : ['twtrview',],
-        'handlers' : [
-            (delicious, { 'delicious.username': 'twtrview',
-                          'delicious.password': 'f00bar', })
-        ]
-    }
-    bot = TwitterBot(u, p, conf)
-    bot.listen()
-
-        

File twitterbot/config.py

         'password': config['password'],
         'users': config['users'],
         'handlers': [],
+        'jobs': [],
     }    
+
     for handler in config['handlers']:
         mod = __import__(handler['module'], fromlist=['handler'])
         del handler['module']
         conf['handlers'].append(
             (getattr(mod, 'handler'), handler)
         )
+
+    for job in config['jobs']:
+        mod = __import__(job['module'], fromlist=['job'])
+        del job['module']
+        conf['jobs'].append(
+            (getattr(mod, 'job'), job)
+        )
+        
     return conf
     
 

File twitterbot/heyfollower.py

+from __future__ import with_statement
+
+import simplejson
+import sqlite3
+
+class Transaction(object):
+    def __init__(self, db):
+        self.db = db
+
+    def __enter__(self):
+        self.cursor = self.db.cursor()
+        return self.cursor
+
+    def __exit__(self, type, value, traceback):
+        self.db.commit()
+        self.cursor.close()
+
+
+class Followers(object):
+    def __init__(self, fname):
+        self.db = sqlite3.connect(fname)
+        with Transaction(self.db) as c:
+            try:
+                c.execute('select * from followers')
+            except sqlite3.OperationalError, e:
+                c.execute('create table followers(name varchar(255), extra text)')
+
+    def save(self, name, extra):
+        with Transaction(self.db) as c:
+            c.execute('insert into followers VALUES (?, ?)',
+                      name, simplejson.dumps(extra))
+
+    __set__ = save
+
+    def __contains__(self, name):
+        with Transaction(self.db) as c:
+            rows = c.execute('select * from followers WHERE name=?', (name,))
+            return rows.rowcount
+
+    def __get__(self, name):
+        with Transaction(self.db) as c:
+            rows = c.execute('select * from followers where name=?', (name,))
+            row = rows.fetchone()
+            if row:
+                name, extra = row
+                return simplejson.loads(extra)
+        raise IndexError()
+        
+
+class HeyFollower(object):
+    def __init__(self):
+        self.followers = None
+        self.api = None
+        self.conf = None
+    
+    def __call__(self, api, conf):
+        self.api = api
+        self.conf = conf
+        self.followers = Followers(self.conf['follower_db'])
+        new = self.update_followers()
+        for u in new:
+            if not conf['debug']:
+                self.api.CreateFriendship(u)
+                self.api.PostDirectMessage(u, 'Thanks for following!')
+            else:
+                print 'created a friends and dmsgd ', u.screen_name
+
+    def update_followers(self):
+        followers = self.api.GetFollowers()
+        new = []
+        for follower in followers:
+            if follower.screen_name not in self.followers:
+                new.append(follower)
+        return new
+
+
+job = HeyFollower()