1
votes

My question is about twython that returns...

401 b'<html>\\n<head>\\n<meta http-equiv="Content-Type" content="text/html; 
charset=utf-8"/>\\n<title>Error 401 
Unauthorized</title>\n</head>\n<body>\n<h2>HTTP ERROR: 401</h2>\n<p>Problem 
accessing \'/1.1/statuses/filter.json\'. Reason:\n<pre>    
Unauthorized</pre>\n</body>\n</html>\n'

I have tried regenerating consumer key & secrete and access token & secrete and it still returns the same thing... Below is my code

tweets = []

class MyStreamer(TwythonStreamer):

    def on_success(self, data):
        """ Stores tweet data as dict """

        # Collect only English Tweets
        if data['lang'] == 'en':
            tweets.append(data)
            print("Received Tweet #", len(tweets))

        # Stop when 1000 tweets are collected
        if len(tweets) >= 1000:
            self.disconnect()

    def on_error(self, status_code, data):
        print(status_code, data)
        self.disconnect()   

stream = MyStreamer(CONSUMER_KEY, CONSUMER_SECRET,
                    ACCESS_TOKEN, ACCESS_TOKEN_SECRET)

# Starts consuming public Statuses that contain the keyword 'cola'
stream.statuses.filter(track='cola')
2

2 Answers

0
votes

Have you set the variables CONSUMER_KEY, CONSUMER_SECRET... ? Moreover you should filter language in the stream. Here is the code. Just replace '***' with your tokens that you get at https://apps.twitter.com/ :

from twython import TwythonStreamer

tweets = []

class MyStreamer(TwythonStreamer):

    def on_success(self, data):

        if 'text' in data:
            tweets.append(data)
            print(data['text'])

        if len(tweets) >= 10:
            self.disconnect()            

    def on_error(self, status_code, data):
        print(status_code)
        self.disconnect()

APP_KEY = '***'
APP_SECRET = '***'
OAUTH_TOKEN = '***'
OAUTH_TOKEN_SECRET = '***'

stream = MyStreamer(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
stream.statuses.filter(track='cola', language='en')

This may help for the stream parameters : https://developer.twitter.com/en/docs/tweets/filter-realtime/guides/basic-stream-parameters

0
votes

I had the same issue. What worked for me is:

Go to dev portal and generate "Access Token & Secret" save them as OAUTH_TOKEN and OAUTH_TOKEN_SECRET.