"AttributeError: module 'tweepy' has no attribute 'StreamListener'" with Python 3.9
Asked Answered
E

4

7
class MyStreamListener(tweepy.StreamListener):
    def on_status(self, status):
        print(status.text)  # prints every tweet received

    def on_error(self, status_code):
        if status_code == 420:  # end of monthly limit rate (500k)
            return False

I use Python 3.9 and installed Tweepy via pip. I get the AttributeError on the class line. My import is just import tweepy. Authentication gets correctly handled. In the streaming.py file, I have the class Stream. But using this class ends in that. There is for example no status.text, even if there is the on_status function. I am a little bit confused.

Emotionalize answered 2/10, 2021 at 12:39 Comment(1)
They didn't update the document I don't know why! I fall into the trap like you too.Finicky
T
12

Tweepy v4.0.0 was released recently and it merged StreamListener into Stream.

I recommend updating your code to subclass Stream instead.
Alternatively, you can downgrade to v3.10.0.

Truthvalue answered 4/10, 2021 at 17:0 Comment(1)
Yes, thanks. That was the way to go.Emotionalize
C
6

As mentioned by @Harmon758, they merged StreamListener into Stream after version 4. Also you don`t need to create the api auth object separately. Here is the code:

from tweepy import Stream

class MyStreamListener(Stream):
    def on_status(self, status):
        print(status.text)  # prints every tweet received

    def on_error(self, status_code):
        if status_code == 420:  # end of monthly limit rate (500k)
            return False


stream = MyStreamListener('consumer_key',
                          'consumer_secret',
                          'access_token',
                          'access_token_secret')

stream.filter(track=["Python"], languages=["en"])
Calorific answered 22/2, 2022 at 15:17 Comment(0)
F
1

If you look at the modules, the correct way to reference StreamListener is tweepy.streaming.StreamListener, not tweepy.StreamListener.

Footboy answered 3/10, 2021 at 22:16 Comment(0)
A
0

For other people coming in the future, this doesn't work anymore, now you need to use twitter api v2. The class is :

tweepy.StreamingClient(bearer_token, *, return_type=Response, wait_on_rate_limit=False, chunk_size=512, daemon=False, max_retries=inf, proxy=None, verify=True)

So you can use it like this :

import tweepy
from tweepy import StreamingClient, StreamRule

bearer_token = 'WXXXXXXXX'
 
class TweetPrinterV2(tweepy.StreamingClient):
    
    def on_tweet(self, tweet):
        print(f"{tweet.id} {tweet.created_at} ({tweet.author_id}): {tweet.text}")
        
 
stream = TweetPrinterV2(bearer_token)
 
rule = StreamRule(value="CryptoApeGod")
stream.add_rules(rule)
 
stream.filter()

There is also an async version using asyncio if you need.

Assignable answered 3/6, 2024 at 16:58 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.