saket.v
saket.v

Reputation: 173

Error handling In Tweepy

I am learning python and have started out a few weeks ago. I have tried to write a code to check for tweets with a particular hashtag in the streaming API and then reply to the tweet in case the a tweet has not been posted to the handle previously. While running the code, I have tried to avoid overstepping the rate limitations so as to not get any error. But there is an issue of duplicate status that Twitter raises once in a while. I would like the code to keep running and not stop on encountering an issue. Please help in this. The following is the code:

import tweepy
from tweepy import Stream
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
import json
import time

consumer_key = 
consumer_secret = 
access_token = 
access_secret = 

auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)

def check(status):
    datafile = file('C:\Users\User\Desktop\Growth Handles.txt', 'r')
    found = False
    for line in datafile:
        if status.user.screen_name in line:
            found = True
            break
    return found


class MyListener(StreamListener):


    def on_status(self, status):
        f=status.user.screen_name
        if check(status) :
            pass
        else:
            Append=open('Growth Handles.txt' , 'a' )
            Append.write(f + "\n")
            Append.close()
            Reply='@' + f + ' Check out Tomorrowland 2014 Setlist . http://.... '
            api = tweepy.API(auth)
            api.update_status(status=Reply)
            time.sleep(45)
        return True

    def on_error(self, status):
        print(status)
        return True



twitter_stream = Stream(auth, MyListener())
twitter_stream.filter(track=['#musiclovers'])

Upvotes: 0

Views: 2578

Answers (1)

Ashwani Agarwal
Ashwani Agarwal

Reputation: 1319

In case, update_status method throws an error

try:
    api.update_status(status=Reply)
except:
    pass

In case twitter_stream gets disconnected.

twitter_stream = Stream(auth, MyListener())
while True:
    twitter_stream.filter(track=['#musiclovers'])

Warning - Your app may got banned if it reaches certain limits, or their system caught you spamming. Check Twitter Rules

Upvotes: 1

Related Questions