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

使用Tweepy 4.14.0开发Twitter提及回复Bot遇Stream属性错误

解决Tweepy 4.14.0中无法导入Stream的问题

报错原因

出现AttributeError: module 'tweepy' has no attribute 'Stream'或ImportError: cannot import name 'Stream' from 'tweepy',通常是以下两种情况:

  • Python环境中Tweepy版本混乱或安装不完整
  • 混淆了Twitter API v1.1和v2的流处理类

解决方案1:使用Twitter API v1.1的流(兼容原有逻辑)

第一步:修复Tweepy安装

先清理并重新安装指定版本的Tweepy,确保环境一致:

pip uninstall -y tweepy
pip install tweepy==4.14.0

第二步:修正代码逻辑

import tweepy

# 初始化API客户端(用于回复推文)
auth = tweepy.OAuthHandler("你的Consumer Key", "你的Consumer Secret")
auth.set_access_token("你的Access Token", "你的Access Token Secret")
api = tweepy.API(auth)

class MentionStreamListener(tweepy.Stream):
    def on_status(self, tweet):
        # 过滤掉转推和非直接提及的推文
        if not tweet.retweeted and tweet.in_reply_to_status_id is None:
            tweet_text = tweet.text
            reply = generate_reply(tweet_text)  # 调用你的回复生成函数
            reply_text = f'@{tweet.user.screen_name} {reply}'
            # 发送回复
            api.update_status(reply_text, in_reply_to_status_id=tweet.id)

# 启动流监听,替换为你的Twitter用户名
stream = MentionStreamListener(auth=auth)
stream.filter(track=["@你的用户名"])

解决方案2:使用Twitter API v2的流(推荐,符合Twitter最新规范)

Tweepy 4.x对API v2支持更完善,推荐使用StreamingClient类:

import tweepy

# 初始化API v2客户端
client = tweepy.Client(
    bearer_token="你的Bearer Token",
    consumer_key="你的Consumer Key",
    consumer_secret="你的Consumer Secret",
    access_token="你的Access Token",
    access_token_secret="你的Access Token Secret"
)

class MentionStream(tweepy.StreamingClient):
    def on_tweet(self, tweet):
        # 过滤掉非直接提及的推文
        if tweet.in_reply_to_user_id is None:
            tweet_text = tweet.text
            reply = generate_reply(tweet_text)
            # 发送回复
            client.create_tweet(
                text=f'@{tweet.author.username} {reply}',
                in_reply_to_tweet_id=tweet.id
            )

# 启动流监听
stream = MentionStream(bearer_token="你的Bearer Token")
stream.add_rules(tweepy.StreamRule("@你的用户名"))
stream.filter(tweet_fields=["author_id", "in_reply_to_user_id"])

内容的提问来源于stack exchange,提问作者NASIM

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 22:35:33