最近想在微信上面实现天气查询,分两个步骤:
1.被动回复:输入天气、xx天气获取天气情况
2.主动推送:每天定时推送天气(针对24小时内产生交互的人)
目前已经实现第一个步骤,如下:
现将实现此功能环节、步骤等整理如下:
前置条件:
1.申请微信订阅号
2.申请百度应用引擎(BAE python环境)
技术知识:
1.python
2.Django
其他知识:
1.HTTP协议
2.JSON
3.WechatPy(Python 微信 SDK)
实现思路:
用户上行文字消息 【XX天气】=>订阅号=>微信客户端=>微信后台=>推送到微信开发者接口=>BAE=>Django(Python)=>WechatPy=>文字解析=>百度天气API
=>协议JSON=>生成文章描述XML=>微信后台=>微信客户端 【页面显示】
实现代码:
百度天气查询【输入地市】:
http://api.map.baidu.com/telematics/v3/weather?location=%s&output=json&ak=YOURAK
#! /usr/bin/env python
# coding=utf-8 import requests
import json class _cityWeather(): #key
appkey='7ed5edfdb07013922a47bd2fbf194d3d'
#url
appurl='http://api.map.baidu.com/telematics/v3/weather?location=%s&output=json&ak=7ed5edfdb07013922a47bd2fbf194d3d' def __init__(self):
pass def getcitynamebyip(self,ip): pass def getcityweather(self,cityname='合肥'):
requrl=self.appurl % (cityname,)
r = requests.get(requrl)
return r.text cityweather = _cityWeather() if __name__ =="__main__": print cityweather.getcityweather('合肥')
Django :
路由【url.py】:
from django.conf.urls import patterns, include, url import weixinviews
import robot urlpatterns = patterns('', # url(r'^$', weixinviews.handleRequest),
url(r'^$', robot.weixin), )
对接微信&消息分流【robot.py】:
# -*- coding: utf-8 -*- from django.http import HttpResponse
from django.template import RequestContext, Template
from django.views.decorators.csrf import csrf_exempt
from django.utils.encoding import smart_str, smart_unicode from wechatpy import parse_message, create_reply
from wechatpy.utils import check_signature
from wechatpy.exceptions import InvalidSignatureException
from wechatpy.replies import BaseReply import reply_text
import reply_event TOKEN = 'YOURTOKEN' # 注意要与微信公众帐号平台上填写一致 @csrf_exempt
def weixin(request):
if request.method == 'GET':
signature = request.GET.get('signature', '')
timestamp = request.GET.get('timestamp', '')
nonce = request.GET.get('nonce', '')
echo_str = request.GET.get('echostr', '')
try:
check_signature(TOKEN, signature, timestamp, nonce)
except InvalidSignatureException:
echo_str = 'error'
response = HttpResponse(echo_str, content_type="text/plain")
return response
else:
reply=None
msg = parse_message(request.body)
if msg.type == 'text':
reply = reply_text.doreply(msg)
elif msg.type=='event':
reply = reply_event.doreply(msg)
else:
pass if not reply or not isinstance(reply, BaseReply):
reply = create_reply('暂不支持文本消息外的其他操作...\r\n回复:xx天气 查询地市天气情况', msg) response = HttpResponse(reply.render() , content_type="application/xml")
return response
文字消息应答【reply_text.py】:
# -*- coding: utf-8 -*- from wechatpy import parse_message, create_reply
from wechatpy.replies import TextReply, ArticlesReply
from wechatpy.utils import check_signature
from wechatpy.exceptions import InvalidSignatureException from webcore.weatherservices import cityweather
from isay9685.models import CityWeahter
import json
import time
from datetime import datetime def doreply(msg):
reply = None try: if msg.content[-2:] == u'天气':
if(len(msg.content) == 2):
cityname = '合肥'
else:
cityname = msg.content[:-2]
reply = replyWeather(cityname, msg)
else:
reply = create_reply(repr(msg), msg) except Exception as e:
print 'error:', e return reply def replyWeather(cityname, msg): reply = None dateid = time.strftime("%Y%m%d")
timeid = time.strftime("%H") cWeahter = CityWeahter.objects.filter(dateid=dateid, timeid=timeid, cityname=cityname)
if cWeahter:
weatherstr = cWeahter[0].wheather
else:
weatherstr = cityweather.getcityweather(cityname)
cw = CityWeahter(dateid=dateid, timeid=timeid, cityname=cityname, wheather=weatherstr, createtime=datetime.now())
cw.save() # weatherstr = '''{"error":0,"status":"success","date":"2015-06-15","results":[{"currentCity":"合肥","pm25":"126","index":[{"title":"穿衣","zs":"热","tipt":"穿衣指数","des":"天气热,建议着短裙、短裤、短薄外套、T恤等夏季服装。"},{"title":"洗车","zs":"不宜","tipt":"洗车指数","des":"不宜洗车,未来24小时内有雨,如果在此期间洗车,雨水和路上的泥水可能会再次弄脏您的爱车。"},{"title":"旅游","zs":"适宜","tipt":"旅游指数","des":"温度适宜,又有较弱降水和微风作伴,会给您的旅行带来意想不到的景象,适宜旅游,可不要错过机会呦!"},{"title":"感冒","zs":"较易发","tipt":"感冒指数","des":"相对今天出现了较大幅度降温,较易发生感冒,体质较弱的朋友请注意适当防护。"},{"title":"运动","zs":"较不宜","tipt":"运动指数","des":"有降水,推荐您在室内进行健身休闲运动;若坚持户外运动,须注意携带雨具并注意避雨防滑。"},{"title":"紫外线强度","zs":"弱","tipt":"紫外线强度指数","des":"紫外线强度较弱,建议出门前涂擦SPF在12-15之间、PA+的防晒护肤品。"}],"weather_data":[{"date":"周一 06月15日 (实时:27℃)","dayPictureUrl":"http://api.map.baidu.com/images/weather/day/xiaoyu.png","nightPictureUrl":"http://api.map.baidu.com/images/weather/night/zhongyu.png","weather":"小雨转中雨","wind":"南风微风","temperature":"28 ~ 22℃"},{"date":"周二","dayPictureUrl":"http://api.map.baidu.com/images/weather/day/dayu.png","nightPictureUrl":"http://api.map.baidu.com/images/weather/night/xiaoyu.png","weather":"大雨转小雨","wind":"北风微风","temperature":"26 ~ 21℃"},{"date":"周三","dayPictureUrl":"http://api.map.baidu.com/images/weather/day/xiaoyu.png","nightPictureUrl":"http://api.map.baidu.com/images/weather/night/yin.png","weather":"小雨转阴","wind":"北风微风","temperature":"24 ~ 20℃"},{"date":"周四","dayPictureUrl":"http://api.map.baidu.com/images/weather/day/duoyun.png","nightPictureUrl":"http://api.map.baidu.com/images/weather/night/duoyun.png","weather":"多云","wind":"东北风3-4级","temperature":"28 ~ 20℃"}]}]} '''
weatherjson = json.loads(weatherstr) if weatherjson and weatherjson.get('error') == 0:
date = weatherjson.get('date')
result = weatherjson.get('results')[0] currentCity = result.get('currentCity')
pm25 = result.get('pm25') wheathernowdatas = result.get('weather_data')[0] weathermsg = repr(wheathernowdatas) reply = ArticlesReply(message=msg) # simply use dict as article
reply.add_article({
'title': wheathernowdatas.get('date'),
})
reply.add_article({
'title':
u'%s %s %s' % (wheathernowdatas.get('weather') , wheathernowdatas.get('temperature') , wheathernowdatas.get('wind')) \
+ '\r\n'\
+ '\r\n'\
+ currentCity + u' PM2.5: ' + pm25 ,
'url': 'http://isay9685.duapp.com'
})
reply.add_article({
'title': u'白天',
'image': wheathernowdatas.get('dayPictureUrl'),
})
reply.add_article({
'title': u'晚上',
'image': wheathernowdatas.get('nightPictureUrl'),
}) return reply
事件消息应答【reply_event.py】:
# -*- coding: utf-8 -*- from wechatpy import parse_message, create_reply
from wechatpy.replies import TextReply, ArticlesReply
from wechatpy.utils import check_signature
from wechatpy.exceptions import InvalidSignatureException from webcore.weatherservices import cityweather
from isay9685.models import CityWeahter
import json
import time
from datetime import datetime def doreply(msg):
reply = None try: if msg.event == 'subscribe':
reply = replySubscribe(msg)
else:
reply = create_reply(repr(msg), msg) except Exception as e:
print 'error:', e
reply = None return reply def replySubscribe(msg): reply = TextReply(content='欢迎关注RYHAN的微信订阅号,回复XX天气即可查询天气情况。\r\n 如:合肥天气', message=msg)
return reply
BAE【requirements.txt】
django==1.5.2
MySQL-python==1.2.4
requests==2.8.1
#pycrypto==2.6.1
PyCrypto
#cryptography==0.8.2
wechatpy
测试微信号: