-
Notifications
You must be signed in to change notification settings - Fork 0
/
103-search_twitter.py
executable file
·46 lines (37 loc) · 1.6 KB
/
103-search_twitter.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
#!/usr/bin/python3
""" Makes a search query using Twitter API and Oauth2 """
if __name__ == "__main__":
import requests
import base64
from sys import argv
def post_bearer(key, secret):
""" fetches the Bearer token """
key = (key + ':' + secret).encode("utf-8")
token = base64.urlsafe_b64encode(key)
token = "Basic " + str(token, 'utf-8')
header = {'Authorization': token,
'Content-Type':
'application/x-www-form-urlencoded;charset=UTF-8'}
res_bearer = requests.post('https://api.twitter.com/oauth2/token',
data={'grant_type': 'client_credentials'},
headers=header).json()
bearer = res_bearer.get('access_token')
bearer = 'Bearer ' + bearer
return bearer
def get_search(query, bearer):
""" Makes a search query """
url = 'https://api.twitter.com/1.1/search/tweets.json'
parameters = {'q': query, 'count': 5, 'result_type': 'recent'}
header = {'Authorization': bearer}
results = requests.get(url, params=parameters, headers=header).json()
return results
def print_nice(results):
""" Print [<UserId>] <UserText> <UserName> """
for result in results.get('statuses'):
usr_id = result.get('id')
usr_txt = result.get('text')
usr_name = result.get('user').get('name')
print('[{}] {} by {}'.format(usr_id, usr_txt, usr_name))
key = post_bearer(argv[1], argv[2])
results = get_search(argv[3], key)
print_nice(results)