├── .gitignore ├── LICENSE ├── MANIFEST.in ├── README ├── README.md ├── docs ├── httpclient.m.html ├── index.html ├── sms.m.html ├── util.m.html └── voice.m.html ├── gendoc.py ├── qcloudsms_py ├── __init__.py ├── httpclient.py ├── sms.py ├── util.py └── voice.py └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *.pyo 3 | *.so 4 | *.class 5 | *~ 6 | *.egg-info/ 7 | build/ 8 | dist/ 9 | test.py 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 qcloudsms 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | recursive-include qcloudsms_py *.py 2 | recursive-include docs * 3 | prune docs/build 4 | include LICENSE 5 | include README 6 | include gendoc.py -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | 腾讯云短信 Python SDK 2 | === 3 | 4 | ## 腾讯短信服务 5 | 6 | 目前`腾讯云短信`为客户提供`国内短信`、`国内语音`和`海外短信`三大服务,腾讯云短信SDK支持以下操作: 7 | 8 | ### 国内短信 9 | 10 | 国内短信支持操作: 11 | 12 | - 指定模板单发短信 13 | - 指定模板群发短信 14 | - 拉取短信回执和短信回复状态 15 | 16 | > `Note` 短信拉取功能需要联系腾讯云短信技术支持(QQ:3012203387)开通权限,量大客户可以使用此功能批量拉取,其他客户不建议使用。 17 | 18 | ### 海外短信 19 | 20 | 海外短信支持操作: 21 | 22 | - 指定模板单发短信 23 | - 指定模板群发短信 24 | - 拉取短信回执和短信回复状态 25 | 26 | > `Note` 海外短信和国内短信使用同一接口,只需替换相应的国家码与手机号码,每次请求群发接口手机号码需全部为国内或者海外手机号码。 27 | 28 | ### 语音通知 29 | 30 | 语音通知支持操作: 31 | 32 | - 发送语音验证码 33 | - 发送语音通知 34 | - 上传语音文件 35 | - 按语音文件fid发送语音通知 36 | - 指定模板发送语音通知类 37 | 38 | ## 开发 39 | 40 | ### 准备 41 | 42 | 在开始开发云短信应用之前,需要准备如下信息: 43 | 44 | - [x] 获取SDK AppID和AppKey 45 | 46 | 云短信应用SDK `AppID`和`AppKey`可在[短信控制台](https://console.cloud.tencent.com/sms)的应用信息里获取,如您尚未添加应用,请到[短信控制台](https://console.cloud.tencent.com/sms)中添加应用。 47 | 48 | - [x] 申请签名 49 | 50 | 一个完整的短信由短信`签名`和短信正文内容两部分组成,短信`签名`须申请和审核,`签名`可在[短信控制台](https://console.cloud.tencent.com/sms)的相应服务模块`内容配置`中进行申请。 51 | 52 | - [x] 申请模板 53 | 54 | 同样短信或语音正文内容`模板`须申请和审核,`模板`可在[短信控制台](https://console.cloud.tencent.com/sms)的相应服务模块`内容配置`中进行申请。 55 | 56 | ### 安装 57 | 58 | #### pip 59 | 60 | qcloudsms_py采用pip进行安装,要使用qcloudsms功能, 只需要执行: 61 | 62 | ```shell 63 | pip install qcloudsms_py 64 | ``` 65 | 66 | #### 手动 67 | 68 | 1. 手动下载或clone最新版本qcloudsms_py代码 69 | 2. 在qcloudsms_py目录运行 `python setup.py install`或直接把qcloudsms_py所在目录加入`sys.path` 70 | 71 | > `Note` python2/python3都支持 72 | 73 | ### 文档 74 | 75 | 若您对接口存在疑问,可以查阅: 76 | 77 | * [API开发指南](https://cloud.tencent.com/document/product/382/5808) 78 | * [SDK文档](https://qcloudsms.github.io/qcloudsms_py/) 79 | * [错误码](https://cloud.tencent.com/document/product/382/3771) 80 | 81 | ### 示例 82 | 83 | - **准备必要参数** 84 | 85 | ```python 86 | # 短信应用SDK AppID 87 | appid = 1400009099 # SDK AppID是1400开头 88 | 89 | # 短信应用SDK AppKey 90 | appkey = "9ff91d87c2cd7cd0ea762f141975d1df37481d48700d70ac37470aefc60f9bad" 91 | 92 | # 需要发送短信的手机号码 93 | phone_numbers = ["21212313123", "12345678902", "12345678903"] 94 | 95 | # 短信模板ID,需要在短信应用中申请 96 | template_id = 7839 # NOTE: 这里的模板ID`7839`只是一个示例,真实的模板ID需要在短信控制台中申请 97 | 98 | # 签名 99 | sms_sign = "腾讯云" # NOTE: 这里的签名"腾讯云"只是一个示例,真实的签名需要在短信控制台中申请,另外签名参数使用的是`签名内容`,而不是`签名ID` 100 | ``` 101 | 102 | - **指定模板ID单发短信** 103 | 104 | ```python 105 | from qcloudsms_py import SmsSingleSender 106 | from qcloudsms_py.httpclient import HTTPError 107 | 108 | ssender = SmsSingleSender(appid, appkey) 109 | params = ["5678"] # 当模板没有参数时,`params = []` 110 | try: 111 | result = ssender.send_with_param(86, phone_numbers[0], 112 | template_id, params, sign=sms_sign, extend="", ext="") # 签名参数不允许为空串 113 | except HTTPError as e: 114 | print(e) 115 | except Exception as e: 116 | print(e) 117 | 118 | print(result) 119 | ``` 120 | 121 | > `Note` 无论单发/群发短信还是指定模板ID单发/群发短信都需要从控制台中申请模板并且模板已经审核通过,才可能下发成功,否则返回失败。 122 | 123 | - **指定模板ID群发** 124 | 125 | ```python 126 | from qcloudsms_py import SmsMultiSender 127 | from qcloudsms_py.httpclient import HTTPError 128 | 129 | msender = SmsMultiSender(appid, appkey) 130 | params = ["5678"] 131 | try: 132 | result = msender.send_with_param(86, phone_numbers, 133 | template_id, params, sign=sms_sign, extend="", ext="") # 签名参数不允许为空串 134 | except HTTPError as e: 135 | print(e) 136 | except Exception as e: 137 | print(e) 138 | 139 | print(result) 140 | ``` 141 | 142 | > `Note:`群发一次请求最多支持200个号码,如有对号码数量有特殊需求请联系腾讯云短信技术支持(QQ:3012203387)。 143 | > `Note` 无论单发/群发短信还是指定模板ID单发/群发短信都需要从控制台中申请模板并且模板已经审核通过,才可能下发成功,否则返回失败。 144 | 145 | - **发送语音验证码** 146 | 147 | ```python 148 | from qcloudsms_py import SmsVoiceVerifyCodeSender 149 | from qcloudsms_py.httpclient import HTTPError 150 | 151 | vvcsender = SmsVoiceVerifyCodeSender(appid, appkey) 152 | try: 153 | result = vvcsender.send("86", phone_numbers[0], "5678", 154 | playtimes=2, ext="") 155 | except HTTPError as e: 156 | print(e) 157 | except Exception as e: 158 | print(e) 159 | 160 | print(result) 161 | ``` 162 | 163 | > `Note` 语音验证码发送只需提供验证码数字,例如当msg=“5678”时,您收到的语音通知为“您的语音验证码是5678”,如需自定义内容,可以使用语音通知。 164 | 165 | 166 | - **发送语音通知** 167 | 168 | ```python 169 | from qcloudsms_py import SmsVoicePromptSender 170 | from qcloudsms_py.httpclient import HTTPError 171 | 172 | vpsender = SmsVoicePromptSender(appid, appkey) 173 | try: 174 | result = vpsender.send("86", phone_numbers[0], 2, "5678", 175 | playtimes=2, ext="") 176 | except HTTPError as e: 177 | print(e) 178 | except Exception as e: 179 | print(e) 180 | 181 | print(result) 182 | ``` 183 | 184 | - **拉取短信回执以及回复** 185 | 186 | ```python 187 | from qcloudsms_py import SmsStatusPuller 188 | from qcloudsms_py.httpclient import HTTPError 189 | 190 | max_num = 10 # 单次拉取最大量 191 | spuller = SmsStatusPuller(appid, appkey) 192 | try: 193 | # 拉取短信回执 194 | callback_result = spuller.pull_callback(max_num) 195 | # 拉取回复 196 | reply_result = spuller.pull_reply(max_num) 197 | except HTTPError as e: 198 | print(e) 199 | except Exception as e: 200 | print(e) 201 | 202 | print(callback_result) 203 | print(reply_result) 204 | ``` 205 | 206 | > `Note:` 短信拉取功能需要联系腾讯云短信技术支持(QQ:3012203387),量大客户可以使用此功能批量拉取,其他客户不建议使用。 207 | 208 | - **拉取单个手机短信状态** 209 | 210 | ```python 211 | from qcloudsms_py import SmsMobileStatusPuller 212 | from qcloudsms_py.httpclient import HTTPError 213 | 214 | begin_time = 1511125600 # 开始时间(unix timestamp) 215 | end_time = 1511841600 # 结束时间(unix timestamp) 216 | max_num = 10 # 单次拉取最大量 217 | mspuller = SmsMobileStatusPuller(appid, appkey) 218 | try: 219 | # 拉取短信回执 220 | callback_result = mspuller.pull_callback("86", phone_numbers[0], 221 | begin_time, end_time, max_num) 222 | # 拉取回复 223 | reply_result = mspuller.pull_reply("86", phone_numbers[0], 224 | begin_time, end_time, max_num) 225 | except HTTPError as e: 226 | print(e) 227 | except Exception as e: 228 | print(e) 229 | 230 | print(callback_result) 231 | print(reply_result) 232 | ``` 233 | 234 | > `Note:` 短信拉取功能需要联系腾讯云短信技术支持(QQ:3012203387),量大客户可以使用此功能批量拉取,其他客户不建议使用。 235 | 236 | - **发送海外短信** 237 | 238 | 海外短信与国内短信发送类似, 发送海外短信只需替换相应国家码。 239 | 240 | 241 | - **上传语音文件** 242 | 243 | ```python 244 | from qcloudsms_py import VoiceFileUploader 245 | from qcloudsms_py.httpclient import HTTPError 246 | 247 | # Note: 语音文件大小上传限制400K字节 248 | with open("/path/to/example.mp3", "rb") as f: 249 | content = f.read() 250 | uploader = VoiceFileUploader(appid, appkey) 251 | try: 252 | result = uploader.upload(content, content_type="mp3") 253 | except HTTPError as e: 254 | print(e) 255 | except Exception as e: 256 | print(e) 257 | 258 | # 上传成功后,result里会带有语音文件的fid 259 | print(result) 260 | ``` 261 | 262 | > `Note` '语音文件上传'功能需要联系腾讯云短信技术支持(QQ:3012203387)才能开通 263 | 264 | - **按语音文件fid发送语音通知** 265 | 266 | ```python 267 | from qcloudsms_py import FileVoiceSender 268 | from qcloudsms_py.httpclient import HTTPError 269 | 270 | # Note:这里fid来自`上传语音文件`接口返回的响应,要按语音 271 | # 文件fid发送语音通知,需要先上传语音文件获取fid 272 | fid = "c799d10a43ec109f02f2288ca3c85b79e7700c98.mp3" 273 | fvsender = FileVoiceSender(appid, appkey) 274 | try: 275 | result = fvsender.send(fid, phone_numbers[0], 276 | nationcode="86", playtimes=2, ext="") 277 | except HTTPError as e: 278 | print(e) 279 | except Exception as e: 280 | print(e) 281 | 282 | print(result) 283 | ``` 284 | 285 | > `Note` 按'语音文件fid发送语音通知'功能需要联系腾讯云短信技术支持(QQ:3012203387)才能开通 286 | 287 | - **指定模板发送语音通知** 288 | 289 | ```python 290 | from qcloudsms_py import TtsVoiceSender 291 | from qcloudsms_py.httpclient import HTTPError 292 | 293 | template_id = 12345 294 | params = ["5678"] 295 | tvsender = TtsVoiceSender(appid, appkey) 296 | Try: 297 | result = tvsender.send(template_id, params, phone_numbers[0], 298 | nationcode="86", playtimes=2, ext="") 299 | except HTTPError as e: 300 | print(e) 301 | except Exception as e: 302 | print(e) 303 | 304 | print(result) 305 | ``` 306 | 307 | #### 使用代理 308 | 309 | 有的环境需要使用代理才能上网,可以指定HTTPSimpleClient的proxy参数来实现, 示例如下: 310 | 311 | ```python 312 | from qcloudsms_py import SmsSingleSender 313 | from qcloudsms_py.httpclient import HTTPSimpleClient, HTTPError 314 | 315 | httpclient = HTTPSimpleClient(proxy="www.proxysever.com:8080") 316 | ssender = SmsSingleSender(appid, appkey, httpclient=httpclient) 317 | template_id = 7839 318 | params = ["5678"] 319 | try: 320 | result = ssender.send_with_param(86, phone_numbers[0], 321 | template_id, params, sign=sms_sign, extend="", ext="") 322 | except HTTPError as e: 323 | print(e) 324 | except Exception as e: 325 | print(e) 326 | 327 | print(result) 328 | ``` 329 | 330 | #### 统一创建对象 331 | 332 | 短信和语音各类的对象可以通过 `qcloudsms_py.QcloudSms` 统一创建,这种 333 | 方式可以避免创建对象时多次传入参数`appid` 和 `appkey`, 示例如下: 334 | 335 | ```python 336 | from qcloudsms_py import QcloudSms 337 | 338 | # 创建QcloudSms对象 339 | qcloudsms = QcloudSms(appid, appkey) 340 | 341 | # 创建单发短信(SmsSingleSender)对象 342 | ssender = qcloudsms.SmsSingleSender() 343 | 344 | # 创建上传语音文件(VoiceFileUploader)对象 345 | uploader = qcloudsms.VoiceFileUploader() 346 | ``` 347 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | README -------------------------------------------------------------------------------- /docs/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | qcloudsms_py API documentation 7 | 8 | 9 | 10 | 11 | 551 | 552 | 853 | 854 | 925 | 926 | 1018 | 1019 | 1033 | 1034 | 1035 | Top 1036 | 1037 |
1038 | 1039 | 1040 | 1078 | 1079 |
1080 | 1081 | 1082 | 1083 | 1084 | 1085 | 1086 |
1087 |

qcloudsms_py module

1088 | 1089 | 1090 | 1091 |
1092 |
#!/usr/bin/env python
1093 | # -*- coding: utf-8 -*-
1094 | from __future__ import absolute_import, division, print_function
1095 | 
1096 | from qcloudsms_py import sms
1097 | from qcloudsms_py import voice
1098 | from qcloudsms_py import httpclient
1099 | from qcloudsms_py.sms import *
1100 | from qcloudsms_py.voice import *
1101 | 
1102 | 
1103 | # human-readable version number
1104 | version = "0.1.3"
1105 | 
1106 | # three-tuple for programmatic comparison
1107 | version_info = (0, 1, 3)
1108 | 
1109 | 
1110 | class QcloudSms(object):
1111 | 
1112 |     SMS_CLASSES = set([cls for cls in sms.__all__])
1113 |     VOICE_CLASSESS = set([cls for cls in voice.__all__])
1114 | 
1115 |     def __init__(self, appid, appkey, httpclient=None):
1116 |         self._appid = appid
1117 |         self._appkey = appkey
1118 |         self._httpclient = httpclient
1119 |         self._cache = {}
1120 | 
1121 |     def __getattr__(self, name):
1122 |         if (name not in self.__class__.SMS_CLASSES and
1123 |                 name not in self.__class__.VOICE_CLASSESS):
1124 |             raise AttributeError("{} is not in {}".format(
1125 |                 name, self.__class__.__name__))
1126 |         if name in self._cache:
1127 |             return lambda: self._cache[name]
1128 | 
1129 |         if name in self.__class__.SMS_CLASSES:
1130 |             cls = getattr(sms, name)
1131 |         else:
1132 |             cls = getattr(voice, name)
1133 |         self._cache[name] = obj = cls(
1134 |             self._appid, self._appkey, self._httpclient
1135 |         )
1136 |         return lambda: obj
1137 | 
1138 |     def new(self, name):
1139 |         if (name not in self.__class__.SMS_CLASSES and
1140 |                 name not in self.__class__.VOICE_CLASSESS):
1141 |             raise AttributeError("{} is not in {}".format(
1142 |                 name, self.__class__.__name__))
1143 |         if name in self.__class__.SMS_CLASSES:
1144 |             return getattr(sms, name)(
1145 |                 self._appid, self._appkey, self._httpclient
1146 |             )
1147 |         else:
1148 |             return getattr(voice, name)(
1149 |                 self._appid, self._appkey, self._httpclient
1150 |             )
1151 | 
1152 | 1153 |
1154 | 1155 |
1156 | 1157 |
1158 |

Module variables

1159 |
1160 |

var version

1161 | 1162 | 1163 |
1164 |
1165 | 1166 |
1167 |
1168 |

var version_info

1169 | 1170 | 1171 |
1172 |
1173 | 1174 |
1175 | 1176 | 1177 |

Classes

1178 | 1179 |
1180 |

class QcloudSms

1181 | 1182 | 1183 |
1184 | 1185 |
1186 |
class QcloudSms(object):
1187 | 
1188 |     SMS_CLASSES = set([cls for cls in sms.__all__])
1189 |     VOICE_CLASSESS = set([cls for cls in voice.__all__])
1190 | 
1191 |     def __init__(self, appid, appkey, httpclient=None):
1192 |         self._appid = appid
1193 |         self._appkey = appkey
1194 |         self._httpclient = httpclient
1195 |         self._cache = {}
1196 | 
1197 |     def __getattr__(self, name):
1198 |         if (name not in self.__class__.SMS_CLASSES and
1199 |                 name not in self.__class__.VOICE_CLASSESS):
1200 |             raise AttributeError("{} is not in {}".format(
1201 |                 name, self.__class__.__name__))
1202 |         if name in self._cache:
1203 |             return lambda: self._cache[name]
1204 | 
1205 |         if name in self.__class__.SMS_CLASSES:
1206 |             cls = getattr(sms, name)
1207 |         else:
1208 |             cls = getattr(voice, name)
1209 |         self._cache[name] = obj = cls(
1210 |             self._appid, self._appkey, self._httpclient
1211 |         )
1212 |         return lambda: obj
1213 | 
1214 |     def new(self, name):
1215 |         if (name not in self.__class__.SMS_CLASSES and
1216 |                 name not in self.__class__.VOICE_CLASSESS):
1217 |             raise AttributeError("{} is not in {}".format(
1218 |                 name, self.__class__.__name__))
1219 |         if name in self.__class__.SMS_CLASSES:
1220 |             return getattr(sms, name)(
1221 |                 self._appid, self._appkey, self._httpclient
1222 |             )
1223 |         else:
1224 |             return getattr(voice, name)(
1225 |                 self._appid, self._appkey, self._httpclient
1226 |             )
1227 | 
1228 | 1229 |
1230 |
1231 | 1232 | 1233 |
1234 |

Ancestors (in MRO)

1235 | 1239 |

Class variables

1240 |
1241 |

var SMS_CLASSES

1242 | 1243 | 1244 | 1245 | 1246 |
1247 |
1248 | 1249 |
1250 |
1251 |

var VOICE_CLASSESS

1252 | 1253 | 1254 | 1255 | 1256 |
1257 |
1258 | 1259 |
1260 |
1261 |

var cls

1262 | 1263 | 1264 | 1265 | 1266 |
1267 |
1268 | 1269 |
1270 |

Methods

1271 | 1272 |
1273 |
1274 |

def __init__(

self, appid, appkey, httpclient=None)

1275 |
1276 | 1277 | 1278 | 1279 | 1280 |
1281 | 1282 |
1283 |
def __init__(self, appid, appkey, httpclient=None):
1284 |     self._appid = appid
1285 |     self._appkey = appkey
1286 |     self._httpclient = httpclient
1287 |     self._cache = {}
1288 | 
1289 | 1290 |
1291 |
1292 | 1293 |
1294 | 1295 | 1296 |
1297 |
1298 |

def new(

self, name)

1299 |
1300 | 1301 | 1302 | 1303 | 1304 |
1305 | 1306 |
1307 |
def new(self, name):
1308 |     if (name not in self.__class__.SMS_CLASSES and
1309 |             name not in self.__class__.VOICE_CLASSESS):
1310 |         raise AttributeError("{} is not in {}".format(
1311 |             name, self.__class__.__name__))
1312 |     if name in self.__class__.SMS_CLASSES:
1313 |         return getattr(sms, name)(
1314 |             self._appid, self._appkey, self._httpclient
1315 |         )
1316 |     else:
1317 |         return getattr(voice, name)(
1318 |             self._appid, self._appkey, self._httpclient
1319 |         )
1320 | 
1321 | 1322 |
1323 |
1324 | 1325 |
1326 | 1327 |
1328 |
1329 | 1330 |

Sub-modules

1331 |
1332 |

qcloudsms_py.httpclient

1333 | 1334 | 1335 | 1336 |
1337 |
1338 |

qcloudsms_py.sms

1339 | 1340 | 1341 | 1342 |
1343 |
1344 |

qcloudsms_py.util

1345 | 1346 | 1347 | 1348 |
1349 |
1350 |

qcloudsms_py.voice

1351 | 1352 | 1353 | 1354 |
1355 |
1356 | 1357 |
1358 |
1359 | 1370 |
1371 | 1372 | -------------------------------------------------------------------------------- /docs/util.m.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | qcloudsms_py.util API documentation 7 | 8 | 9 | 10 | 11 | 551 | 552 | 853 | 854 | 925 | 926 | 1018 | 1019 | 1033 | 1034 | 1035 | Top 1036 | 1037 |
1038 | 1039 | 1040 | 1060 | 1061 |
1062 | 1063 | 1064 | 1065 | 1066 | 1067 | 1068 |
1069 |

qcloudsms_py.util module

