Photo by Benjamin Balázs on Unsplash
Before you can connect to the Streaming API you need create a Twitter application. This will give you the necessary OAuth credentials. To do this, go to dev.twitter.com/apps, login to your Twitter account then click the Create a new application button and follow the instructions.
To connect to the Streaming using Twython, you need create a subclass of TwythonStreamer
1from twython import TwythonStreamer23class TweetStreamer(TwythonStreamer):4 def on_success(self, data):5 if 'text' in data:6 print data['text'].encode('utf-8')78 def on_error(self, status_code, data):9 print status_code10 self.disconnect()
Now we will instanstiate the TweetStreamer
class and pass in the oauth details
1# replace these with the details from your Twitter Application2consumer_key = ''3consumer_secret = ''4access_token = ''5access_token_secret = ''67streamer = TweetStreamer(consumer_key, consumer_secret,8 access_token, access_token_secret)910streamer.statuses.filter(track = 'python')
The method on_success
on the class TweetStreamer
will get called for each tweet we receive from the streaming api. The statuses.filter
call, will find tweets that contain the word python. Running this script will start printing tweets to the console.