Skip to content

Instantly share code, notes, and snippets.

@aniruddha27
Last active July 5, 2021 05:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aniruddha27/9e7c5ae250c6f0239f940b8315b3518c to your computer and use it in GitHub Desktop.
Save aniruddha27/9e7c5ae250c6f0239f940b8315b3518c to your computer and use it in GitHub Desktop.
class MyStreamListener(tweepy.StreamListener):
def __init__(self, time_limit=300):
self.start_time = time.time()
self.limit = time_limit
super(MyStreamListener, self).__init__()
def on_connect(self):
print("Connected to Twitter API.")
def on_status(self, status):
# Tweet ID
tweet_id = status.id
# User ID
user_id = status.user.id
# Username
username = status.user.name
# Tweet
if status.truncated == True:
tweet = status.extended_tweet['full_text']
hashtags = status.extended_tweet['entities']['hashtags']
else:
tweet = status.text
hashtags = status.entities['hashtags']
# Read hastags
hashtags = read_hashtags(hashtags)
# Retweet count
retweet_count = status.retweet_count
# Language
lang = status.lang
# If tweet is not a retweet and tweet is in English
if not hasattr(status, "retweeted_status") and lang=="en":
# Connect to database
dbConnect(user_id, username, tweet_id, tweet, retweet_count, hashtags)
if (time.time() - self.start_time) > self.limit:
print(time.time(), self.start_time, self.limit)
return False
def on_error(self, status_code):
if status_code == 420:
# Returning False in on_data disconnects the stream
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment