Twitter Datafeed with Python and TweePy Jul13


Related Posts

Share This

Twitter Datafeed with Python and TweePy

First of all, get TweePy and install it.

Then follow these steps to create an access to Twitter:
● Create a twitter account.
● Go to and log in.
● Click on “Create an application”
● Fill out the form.
● At the bottom of the page, click “Create my access token”
● Refresh until you get your access keys

Run the following script to get the Tweets associated with the word ‘Hello’ including your access keys:

OAUTH_KEYS = {'consumer_key': "your_key",
'consumer_secret': "your_key",
'access_token_key': "your_key",
'access_token_secret': "your_key"}

import sys
import tweepy

auth = tweepy.OAuthHandler(OAUTH_KEYS['consumer_key'], OAUTH_KEYS['consumer_secret'])
auth.set_access_token(OAUTH_KEYS['access_token_key'], OAUTH_KEYS['access_token_secret'])
api = tweepy.API(auth)

class CustomStreamListener(tweepy.StreamListener):

def on_status(self, status):
print status.text
f = open('tweepy_output.txt','a')
f.write(status.text.encode('utf-8') + '\n')
# or do whatever else you want with the stream

def on_error(self, status_code):
print >> sys.stderr, 'Encountered error with status code:', status_code
return True # Don't kill the stream

def on_timeout(self):
print >> sys.stderr, 'Timeout...'
return True # Don't kill the stream

sapi = tweepy.streaming.Stream(auth, CustomStreamListener())