Garciat
10/1/2014 - 9:49 PM

requires pip packages: requests

requires pip packages: requests

import requests
import base64
import json
import sys

def log(msg):
	sys.stderr.write(msg)
	sys.stderr.write('\n')

client_key= ''
client_secret = ''

bearer_token = '%s:%s' % (client_key, client_secret)

encoded_bearer_token = base64.b64encode(bearer_token.encode('ascii')).decode('ascii')

request_token_url = 'https://api.twitter.com/oauth2/token'

request_token_headers = {
	'Authorization': 'Basic %s' % encoded_bearer_token,
	'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
}

request_token_body = {
	'grant_type': 'client_credentials'
}

log('Requesting access tokens...')

r = requests.post(request_token_url, data = request_token_body, headers = request_token_headers)

oauth_tokens = json.loads(r.text)

protected_url = 'https://api.twitter.com/1.1/search/tweets.json'

search_query = {
	'q': '#python',
	'result_type': 'recent',
	'count': 30
}

request_headers = {
	'Authorization': 'Bearer %s' % oauth_tokens['access_token']
}

log('Fetching tweets...')

r = requests.get(protected_url, params = search_query, headers = request_headers)

response = json.loads(r.text)

print(json.dumps(response, indent = 2))