1070 | 1071 | 1072 | 1073 |
1074 |
#!/usr/bin/env python
1075 | # -*- coding: utf-8 -*-
1076 | 
1077 | from __future__ import absolute_import, division, print_function
1078 | 
1079 | import random
1080 | import time
1081 | import hashlib
1082 | import json
1083 | 
1084 | from qcloudsms_py.httpclient import HTTPError, HTTPSimpleClient, utf8
1085 | 
1086 | 
1087 | def get_random():
1088 |     """Get a random number"""
1089 |     return random.randint(100000, 999999)
1090 | 
1091 | 
1092 | def get_current_time():
1093 |     """Get current time"""
1094 |     return int(time.time())
1095 | 
1096 | 
1097 | def calculate_signature(appkey, rand, time, phone_numbers=None):
1098 |     """Calculate a request signature according to parameters.
1099 | 
1100 |     :param appkey: sdk appkey
1101 |     :param random: random string
1102 |     :param time: unix timestamp time
1103 |     :param phone_numbers: phone number array
1104 |     """
1105 |     raw_text = "appkey={}&random={}&time={}".format(appkey, rand, time)
1106 |     if phone_numbers:
1107 |         raw_text += "&mobile={}".format(
1108 |             ",".join(map(str, phone_numbers)))
1109 |     return hashlib.sha256(utf8(raw_text)).hexdigest()
1110 | 
1111 | 
1112 | def calculate_auth(appkey, rand, time, file_sha1sum):
1113 |     """Calculate a auth signature for uploading voice file.
1114 | 
1115 |     :param appkey: sdk appkey
1116 |     :param random: random string
1117 |     :param time: unix timestamp time
1118 |     :param file_sha1sum: voice file sha1 sum
1119 |     """
1120 |     raw_text = "appkey={}&random={}&time={}&content-sha1={}".format(
1121 |         appkey, rand, time, file_sha1sum
1122 |     )
1123 |     return hashlib.sha256(utf8(raw_text)).hexdigest()
1124 | 
1125 | 
1126 | def sha1sum(content):
1127 |     return hashlib.sha1(utf8(content)).hexdigest()
1128 | 
1129 | 
1130 | _http_simple_client = HTTPSimpleClient()
1131 | 
1132 | 
1133 | def api_request(req, httpclient=None):
1134 |     """Make a API request and return response.
1135 | 
1136 |     :param req: `qcloudsms_py.httpclient.HTTPRequest` instance
1137 |     :param httpclient: `qcloudsms_py.httpclient.HTTPClientInterface` instance
1138 |     """
1139 |     if httpclient:
1140 |         res = httpclient.fetch(req)
1141 |     else:
1142 |         res = _http_simple_client.fetch(req)
1143 |     if not res.ok():
1144 |         raise HTTPError(res.code, res.reason)
1145 |     return res.json()
1146 | 
1147 | 1148 |
1149 | 1150 |
1151 | 1152 |
1153 | 1154 |

Functions

1155 | 1156 |
1157 |
1158 |

def api_request(

req, httpclient=None)

1159 |
1160 | 1161 | 1162 | 1163 | 1164 |

Make a API request and return response.

1165 |

:param req: qcloudsms_py.httpclient.HTTPRequest instance 1166 | :param httpclient: qcloudsms_py.httpclient.HTTPClientInterface instance

1167 |
1168 | 1169 |
1170 |
def api_request(req, httpclient=None):
1171 |     """Make a API request and return response.
1172 | 
1173 |     :param req: `qcloudsms_py.httpclient.HTTPRequest` instance
1174 |     :param httpclient: `qcloudsms_py.httpclient.HTTPClientInterface` instance
1175 |     """
1176 |     if httpclient:
1177 |         res = httpclient.fetch(req)
1178 |     else:
1179 |         res = _http_simple_client.fetch(req)
1180 |     if not res.ok():
1181 |         raise HTTPError(res.code, res.reason)
1182 |     return res.json()
1183 | 
1184 | 1185 |
1186 |
1187 | 1188 |
1189 | 1190 | 1191 |
1192 |
1193 |

def calculate_auth(

appkey, rand, time, file_sha1sum)

1194 |
1195 | 1196 | 1197 | 1198 | 1199 |

Calculate a auth signature for uploading voice file.

1200 |

:param appkey: sdk appkey 1201 | :param random: random string 1202 | :param time: unix timestamp time 1203 | :param file_sha1sum: voice file sha1 sum

1204 |
1205 | 1206 |
1207 |
def calculate_auth(appkey, rand, time, file_sha1sum):
1208 |     """Calculate a auth signature for uploading voice file.
1209 | 
1210 |     :param appkey: sdk appkey
1211 |     :param random: random string
1212 |     :param time: unix timestamp time
1213 |     :param file_sha1sum: voice file sha1 sum
1214 |     """
1215 |     raw_text = "appkey={}&random={}&time={}&content-sha1={}".format(
1216 |         appkey, rand, time, file_sha1sum
1217 |     )
1218 |     return hashlib.sha256(utf8(raw_text)).hexdigest()
1219 | 
1220 | 1221 |
1222 |
1223 | 1224 |
1225 | 1226 | 1227 |
1228 |
1229 |

def calculate_signature(

appkey, rand, time, phone_numbers=None)

1230 |
1231 | 1232 | 1233 | 1234 | 1235 |

Calculate a request signature according to parameters.

1236 |

:param appkey: sdk appkey 1237 | :param random: random string 1238 | :param time: unix timestamp time 1239 | :param phone_numbers: phone number array

1240 |
1241 | 1242 |
1243 |
def calculate_signature(appkey, rand, time, phone_numbers=None):
1244 |     """Calculate a request signature according to parameters.
1245 | 
1246 |     :param appkey: sdk appkey
1247 |     :param random: random string
1248 |     :param time: unix timestamp time
1249 |     :param phone_numbers: phone number array
1250 |     """
1251 |     raw_text = "appkey={}&random={}&time={}".format(appkey, rand, time)
1252 |     if phone_numbers:
1253 |         raw_text += "&mobile={}".format(
1254 |             ",".join(map(str, phone_numbers)))
1255 |     return hashlib.sha256(utf8(raw_text)).hexdigest()
1256 | 
1257 | 1258 |
1259 |
1260 | 1261 |
1262 | 1263 | 1264 |
1265 |
1266 |

def get_current_time(

)

1267 |
1268 | 1269 | 1270 | 1271 | 1272 |

Get current time

1273 |
1274 | 1275 |
1276 |
def get_current_time():
1277 |     """Get current time"""
1278 |     return int(time.time())
1279 | 
1280 | 1281 |
1282 |
1283 | 1284 |
1285 | 1286 | 1287 |
1288 |
1289 |

def get_random(

)

1290 |
1291 | 1292 | 1293 | 1294 | 1295 |

Get a random number

1296 |
1297 | 1298 |
1299 |
def get_random():
1300 |     """Get a random number"""
1301 |     return random.randint(100000, 999999)
1302 | 
1303 | 1304 |
1305 |
1306 | 1307 |
1308 | 1309 | 1310 |
1311 |
1312 |

def sha1sum(

content)

