0

So I have this code ->

import tweepy

ckey = ''
csecret = ''
atoken = ''
asecret = ''



auth = tweepy.OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)

api = tweepy.API(auth)

recent_post = api.user_timeline(screen_name = 'DropSentry', count = 1, include_rts = True)

print(recent_post)

which prints the recent post of a user. However is there a way to run this code 24/7? For example I want that my code prints again whenever the user posts something new.

Haider
  • 81
  • 7
  • Does this answer your question? [Using tweepy to stream users' timeline and filtered tweets](https://stackoverflow.com/questions/22675561/using-tweepy-to-stream-users-timeline-and-filtered-tweets) – Prayson W. Daniel May 02 '21 at 13:03

1 Answers1

1

The parameter 'since_id' in the method user_timeline can help you to do this thing.

You need to get the id of the last status the user post and give it in the parameter 'since_id'

recent_id = 1388810249122062337 #hardcode the last recent post id from the user
while True:
  recent_post = api.user_timeline(screen_name = 'DropSentry', count = 1, since_id=recent_id, include_rts = True)
  if recent_post:
    print(recent_post)
    recent_id = recent_post[0].id
  time.sleep(10) # To avoid spamming the API, you can put the number of seconds you want

But this piece of code will lose message if user post multiple messages in the 10 seconds gap. So, you can also get all messages from the user in the meantime and print them all.

recent_id = 1388810249122062337 #hardcode the last recent post id from the user
while True:
  recent_posts = api.user_timeline(screen_name = 'DropSentry', since_id=recent_id, include_rts = True)
  if recent_posts:
    for recent_post in recent_posts:
      print(recent_post)
      recent_id = recent_post.id
  time.sleep(10) # To avoid spamming the API, you can put the number of seconds you want
thomaslecouffe
  • 144
  • 1
  • 6