-
Notifications
You must be signed in to change notification settings - Fork 0
/
clickatell_lib.py
235 lines (182 loc) · 5.82 KB
/
clickatell_lib.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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
#!/usr/bin/python
"""
Python module which can be used to send SMS messages via the Clickatell HTTP/S API
Interface on https://api.clickatell.com/
See U{the Clickatell HTTP/S API documentation<http://www.clickatell.com/downloads/http/Clickatell_http_2.2.7.pdf>}
for more information on how their HTTP/S API interface works
"""
import urllib
import urllib2
def hex_chars(message):
hex_string=[]
for c in message:
hex_string.append("%04x"%ord(c))
return ''.join(hex_string)
class ClickatellError (Exception):
"""
Base class for Clickatell errors
"""
class ClickatellAuthenticationError (ClickatellError):
pass
class Clickatell(object):
"""
Provides a wrapper around the Clickatell HTTP/S API interface
"""
def __init__ (self, username, password, api_id, user_agent='pyclickatell'):
"""
Initialise the Clickatell class
Expects:
- username - your Clickatell Central username
- password - your Clickatell Central password
- api_id - your Clickatell Central HTTP API identifier
"""
self.has_authed = False
self.username = username
self.password = password
self.api_id = api_id
self.session_id = None
self.user_agent = user_agent
def auth (self):
"""
Authenticate against the Clickatell API server
"""
url = 'https://api.clickatell.com/http/auth'
post = [
('user', self.username),
('password', self.password),
('api_id', self.api_id),
]
result = self.curl (url, post)
if result[0] == 'OK':
assert (32 == len(result[1]))
self.session_id = result[1]
self.has_authed = True
return True
else:
return False
def getbalance (self):
"""
Get the number of credits remaining at Clickatell
"""
if self.has_authed == False:
self.auth()
url = 'https://api.clickatell.com/http/getbalance'
post = [
('session_id', self.session_id),
]
result = self.curl (url, post)
if result[0] == 'Credit':
assert (0 <= result[1])
return result[1]
else:
return False
def getmsgcharge (self, apimsgid):
"""
Get the message charge for a previous sent message
"""
if self.has_authed == False:
self.auth()
assert (32 == len(apimsgid))
url = 'https://api.clickatell.com/http/getmsgcharge'
post = [
('session_id', self.session_id),
('apimsgid', apimsgid),
]
result = self.curl (url, post)
result = ' '.join(result).split(' ')
if result[0] == 'apiMsgId':
assert (apimsgid == result[1])
assert (0 <= result[3])
return result[3]
else:
return False
def ping (self):
"""
Ping the Clickatell API interface to keep the session open
"""
if self.has_authed == False:
self.auth()
url = 'https://api.clickatell.com/http/ping'
post = [
('session_id', self.session_id),
]
result = self.curl (url, post)
if result[0] == 'OK':
return True
else:
self.has_authed = False
return False
def sendmsg (self, message):
"""
Send a mesage via the Clickatell API server
message = {
'to': 'to_msisdn',
'sender': 'from_msisdn',
'text': 'This is a test message',
'climsgid': 'random_md5_hash',
}
result = clickatell.sendmsg(message)
if result[0] == True:
print "Message was sent successfully"
print "Clickatell returned %s" % result[1]
else:
print "Message was not sent"
"""
if self.has_authed == False:
self.auth()
url = 'https://api.clickatell.com/http/sendmsg'
unicode=0
try:
msg_text=message['text'].encode("ascii")
except:
# The message has non-ascii characters, convert into Unicode
unicode=1
msg_text=hex_chars(message['text'])
post = [
('session_id', self.session_id),
('to', message['to']),
('text', msg_text),
('unicode', str(unicode))
]
#print "Unicode string is [%s]"%msg_text
if 'sender' in message:
post.append(('from', message['sender']))
if 'climsgid' in message:
post.append(('climsgid', message['climsgid']))
result = self.curl (url, post)
if result[0] == 'ID':
print result[1]
assert (result[1])
return (True, result[1])
else:
print result
return (False, )
def tokenpay (self, voucher):
"""
Redeem a voucher via the Clickatell API interface
"""
if self.has_authed == False:
self.auth()
assert (16 == len(voucher))
url = 'https://api.clickatell.com/http/token_pay'
post = [
('session_id', self.session_id),
('token', voucher),
]
result = self.curl (url, post)
if result[0] == 'OK':
return True
else:
return False
def curl (self, url, post_list):
"""
Inteface for sending web requests to the Clickatell API Server
"""
post_data = {}
for item in post_list:
post_data[item[0]] = item[1]
req = urllib2.Request(url=url, data=urllib.urlencode(post_data))
req.add_header("User-Agent", self.user_agent)
req.add_header("Accept", '')
fp = urllib2.urlopen(req)
return fp.read().split(": ")