简体   繁体   中英

Python Tweepy for Twitter API returns 'error 401 : Unauthorized'

The below code has worked perfectly for the past 6 months for retrieving Followers of some Twitter Accounts. Suddenly this morning, the code has stopped to work returning 'Error 401 : Unauthorized'.

I checked my App on dev.twitter.com, it is still valid. I updated Tweepy. No idea why this is not working anymore.

Code Fails on 'Cursor.next' line.

import tweepy
import mysql.connector
import time

consumer_key = 'secretkey'
consumer_secret = 'secretsecret'
access_token = 'secrettoken'
access_token_secret = 'secrettokensecret'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)



for twit_name in twit_name_array:
 api = tweepy.API(auth)
 t0= time.clock()

 data = api.rate_limit_status()
 user_followers_remaining = data['resources']['followers']['/followers/ids']['remaining']
 print(user_followers_remaining)
 id_i = twit_name[1]

 countpage = 0
 countx = 0

 def limit_handled(cursor):
    while True:
        data = api.rate_limit_status()
        user_followers_remaining = data['resources']['followers']['/followers/ids']['remaining']

        if user_followers_remaining>0:
            try:
                yield cursor.next()
            except BaseException as e:
                print('failed_on_CURSOR_NEXT', str(e))
                global api
                api = tweepy.API(auth)
                try:
                    yield cursor.next()
                except BaseException as e:
                    print('failed_on_CURSOR_NEXT_2', str(e))
                    break
        else:
            for min_remain in range(-3, 0):
                print('##### TIMEOUT #####  -----  Out of queries, waiting ' + str(min_remain*5) + 'min')
                time.sleep(5*60)

As mentioned by @advance512, I had to login again to solve this issue. The following piece of code did the trick :

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

def limit_handled(cursor):
    while True:
        try:
            yield cursor.next()
        except BaseException as e:
            print('failed_on_CURSOR_NEXT', str(e))
            time.sleep(5)
            global api
            api = tweepy.API(auth)
            yield cursor.next()

for followers in limit_handled(tweepy.Cursor(api.followers_ids, id = id_i).pages()):
    for fll in followers:
        process_follower(fll)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM