使用Twitter流API,是否可以仅显示特定用户的推文?

13
我目前正在使用Twitter API检索特定用户发布的推文。为了举例说明,我们将以@justinbieber为例。
当使用https://stream.twitter.com/1.1/statuses/filter.json资源,将关注(follow)设置为所需的用户ID(@justinbieber = 27260086),并让其运行时,尽管我只期望得到@justinbieber的推文,但最终会获取来自他数百万粉丝的对他的推文。显然,这意味着我得到了比我想要的更多的信息,而且据我发现,有时会错过用户自己发布的推文!
我尝试了更改https://dev.twitter.com/docs/streaming-apis/parameters中的每个参数,但都没有成功。
关注(follow)参数说明:
For each user specified, the stream will contain:

   Tweets created by the user.
   Tweets which are retweeted by the user.
   Replies to any Tweet created by the user.
   Retweets of any Tweet created by the user.
   Manual replies, created without pressing a reply button (e.g. “@twitterapi I agree”).

由于文档中没有提供获取特定用户推文的方法,因此我认为除了自己筛选结果之外没有其他方式(这意味着我可能会错过用户自己的推文!),但如果有人知道解决办法,我很想知道。

在有人建议使用statuses/user_timeline之类的东西之前,我知道它能够做到我想要的事情,但它有两个缺点让我选择使用流API:

  • 每个请求都意味着我失去了一个请求,而且由于Twitter有速率限制,所以我想避免这种情况。
  • 每个请求都需要HTTP协议的昂贵开销。谈判花费了太多时间。

我想做的事情是可能吗?@justinbieber只是高开销Twitter账户的一个示例。我想使用这段代码检索许多高开销的账户的推文,因此速度和查看每个用户的每条推文的能力是必需的。

4个回答

6
使用json_decode之后,您可以使用以下IF语句来确定推文的类型:
    // if it is a retweet        
    if (isset($data['retweeted_status']))
    {
         //TODO
    }

    // if it is a reply
    else if (isset($data['in_reply_to_status_id_str']))
    {
         //TODO
    }

    // if it is a mention
    else if (isset($data['in_reply_to_user_id_str']))
    {
         //TODO
    }

    // if it is an original tweet
    else
    {
         //TODO
    }

0
在 Twitter API v2 中,你可以使用运算符来获取你所需的推文。要获取特定用户的推文,你可以创建如下规则:
from:username -is:retweet -is:reply

然后使用过滤流终端点,在推文发布时获取最新的推文。您也可以在规则中组合多个用户名。

资源:

这是一个非常好的例子: https://developer.twitter.com/en/docs/tutorials/stream-tweets-in-real-time

如何构建规则: https://developer.twitter.com/en/docs/twitter-api/tweets/filtered-stream/integrate/build-a-rule

了解过滤流: https://developer.twitter.com/en/docs/twitter-api/tweets/filtered-stream/introduction


0

我曾经遇到过类似的问题,并通过从arstechnica提取的这段小代码解决了它。

如果你正在使用Python,pycurl可以胜任此工作。它提供了一种执行每个接收到的小数据块的函数的方法。

import pycurl, json

STREAM_URL = "http://chirpstream.twitter.com/2b/user.json"

USER = "YOUR_USERNAME"
PASS = "XXXXXXXXX"


def on_receive(self, data):
    self.buffer += data
    if data.endswith("rn") and self.buffer.strip():
        content = json.loads(self.buffer)
        self.buffer = ""

        if "text" in content and content['user'] == 'justinbieber':
            print u"{0[user][name]}: {0[text]}".format(content)

conn = pycurl.Curl()
conn.setopt(pycurl.USERPWD, "%s:%s" % (USER, PASS))
conn.setopt(pycurl.URL, STREAM_URL)
conn.setopt(pycurl.WRITEFUNCTION, on_receive)
conn.perform()

您可以在这里找到更多信息 实时Twitter流API


-1

如果我的理解是正确的,您应该可以使用用户流来实现此目的。


除非我使用不正确,否则用户流也对我无效。例如,如果您查看沃尔玛的 Twitter 动态(由于支持查询而相当稳定)https://twitter.com/Walmart/with_replies,您会发现他们发送给其他用户的推文未在流中显示。我收到的唯一推文是由 @walmart 发布的,不涉及任何其他用户的推文。 - Simon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接