forked from ALADEGAZALIY/python-enterprise-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpython_FAS_sample.py
56 lines (46 loc) · 1.76 KB
/
python_FAS_sample.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# Sample Python Script for Searching with the Full-Archive Search API (with Python 3)
import base64
import json
import urllib.request
import urllib.parse
# Insert Gnip Console Username and Password Below
UN = ''
PWD = ''
# Insert Your Account Name and Stream Label Into the URL
base_url = 'https://gnip-api.twitter.com/search/fullarchive/accounts/<INSERT_ACCOUNT_NAME_HERE>/<INSERT_STREAM_LABEL_HERE>.json?query='
# Create URL Structure
class RequestWithMethod(urllib.request.Request):
def __init__(self, base_url, method, headers={}):
self._method = method
urllib.request.Request.__init__(self, base_url, headers)
def get_method(self):
if self._method:
return self._method
else:
return urllib.request.Request.get_method(self)
#Create Endpoint & Add Credentials
def create_rules_endpoint(query):
new_url = base_url + query
base64string = ('%s:%s' % (UN, PWD)).replace('\n', '')
base = base64.b64encode(base64string.encode('ascii'))
final_final_url = urllib.request.Request(new_url)
final_final_url.add_header('Authorization', 'Basic %s' % base.decode('ascii'))
return final_final_url
# Take in the Endpoint and Make the Request
def make_request(search_endpoint):
try:
response = urllib.request.urlopen(search_endpoint)
response_data = response.read()
handle_response(response_data)
except urllib.request.HTTPError as error:
print("ERROR: %s" % error)
# Handle the Returned Data and Print Tweet Text
def handle_response(data):
tweets_returned = json.loads(data)
for tweet in tweets_returned['results']:
tweet_text = tweet['text']
print("TWEET_TEXT: %s:" % tweet_text)
# Create the Endpoint Variable w/ Sample Query Keyword
search_endpoint = create_rules_endpoint('coffee')
# Make the Request by Passing in Search Endpoint
make_request(search_endpoint)