使用Tweepy V2 API过滤特定作者推文遇422错误的解决咨询
解决Tweepy V2 StreamingClient无法过滤特定作者推文的问题
问题根源
Twitter API v2的过滤流规则对from:操作符有明确限制:正向匹配必须使用用户的数字ID,不能直接用用户名。而否定匹配(如-from:samsung)可以使用用户名,这就是你用from:samsung触发422错误的原因。
解决步骤
获取目标用户的数字ID
可以通过Tweepy的Client查询用户名对应的ID,示例代码:import tweepy client = tweepy.Client(bearer_token="your_bearer_token") user = client.get_user(username="samsung") print(user.data.id) # 输出目标用户的数字ID修改流过滤规则
将StreamRule中的from:samsung替换为from:用户ID(比如samsung的ID为13869422),修正后的完整代码:class TweetPrinterV2(tweepy.StreamingClient): def on_tweet(self, tweet): print(tweet.text) return streaming_client = TweetPrinterV2('your_bearer_token') # 使用用户ID替换用户名 streaming_client.add_rules(tweepy.StreamRule("from:13869422")) streaming_client.filter(tweet_fields=['author_id'])
补充说明
- 若需监听多个用户,可用逗号分隔多个ID:
from:13869422,from:另一个用户ID - 添加新规则前,建议调用
streaming_client.get_rules()查看现有规则,避免重复添加导致冲突
内容的提问来源于stack exchange,提问作者user17659602
相关产品推荐
相关产品推荐

