Commits

Bruno Bord  committed d0b2a4b Merge

merged oauth branch, now OAuth-ready

  • Participants
  • Parent commits 5e64633, 1200ea0

Comments (0)

Files changed (4)

File src/home_at_home/config.py

 MONGO_HOST = 'localhost'
 MONGO_DB = 'twitter'
 MONGO_COLLECTION = 'tweets'
+### DO NOT EDIT THESE
+TWITTER_CONSUMER_KEY = 'cHgvJTj3wZcmRS2fHGMLHA'
+TWITTER_CONSUMER_SECRET = 'RcGdM8c3lZBYYoysvbuqmTLtxxtrLz7EVyveksoKxE'
 
-TWITTER_USERNAME = '<username>'
+TWITTER_EMAIL = 'email@example.com'
+TWITTER_USERNAME = 'my_twitter_username'
 TWITTER_PASSWORD = "If this is your password, it's not my fault"
 
 try:

File src/home_at_home/hath.py

 from cmd import Cmd
 import argparse
 from config import MONGO_DB, MONGO_HOST, MONGO_COLLECTION
-from config import TWITTER_USERNAME, TWITTER_PASSWORD
 from storage import Storage
 from query import parse_queryargs
+from config import TWITTER_USERNAME
+from config import TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET
+
+try:
+    from config import TWITTER_TOKEN, TWITTER_TOKEN_SECRET
+except ImportError:
+    print "You seem not to have configured Twitter Oauth elements."
+    
+    answer = raw_input('Do you wish to do the Oauth Dance (y/n)? ')
+    if answer.lower() == 'y':
+        from twitter.oauth_dance import oauth_dance
+        oauth_token, oauth_token_secret = oauth_dance('Home Timeline At Home',
+            TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET)
+        print "Now that you've registered, you must add these lines to your local_config.py, and restart the program"
+        print "TWITTER_TOKEN = '%s'" % oauth_token 
+        print "TWITTER_TOKEN_SECRET = '%s'" % oauth_token_secret
+        
+        sys.exit() 
 
 
 class HomeAtHome(Cmd, object):
             dbname=arguments.db,
             collection=arguments.collection,
             twitter_username=arguments.twitter_username,
-            twitter_password=arguments.twitter_password
+            twitter_config=(
+                TWITTER_TOKEN, TWITTER_TOKEN_SECRET,
+                TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET
+            )
         )
 
     def do_quit(self, args):
         if not args:
             print "Wrong usage: you must type a text for you tweet"
             return
-        self.store.connection.PostUpdate(args.decode('utf'))
+        self.store.connection.statuses.update(status=args.decode('utf'))
         print "Posted"
 
 
         help='the MongoDb database name', default=MONGO_DB)
     parser.add_argument('--collection', metavar=str,
         help='the MongoDb collection name', default=MONGO_COLLECTION)
+#    parser.add_argument('--twitter-email',
+#        help='your twitter email', default=TWITTER_EMAIL)
     parser.add_argument('--twitter-username',
         help='your twitter username', default=TWITTER_USERNAME)
-    parser.add_argument('--twitter-password',
-        help='your twitter password', default=TWITTER_PASSWORD)
+#    parser.add_argument('--twitter-password',
+#        help='your twitter password', default=TWITTER_PASSWORD)
 
     arguments = parser.parse_args()
 

File src/home_at_home/storage.py

 from pymongo import Connection
 from pymongo import ASCENDING, DESCENDING
 
-from twitter_plus import ExtendedApi as Api
+from twitter import Twitter as Api
+from twitter import OAuth
 from utils import twitter_time_to_dict
 from query import parse_queryargs
 from termcolor import colored
     MongoDb database."""
     
     def __init__(self, host='localhost', dbname='twitter', collection='tweets',
-        twitter_username='', twitter_password=''):
+        twitter_username='', twitter_config=()):
         try:
             connection = Connection(host)
         except:
-            logging.error('Issues with the database connection. Please check')
+            print "Issues with the database connection. Please check"
             sys.exit()
         self.store = connection[dbname][collection]
         self.twitter_username = twitter_username
-        self.twitter_password = twitter_password
+        self.token, self.token_key, self.con_secret, self.con_secret_key = twitter_config
 
     @property
     def connection(self):
         "Return Twitter API connection."
         if not hasattr(self, "__connection"):
-            self.__connection = Api(
-                username=self.twitter_username,
-                password=self.twitter_password
-            )
+            self.__connection = Api(auth=OAuth(
+                self.token,
+                self.token_key,
+                self.con_secret,
+                self.con_secret_key))
         return self.__connection
 
     def count(self):
         page = 1
         while True:
             try:
-                timeline = self.connection.GetHomeTimeline(page=page, count=200, since_id=since_id)
-            except:
+                timeline = self.connection.statuses.home_timeline(page=page, count=200, since_id=since_id)
+            except Exception, e:
                 print "Problems with Twitter API. Try again later"
+                logging.debug('Exception: %s' % e)
                 break
             if timeline:
                 for tweet in timeline:
                     self.store.insert({
-                        'from': tweet.user.screen_name,
-                        'text': tweet.GetText(),
-                        '_id': long(tweet.id),
-                        "in_reply_to_screen_name": tweet.in_reply_to_screen_name,
-                        "in_reply_to_status_id": tweet.in_reply_to_status_id,
-                        'created_at': twitter_time_to_dict(tweet.created_at),
+                        'from': tweet["user"]["screen_name"],
+                        'text': tweet['text'],
+                        '_id': long(tweet['id']),
+                        "in_reply_to_screen_name": tweet["in_reply_to_screen_name"],
+                        "in_reply_to_status_id": tweet["in_reply_to_status_id"],
+                        'created_at': twitter_time_to_dict(tweet["created_at"]),
                     })
                 page += 1
             else:

File src/home_at_home/twitter_plus.py

-#-*- coding: utf-8 -*-
-"An Extended Twitter API"
-import simplejson
-from twitter import *
-
-
-class ExtendedApi(Api):
-    
-    def GetHomeTimeline(self, user=None, count=None, since=None, since_id=None,
-        page=None, max_id=None):
-        '''Home timeline, based on Friends Timeline'''
-        if not user and not self._username:
-            raise TwitterError("User must be specified if API is not authenticated.")
-        if user:
-            url = 'http://twitter.com/statuses/home_timeline/%s.json' % user
-        else:
-            url = 'http://twitter.com/statuses/home_timeline.json'
-        parameters = {}
-        if count is not None:
-            try:
-                if int(count) > 200:
-                    raise TwitterError("'count' may not be greater than 200")
-            except ValueError:
-                raise TwitterError("'count' must be an integer")
-            parameters['count'] = count
-        if since:
-            parameters['since'] = since
-        if since_id:
-            parameters['since_id'] = since_id
-        if max_id:
-            parameters['max_id'] = max_id
-        if page:
-            parameters['page'] = page
-            
-        json = self._FetchUrl(url, parameters=parameters)
-        data = simplejson.loads(json)
-        self._CheckForTwitterError(data)
-        
-        return [Status.NewFromJsonDict(x) for x in data]