Firstly need to register on Twitter developer portal. Get the connection key and secrets.
import base64
import requests
client_key = 'Odk1YHrLxxxxxxxxxuTfYATR'
client_secret = 'kYRiUVMVuD2I026mxxxxxxrxxxxxxxxxxx4qO56tmiAXLj'
key_secret = '{}:{}'.format(client_key, client_secret).encode('ascii')
b64_encoded_key = base64.b64encode(key_secret)
b64_encoded_key = b64_encoded_key.decode('ascii')
base_url = 'https://api.twitter.com/'
auth_url = '{}oauth2/token'.format(base_url)
auth_headers = {
'Authorization': 'Basic {}'.format(b64_encoded_key),
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
}
auth_data = {
'grant_type': 'client_credentials'
}
auth_resp = requests.post(auth_url, headers=auth_headers, data=auth_data)
access_token = auth_resp.json()['access_token']
print(auth_resp.status_code)
#print(access_token)
search_headers = {
'Authorization': 'Bearer {}'.format(access_token)
}
search_params = {
'q': 'brisbane',
#'result_type': 'recent',
'count': 20,
'tweet_model':'extended'
#'geocode': '-27.470125,153.021072,1500km' #brisbane
#'geocode': '-33.865143,151.209900,1500km' #sydney
}
search_url = 'https://api.twitter.com/1.1/search/tweets.json'
search_resp = requests.get(search_url, headers=search_headers, params=search_params)
#print(search_resp.url)
tweet_data = search_resp.json()
print(search_resp.status_code)
for t in tweet_data['statuses']:
print(t['text'] + '\n')