[英]Twitter Streaming API: only show tweets directed at a user and tweets from a user
I use the Twitter streaming API to retrieve the tweets that a certain user writes.我使用 Twitter 流 API 来检索某个用户写的推文。 To do so, I use为此,我使用
stream.filter(follow=['user_id'])
However, I do not only get the tweets of this user ID, but I guess also replies, retweets (?), I am not quite sure what all these tweets are that I get, but actually I only want to get those tweets which this single user writes.但是,我不仅得到了这个用户 ID 的推文,而且我想还有回复、转发(?),我不太确定我得到的所有这些推文是什么,但实际上我只想得到那些推文单用户写入。 Is there a way I can exclude the other messages?有没有办法排除其他消息?
Also, I want to get all tweets that are directed at this person, so all tweets where this account is mentioned.此外,我想获取所有针对此人的推文,因此所有提及此帐户的推文。 Consequently, I would use.因此,我会使用。 However, here I have the same problem as I get quite some tweets that do not only meet this criterion.但是,在这里我遇到了同样的问题,因为我收到了很多不仅符合此标准的推文。
stream.filter(track=["@screen_name"])
I read that I might implement something like我读到我可能会实现类似的东西
def on_status(self, status):
if status.retweeted_status:
return
print(status)
but I do not even know what exactly the code delivers me neither what I have to exclude, so I would be really thankful if you could help me with my problem.但我什至不知道代码到底给我提供了什么,也不知道我必须排除什么,所以如果你能帮助我解决我的问题,我将非常感激。
Here's an example in which you can stream statuses posted by @elonmusk using the start_twitter_stream
function:这是一个示例,您可以在其中使用start_twitter_stream
函数流式传输@elonmusk发布的状态:
from tweepy import API, OAuthHandler, Stream
import os
TARGET_SCREEN_NAME = 'elonmusk'
class TweetListener(Stream):
def on_status(self, status):
if status.user.screen_name == TARGET_SCREEN_NAME:
print(status.text)
def get_twitter_auth():
auth = OAuthHandler(
os.environ['TWITTER_CONSUMER_KEY'],
os.environ['TWITTER_CONSUMER_SECRET'])
auth.set_access_token(
os.environ['TWITTER_ACCESS_KEY'],
os.environ['TWITTER_ACCESS_SECRET'])
print('Authenticated with Twitter API')
return API(auth)
def get_user_id(screen_name):
api = get_twitter_auth()
try:
user = api.get_user(screen_name=username)
return user.id_str
except errors.Forbidden:
print(f'@{TARGET_SCREEN_NAME} has been suspended')
return None
def start_twitter_stream():
target_user_id = get_user_id(TARGET_SCREEN_NAME)
if target_user_id is None: return
stream = TweetListener(
os.environ['TWITTER_CONSUMER_KEY'],
os.environ['TWITTER_CONSUMER_SECRET'],
os.environ['TWITTER_ACCESS_KEY'],
os.environ['TWITTER_ACCESS_SECRET'])
print(f'Started streaming from @{TARGET_SCREEN_NAME}')
stream.filter(follow=[target_user_id])
References:参考:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.