如何通过已知的访问令牌从twitter打印推文?

时间:2013-07-15 03:15:30

标签: python twitter

from rauth.service import OAuth1Service

class TwitterClient:

    KNOWN_USERS = ['177512438-pJTdMgOPLJ8hCQFfDbPmkU3LRcCSHZd5VqoM3WaY', '7Z50XjV1CqDF1753Rzd4MkzSYN1oCY2FaaFtAZU']

    def __init__(self):
        # Get a real consumer key & secret from https://dev.twitter.com/apps/new
        self.twitter = OAuth1Service(
            name='twitter',
            consumer_key='ZjXNoqpLfhQvYBgkjrrvxQ',
            consumer_secret='8O4NjcsNed8uGICjDLNTjPiNwqjPezovWZIVru1c',
            request_token_url='https://api.twitter.com/oauth/request_token',
            access_token_url='https://api.twitter.com/oauth/access_token',
            authorize_url='https://api.twitter.com/oauth/authorize',
            base_url='https://api.twitter.com/1/')
        #self.KNOWN_USERS = ['177512438-pJTdMgOPLJ8hCQFfDbPmkU3LRcCSHZd5VqoM3WaY', '7Z50XjV1CqDF1753Rzd4MkzSYN1oCY2FaaFtAZU']

    def new_session(self):
        request_token, request_token_secret = self.twitter.get_request_token()
        authorize_url = self.twitter.get_authorize_url(request_token)
        print 'Visit this URL in your browser: ' + authorize_url
        pin = raw_input('Enter PIN from browser: ')
        session = self.twitter.get_auth_session(request_token,
                                                request_token_secret,
                                                method='POST',
                                                data={'oauth_verifier': pin})
        print session.access_token, session.access_token_secret # Save this to database
        return session

    def reuse_session(self, user2):
        access_token = user2[0]
    access_token_secret = user2[1]
        session = self.twitter.get_session((access_token, access_token_secret))
        return session

    def init_session(self, user2):
        if user2[0] == self.KNOWN_USERS[0] and user2[1] == self.KNOWN_USERS[1] : session = self.reuse_session(user2)
        else                        : session = self.new_session()
        return session

    def list_tweets(self, user2):
        session = self.init_session(user2)
        params = {'include_rts': 1,  # Include retweets
                  'count': 10}       # 10 tweets

        r = session.get('statuses/home_timeline.json', params=params)

        for i, tweet in enumerate(r.json(), 1):
            handle = tweet['user']['screen_name'].encode('utf-8')
            text = tweet['text'].encode('utf-8')
            print '{0}. @{1} - {2}'.format(i, handle, text)

    tc = TwitterClient()

    user1 = ['177512438-pJTdMgOPLJ8hCQFfDbPmkU3LRcCSHZd5VqoM3WaY', '7Z50XjV1CqDF1753Rzd4MkzSYN1oCY2FaaFtAZU']
    tc.list_tweets( user1 )

但这会在第50行中出现以下错误:

string indices must be integer

所以我写这个:

from rauth.service import OAuth1Service

class TwitterClient:

    KNOWN_USERS = { # (access_token, access_token_secret)
        'user1' : ('177512438-pJTdMgOPLJ8hCQFfDbPmkU3LRcCSHZd5VqoM3WaY', '7Z50XjV1CqDF1753Rzd4MkzSYN1oCY2FaaFtAZU')
    }

    def __init__(self):
        # Get a real consumer key & secret from https://dev.twitter.com/apps/new
        self.twitter = OAuth1Service(
            name='twitter',
            consumer_key='ZjXNoqpLfhQvYBgkjrrvxQ',
            consumer_secret='8O4NjcsNed8uGICjDLNTjPiNwqjPezovWZIVru1c',
            request_token_url='https://api.twitter.com/oauth/request_token',
            access_token_url='https://api.twitter.com/oauth/access_token',
            authorize_url='https://api.twitter.com/oauth/authorize',
            base_url='https://api.twitter.com/1.1/')

    def new_session(self):
        request_token, request_token_secret = self.twitter.get_request_token()
        authorize_url = self.twitter.get_authorize_url(request_token)
        print 'Visit this URL in your browser: ' + authorize_url
        pin = raw_input('Enter PIN from browser: ')
        session = self.twitter.get_auth_session(request_token,
                                                request_token_secret,
                                                method='POST',
                                                data={'oauth_verifier': pin})
        print session.access_token, session.access_token_secret # Save this to database
        return session

    def reuse_session(self, user1):
        access_token, access_token_secret = self.KNOWN_USERS[user1]
        session = self.twitter.get_session((access_token, access_token_secret))
        return session

    def init_session(self, user1):
        if user1 in self.KNOWN_USERS : session = self.reuse_session(user1)
        else                        : session = self.new_session()
        return session

    def list_tweets(self, user1):
        session = self.reuse_session(user1)
        params = {'include_rts': 1,  # Include retweets
                  'count': 10}       # 10 tweets

        r = session.get('statuses/home_timeline.json', params=params)
    print r.json
        #for i, tweet in enumerate(r.json(), 1):
            #handle = tweet['user']['screen_name'].encode('utf-8')
            #text = tweet['text'].encode('utf-8')
            #print '{0}.  - {2}'.format(i, text)

tc = TwitterClient()

tc.list_tweets('user1')

但是我收到以下错误:

<bound method Response.json of <Response [401]>>

1 个答案:

答案 0 :(得分:0)

使用您提供给我们的最少信息,我猜测您的GET请求失败,导致您收到如下所示的JSON对象:

{"errors":[{"message":"Bad Authentication data","code":215}]}

这将解码为字典,当你迭代它时,你将得到字典中的键,这是字符串。当您尝试使用字典键索引这些字符串时,您将获得只能使用整数索引到字符串(或任何序列)的错误。

通过在迭代之前打印r.json()来验证这一点。通过阅读您收到的错误消息修复它,并解决它向您报告的问题。