Twitter

Twitter api streamlistener

A short example on using the Twitter API StreamListener with Python.

import sys
import tweepy
import csv

# Stick your Twitter API keys into variables
consumer_key=""
consumer_secret=""
access_key = ""
access_secret = ""

# Use your keys to access Twitter
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)

# Create customStreamListener object

class CustomStreamListener(tweepy.StreamListener):

def on_status(self, status):
print (status.author.screen_name, status.created_at, status.text)
# Writing status data
with open('OutputStreaming.txt', 'w') as f:
writer = csv.writer(f)
writer.writerow([status.author.screen_name, status.created_at, status.text.encode('utf-8')])

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

# Writing csv titles
with open('OutputStreaming.txt', 'w') as f:
writer = csv.writer(f)
writer.writerow(['Author', 'Date', 'Text'])

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

# The term you want to track in the stream
streamingAPI.filter(track=['#brexitruling'])