Periodic HTTP 401 errors from Twitter


#1

Doing a post here since this seems more active, but this issue has also been raised with Tweepy

I am receiving HTTP 401 errors while running through a script I created that reads the Twitter stream and retweets things that match the parameters I have set. It occasionally fails during the retweet section with:

tweepy.error.TweepError: Twitter error response: status code = 401

I confirmed that the time is valid on the system and within the ~15 minute wiggle room. The code works the majority of the time, so I am not sure why it would throw the 401 status. Maybe a side question, but is there a more verbose error I can print? I know Twitter will return more information on why it threw 401 (such as unauthorized)

I snipped out some non-interesting parts, but here is the main part of the code:

def doRetweet(id_string):
    # authenticate against the Twitter API
    api = tweepy.API(auth)
    # actually do the retweet
    api.retweet(id_string)
    print('I did the retweet')
    print()
    return
class StdOutListener(tweepy.StreamListener):
    def on_data(self, data):
            
        # Twitter returns data in JSON format - we need to decode it first
        decoded = json.loads(data)
        
        # grab some data we use later
        tweet_id = decoded['id_str']

        doRetweet(tweet_id)

        return True

    def on_error(self, status):
        print('The below status code was returned from Twitter')
        print(status)
        if status_code == 420:
            #returning False in on_data disconnects the stream
            return False
            
    def on_exception(self, exception):
        raise exception
        return False
	    
try:
    if __name__ == '__main__':
        l = StdOutListener()
        auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
        auth.set_access_token(access_token, access_token_secret)

        # Authenticate with the streaming API and filter what we initially receive
        # spaces are AND operators, while a comma indicates OR. More info here: https://dev.twitter.com/streaming/overview/request-parameters
        stream = tweepy.Stream(auth, l)
        stream.filter(track=['#blah'], languages=['en'])
except KeyboardInterrupt:
    sys.exit()