You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Tweepy V2 API过滤特定作者推文遇422错误的解决咨询

解决Tweepy V2 StreamingClient无法过滤特定作者推文的问题

问题根源

Twitter API v2的过滤流规则对from:操作符有明确限制:正向匹配必须使用用户的数字ID,不能直接用用户名。而否定匹配(如-from:samsung)可以使用用户名,这就是你用from:samsung触发422错误的原因。

解决步骤

  1. 获取目标用户的数字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
    
  2. 修改流过滤规则
    将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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 19:31:15