forked from yasulab/SimpleTwitterBot
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathappengine_twitter.py
170 lines (132 loc) · 4.8 KB
/
appengine_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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
AppEngine-Twitter
Twitter API wrapper for applications on Google App Engine
See: http://0-oo.net/sbox/python-box/appengine-twitter
License: http://0-oo.net/pryn/MIT_license.txt (The MIT license)
See also:
http://apiwiki.twitter.com/Twitter-API-Documentation
http://code.google.com/intl/ja/appengine/docs/python/urlfetch/
'''
__author__ = '[email protected]'
__version__ = '0.1.0'
import base64
import urllib
from appengine_oauth import AppEngineOAuth
from django.utils import simplejson
from google.appengine.api import urlfetch
class AppEngineTwitter(object):
def __init__(self, tw_name='', tw_pswd=''):
'''
Note: Some actions require password or OAuth.
'''
self._api_url = 'https://twitter.com'
self._search_url = 'http://search.twitter.com'
self.tw_name = tw_name
self._oauth = None
self._headers = {}
if tw_pswd != '':
auth = base64.encodestring(tw_name + ':' + tw_pswd)[:-1]
self._headers['Authorization'] = 'Basic ' + auth
def update(self, message):
'''
Post a tweet
Sucess => Retrun 200 / Fialed => Return other HTTP status
'''
return self._post('/statuses/update.json', {'status': message})
# ref : https://dev.twitter.com/docs/api/1/post/statuses/retweet/%3Aid
def retweet(self, id):
'''
Post a tweet
Sucess => Retrun 200 / Fialed => Return other HTTP status
'''
return self._post('/statuses/retweet/' + id + '.json', {})
def follow(self, target_name):
'''
Sucess => Return 200 / Already following => Return 403 /
Fialed => Return other HTTP status
'''
return self._post('/friendships/create.json', {'screen_name': target_name})
def is_following(self, target_name):
'''
Yes => Return True / No => Return False /
Fialed => Return HTTP status except 200
'''
if self.tw_name == '':
# With OAuth, screen_name is not required.
self.verify()
user_info = simplejson.loads(self.last_response.content)
self.tw_name = user_info['screen_name']
status = self._get('/friendships/exists.json',
{'user_a': self.tw_name, 'user_b': target_name})
if status == 200:
return (self.last_response.content == 'true')
else:
return status
def verify(self):
'''
Verify user_name and password, and get user info
Sucess => Return 200 / Fialed => Return other HTTP status
'''
return self._get('/account/verify_credentials.json', {})
def search(self, keyword, params={}):
'''
Sucess => Return Array of dict / Fialed => Return HTTP status except 200
'''
params['q'] = keyword
return self._search('/search.json', params)
# OAuth methods
# (See http://0-oo.net/sbox/python-box/appengine-oauth )
def set_oauth(self, key, secret, acs_token='', acs_token_secret=''):
'''
Set OAuth parameters
'''
self._oauth = AppEngineOAuth(key, secret, acs_token, acs_token_secret)
def prepare_oauth_login(self):
'''
Get request token, request token secret and login URL
'''
dic = self._oauth.prepare_login(self._api_url + '/oauth/request_token/')
dic['url'] = self._api_url + '/oauth/authorize?' + dic['params']
return dic
def exchange_oauth_tokens(self, req_token, req_token_secret):
'''
Exchange request token for access token
'''
return self._oauth.exchange_tokens(self._api_url + '/oauth/access_token/',
req_token,
req_token_secret)
# Private methods
def _post(self, path, params):
url = self._api_url + path
if self._oauth != None:
params = self._oauth.get_oauth_params(url, params, 'POST')
res = urlfetch.fetch(url=url,
payload=urllib.urlencode(params),
method='POST',
headers=self._headers)
self.last_response = res
return res.status_code
def _get(self, path, params):
url = self._api_url + path
if self._oauth != None:
params = self._oauth.get_oauth_params(url, params, 'GET')
url += '?' + urllib.urlencode(params)
res = urlfetch.fetch(url=url, method='GET', headers=self._headers)
self.last_response = res
return res.status_code
def _search(self, path, params):
'''
FYI http://apiwiki.twitter.com/Rate-limiting (Especially 503 error)
'''
url = url=self._search_url + path + '?' + urllib.urlencode(params)
res = urlfetch.fetch(url=url, method='GET')
self.last_response = res
if res.status_code == 200:
return simplejson.loads(res.content)['results']
elif res.status_code == 503:
err_msg = 'Rate Limiting: Retry After ' + res.headers['Retry-After']
else:
err_msg = 'Error: HTTP Status is ' + str(res.status_code)
raise Exception('Twitter Search API ' + err_msg)