-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwitter.py
More file actions
61 lines (55 loc) · 1.96 KB
/
twitter.py
File metadata and controls
61 lines (55 loc) · 1.96 KB
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
57
58
59
60
61
import requests
import urllib
class Twitter(object):
def __init__(self):
self.bearer_token = None
def acquire_token(self, key, secret):
pre_token = '{key}:{secret}'.format(
key=urllib.quote(key),
secret=urllib.quote(secret)
).encode('base64').replace('\n', '')
response = requests.post(
'https://api.twitter.com/oauth2/token',
headers={
'Authorization': 'Basic {base}'.format(base=pre_token),
'Content-Type':
'application/x-www-form-urlencoded;charset=UTF-8'
},
data='grant_type=client_credentials'
).json()
if response['token_type'] == 'bearer':
self.bearer_token = response['access_token']
def get_profile(self, screen_name):
profile = self._get_request(
'users/show.json',
{
'screen_name': screen_name
}
)
profile['high_profile_image_url'] = ''.join(
profile['profile_image_url'].rsplit('_normal', 1)
)
return profile
def get_timeline(self, screen_name, count=100):
return self._get_request(
'statuses/user_timeline.json',
{
'screen_name': screen_name,
'count': count
}
)
def _get_request(self, endpoint, params=None):
twitter_response = requests.get(
'https://api.twitter.com/1.1/{}'.format(endpoint),
headers={
'Authorization': 'Bearer {bearer}'.format(
bearer=self.bearer_token
)
},
params=params
).json()
if type(twitter_response) is dict and 'error' in twitter_response:
raise Exception(str(twitter_response))
if type(twitter_response) is dict and 'errors' in twitter_response:
raise Exception(str(twitter_response))
return twitter_response