使用 tweepy 获取用户的最新消息

getting latest message of user with tweepy

所以我有这个代码 ->

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)

打印用户最近的 post。但是有没有办法 运行 这个代码 24/7?例如,我希望我的代码在用户 post 有新东西时再次打印。

方法user_timeline中的参数'since_id'可以帮你做这件事

您需要获取用户post最后状态的id,并在参数'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

但是如果用户 post 在 10 秒的间隔内有多个消息,这段代码将丢失消息。因此,您还可以同时获取用户的所有消息并将其全部打印出来。

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