Python 發送 HiNet 企業簡訊
由 darkranger 在 週六, 09/07/2013 - 22:35 發表,更新日期:週曰, 05/15/2016 - 19:31
HiNet 企業簡訊(Socket to Air)是中華電信的線上簡訊發送服務,由於這項服務可讓用戶自行撰寫程式來連結伺服器,因此有提供通訊規格說明和許多程式語言的程式碼範例,包含 C(Unix、Windows)、Java、VB .NET、Perl 以及 PHP 等。不過沒有 Python 的範例,所以 DR 主要參考(更精確的說就是照抄)PHP 版本的範例,寫了一段用 Python 發送的版本。
以下程式碼僅單純示範如何登入 HiAir 伺服器,並發送一則文字簡訊給指定的國際號碼:
#!/usr/bin/python # -*- coding: utf-8 -*- import os, sys import socket, struct HOST = "api.hiair.hinet.net" PORT = 8000 USER = "AAAAAAAA" PASSWD = "BBBBBBBB" SEND_MSG_LENGTH = 266 RECV_MSG_LENGTH = 244 SEND_SET_LENGTH = 100 SEND_CONTENT_LENGTH = 160 def connectMsg(): msgSet = USER + "\0" + PASSWD + "\0" data_input = struct.pack("B", 0) + struct.pack("B", 1) + struct.pack("B", 1) + struct.pack("B", 0) + \ struct.pack("B", len(msgSet)) + struct.pack("B", 0) + msgSet zeroes = SEND_MSG_LENGTH - len(data_input) data_input = data_input + "".ljust(zeroes, "\0") return data_input def sendMsg(msg_type, number, text): msgSet = number + "\0" + "01" + "\0" zeroes = SEND_SET_LENGTH - len(msgSet) msgSet = msgSet + "".ljust(zeroes, "\0") zeroes = SEND_CONTENT_LENGTH - len(text) msgContent = text + "".ljust(zeroes, "\0") data_input = struct.pack("B", msg_type) + struct.pack("B", 1) + struct.pack("B", 1) + struct.pack("B", 0) + \ struct.pack("B", len(msgSet)) + struct.pack("B", len(text)) + msgSet + msgContent return data_input def returnMsg(data_output): returnCode = struct.unpack("B", data_output[0:1])[0] returnLength = struct.unpack("B", data_output[3:4])[0] returnLength = returnLength + 84 returnContent = data_output[84:returnLength] return (returnCode, returnContent) def sms(msg_type, number, text): try: ip = socket.gethostbyname(HOST) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((ip, PORT)) s.sendall(connectMsg()) (returnCode, returnContent) = returnMsg(s.recv(RECV_MSG_LENGTH)) if returnCode == 0: s.sendall(sendMsg(msg_type, number, text)) (returnCode, returnContent) = returnMsg(s.recv(RECV_MSG_LENGTH)) s.close() print returnContent except Exception, error: exc_type, exc_obj, exc_tb = sys.exc_info() print "%s:%d: %s" % (os.path.split(exc_tb.tb_frame.f_code.co_filename)[1], exc_tb.tb_lineno, error) if __name__ == "__main__": msg_type = 15 number = "+886952000000" text = "SMS text message." sms(msg_type, number, text)