0

My application is to retweet a hashtag using Tweepy. Retweeting the hashtag works, I am having trouble getting errors 2 and 3 to work. Errors 1. Your own id (done) 2. If tweet has already been RTd 3. If tweet to RT comes from protected source

Accessing api.retweet(doTweet) within the StdOutListener does not allow it to fall through to on_error(). How else can I do this? I am Python noob.

class StdOutListener(tweepy.StreamListener):
    def on_data(self, data):      
        all_data = json.loads(data)
        username = all_data["user"]["screen_name"]
        doTweet = all_data["id"]
        if username != our_own_id:
            #make sure you haven't already retweeted
            #make sure tweets aren't protected
            print(username) # just so we know it's working
            api.retweet(doTweet)
        return True

    def on_error(self, status_code):
        print('error')
        read_error = json.loads(status_code)
        print('Got an error with status code: ' + str(read_error))          
        return True # To continue listening

    def on_timeout(self):
        print('Timeout...')
        return True # To continue listening

try:
    if __name__ == '__main__':  
      listener = StdOutListener() 
      stream = tweepy.Stream(auth, listener)
      stream.filter(track=['#love'])

except KeyboardInterrupt:
   sys.exit()
5
  • I have tried to put api.retweet() in main without success.
    – Tom
    May 10, 2016 at 19:12
  • I don't understand what the errors are. And please fix your indentation May 10, 2016 at 20:27
  • @ValentinLorentz what should I change in the indentation? this is what I copy-pasted from IDLE.
    – Tom
    May 10, 2016 at 22:18
  • @ValentinLorentz just re-copy-pasted and the try: line is now weirdly formatted. So that's a question: how to format?
    – Tom
    May 10, 2016 at 22:20
  • Errors: added stream.filter(track=['#love']) (#love gets a lot of tweets). I am looking for a way to error check for this error message: tweepy.error.TweepError: [{'message': 'You have already retweeted this tweet.', 'code': 327}]
    – Tom
    May 10, 2016 at 22:21

1 Answer 1

2

You could modify your call to api.retweet in your on_data method as follows:

...
if username != our_own_id:
    print(username) # just so we know it's working
    try:
        api.retweet(doTweet)
    except tweepy.TweepError as e:
        # add here a more complex error handling
        print(e)

Hope it helps.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.