1313 |
1314 | 1315 | 1316 | 1317 | 1318 |
1319 | 1320 |
1321 |
def sha1sum(content):
1322 |     return hashlib.sha1(utf8(content)).hexdigest()
1323 | 
1324 | 1325 |
1326 |
1327 | 1328 |
1329 | 1330 | 1331 | 1332 |
1333 | 1334 |
1335 |
1336 | 1347 |
1348 | 1349 | -------------------------------------------------------------------------------- /gendoc.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | import pdoc 4 | import sys 5 | 6 | 7 | PROJECT_PATH = "." 8 | DOCS_PATH = "./docs/" 9 | PACKAGE_NAME = "qcloudsms_py" 10 | 11 | 12 | def gen_module_doc(module, path): 13 | text = module.html(external_links=True) 14 | with open(path + "index.html", "w") as f: 15 | f.write(text.encode("utf-8")) 16 | # submodules 17 | for submodule in module.submodules(): 18 | name = submodule.name[submodule.name.rindex(".") + 1: ] 19 | if submodule.is_package(): 20 | path += "{}/".format(name) 21 | gen_module_doc(path, submodule) 22 | else: 23 | text = submodule.html(external_links=True) 24 | with open(path + name + ".m.html", "w") as f: 25 | f.write(text.encode("utf-8")) 26 | 27 | 28 | if __name__ == "__main__": 29 | sys.path.append(PROJECT_PATH) 30 | pdoc.import_path.append(PROJECT_PATH) 31 | package = pdoc.Module(pdoc.import_module(PACKAGE_NAME), 32 | allsubmodules=True) 33 | gen_module_doc(package, DOCS_PATH) 34 | -------------------------------------------------------------------------------- /qcloudsms_py/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from __future__ import absolute_import, division, print_function 4 | 5 | from qcloudsms_py import sms 6 | from qcloudsms_py import voice 7 | from qcloudsms_py import httpclient 8 | from qcloudsms_py.sms import * 9 | from qcloudsms_py.voice import * 10 | 11 | 12 | # human-readable version number 13 | version = "0.1.3" 14 | 15 | # three-tuple for programmatic comparison 16 | version_info = (0, 1, 3) 17 | 18 | 19 | class QcloudSms(object): 20 | 21 | SMS_CLASSES = set([cls for cls in sms.__all__]) 22 | VOICE_CLASSESS = set([cls for cls in voice.__all__]) 23 | 24 | def __init__(self, appid, appkey, httpclient=None): 25 | self._appid = appid 26 | self._appkey = appkey 27 | self._httpclient = httpclient 28 | self._cache = {} 29 | 30 | def __getattr__(self, name): 31 | if (name not in self.__class__.SMS_CLASSES and 32 | name not in self.__class__.VOICE_CLASSESS): 33 | raise AttributeError("{} is not in {}".format( 34 | name, self.__class__.__name__)) 35 | if name in self._cache: 36 | return lambda: self._cache[name] 37 | 38 | if name in self.__class__.SMS_CLASSES: 39 | cls = getattr(sms, name) 40 | else: 41 | cls = getattr(voice, name) 42 | self._cache[name] = obj = cls( 43 | self._appid, self._appkey, self._httpclient 44 | ) 45 | return lambda: obj 46 | 47 | def new(self, name): 48 | if (name not in self.__class__.SMS_CLASSES and 49 | name not in self.__class__.VOICE_CLASSESS): 50 | raise AttributeError("{} is not in {}".format( 51 | name, self.__class__.__name__)) 52 | if name in self.__class__.SMS_CLASSES: 53 | return getattr(sms, name)( 54 | self._appid, self._appkey, self._httpclient 55 | ) 56 | else: 57 | return getattr(voice, name)( 58 | self._appid, self._appkey, self._httpclient 59 | ) 60 | -------------------------------------------------------------------------------- /qcloudsms_py/httpclient.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | from __future__ import absolute_import, division, print_function 5 | 6 | import re 7 | import json 8 | import sys 9 | import socket 10 | 11 | if sys.version_info >= (3,): 12 | from http import client as httplib 13 | from urllib import parse as urlparse 14 | else: 15 | import httplib 16 | import urlparse 17 | 18 | 19 | class HTTPRequest(object): 20 | 21 | def __init__(self, url, method="GET", headers=None, body=None): 22 | """ 23 | :param url: HTTP request URL. 24 | :param method: (optiona) HTTP method. 25 | :param headers: (optional) Dictionary for HTTP request headers. 26 | :param body: (optional) Dictionary for HTTP request body. 27 | :param connect_timeout: (optional) HTTP connection timeout. 28 | :param request_timeout: (optional) HTTP request timeout. 29 | """ 30 | self.url = url 31 | self.method = method 32 | self.headers = headers 33 | self.body = body 34 | 35 | 36 | class HTTPResponse(object): 37 | 38 | def __init__(self, request, code, body, 39 | headers=None, reason=None): 40 | """ 41 | :param request: HTTPRequest instance. 42 | :param code: HTTP status code. 43 | :param body: Raw bytes of HTTP response body. 44 | :param headers: (optional) Dictionary for HTTP response headers. 45 | :param reason: (optional) HTTP status reason. 46 | """ 47 | self.request = request 48 | self.code = code 49 | self.body = body 50 | self.headers = headers 51 | self.reason = reason or httplib.responses.get(code, "Unknown") 52 | 53 | def ok(self): 54 | if self.code == 200 or self.code == "200": 55 | return True 56 | return False 57 | 58 | def json(self): 59 | if sys.version_info >= (3, ) and sys.version_info < (3, 6): 60 | return json.loads(self.body.decode("utf-8"), 61 | encoding="utf=8") 62 | return json.loads(self.body, encoding="utf-8") 63 | 64 | 65 | class HTTPError(Exception): 66 | 67 | def __init__(self, code, reason=None): 68 | self.code = code 69 | self.reason = reason or httplib.responses.get(code, "Unknown") 70 | super(HTTPError, self).__init__(code, reason) 71 | 72 | def __str__(self): 73 | return "HTTP {}: {}".format(self.code, self.reason) 74 | __repr__ = __str__ 75 | 76 | 77 | if sys.version_info >= (3,): 78 | unicode_type = str 79 | else: 80 | unicode_type = unicode 81 | 82 | 83 | def utf8(value): 84 | """Converts a string argument to a byte string. 85 | 86 | If the argument is already a byte string or None, it is returned 87 | unchanged. Otherwise it must be a unicode string and is encoded 88 | as utf8. 89 | 90 | NOTE: This method copy from https://github.com/tornadoweb/tornado and 91 | copyright belongs to the original author. 92 | """ 93 | if isinstance(value, (bytes, type(None))): 94 | return value 95 | if not isinstance(value, unicode_type): 96 | raise TypeError( 97 | "Expected bytes, unicode, or None; got %r" % type(value) 98 | ) 99 | return value.encode("utf-8") 100 | 101 | 102 | class HTTPClientInterface(object): 103 | 104 | def fetch(self, req): 105 | raise NotImplementedError 106 | 107 | 108 | class HTTPSimpleClient(HTTPClientInterface): 109 | 110 | PATTERN = "(?:http.*://)?(?P[^:/ ]+).?(?P[0-9]*).*" 111 | 112 | def __init__(self, connect_timeout=60, request_timeout=60, 113 | proxy=None): 114 | self._connect_timeout = connect_timeout 115 | self._request_timeout = request_timeout 116 | if isinstance(proxy, (list, tuple)): 117 | self._proxy = (proxy[0], int(proxy[1])) 118 | elif isinstance(proxy, (bytes, unicode_type)): 119 | result = re.search(self.__class__.PATTERN, proxy) 120 | if not result: 121 | raise ValueError("invalid proxy") 122 | self._proxy = ( 123 | result.group("host"), 124 | int(result.group("port")) if result.group("port") else 80 125 | ) 126 | elif proxy is None: 127 | self._proxy = None 128 | else: 129 | raise ValueError("invalid proxy") 130 | 131 | def fetch(self, req): 132 | result = urlparse.urlparse(req.url) 133 | if self._proxy: 134 | host, port = self._proxy 135 | else: 136 | host, port = (result.hostname, result.port) 137 | 138 | if result.scheme == "https": 139 | conn = httplib.HTTPSConnection( 140 | host, 141 | port=port, 142 | timeout=self._connect_timeout 143 | ) 144 | else: 145 | conn = httplib.HTTPConnection( 146 | host, 147 | port=port, 148 | timeout=self._connect_timeout 149 | ) 150 | 151 | if self._proxy: 152 | conn.set_tunnel(result.hostname, result.port) 153 | 154 | # Send request 155 | try: 156 | conn.request( 157 | req.method, 158 | "{}?{}".format(result.path, result.query), 159 | body=utf8(req.body), 160 | headers=req.headers 161 | ) 162 | response = conn.getresponse() 163 | res = HTTPResponse( 164 | request=req, 165 | code=response.status, 166 | body=response.read(), 167 | headers=dict(response.getheaders()), 168 | reason=response.reason 169 | ) 170 | except socket.gaierror: 171 | # client network error, raise 172 | raise 173 | except OSError: 174 | # client network error, raise 175 | raise 176 | finally: 177 | conn.close() 178 | return res 179 | -------------------------------------------------------------------------------- /qcloudsms_py/sms.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | from __future__ import absolute_import, division, print_function 5 | 6 | import json 7 | 8 | from qcloudsms_py import util 9 | from qcloudsms_py.httpclient import HTTPRequest 10 | 11 | 12 | __all__ = [ 13 | "SmsSingleSender", 14 | "SmsMultiSender", 15 | "SmsStatusPuller", 16 | "SmsMobileStatusPuller" 17 | ] 18 | 19 | 20 | class SmsSingleSender(object): 21 | 22 | def __init__(self, appid, appkey, httpclient=None): 23 | self._appid = appid 24 | self._appkey = appkey 25 | self._url = "https://yun.tim.qq.com/v5/tlssmssvr/sendsms" 26 | self._httpclient = httpclient 27 | 28 | def send(self, sms_type, nationcode, phone_number, msg, 29 | extend="", ext="", url=None): 30 | """Send single SMS message. 31 | 32 | :param msg_type: SMS message type, Enum{0: normal SMS, 1: marketing SMS} 33 | :param nationcode: nation dialing code, e.g. China is 86, USA is 1 34 | :param phone_number: phone number 35 | :param msg: SMS message content 36 | :param extend: extend field, default is empty string 37 | :param ext: ext field, content will be returned by server as it is 38 | :param url: custom url 39 | """ 40 | rand = util.get_random() 41 | now = util.get_current_time() 42 | url = "{}?sdkappid={}&random={}".format( 43 | url if url else self._url, self._appid, rand) 44 | req = HTTPRequest( 45 | url=url, 46 | method="POST", 47 | headers={"Content-Type": "application/json"}, 48 | body=json.dumps({ 49 | "tel": { 50 | "nationcode": str(nationcode), 51 | "mobile": str(phone_number) 52 | }, 53 | "type": int(sms_type), 54 | "msg": str(msg), 55 | "sig": util.calculate_signature( 56 | self._appkey, rand, now, [phone_number]), 57 | "time": now, 58 | "extend": str(extend), 59 | "ext": str(ext) 60 | }) 61 | ) 62 | return util.api_request(req, self._httpclient) 63 | 64 | def send_with_param(self, nationcode, phone_number, template_id, 65 | params, sign="", extend="", ext="", url=None): 66 | """Send single SMS message with template paramters. 67 | 68 | :param nationcode: nation dialing code, e.g. China is 86, USA is 1 69 | :param phone_number: phone number 70 | :param template_id: template id 71 | :param params: template parameters 72 | :param sign: Sms user sign 73 | :param extend: extend field, default is empty string 74 | :param ext: ext field, content will be returned by server as it is 75 | :param url: custom url 76 | """ 77 | rand = util.get_random() 78 | now = util.get_current_time() 79 | url = "{}?sdkappid={}&random={}".format( 80 | url if url else self._url, self._appid, rand) 81 | req = HTTPRequest( 82 | url=url, 83 | method="POST", 84 | headers={"Content-Type": "application/json"}, 85 | body=json.dumps({ 86 | "tel": { 87 | "nationcode": str(nationcode), 88 | "mobile": str(phone_number) 89 | }, 90 | "sign": str(sign), 91 | "tpl_id": int(template_id), 92 | "params": params, 93 | "sig": util.calculate_signature( 94 | self._appkey, rand, now, [phone_number]), 95 | "time": now, 96 | "extend": str(extend), 97 | "ext": str(ext) 98 | }) 99 | ) 100 | return util.api_request(req, self._httpclient) 101 | 102 | 103 | 104 | class SmsMultiSender(object): 105 | 106 | def __init__(self, appid, appkey, httpclient=None): 107 | self._appid = appid 108 | self._appkey = appkey 109 | self._url = "https://yun.tim.qq.com/v5/tlssmssvr/sendmultisms2" 110 | self._httpclient = httpclient 111 | 112 | def send(self, sms_type, nationcode, phone_numbers, msg, 113 | extend="", ext="", url=None): 114 | """Send a SMS messages to multiple phones at once. 115 | 116 | :param number: SMS message type, Enum{0: normal SMS, 1: marketing SMS} 117 | :param nationcode: nation dialing code, e.g. China is 86, USA is 1 118 | :param phone_numbers: phone number array 119 | :param msg: SMS message content 120 | :param extend: extend field, default is empty string 121 | :param ext: ext field, content will be returned by server as it is 122 | :param url: custom url 123 | """ 124 | rand = util.get_random() 125 | now = util.get_current_time() 126 | url = "{}?sdkappid={}&random={}".format( 127 | url if url else self._url, self._appid, rand) 128 | req = HTTPRequest( 129 | url=url, 130 | method="POST", 131 | headers={"Content-Type": "application/json"}, 132 | body=json.dumps({ 133 | "tel": [{"nationcode": nationcode, "mobile": pn} 134 | for pn in phone_numbers], 135 | "type": int(sms_type), 136 | "msg": str(msg), 137 | "sig": util.calculate_signature( 138 | self._appkey, rand, now, phone_numbers), 139 | "time": now, 140 | "extend": str(extend), 141 | "ext": str(ext) 142 | }) 143 | ) 144 | return util.api_request(req, self._httpclient) 145 | 146 | def send_with_param(self, nationcode, phone_numbers, template_id, 147 | params, sign="", extend="", ext="", url=None): 148 | """ 149 | Send a SMS messages with template parameters to multiple 150 | phones at once. 151 | 152 | :param nationcode: nation dialing code, e.g. China is 86, USA is 1 153 | :param phone_numbers: multiple phone numbers 154 | :param template_id: template id 155 | :param params: template parameters 156 | :param sign: Sms user sign 157 | :param extend: extend field, default is empty string 158 | :param ext: ext field, content will be returned by server as it is 159 | :param url: custom url 160 | """ 161 | rand = util.get_random() 162 | now = util.get_current_time() 163 | url = "{}?sdkappid={}&random={}".format( 164 | url if url else self._url, self._appid, rand) 165 | req = HTTPRequest( 166 | url=url, 167 | method="POST", 168 | headers={"Content-Type": "application/json"}, 169 | body=json.dumps({ 170 | "tel": [{"nationcode": nationcode, "mobile": pn} 171 | for pn in phone_numbers], 172 | "sign": sign, 173 | "tpl_id": int(template_id), 174 | "params": params, 175 | "sig": util.calculate_signature( 176 | self._appkey, rand, now, phone_numbers), 177 | "time": now, 178 | "extend": str(extend), 179 | "ext": str(ext) 180 | }) 181 | ) 182 | return util.api_request(req, self._httpclient) 183 | 184 | 185 | class SmsStatusPuller(object): 186 | 187 | def __init__(self, appid, appkey, httpclient=None): 188 | self._appid = appid 189 | self._appkey = appkey 190 | self._url = "https://yun.tim.qq.com/v5/tlssmssvr/pullstatus" 191 | self._httpclient = httpclient 192 | 193 | def _pull(self, sms_type, max_num, url=None): 194 | """Pull SMS message status. 195 | 196 | :param msg_type: SMS message type, Enum{0: normal SMS, 1: marketing SMS} 197 | :param max_num: maximum number of message status 198 | :param url: custom url 199 | """ 200 | rand = util.get_random() 201 | now = util.get_current_time() 202 | url = "{}?sdkappid={}&random={}".format( 203 | url if url else self._url, self._appid, rand) 204 | req = HTTPRequest( 205 | url=url, 206 | method="POST", 207 | headers={"Content-Type": "application/json"}, 208 | body=json.dumps({ 209 | "sig": util.calculate_signature( 210 | self._appkey, rand, now), 211 | "time": now, 212 | "type": sms_type, 213 | "max": max_num 214 | }) 215 | ) 216 | return util.api_request(req, self._httpclient) 217 | 218 | def pull_callback(self, max_num, url=None): 219 | """Pull callback SMS messages status. 220 | 221 | :param max_num: maximum number of message status 222 | :param url: custom url 223 | """ 224 | return self._pull(0, max_num, url) 225 | 226 | def pull_reply(self, max_num, url=None): 227 | """Pull reply SMS messages status. 228 | 229 | :param max_num: maximum number of message status 230 | :param url: custom url 231 | """ 232 | return self._pull(1, max_num, url) 233 | 234 | 235 | class SmsMobileStatusPuller(object): 236 | 237 | def __init__(self, appid, appkey, httpclient=None): 238 | self._appid = appid; 239 | self._appkey = appkey; 240 | self._url = "https://yun.tim.qq.com/v5/tlssmssvr/pullstatus4mobile" 241 | self._httpclient = httpclient 242 | 243 | def _pull(self, msg_type, nationcode, mobile, 244 | begin_time, end_time, max_num, url=None): 245 | """Pull SMS messages status for single mobile. 246 | 247 | :param msg_type: SMS message type, Enum{0: normal SMS, 1: marketing SMS} 248 | :param nationcode: nation dialing code, e.g. China is 86, USA is 1 249 | :param mobile: mobile number 250 | :param begin_time: begin time, unix timestamp 251 | :param end_time: end time, unix timestamp 252 | :param max_num: maximum number of message status 253 | :param url: custom url 254 | """ 255 | rand = util.get_random() 256 | now = util.get_current_time() 257 | url = "{}?sdkappid={}&random={}".format( 258 | url if url else self._url, self._appid, rand) 259 | req = HTTPRequest( 260 | url=url, 261 | method="POST", 262 | headers={"Content-Type": "application/json"}, 263 | body=json.dumps({ 264 | "sig": util.calculate_signature( 265 | self._appkey, rand, now), 266 | "type": msg_type, 267 | "time": now, 268 | "max": max_num, 269 | "begin_time": begin_time, 270 | "end_time": end_time, 271 | "nationcode": str(nationcode), 272 | "mobile": str(mobile) 273 | }) 274 | ) 275 | return util.api_request(req, self._httpclient) 276 | 277 | def pull_callback(self, nationcode, mobile, begin_time, 278 | end_time, max_num, url=None): 279 | """Pull callback SMS message status for single mobile. 280 | 281 | :param nationcode: nation dialing code, e.g. China is 86, USA is 1 282 | :param mobile: mobile number 283 | :param begin_time: begin time, unix timestamp 284 | :param end_time: end time, unix timestamp 285 | :param max_num: maximum number of message status 286 | :param url: custom url 287 | """ 288 | return self._pull(0, nationcode, mobile, 289 | begin_time, end_time, max_num, url) 290 | 291 | def pull_reply(self, nationcode, mobile, begin_time, 292 | end_time, max_num, url=None): 293 | """Pull reply SMS message status for single mobile. 294 | 295 | :param nationcode: nation dialing code, e.g. China is 86, USA is 1 296 | :param mobile: mobile number 297 | :param begin_time: begin time, unix timestamp 298 | :param end_time: end time, unix timestamp 299 | :param max_num: maximum number of message status 300 | :param url: custom url 301 | """ 302 | return self._pull(1, nationcode, mobile, 303 | begin_time,end_time, max_num, url) 304 | -------------------------------------------------------------------------------- /qcloudsms_py/util.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | from __future__ import absolute_import, division, print_function 5 | 6 | import random 7 | import time 8 | import hashlib 9 | import json 10 | 11 | from qcloudsms_py.httpclient import HTTPError, HTTPSimpleClient, utf8 12 | 13 | 14 | def get_random(): 15 | """Get a random number""" 16 | return random.randint(100000, 999999) 17 | 18 | 19 | def get_current_time(): 20 | """Get current time""" 21 | return int(time.time()) 22 | 23 | 24 | def calculate_signature(appkey, rand, time, phone_numbers=None): 25 | """Calculate a request signature according to parameters. 26 | 27 | :param appkey: sdk appkey 28 | :param random: random string 29 | :param time: unix timestamp time 30 | :param phone_numbers: phone number array 31 | """ 32 | raw_text = "appkey={}&random={}&time={}".format(appkey, rand, time) 33 | if phone_numbers: 34 | raw_text += "&mobile={}".format( 35 | ",".join(map(str, phone_numbers))) 36 | return hashlib.sha256(utf8(raw_text)).hexdigest() 37 | 38 | 39 | def calculate_auth(appkey, rand, time, file_sha1sum): 40 | """Calculate a auth signature for uploading voice file. 41 | 42 | :param appkey: sdk appkey 43 | :param random: random string 44 | :param time: unix timestamp time 45 | :param file_sha1sum: voice file sha1 sum 46 | """ 47 | raw_text = "appkey={}&random={}&time={}&content-sha1={}".format( 48 | appkey, rand, time, file_sha1sum 49 | ) 50 | return hashlib.sha256(utf8(raw_text)).hexdigest() 51 | 52 | 53 | def sha1sum(content): 54 | return hashlib.sha1(utf8(content)).hexdigest() 55 | 56 | 57 | _http_simple_client = HTTPSimpleClient() 58 | 59 | 60 | def api_request(req, httpclient=None): 61 | """Make a API request and return response. 62 | 63 | :param req: `qcloudsms_py.httpclient.HTTPRequest` instance 64 | :param httpclient: `qcloudsms_py.httpclient.HTTPClientInterface` instance 65 | """ 66 | if httpclient: 67 | res = httpclient.fetch(req) 68 | else: 69 | res = _http_simple_client.fetch(req) 70 | if not res.ok(): 71 | raise HTTPError(res.code, res.reason) 72 | return res.json() 73 | -------------------------------------------------------------------------------- /qcloudsms_py/voice.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | from __future__ import absolute_import, division, print_function 5 | 6 | import json 7 | 8 | from qcloudsms_py import util 9 | from qcloudsms_py.httpclient import HTTPRequest 10 | 11 | 12 | __all__ = [ 13 | "SmsVoiceVerifyCodeSender", 14 | "SmsVoicePromptSender", 15 | "PromptVoiceSender", 16 | "CodeVoiceSender", 17 | "TtsVoiceSender", 18 | "FileVoiceSender", 19 | "VoiceFileUploader" 20 | ] 21 | 22 | 23 | class PromptVoiceSender(object): 24 | 25 | def __init__(self, appid, appkey, httpclient=None): 26 | self._appid = appid 27 | self._appkey = appkey 28 | self._url = "https://cloud.tim.qq.com/v5/tlsvoicesvr/sendvoiceprompt" 29 | self._httpclient = httpclient 30 | 31 | def send(self, nationcode, phone_number, prompttype, 32 | msg, playtimes=2, ext="", url=None): 33 | """Send a voice prompt message. 34 | 35 | :param naction_code: nation dialing code, e.g. China is 86, USA is 1 36 | :param phone_number: phone number 37 | :param prompttype: voice prompt type, currently value is 2 38 | :param msg: voice prompt message 39 | :param playtimes: playtimes, optional, max is 3, default is 2 40 | :param ext: ext field, content will be returned by server as it is 41 | :param url: custom url 42 | """ 43 | rand = util.get_random() 44 | now = util.get_current_time() 45 | url = "{}?sdkappid={}&random={}".format( 46 | url if url else self._url, self._appid, rand) 47 | req = HTTPRequest( 48 | url=url, 49 | method="POST", 50 | headers={"Content-Type": "application/json"}, 51 | body=json.dumps({ 52 | "tel": { 53 | "nationcode": str(nationcode), 54 | "mobile": str(phone_number) 55 | }, 56 | "prompttype": prompttype, 57 | "promptfile": str(msg), 58 | "playtimes": int(playtimes), 59 | "sig": util.calculate_signature( 60 | self._appkey, rand, now, [phone_number]), 61 | "time": now, 62 | "ext": str(ext) 63 | }) 64 | ) 65 | return util.api_request(req, self._httpclient) 66 | 67 | 68 | # For compatibility with old API 69 | SmsVoicePromptSender = PromptVoiceSender 70 | 71 | 72 | class CodeVoiceSender(object): 73 | 74 | def __init__(self, appid, appkey, httpclient=None): 75 | self._appid = appid 76 | self._appkey = appkey 77 | self._url = "https://cloud.tim.qq.com/v5/tlsvoicesvr/sendcvoice" 78 | self._httpclient = httpclient 79 | 80 | def send(self, nationcode, phone_number, msg, 81 | playtimes=2, ext="", url=None): 82 | """Send code voice. 83 | 84 | :param nationcode: nation dialing code, e.g. China is 86, USA is 1 85 | :param phone_number: phone number 86 | :param msg: voice verify code message 87 | :param playtimes: playtimes, optional, max is 3, default is 2 88 | :param ext: ext field, content will be returned by server as it is 89 | :param url: custom url 90 | """ 91 | rand = util.get_random() 92 | now = util.get_current_time() 93 | url = "{}?sdkappid={}&random={}".format( 94 | url if url else self._url, self._appid, rand) 95 | req = HTTPRequest( 96 | url=url, 97 | method="POST", 98 | headers={"Content-Type": "application/json"}, 99 | body=json.dumps({ 100 | "tel": { 101 | "nationcode": str(nationcode), 102 | "mobile": str(phone_number) 103 | }, 104 | "msg": msg, 105 | "playtimes": int(playtimes), 106 | "sig": util.calculate_signature( 107 | self._appkey, rand, now, [phone_number]), 108 | "time": now, 109 | "ext": str(ext) 110 | }) 111 | ) 112 | return util.api_request(req, self._httpclient) 113 | 114 | # For compatibility with old API 115 | SmsVoiceVerifyCodeSender = CodeVoiceSender 116 | 117 | 118 | class TtsVoiceSender(object): 119 | 120 | def __init__(self, appid, appkey, httpclient=None): 121 | self._appid = appid 122 | self._appkey = appkey 123 | self._url = "https://cloud.tim.qq.com/v5/tlsvoicesvr/sendtvoice" 124 | self._httpclient = httpclient 125 | 126 | def send(self, template_id, params, phone_number, 127 | nationcode="86", playtimes=2, ext="", url=None): 128 | """Send tts voice. 129 | 130 | :param template_id: template id 131 | :param params: template parameters 132 | :param phone_number: phone number 133 | :param nationcode: nation dialing code, e.g. China is 86, USA is 1 134 | :param playtimes: playtimes, optional, max is 3, default is 2 135 | :param ext: ext field, content will be returned by server as it is 136 | :param url: custom url 137 | """ 138 | rand = util.get_random() 139 | now = util.get_current_time() 140 | url = "{}?sdkappid={}&random={}".format( 141 | url if url else self._url, self._appid, rand) 142 | req = HTTPRequest( 143 | url=url, 144 | method="POST", 145 | headers={"Content-Type": "application/json"}, 146 | body=json.dumps({ 147 | "tel": { 148 | "nationcode": str(nationcode), 149 | "mobile": phone_number 150 | }, 151 | "tpl_id": int(template_id), 152 | "params": params, 153 | "sig": util.calculate_signature( 154 | self._appkey, rand, now, [phone_number]), 155 | "time": now, 156 | "playtimes": playtimes, 157 | "ext": str(ext) 158 | }) 159 | ) 160 | return util.api_request(req, self._httpclient) 161 | 162 | 163 | class FileVoiceSender(object): 164 | 165 | def __init__(self, appid, appkey, httpclient=None): 166 | self._appid = appid 167 | self._appkey = appkey 168 | self._url = "https://cloud.tim.qq.com/v5/tlsvoicesvr/sendfvoice" 169 | self._httpclient = httpclient 170 | 171 | def send(self, fid, phone_number, nationcode="86", 172 | playtimes=2, ext="", url=None): 173 | """Send file voice. 174 | 175 | :param fid: voice file fid 176 | :param phone_number: phone number 177 | :param nationcode: nation dialing code, e.g. China is 86, USA is 1 178 | :param playtimes: playtimes, optional, max is 3, default is 2 179 | :param ext: ext field, content will be returned by server as it is 180 | :param url: custom url 181 | """ 182 | rand = util.get_random() 183 | now = util.get_current_time() 184 | url = "{}?sdkappid={}&random={}".format( 185 | url if url else self._url, self._appid, rand) 186 | req = HTTPRequest( 187 | url=url, 188 | method="POST", 189 | headers={"Content-Type": "application/json"}, 190 | body=json.dumps({ 191 | "tel": { 192 | "nationcode": str(nationcode), 193 | "mobile": phone_number 194 | }, 195 | "fid": fid, 196 | "sig": util.calculate_signature( 197 | self._appkey, rand, now, [phone_number]), 198 | "time": now, 199 | "playtimes": playtimes, 200 | "ext": str(ext) 201 | }) 202 | ) 203 | return util.api_request(req, self._httpclient) 204 | 205 | 206 | class VoiceFileUploader(object): 207 | 208 | CONTENT_TYPES = { 209 | "wav": "audio/wav", 210 | "mp3": "audio/mpeg" 211 | } 212 | 213 | def __init__(self, appid, appkey, httpclient=None): 214 | self._appid = appid 215 | self._appkey = appkey 216 | self._url = "https://cloud.tim.qq.com/v5/tlsvoicesvr/uploadvoicefile" 217 | self._httpclient = httpclient 218 | 219 | def upload(self, file_content, content_type="mp3", url=None): 220 | """Upload voice file. 221 | 222 | :param file_content: voice file content 223 | :param content_type: voice file content type 224 | :param url: custom url 225 | """ 226 | if content_type not in self.__class__.CONTENT_TYPES: 227 | raise ValueError("invalid content") 228 | rand = util.get_random() 229 | now = util.get_current_time() 230 | url = "{}?sdkappid={}&random={}&time={}".format( 231 | url if url else self._url, self._appid, rand, now) 232 | file_sha1sum = util.sha1sum(file_content) 233 | req = HTTPRequest( 234 | url=url, 235 | method="POST", 236 | headers={ 237 | "Content-Type": self.__class__.CONTENT_TYPES[content_type], 238 | "x-content-sha1": file_sha1sum, 239 | "Authorization": util.calculate_auth( 240 | self._appkey, rand, now, file_sha1sum 241 | ) 242 | }, 243 | body=file_content 244 | ) 245 | return util.api_request(req, self._httpclient) 246 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | import codecs 4 | try: 5 | from setuptools import setup 6 | except ImportError: 7 | from distutils.core import setup 8 | 9 | 10 | with codecs.open("README", encoding="utf-8") as f: 11 | long_description = f.read() 12 | 13 | setup( 14 | name="qcloudsms_py", 15 | version="0.1.4", 16 | description="qcloudsms python sdk", 17 | packages=["qcloudsms_py"], 18 | author="qcloudsms", 19 | author_email="qcloudsms@gmail.com", 20 | url="https://gitub.com/qcloudsms/qcloudsms_py", 21 | license="https://opensource.org/licenses/MIT", 22 | classifiers=[ 23 | "License :: OSI Approved :: MIT License", 24 | "Programming Language :: Python :: 2.7", 25 | "Programming Language :: Python :: 3", 26 | "Programming Language :: Python :: 3.5", 27 | "Programming Language :: Python :: 3.6", 28 | "Programming Language :: Python :: Implementation :: CPython", 29 | "Programming Language :: Python :: Implementation :: PyPy" 30 | ] 31 | ) 32 | --------------------------------------------------------------------------------