python - 仅使用 Twitter 流 API 显示来自单个用户的推文
问题描述
我需要以流格式从单个用户那里获取推文。但是,它仍会显示所有转推此用户或回复推文的推文。
topic = "tweets"
accounts = ['user_id1', 'user_id2']
class TwitterStreamer():
def __init__(self):
pass
def stream_tweets(self, topic, accounts):
listener = StreamListener(topic)
auth = tweepy.OAuthHandler(api_key, api_secret_key)
auth.set_access_token(access_token, access_secret_token)
stream = tweepy.Stream(auth, listener)
stream.filter(follow=accounts)
class StreamListener(tweepy.StreamListener):
def __init__(self, file_prefix):
self.prefix = file_prefix
@property
def fetched_tweets_filename(self):
topic
date = datetime.datetime.now().strftime("%Y-%m-%d")
return f"{self.prefix}_{date}.txt"
def on_data(self, data):
try:
print(data)
with open(self.fetched_tweets_filename, 'a') as tf:
tf.write(data)
return True
except BaseException as e:
print("Error on_data %s" % str(e))
return True
def on_exception(self, exception):
print('exception', exception)
stream_tweets(topic, accounts)
def on_status(self, accounts, status):
if status.user.id_str != accounts:
return
print(status.text)
def stream_tweets(topic, accounts):
listener = StreamListener(topic)
auth = tweepy.OAuthHandler(api_key, api_secret_key)
auth.set_access_token(access_token, access_secret_token)
stream = tweepy.Stream(auth, listener)
stream.filter(track=accounts)
if __name__ == '__main__':
twitter_streamer = TwitterStreamer()
twitter_streamer.stream_tweets(topic, accounts)
我不知道我做错了什么,但我觉得 on_status 命令根本不起作用。
谢谢你的帮助!
解决方案
不要更改 的参数on_status
。你的accounts
变量是一个全局变量,你应该这样使用它。此外,status.user.id_str
is a str
but accounts
is a List[str]
。您需要not ... in ...
运算符而不是!=
. 换句话说,请尝试以下更改:
def on_status(self, status):
if not status.user.id_str in accounts:
return
print(status.text)
推荐阅读
- julia - 是否可以表示依赖于另一种参数类型的字段类型?
- groovy - 将代码从 tradingview 转换为 Tryd
- javascript - 如何根据排名和按钮将内容添加到数据库?
- azure-devops - 如何在复制到 blob 之前对其进行清理(Azure 发布管道)
- c - C:为什么在 fork() 子块没有运行之后?
- react-native - 如何在使用 CUSTOM_AUTH 身份验证流程登录期间保留 CognitoUser
- angular - 角度 CORS 请求失败
- python - ImportError:无法导入名称“类型”
- javascript - 生成器产生的承诺在等待时未同时解决
- html - 在项目中实现SASS会不会太难?