Skip to content

Instantly share code, notes, and snippets.

@gccyugi
Created May 23, 2012 06:53
Show Gist options
  • Save gccyugi/2773607 to your computer and use it in GitHub Desktop.
Save gccyugi/2773607 to your computer and use it in GitHub Desktop.
smsbao-python-api
# -*- coding: utf-8 -*-
#
# Author: yugi
# Email: [email protected]
# Update: 2012/5/23 14:07
import md5 as mmd5
def md5(e):
m = mmd5.new()
m.update(e)
return m.hexdigest()
def httpget(url):
import urllib2
res = urllib2.urlopen(url)
return res.read()
def safestr(obj, encoding='utf-8'):
if isinstance(obj, unicode):
return obj.encode('utf-8')
elif isinstance(obj, str):
return obj
else:
return str(obj)
def safeunicode(obj, encoding='utf-8'):
if isinstance(obj, unicode):
return obj
elif isinstance(obj, str):
return obj.decode(encoding)
else:
if hasattr(obj, '__unicode__'):
return unicode(obj)
else:
return str(obj).decode(encoding)
def urlquote(val):
from urllib import quote
if val is None:
return ''
if not isinstance(val, unicode):
val = str(val)
else:
val = val.encode('utf-8')
return quote(val)
class Smsbao(object):
content_max_len = 62
errmsgs = {
'30': u'密码错误',
'40': u'账号不存在',
'41': u'余额不足',
'42': u'帐号过期',
'43': u'IP地址限制',
'50': u'内容含有敏感词',
'51': u'手机号码不正确'
}
def __init__(self, username, password,
api_smsbao = 'api.smsbao.com'):
self._username = username
self._password = password
self._api_smsbao = api_smsbao
def info(self):
tmpl = 'http://%s/query?u=%s&p=%s'
url = tmpl % (self._api_smsbao, self._username,
md5(self._password))
res = httpget(url)
if len(res) > 0:
if res[0] == '0':
cnt_used, cnt_remain = res[2:].split(',')
return True, (cnt_used, cnt_remain)
else:
return False, self.errmsgs[res] or u'未知错误'
return False, u'返回结果格式有误'
def send(self, phone, content):
tmpl = 'http://%s/sms?u=%s&p=%s&m=%s&c=%s'
url = tmpl % (self._api_smsbao, self._username,
md5(self._password), phone,
urlquote(content))
content_len = len(safeunicode(content))
if content_len > self.content_max_len:
return False, u'消息太长了'
res = httpget(url)
if len(res) > 0 and res[0] == '0':
return True
return False, self.errmsgs[res] or u'未知错误'
if __name__ == '__main__':
s = Smsbao('<username>', '<password>')
# info
rc, info = s.info()
if rc:
print info
# send
s.send('<phonenumber>', '测试中文, haha')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment