获取推文回复特定用户的特定推文

Hug*_*uga 9 python twitter tweepy tweets twitter-streaming-api

我正在尝试浏览特定用户的推文并获得该推文的所有回复.我发现twitter的APIv1.1不直接支持它.

获取特定推文的回复是否存在攻击或解决方法?我正在使用python Streaming API.

Jua*_* E. 15

有一种使用REST API的解决方法.

您将需要您要查找回复的原始推文作者的id_str和@username.

您应该将Search API用于作者的"@username".查看结果,查找"in_reply_to_status_id"字段,以与要回复的特定推文的id_str进行比较.

  • 你能写下你编程的方式吗? (4认同)

小智 6

以下是使用tweepy使用其余API获取"username"所做推文的回复的解决方法

1)找到需要获取回复的推文的tweet_id

2)使用api的搜索方法查询以下内容(q ="@ username",since_id = tweet_id)并检索自tweet_id以来的所有推文

3)匹配in_reply_to_status_id到tweet_id的结果是帖子的回复.

  • 您将如何编程? (3认同)

Lav*_*uja 6

我找到了获取原作者推文回复的确切代码。除了获取回复之外,Twitter 用户大多通过回复回复来创建话题(这与获取原作者创建的整个话题不同)。

这是我编写的一个简单的递归,可以解决我的问题。此函数urls使用所有回复的 URL 以及对作者回复的回复更新列表。

def update_urls(tweet, api, urls):
    tweet_id = tweet.id
    user_name = tweet.user.screen_name
    max_id = None
    replies = tweepy.Cursor(api.search, q='to:{}'.format(user_name),
                                since_id=tweet_id, max_id=max_id, tweet_mode='extended').items()
    
    for reply in replies:
        if(reply.in_reply_to_status_id == tweet_id):
            urls.append(get_twitter_url(user_name, reply.id))
            try:
                for reply_to_reply in update_urls(reply, api, urls):
                    pass
            except Exception:
                pass
        max_id = reply.id
    return urls
Run Code Online (Sandbox Code Playgroud)

如果您打算使用该update_urls功能,以下是您可能需要的一些附加功能:

def get_api():
    auth=tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_key, access_secret)
    api = tweepy.API(auth, wait_on_rate_limit=True)
    return api

def get_tweet(url):
    tweet_id = url.split('/')[-1]
    api = get_api()
    tweet = api.get_status(tweet_id)
    return tweet

def get_twitter_url(user_name, status_id):
    return "https://twitter.com/" + str(user_name) + "/status/" + str(status_id)
Run Code Online (Sandbox Code Playgroud)

运行确切的代码:

api = get_api()
tweet = get_tweet(url)
urls = [url]
urls = update_urls(tweet, api, urls)
Run Code Online (Sandbox Code Playgroud)

如果您想获取特定 URL 的内容,只需调用get_tweet(url)并使用 tweet 对象即可获取tweet.texttweet.user等信息。


小智 5

replies=[] 
non_bmp_map = dict.fromkeys(range(0x10000, sys.maxunicode + 1), 0xfffd)  
for full_tweets in tweepy.Cursor(api.user_timeline,screen_name=name,timeout=999999).items(10):
  for tweet in tweepy.Cursor(api.search,q='to:'+name,result_type='recent',timeout=999999).items(1000):
    if hasattr(tweet, 'in_reply_to_status_id_str'):
      if (tweet.in_reply_to_status_id_str==full_tweets.id_str):
        replies.append(tweet.text)
  print("Tweet :",full_tweets.text.translate(non_bmp_map))
  for elements in replies:
       print("Replies :",elements)
  replies.clear()
Run Code Online (Sandbox Code Playgroud)

上面的代码将获取用户(姓名)最近的 10 条推文以及对该特定推文的回复。回复将保存到名为replies的列表中。您可以通过增加项目计数来检索更多推文(例如:items(100))。