Skip to content

Instantly share code, notes, and snippets.

@hiway
Last active July 20, 2023 15:56
Show Gist options
  • Save hiway/4427458 to your computer and use it in GitHub Desktop.
Save hiway/4427458 to your computer and use it in GitHub Desktop.
A bare-minimum implementation of Twitter's Streaming API using python-requests library. Prints out tweets as they come in.
consumer_key = ''
consumer_secret = ''
access_token = ''
access_token_secret = ''
requests==0.14.2
requests-oauth==0.4.1
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import json
import auth
import requests
from oauth_hook import OAuthHook
OAuthHook.consumer_key = auth.consumer_key
OAuthHook.consumer_secret = auth.consumer_secret
oauth_hook = OAuthHook(auth.access_token,
auth.access_token_secret)
client = requests.session(hooks={'pre_request':oauth_hook})
r = client.post('https://userstream.twitter.com/1.1/user.json',
prefetch=False, verify=False)
# Set chunk_size to a very small number
# if you don't want to wait forever
for line in r.iter_lines(chunk_size=1, decode_unicode=True):
if line: # filter out keep-alive new lines
data = json.loads(line)
if data.has_key('text'):
try:
print "%s: %s" % (data['user']['screen_name'],
data['text'],)
except:
print "Couldn't print tweet with ID: %s" % data['id']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment