Twilio是一个做成开放插件的电话跟踪服务,可以通过twilio相关功能接入物联网设备达到及时提醒的功能。
本程序代码需要注册twilio账号,并部署在服务器,可实现每天定时短信天气提醒。
服务器send.py程序:
#coding=utf-8
from twilio.rest import Client
import json , requests , sys , time ,datetime
dir=r"url" //url为文件地址
while True:
dtime=datetime.datetime.now()
kk=dtime.strftime("%H")
if kk!="11":
time.sleep(1)
else:
oldfile=open(dir+r"\oldfile.txt","r")
filething=oldfile.read()
filelist=filething.split("\n")
for i in filelist:
thinglist=i.split()
if(thinglist!=[]):
jsonWeather=open(dir+"\_city.json",'r',encoding='utf-8')
jsonread=json.load(jsonWeather)
sname=thinglist[5]
scode=""
for s in jsonread:
if(sname==s["city_name"]):
scode=s["city_code"]
url=r"http://t.weather.sojson.com/api/weather/city/"+scode
response=requests.get(url)
response.raise_for_status()
weatherData=json.loads(response.text)
w=weatherData["data"]
s=w["wendu"]
k="现在温度:"
k+=s
k+="℃"
k+=" 天气:"
s+="to mo"+w["forecast"][0]["high"]
s+="to mo"+w["forecast"][0]["low"]
s+="to we:"+w["forecast"][0]["type"]
k+=w["forecast"][0]["type"]
account_sid = thinglist[1]
auth_token = thinglist[3]
client = Client(account_sid, auth_token)
message = client.messages.create(
to=thinglist[7],
from_=thinglist[9]+" "+thinglist[10],
body=k)
time.sleep(72000)
oldfile.txt里存放用户信息,
_city.json为json文件类型的城市信息,信息摘要如下:
[
{
"_id": 1,
"id": 1,
"pid": 0,
"city_code": "101010100",
"city_name": "北京"
},
{
"_id": 165,
"id": 166,
"pid": 11,
"city_code": "101050101",
"city_name": "哈尔滨"
}
]
结果如下:(示例程序中定在每天十一点自动发信息,以下演示并非设置十一点发送)
twilio对于短信字数还是有要求的,毕竟免费发短息已经是很大仁慈了。
短时间内发送多条短息会有接收不到短情况。