forked from coolsms/python-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
coolsms.py
338 lines (292 loc) · 10.7 KB
/
coolsms.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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
# -*- coding: utf8 -*-
from hashlib import md5
import sys
import hmac
import mimetypes
import uuid
import json
import time
import platform
# sys.version_info.major is available in python version 2.7
# use sys.version_info[0] for python 2.6
if sys.version_info[0] == 2:
from httplib import HTTPSConnection
from urllib import urlencode
else:
from http.client import HTTPSConnection
from urllib.parse import urlencode
"""
Copyright (C) 2008-2015 NURIGO
http://www.coolsms.co.kr
"""
__version__ = "1.1"
# send multipart form to the server
def post_multipart(host, selector, fields, files):
content_type, body = encode_multipart_formdata(fields, files)
h = HTTPSConnection(host)
h.putrequest('POST', selector)
h.putheader('content-type', content_type)
h.putheader('content-length', str(len(body.encode('utf-8'))))
h.putheader('User-Agent', 'sms-python')
h.endheaders()
h.send(body.encode('utf-8'))
resp = h.getresponse()
return resp.status, resp. reason, resp.read().decode()
# format multipart form
def encode_multipart_formdata(fields, files):
boundary = str(uuid.uuid1())
crlf = '\r\n'
l = []
for key, value in fields.items():
l.append('--' + boundary)
l.append('Content-Disposition: form-data; name="%s"' % key)
l.append('')
l.append(value)
l.append('')
body = crlf.join(l)
for key, value in files.items():
body += '--' + boundary + crlf
body += 'Content-Type: %s' % get_content_type(value['filename']) + crlf
body += 'Content-Disposition: form-data; name="%s"; filename="%s"' % (key, value['filename']) + crlf
body += crlf
body = body.encode('utf-8') + value['content'] + crlf
body += '--' + boundary + '--' + crlf
body += crlf
content_type = 'multipart/form-data; boundary=%s' % boundary
return content_type, body
def get_content_type(filename):
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
# class rest
# SMS Gateway access url : https://api.coolsms.co.kr/{verson}/{resource name}
class rest:
# SMS Gateway address
host = 'api.coolsms.co.kr'
# use secure channel as default
port = 443
# api version
api_version = '1.5'
# API Key
api_key = None
# API Secret
api_secret = None
# solution registration key
srk = None
# message type (sms, lms, mms)
mtype = 'sms'
# image file
imgfile = None
# error handle
error_string = None
# TRUE : test mode
test = False
# application version
app_version = 'APP 1.0'
# constructor
def __init__(self, api_key=str(), api_secret=str(), app_version=None, srk=None, test=False, api_version=None):
self.api_key = api_key
self.api_secret = api_secret
self.srk = srk
if app_version:
self.app_version = app_version
self.test = test
if api_version:
self.api_version = api_version
# return salt, timestamp, signature
def __get_signature__(self):
salt = str(uuid.uuid1())
timestamp = str(int(time.time()))
data = timestamp + salt
return timestamp, salt, hmac.new(self.api_secret.encode(), data.encode(), md5)
# error handle
def __set_error__(self, error_str):
self.error_string = error_str
# return message type set
def get_type(self):
return self.mtype
# return error string set
def get_error(self):
return self.error_string
# set one of sms , lms , mms
def set_type(self, mtype):
if mtype.lower() not in ['sms', 'lms', 'mms']:
return False
self.mtype = mtype.lower()
return True
# set image file path
def set_image(self, image):
self.imgfile = image
# access to send resource
def send(self, to=None, text=None, sender=None, mtype=None, subject=None, image=None, datetime=None, extension=None, app_version=None, country=None):
"""Request to REST API server to send SMS messages
Arguments:
to : A comma seperated string which contains phone numbers.
text : Message content
sender : sender id
mtype : one of sms, lms, mms
subject : If you send LMS or MMS, you should input the subject of the message(s).
image : Include image, when you send MMS.
datetime : Use this field when you send scheduled messages.
extension : JSON formatted string. Please refer to API document.
app_version : You'd better set this field as your own application's name. It's useful when you need any
help from COOLSMS service center.
Returns:
A JSON type string will be returned. On failure, False will be returned.
"""
# convert list to a comma seperated string
if sys.version_info[0] == 2:
t_temp = text.decode('utf-8')
text = t_temp.encode('utf-8')
text = unicode(text, encoding='utf-8')
if type(to) == list:
to = ','.join(to)
if mtype:
if mtype.lower() not in ['sms', 'lms', 'mms']:
self.__set_error__('invalid message type')
return False
else:
mtype = self.get_type()
os_platform = platform.system()
dev_lang = "Python %s" % platform.python_version()
sdk_version = "sms-python %s" % __version__
if app_version:
self.app_version = app_version
# get authentication info.
timestamp, salt, signature = self.__get_signature__()
fields = {'api_key': self.api_key,
'timestamp': timestamp,
'salt': salt,
'signature': signature.hexdigest(),
'type': mtype,
'os_platform': os_platform,
'dev_lang': dev_lang,
'sdk_version': sdk_version,
'app_version': self.app_version}
if self.test:
fields['mode'] = 'test'
if self.srk:
fields['srk'] = self.srk
if to:
fields['to'] = to
if text:
fields['text'] = text
if sender:
fields['from'] = sender
if subject:
fields['subject'] = subject
if datetime:
fields['datetime'] = datetime
if extension:
fields['extension'] = extension
if country:
fields['country'] = country
if image is None:
image = self.imgfile
if mtype.lower() == 'mms':
if image is None:
self.__set_error__('image file path input required')
return False
try:
with open(image, 'rb') as content_file:
content = content_file.read()
except IOError as e:
self.__set_error__("I/O error({0}): {1}".format(e.errno, e.strerror))
return False
except:
self.__set_error__("Unknown error")
return False
files = {'image': {'filename': image, 'content': content}}
else:
files = {}
# request post multipart-form
host = self.host + ':' + str(self.port)
selector = "/sms/%s/send" % self.api_version
try:
status, reason, response = post_multipart(host, selector, fields, files)
except Exception as e:
print(e)
self.__set_error__("could not connect to server")
return False
if status != 200:
try:
err = json.loads(response)
except:
self.__set_error__("%u:%s" % (status, reason))
return False
self.__set_error__("%s:%s" % (err['code'], reason))
return False
return json.loads(response)
# access to sent resource
def status(self, page=1, count=20, s_rcpt=None, s_start=None, s_end=None, mid=None):
params = dict()
if page:
params['page'] = page
if count:
params['count'] = count
if s_rcpt:
params['s_rcpt'] = s_rcpt
if s_start:
params['s_start'] = s_start
if s_end:
params['s_end'] = s_end
if mid:
params['mid'] = mid
response, obj = self.request_get('sent', params)
return obj
# access to status resource
def line_status(self, count=1):
params = dict()
if count:
params['count'] = count
response, obj = self.request_get('status', params)
return obj
# access to balance resource
def balance(self):
response, obj = self.request_get('balance')
return int(obj['cash']), int(obj['point'])
# access to cancel resource
def cancel(self, mid=None, gid=None):
if mid is None and gid is None:
return False
params = dict()
if mid:
params['mid'] = mid
if gid:
params['gid'] = gid
response, obj = self.request_post('cancel', params)
if response.status == 200:
return True
return False
def request_get(self, resource, params=None):
timestamp, salt, signature = self.__get_signature__()
base_params = {'api_key': self.api_key, 'timestamp': timestamp,
'salt': salt, 'signature': signature.hexdigest()}
if params:
base_params.update(params.items())
params_str = urlencode(base_params)
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain",
"User-Agent": "sms-python"}
conn = HTTPSConnection(self.host, self.port)
conn.request("GET", "/sms/%s/%s?" % (self.api_version, resource) + params_str, None, headers)
response = conn.getresponse()
data = response.read()
conn.close()
obj = response, json.loads(data)
return obj
def request_post(self, resource, params=None):
timestamp, salt, signature = self.__get_signature__()
base_params = {'api_key': self.api_key, 'timestamp': timestamp, 'salt': salt,
'signature': signature.hexdigest()}
if params:
base_params.update(params)
params_str = urlencode(base_params)
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain",
"User-Agent": "sms-python"}
conn = HTTPSConnection(self.host, self.port)
conn.request("POST", "/sms/%s/%s" % (self.api_version, resource), params_str, headers)
response = conn.getresponse()
data = response.read()
conn.close()
json_obj = None
if data:
json_obj = json.loads(data)
return response, json_obj