skip to Main Content

I’m trying to create a data stream in Python using the Twitter API, but I’m unable to import the StreamListener correctly.

Here’s my code:

import tweepy
from tweepy import Stream
from tweepy.streaming import StreamListener

class MyListener(StreamListener):
 
    def on_data(self, data):
        try:
            with open('python.json', 'a') as f:
                f.write(data)
                return True
        except BaseException as e:
            print("Error on_data: %s" % str(e))
        return True
 
    def on_error(self, status):
        print(status)
        return True
 
twitter_stream = Stream(auth, MyListener())
twitter_stream.filter(track=['#python'])

And I’m getting this error:

Traceback (most recent call last):
  File "c:UsersUserDocumentsGitHubtempCodeRunnerFile.python", line 6, in <module>
    from tweepy.streaming import StreamListener
ImportError: cannot import name 'StreamListener' from 'tweepy.streaming' (C:UsersUserAppDataLocalProgramsPythonPython39libsite-packagestweepystreaming.py)

3

Answers


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

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

    Login or Signup to reply.
  2. For Tweepy v4, you don’t need to use StreamListener. The following is an edited code for v4:

    import tweepy
    
    class MyListener(tweepy.Stream):
        def on_data(self, data):
            try:
                with open('python.json', 'a') as f:
                    f.write(data)
                    return True
            except BaseException as e:
                print("Error on_data: %s" % str(e))
            return True
     
        def on_error(self, status):
            print(status)
            return True
     
    twitter_stream = MyListener(
      "Consumer Key here", "Consumer Secret here",
      "Access Token here", "Access Token Secret here"
    )
    twitter_stream.filter(track=['#python'])
    
    Login or Signup to reply.
  3. A slight tweak will fix this

    #from tweepy.streaming import StreamListener #OLD CODE
    
    import tweepy # NEW CODE
    
    #class TweetListener (StreamListener): #OLD CODE
    
    class TweetListener (tweepy.Stream): # NEW CODE
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search