写一个程序每天把天气预报发送到手机

在武汉这鬼地方,三天两头雨雨晴晴,天天去中国天气网看天气预报这种事情怎么能容忍。

        有了需求一切都好办了。

        首先是这个网页上有一些天气预报的API介绍,http://blog.csdn.net/fengyun1989/article/details/7341166。果断选择中央电视台的,遗憾的是竟然没有官方说明,奇了个怪。

        这是某位网友对返回格式的注释。http://blog.mynook.info/2012/08/18/weather-com-cn-api.html 

        使用方法很简单,调用  http://m.weather.com.cn/data/101190101.html  就可以返回天气信息,注意后面的代码,这是某城市对应的代码。 本氓已将一份很全的城市代码分享到自己的github上,需要的话请移步这里 https://gist.github.com/snnugiser/5847855  (吐了个槽,人人为毛不能加https的链接)

       本来打算用php写,也顺便学学这个传说中很X的语言,后来想还是用shell写方便些。用curl可以很方便调用web接口,可以直接返回实时天气,比如         

curl http://m.weather.com.cn/data/101190101.html 

返回数据如下

{"weatherinfo":{"city":"武汉","city_en":"wuhan","date_y":"2013年6月30日","date":"","week":"星期日","fchh":"11","cityid":"101200101","temp1":"32℃~26℃","temp2":"33℃~27℃","temp3":"34℃~28℃","temp4":"35℃~28℃","temp5":"35℃~28℃","temp6":"35℃~28℃","tempF1":"89.6℉~78.8℉","tempF2":"91.4℉~80.6℉","tempF3":"93.2℉~82.4℉","tempF4":"95℉~82.4℉","tempF5":"95℉~82.4℉","tempF6":"95℉~82.4℉","weather1":"阵雨转阴","weather2":"多云","weather3":"多云","weather4":"多云","weather5":"多云","weather6":"多云","img1":"3","img2":"2","img3":"1","img4":"99","img5":"1","img6":"99","img7":"1","img8":"99","img9":"1","img10":"99","img11":"1","img12":"99","img_single":"3","img_title1":"阵雨","img_title2":"阴","img_title3":"多云","img_title4":"多云","img_title5":"多云","img_title6":"多云","img_title7":"多云","img_title8":"多云","img_title9":"多云","img_title10":"多云","img_title11":"多云","img_title12":"多云","img_title_single":"阵雨","wind1":"微风","wind2":"微风","wind3":"微风","wind4":"微风","wind5":"微风","wind6":"微风","fx1":"微风","fx2":"微风","fl1":"小于3级","fl2":"小于3级","fl3":"小于3级","fl4":"小于3级","fl5":"小于3级","fl6":"小于3级","index":"热","index_d":"天气热,建议着短裙、短裤、短薄外套、T恤等夏季服装。","index48":"炎热","index48_d":"天气炎热,建议着短衫、短裙、短裤、薄型T恤衫等清凉夏季服装。","index_uv":"弱","index48_uv":"中等","index_xc":"不宜","index_tr":"适宜","index_co":"较不舒适","st1":"31","st2":"25","st3":"33","st4":"27","st5":"34","st6":"28","index_cl":"较不宜","index_ls":"不太适宜","index_ag":"极不易发"}}

        天气信息已经有了,下一步是考虑如何发消息到手机。大概两年前的时候中国移动升级了飞信服务协议,以前的第三方接口大多不能用了。无奈之下决定使用139邮箱的短信提醒。也就是先把天气预报发送到邮箱,然后邮箱把邮件内容发送到手机。因此这个程序的流程是这样的

1. 调用中国天气网的天气预报接口,返回天气信息。

2.将天气信息提取,发送到邮箱。

3.邮箱发送邮件提醒到手机。

        本氓用mutt+msmtp发送邮件,具体安装和配置参看这里 http://huangrs.blog.51cto.com/2677571/967457

如何让程序每天定时运行呢,linux有一个很好的服务crontab,可以设定需要某个时刻运行的程序。如何使用请看这里http://linux.vbird.org/linux_basic/0430cron.php。

        本着开源的精神,代码已托管至github,请移步这里https://github.com/snnugiser/weather。欢迎下载使用

你可能感兴趣的:(天气预报,crontab,Mutt,定时发送)