根據大神的文章,網易SMS-SDK,只使用其中發送模板短信部分,學習python。
云信短信API對接
功能說明:
- 基于python3 +請求實現。
- 網易官方未提供的Python版本的SDK包,只提供接口和參數說明。
- 并且官方文檔給出的示例,有錯誤。(校驗有坑,傳入參數有坑)
- 全部接口都已測試,如果使用異常,仔細對照一下傳參示例。
使用說明:
- 網易云信官網,注冊一個測試帳號,默認送幾十條免費測試短信。
- 拿到APP_KEY和APP_SECRET,傳入模塊。
- 云信上,需要配置一下模板短信的模板,需人工審核。
- 對應的ID,代碼里的KEY,ID,都作了錯誤處理,非真實有效值,請注意替換。
import time, hashlib, uuid, requests
class NeteaseSmsAPI(object):
""" 網易云信短信驗證碼服務 API 接口:
"""
APP_KEY = '*********************'
APP_SECRET = '*********************'
# 接口列表:
API_URLS = {
"send": "https://api.netease.im/sms/sendcode.action",
"verify": "https://api.netease.im/sms/verifycode.action",
"send_template": "https://api.netease.im/sms/sendtemplate.action",
"query_status": "https://api.netease.im/sms/querystatus.action",
}
def __init__(self, app_key=None, app_secret=None):
self.app_key = app_key or self.APP_KEY
self.app_secret = app_secret or self.APP_SECRET
self.urls = self.API_URLS
@property
def nonce(self):
return uuid.uuid4().hex
@property
def curtime(self):
return str(int(time.time()))
def checksum(self, nonce, curtime):
s = "{}{}{}".format(self.app_secret, nonce, curtime).encode(encoding="utf-8")
return hashlib.sha1(s).hexdigest()
@property
def http_headers(self):
""" 構造 HTTP 請求頭
:return:
"""
nonce = self.nonce
curtime = self.curtime
checksum = self.checksum(nonce, curtime)
return {
"AppKey": self.app_key,
"CurTime": curtime,
"Nonce": nonce,
"CheckSum": checksum,
"Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
}
@staticmethod
def _post(url, data, headers):
r = requests.post(url, data=data, headers=headers)
# print("url: {}\nHTTP-header: {}\nHTTP-data: {}".format(url, headers, data))
# print("\tstatus: {} \tresult: {}".format(r.status_code, r.content))
return r.json() if r.status_code == 200 else {}
def send_template(self, template_id, mobiles, params=None):
""" 發送模板短信
:param template_id: 模板 ID, 目前測試發現: 只支持通知類模板, 不支持驗證碼模板.
:param mobiles: 手機號列表
:param params: 參數列表
:return:
"""
url = self.urls.get("send_template")
data = {
"mobiles": str([mobiles]) if not isinstance(mobiles, list) else mobiles
}
if template_id:
data.update({"templateid": str(template_id)})
if params:
params = [params] if not isinstance(params, list) else params
data.update({"params": str(params)})
return self._post(url, data=data, headers=self.http_headers)
讀取短信內容文檔
包括短信簽名,70字計1條短信費
def param():
with open(r'D:\SMS\SMS.txt') as f:
line = f.readlines()
if len(line[0]+8) < 40:
return line
else:
print('短信內容太長了,請再精簡一些')
讀取號碼文檔
def mobiles():
with open(r'D:\SMS\number.txt','r') as f:
line = f.readlines()
l = []
for row in line:
l.append(row[0:11])
return l
交互確認
初始密碼、確認短信內容、確認短信手機號碼等內容
def run():
params = param()
mima_queren = input('請輸入密碼: ')
if mima_queren == str('********'):
print('你現在準備發送的短信內容為:')
print(params[0],params[1])
neiront_queren = input("請確認:['Y'OR'N'] ")
if neiront_queren == ('y' or 'Y') :
print('請檢查手機號碼')
number_queren = input("是否檢查完畢:['Y'OR'N'] ")
if number_queren == ('y' or 'Y'):
for mobile in mobiles():
print('開始發送短信:{}'.format(mobile))
# 模板ID
template_id = '******'
api = NeteaseSmsAPI()
api.send_template(template_id, mobile,params)
else:
print('請檢查完畢再開始!')
else:
print('請重新編輯短信再開始!')
else:
print('密碼不對,請重新開始')
主程序
if __name__ == '__main__':
run()
利用pyinstaller打包成exe
cmd模式下,切換到當前目錄
pyintaller --onefile NeteastSMS.py
基本語法:
pyinstaller options myscript.py
常用的可選參數如下:
- --onefile 將結果打包成一個可執行文件
- --onedir 將所有結果打包到一個文件夾中,該文件夾包括一個可執行文件和可執行文件執行時需要的依賴文件(默認)
- --paths=DIR 設置導入路徑
- --distpath=DIR 設置將打包的結果文件放置的路徑
- --specpath=DIR 設置將spec文件放置的路徑
- --windowed 使用windows子系統執行,不會打開命令行(只對windows有效)
- --nowindowed 使用控制臺子系統執行(默認)(只對windows有效)
- --icon=<FILE.ICO> 將file.ico添加為可執行文件的資源(只對windows有效)