Search code examples
pythonpython-3.xtweepy

name 'fetched_tweets_filename' is not defined


Unclear what's going wrong here. From what I see I have defined the fetched_tweets_filename variable above. I pass in fetched_tweets_filename to the initialization of the instance listener of the StdOutListener class. Receiving the following error:

Traceback (most recent call last):
File "twitter_scraper.py", line 51, in <module> main()
File "twitter_scraper.py", line 39, in main
listener = StdOutListener(fetched_tweets_filename)
File "twitter_scraper.py", line 20, in __init__
self.fetched_tweets_filename = fetched_tweets_filename
NameError: name 'fetched_tweets_filename' is not defined

I define fetched_tweets_filename right above it. I am not the most experienced Python programmer so I may be doing something obvious.

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

import twitter_credentials

class StdOutListener(StreamListener):

    #basic class that prints received tweets to stdout

    def __init__(self, scraped_tweets_filename):
        self.fetched_tweets_filename = fetched_tweets_filename

    def on_data(self, data):
        try:
            print(data)
            with open(self.fetched_tweets_filename, 'a') as tf:
                tf.write(data)
            return True
        except BaseException as e:
            print("Error on_data: %s" % str(e))
        return True

    def on_error(self,status):
        print(status)

def main():
    hash_tag_list = ["Greenpoint", "Williamsburg", "Boerum Hill", "Brooklyn Heights", "Brooklyn Navy Yard", "Clinton Hill", "Dumbo", "Fort Greene", "Fulton Ferry", "Fulton Mall", "Vinegar Hill", "BedStuy", "Bedford-Stuyvesant", "Bedford Stuyvesant", "Ocean Hill", "Stuyvesant Heights", "Bushwick"]
    fetched_tweets_filename = "tweets_scraped.json"

    listener = StdOutListener(fetched_tweets_filename)

    auth = OAuthHandler(twitter_credentials.CONSUMER_KEY, twitter_credentials.CONSUMER_SECRET)

    auth.set_access_token(twitter_credentials.ACCESS_TOKEN, twitter_credentials.ACCESS_TOKEN_SECRET)

    stream = Stream(auth, listener)

    stream.filter(track=hash_tag_list)


if __name__ == "__main__":
    main()

Solution

  • Here def __init__(self, scraped_tweets_filename): self.fetched_tweets_filename = fetched_tweets_filename you should have def __init__(self, scraped_tweets_filename): self.fetched_tweets_filename = scraped_tweets_filename