【问题标题】:getting latest message of user with tweepy使用 tweepy 获取用户的最新消息
【发布时间】:2021-07-25 01:27:03
【问题描述】:

所以我有这个代码 ->

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)

打印用户最近的帖子。但是,有没有办法 24/7 运行此代码?例如,我希望每当用户发布新内容时再次打印我的代码。

【问题讨论】:

标签: python twitter tweepy


【解决方案1】:

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

你需要获取用户发布的最后一个状态的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

但是如果用户在 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

【讨论】:

  • 这有点奇怪,我一直在尝试使用该代码并收到此错误:SyntaxError:十进制整数文字中的前导零是不允许的;对八进制整数使用 0o 前缀
  • 奇怪的是,我用recent_id = 1388810249122062337 进行了测试,它可以工作
  • 对于第一个sn-p,它不是recent_post.id 而是recent_post[0].id。我编辑答案
  • 我只有一个问题,如果我执行代码它会给我所有信息,但我只需要'文本'我该怎么做?
  • 在第一个sn-p中, print(recent_post[0].text) 在第二个 print(recent_post.text)
猜你喜欢
  • 1970-01-01
  • 2012-08-08
  • 2013-03-04
  • 1970-01-01
  • 2014-11-04
  • 1970-01-01
  • 1970-01-01
  • 2019-04-13
  • 2016-11-02
相关资源
最近更新 更多