Search code examples
pythontweepy

Need help to resolve `AttributeError: module 'tweepy' has no attribute 'Stream'`


I've been trying to work with the Twitter API v2 to access tweets for free, but I keep hitting a dead end. It's been quite frustrating as my code isn't working as expected. I keep getting this an attribute error. I tried googling, but the solutions provided for those code snippets doesnt seem to work,

Here's the full error message I'm getting:

Traceback (most recent call last):
  File "filepath\twitter.py", line 21, in <module>
    class TweetStreamListener(tweepy.Stream):
AttributeError: module 'tweepy' has no attribute 'Stream'

If anyone has experience working with the Twitter API v2 and has encountered a similar problem, your insights would be greatly appreciated. Thanks in advance for your help!

import tweepy
import json
import csv
from kafka import KafkaProducer

api_key = 'x'
api_secret = 'y'
access_token = 'z'
access_token_secret = '&'

kafka_bootstrap_server = 'localhost:9092'
kafka_topic = 'twitter_data'

csv_output = 'filepath/twitter-data-from-api.csv'

kafka_producer = KafkaProducer(bootstrap_servers=kafka_bootstrap_server)

class TweetStreamListener(tweepy.Stream):
    def on_status(self, status):
        try:
            tweet_id = status.id
            tweet_text = status.text
            tweet_created = status.created_at.strftime('%Y-%m-%d %H:%M:%S')

            tweet_data = {
                'id': tweet_id,
                'text': tweet_text,
                'created at': tweet_created
            }

            kafka_producer.send(kafka_topic,
                                json.dumps(tweet_data).encode("UTF-8"),
                                api_version=(3, 5, 0))

            with open(csv_output, 'a', newline='', encoding='utf-8') as f:
                writer = csv.writer(f)
                writer.writerows([[tweet_id, tweet_text, tweet_created]])

        except Exception as e:
            print(f"Error: {str(e)}")

def extract_data():
    auth = tweepy.OAuthHandler(api_key, api_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth)

    twitter_stream_listener = TweetStreamListener(api.auth, None)
    stream = tweepy.Stream(auth=api.auth, listener=twitter_stream_listener)

    stream.filter(['Key1', 'Key2', 'Key3'])

    kafka_producer.close()

extract_data()

Solution

  • According to the Tweepy documentation:

    Stream and AsyncStream were deprecated in v4.13 and removed with v4.14.

    Currently, you should use StreamingClient class or downgrade your library.