閑來無事的時候看了下微信api,發(fā)現(xiàn)未認證用戶可用接口少的可憐,不過自動回復功能還是有點用的,就用django寫了個微信自動回復的功能,回復的數(shù)據(jù)是通過solr去搜索獲取的。加上url,綁定到二級域名就可以直接用了。注意view方法必須加@csrf_exempt,django寫這種類似的接口還是太重,tornado會簡潔很多。
示例截圖:
實際應用中,應該先要判斷用戶是否搜索還是正常對話,實現(xiàn)基本的help等幫助提示。

Paste_Image.png
核心代碼
from django.views.decorators.csrf import csrf_exempt
import hashlib
from django.shortcuts import loader
from django.http import HttpResponse
from lxml import etree
import time,re
import pysolr
# Create your views here.
@csrf_exempt
def yunsearch_index(request):
# if這里用來實現(xiàn)微信api的驗證,驗證使用GET,用戶發(fā)送消息是POST請求
if request.method == 'GET':
signature = request.GET.get('signature',None)
timestamp = request.GET.get('timestamp',None)
nonce = request.GET.get('nonce',None)
echostr = request.GET.get('echostr',None)
#配置自己申請的token
token = 'yourtoken'
hashlist = [token,timestamp,nonce]
hashlist.sort()
try:
hashstr = ''.join(hashlist)
except:
hashstr = ''
hashstr = hashlib.sha1(hashstr).hexdigest()
if hashstr == signature:
return HttpResponse(echostr)
else:
return HttpResponse('hahaha')
else:
# 這里是根據(jù)公眾號中收到的消息(/關鍵詞)去返回相關的資源信息,使用文本消息接口
str_xml = etree.fromstring(request.body)
fromUser = str_xml.find('ToUserName').text
toUser = str_xml.find('FromUserName').text
query = str_xml.find('Content').text
nowtime = str(int(time.time()))
regq = re.compile(r'\/.*$')
# 這里是去獲取數(shù)據(jù)的方法,根據(jù)需要去獲取自己網(wǎng)站的數(shù)據(jù)就好
if regq.search(query):
solr = pysolr.Solr('http://127.0.0.1:8080/solr/solrindex/',timeout=4)
contextsolr = solr.search(query.strip('/'),fl="shorturl,text",df="text",wt="python",start=0,rows=5).docs
else:
contextsolr = []
#用模板構(gòu)建返回給微信的數(shù)據(jù)
t = loader.get_template('text.xml')
c = {'toUser': toUser, 'fromUser': fromUser,'nowtime': nowtime, 'contextsolr': contextsolr}
return HttpResponse(t.render(c))
xml模板
根據(jù)搜索出來的shorturl,直接返回網(wǎng)盤鏈接給用戶
<xml>
<ToUserName><![CDATA[{{ toUser }}]]></ToUserName>
<FromUserName><![CDATA[{{ fromUser }}]]></FromUserName>
<CreateTime>{{ nowtime }}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
{% if contextsolr %}
<Content>{% for item in contextsolr %}{{item.text}} http://pan.baidu.com/s/{{item.shorturl}}
{% endfor %}需更多結(jié)果請前往網(wǎng)站xxxx.com</Content>
{% else %}
<Content><![CDATA[沒有相關的資源,請更換關鍵詞搜索,關鍵詞前加斜杠"/"即可搜索,例如"/小說"]]></Content>
{% endif %}
</xml>