![[實(shí)踐]微信機(jī)器人小蝸牛有道翻譯小助手——DjangoSAE_第1頁](http://file2.renrendoc.com/fileroot_temp3/2021-12/1/52d02049-a6f8-4599-b5da-1c192a914018/52d02049-a6f8-4599-b5da-1c192a9140181.gif)
![[實(shí)踐]微信機(jī)器人小蝸牛有道翻譯小助手——DjangoSAE_第2頁](http://file2.renrendoc.com/fileroot_temp3/2021-12/1/52d02049-a6f8-4599-b5da-1c192a914018/52d02049-a6f8-4599-b5da-1c192a9140182.gif)
![[實(shí)踐]微信機(jī)器人小蝸牛有道翻譯小助手——DjangoSAE_第3頁](http://file2.renrendoc.com/fileroot_temp3/2021-12/1/52d02049-a6f8-4599-b5da-1c192a914018/52d02049-a6f8-4599-b5da-1c192a9140183.gif)
![[實(shí)踐]微信機(jī)器人小蝸牛有道翻譯小助手——DjangoSAE_第4頁](http://file2.renrendoc.com/fileroot_temp3/2021-12/1/52d02049-a6f8-4599-b5da-1c192a914018/52d02049-a6f8-4599-b5da-1c192a9140184.gif)
![[實(shí)踐]微信機(jī)器人小蝸牛有道翻譯小助手——DjangoSAE_第5頁](http://file2.renrendoc.com/fileroot_temp3/2021-12/1/52d02049-a6f8-4599-b5da-1c192a914018/52d02049-a6f8-4599-b5da-1c192a9140185.gif)
版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
1、微信機(jī)器人:小蝸牛有道翻譯小助手djanqo + sae +微信公眾帳號(hào)自動(dòng)回復(fù)開放接口序某一天上著多核程序設(shè)計(jì)的課上,無聊刷rss,偶然看見一片文章,一個(gè)哥們用微信公 眾帳號(hào)白動(dòng)回復(fù)接口和php寫了一個(gè)白動(dòng)翻譯的機(jī)器人,讓我眼前一亮,我決定h己動(dòng)手 做一個(gè),技術(shù)上選了 django,服務(wù)器用的是sae。準(zhǔn)備工作sina app engine首先作為一個(gè)丿畐絲開發(fā)者要解決服務(wù)器的問題。去sae的官網(wǎng)上用新浪微博的帳號(hào)注 冊一個(gè)帳號(hào),成功后會(huì)贈(zèng)給你500云豆,可供一個(gè)開發(fā)者試用大概5天。sae非常優(yōu)秀, 如果以示我們想在上而寫點(diǎn)應(yīng)用什么的,可以去屮請實(shí)名認(rèn)證和開發(fā)者認(rèn)證,那樣每個(gè)月部 會(huì)給你一定
2、數(shù)量的云豆,應(yīng)該能滿足fi常需求。由于現(xiàn)在sae±部署python還處于公測 階段,因此我們要去屮請開通可以在上面部署python程序的權(quán)限,現(xiàn)在很好屮請的,不一 會(huì)就會(huì)收到已經(jīng)為你開放了部署python應(yīng)用權(quán)限的郵件,網(wǎng)上搜到的啥啥述需耍排隊(duì)都是 過去了(不排除當(dāng)你看到這篇文章時(shí)sae已經(jīng)可以允許所有開發(fā)者部署python的應(yīng)用了)。尊敬的用戶,你好:我們已經(jīng)為您開通sae python平臺(tái)的應(yīng)用創(chuàng)建權(quán)限,謝謝你對sae python的關(guān)注。開發(fā)者手冊 :文檔、dev server 示例代碼:https: /github. com/saepython/saepythondevgui
3、de faq: http:/appstack sae python郵件列表:http: /groups. google. com/group/sae-python2012-12-28ok,完成這些后,就可以到sae的文檔中心讀文檔來照著文檔里面的樣例創(chuàng)建一個(gè)應(yīng)用了。有道api然后,去有道api屮請一-個(gè)key,申請的時(shí)候網(wǎng)站地址隨便填就行。有道api非常簡單, 直接以get的形式把要翻譯的文木發(fā)送到指定的url,然后它會(huì)給我們回復(fù)翻譯結(jié)果,我們 可以選擇xmk json等返回格式,我選得是xml,接著,在瀏覽器里面按著指定的格式輸入 url,就可以看到返回結(jié)果啦:htm i view plai
4、ncopy1. <?xml version="1.0n encoding=llutf-8,?>2. <youdao-fanyi>3. <errorcode>0</errorcode>4. <query>< ! cdata這里是有道翻譯 api ></query>5. <!-有道翻譯->6. <translation>7. <paragraph><!cdatahere is the youdao translation apix/parag raph>8&
5、lt;/translation>9 </youdao-fanyi>注意,如呆是對詞進(jìn)行翻譯的話有的詞還會(huì)返回一些啥網(wǎng)絡(luò)釋義,基木釋義啥的,貝體 對這個(gè)xml解析的方法請看下面的代碼。微信公眾帳號(hào)接著,我們要去微信的公眾帳號(hào)平臺(tái)去屮請一個(gè)公眾帳號(hào),不能用現(xiàn)有的已綁定私人微 信帳號(hào)的qq號(hào)屮請,我用的是一個(gè)平吋不用的qq號(hào)申請的,屮請成功后,可以大致看 看微信公眾帳號(hào)的管理平臺(tái)(現(xiàn)在你知道那些公眾帳號(hào),比如王力宏的帳號(hào)啥的是怎么運(yùn)作 的了吧),接著去這里仔細(xì)閱讀微信公眾帳號(hào)自動(dòng)回復(fù)開放接口的文檔,你要從這里學(xué)一種 如何讓用戶認(rèn)證的思想(就是如果用戶做了 xx,給我返冋了 xx結(jié)果
6、,那么我就能確定, 用戶是“合法”的),或者認(rèn)證的方法。人致有一個(gè)認(rèn)識(shí)示,趕緊下載他給的樣例php源碼, 也是唯一的可以參考的源碼,仔細(xì)閱讀,如下:php view plain copy|1- <?php2. /*3. * wechat php test4*/56. /define your token7. define (token1', “weixin”);8. $wechatobj = new wechatcallbackapitest();9. $wechatobj->valid();10.11- class wechatcallbackapitestpublic
7、function valid() $echostr = $_getechostr"/valid signature 丿 option if($this->checksignature() echo $echostr;exit; public function responsemsg()/get post data, may be due to the different environments $poststr = $globalshttp_raw_post_data”;/extract post dataif (!emptyempty($poststr) echostr$p
8、ostobj = simplexml_load_string($poststr, implexmlelement libxml_nocdata);romusername = $postobj->fromusername;$tousername = $postobj>tousername;$keyword = trim($postobj>content);$time = time();$texttpl = f,<xml><tousername><!cdata%s></tousername> <fromllsername>
9、;< ! cdata%s ></fromusername> <createtime>%s</createtime><msgtype><icdata%s></msgtype><content><!cdata%s></content> <funcflag>0</funcflag></xml>"if(!emptyempty( $keyword )$msgtype = "text'1;49.$resultstr 二 sp
10、rintf($texttpl, $fromusername, $tousername, $time, $msgtype> $contentstr);3.54 8.59.60.echo $resuitstr;elseecho "input something”; else echo “;exit;0.7172.73.74 8.79. 80 private function checksignature()$signature = $_get"signatu
11、re"$timestamp = $_get "timestamp11 ;$nonce = $_get"nonce"$token = token;$tmpa廿 =array($token, $timestamp, $nonce);sort($tmpanr);$tmpstr = implode( $tmparr );$tmpstr = shal( $tmpstr );if( $tmpstr = $signature )return true;elsereturn false;81. ?>很簡單吧,以至于被一些人說寫的很水,但是我覺得,這份php源碼還是
12、很有含金最 的;網(wǎng)上一些哥們還抱怨啥啥的直接部署樣例php不能運(yùn)行啥的,拜托,有點(diǎn)職業(yè)精神好 不好,連我這個(gè)z前完全不會(huì)php的人都能看出來要調(diào)用里面的responsemsg()方法才能 實(shí)現(xiàn)自動(dòng)回復(fù),樣例里而的只是調(diào)用了微信接入的認(rèn)證功能的函數(shù)。上而的代碼寫的很好,不需要我多解釋,相信大家能看出來它是怎么工作的。設(shè)計(jì)與實(shí)現(xiàn)接著就可以實(shí)現(xiàn)我們自己的應(yīng)用了,首先把我們在sae上創(chuàng)建的應(yīng)用通過svn檢出 到木地,然后切換到檢出的目錄,用django的命令創(chuàng)建一個(gè)應(yīng)用,目錄結(jié)構(gòu)如下:ltushuatliushuailenovog460:/svn$ tree1 littlesnatl1 configy
13、ami indexwsgilittesnatl_tntt_.pylog txt resulthtml settings.pyurlspy viewspywsgipy managepy resulthtml3 directories, 11 files.其!«, index.wsgi和config.yaml是sae規(guī)定的文件,具體請仔細(xì)閱讀sae的文檔。z后就可以編寫我們自己的服務(wù)端代碼了,大致思想就是:用戶a向公眾帳號(hào)發(fā)送一 條消息,微信平臺(tái)會(huì)按著公眾帳號(hào)預(yù)先的設(shè)置,把用戶a的消息內(nèi)容和一些其他信息(如 創(chuàng)建時(shí)間等)以xml的形式post到我們預(yù)先設(shè)置好的url上(這個(gè)url的服務(wù)端
14、就是我們要 寫的在sae ±的應(yīng)用),我們要做的就是每當(dāng)接受到微信post請求,我們解析微信平臺(tái) post過來的xml,得到用戶a的消息內(nèi)容,把消息內(nèi)容以get的形式發(fā)送到有道api,獲取 有道api返回的xml (或json等),解析,之后按微信平臺(tái)規(guī)定的格式構(gòu)造成一個(gè)xml, 作為微信平臺(tái)post請求的結(jié)果給其返回,微信平臺(tái)收到結(jié)果后,會(huì)把消息白動(dòng)回復(fù)給用戶, 用戶就能收到翻譯結(jié)果了。用一個(gè)圖表示上述過程如下:用戶a微信公眾賬號(hào)平臺(tái)t-6rpturn-5 returfysae平臺(tái)django服務(wù)卅源碼下面貼出邏輯處理部分代碼如下(views.py),各函數(shù)功能不言而喻:on vi
15、ew plain copy1. # coding: utf-8 -*-2. from django.http import httpresponse3. from django.template import requestcontext, template4. from djangoviews.decorators.csrf import csrf_exempt5. from django.utils.encoding import smartstr, smartyunicode6.6. import xml.ettee.elemenas et7. import urllib,urllib2
16、>timjhashlib9.8. token = ”你設(shè)置的 token"11.9. youdao_key =你申請到的冇道的key10. youdao_key_from ="有道的 key-from1111. youdao_doc_type = “xml”15.12. csrf_exempt17 def handlerequest(request):18. if request>method = 'get:19. #response = httpresponse(requestget'echostr',content_type=ntex
17、t/p lain")20. response = httpresponse(checksignature(request),content_type="text/plain11) return responseelif request.method = 'post':#c = requestcontext(request,'result,:responsemsg(request)#t = template(1result1)#response = httpresponse(trender(c)content_type=happlication/xml
18、")response = httpresponse(responsemsg(request)content_type=”applicati on/xml")return responseelse:return nonedef checksignature(request):global tokensignature = request.get.get(”signaturej none)timestamp = request.get.get("timestamp'' none)nonce = request .get.get(h non ce'
19、;' none)echos tr = reques t. get.ge t(,chostr",n one)token = tokentmplist = token,timestamp,noneetmplistsort()tmpstr = n%s%s%s11 % tuple(tmplist)tmpstr = hashlibeshal(tmpstr)hexdigest()if tmpstr = signature:return echostrelse:return nonedef responsemsg(request):rawstr 二 smart_str(requestraw
20、_post_data)#rawstr = smart_str(request.post'xmu)msg = parasemsgxml(et.fromstring(rawstr)querystr = msg-get('content* 1 you have input nothing)raw_youdaourl = nhttp:/fanyiyoudaocom/openapido?keyfrom=%s&key=%s&ty pe=data&doctype=%s&version=l.l&q=n % (youdao_key_from,youdao_
21、key,youdao_doc_ type)youdaourl = n%s%s" % (rawyoudaourl urllib2.quote(querystr)req = urllib2.request(url=youdaourl)result = urllib2.urlopen(req).read()replycontent 二 paraseyoudaoxml(et.fromstring(result) return getreplyxml(msg,replycontent)def parasemsgxml(rootelem):msg = if rootelem.tag = '
22、;xml':for child in rootelem:msgchild.tag = smart_str(child.text)return msgdef paraseyoudaoxml(rootelem):replycontent 二''if rootelem.tag = 1youdao-fanyi':for child in rootelem:#錯(cuò)誤碼if child.tag = 1errorcode':if child.text = *20*:return 'too long to translatenelif child.text = 1
23、301:return 'can not be able to translate with effectn elif child.text = '40':return 'can not be able to support this languagerf elif child.text = 150*:return 'invalid keyn#査詢字符串elif child.tag = 'query':replycontent = ”s%srt % (replycontent child.text)#有道翻譯elif child.tag =
24、 'translation1: replycontent = *%s%sn%sn * % (replycontent' -' * 3 + u'有道翻譯,+ 1 -' * 3, ch訂d0 .text)#有道詞典基本詞典elif child.tag = 1 basic':97.replycontent = ,l%s%snn % (replycontent1 - * * 3 + u*基本詞典* 3)98.for c in child:99.if c.tag = 1 phonetic1:100.replycontent = f%s%sn1 % (rep
25、lycontent c.text)101.elif c.tag = *explains1:102.-for ex in c.findall( 'ex'):103.replycontent 二'%s%srt % (replycontent, ex.text)104.105.#有道詞典網(wǎng)絡(luò)釋義106.elif child.tag = 'web1:107.義,+ ,108.replycontent = "%s%sn" % (replycontent, ' -' * 3 + u'網(wǎng)絡(luò)釋-* * 3)for explain in
26、 child.findall('explain'):109.for key in explain.findall('key1):110.replycontent = *%s%sn' % (replycontent key.text)111.for value in explain.findall('value'):112.for ex in value.findall('ex1):113 replyconterrt = '%s%s% (replycontent,ex.text)114.replycontent = ,%s%sn,
27、% (replycontent1 -1)115. return replycontent116.116. def getreplyxml(msg replycontent):117. exttpl = h<xmlxtousername>< ! cdata%s ></tousernamexfromllsername>< ! cdata%s></fromusernamexcreatetime>%s</createtime><msgtype><!cdata%s> </msgtypexcontent&
28、gt;<!cdata%s></content><funcflag>0</funcflag></xml>h;118. ext邛 1 = ext邛 1 % (msg' fromllsername1 jmsg 'tousername' ,str(int(time.t imeo) * text/ replyc ontent)119. return ext邛1之后通過svn把項(xiàng)目部署到sae上,就ok啦遇到的問題現(xiàn)在網(wǎng)上這種參考的代碼還很少,在sae±部署調(diào)試也非常困難,無奈下我自己寫了 個(gè)腳木,模仿微信平臺(tái)給自己部署在sae±的服務(wù)端post消息,看返|叫的結(jié)果。如果出 現(xiàn)錯(cuò)誤,django都會(huì)產(chǎn)生一個(gè)優(yōu)美的錯(cuò)謀頁面,獲取這個(gè)錯(cuò)誤頁面把它寫到本地的一個(gè)html 里而,用瀏覽器打開就町以知道是什么錯(cuò)誤了。寫的過程中
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 高凈值人群海外稅務(wù)籌劃與財(cái)富保護(hù)策略
- 現(xiàn)代辦公樓的安全生產(chǎn)隱患識(shí)別與處理
- 食堂防火應(yīng)急預(yù)案
- 臨時(shí)倉儲(chǔ)保管合同范本
- 2025年跨國資金借貸合同(五)
- 個(gè)人汽車買賣合同轉(zhuǎn)讓協(xié)議
- 產(chǎn)品經(jīng)銷合同范本
- 臨時(shí)停薪留職合同模板
- 兩人合資創(chuàng)業(yè)合同協(xié)議書
- 產(chǎn)品經(jīng)銷合同范本:三方合作案例分析
- Unit6AtthesnackbarStorytimeDiningwithdragons(課件)譯林版英語四年級(jí)上冊
- 2023年四川省公務(wù)員錄用考試《行測》真題卷及答案解析
- 機(jī)電一體化系統(tǒng)設(shè)計(jì)-第5章-特性分析
- 2025年高考物理復(fù)習(xí)壓軸題:電磁感應(yīng)綜合問題(原卷版)
- 雨棚鋼結(jié)構(gòu)施工組織設(shè)計(jì)正式版
- 醫(yī)院重點(diǎn)監(jiān)控藥品管理制度
- 2024尼爾森IQ中國本土快消企業(yè)調(diào)研報(bào)告
- 2024年印度辣椒行業(yè)狀況及未來發(fā)展趨勢報(bào)告
- 骨科醫(yī)院感染控制操作流程
- 鑄鋁焊接工藝
- (正式版)HGT 6313-2024 化工園區(qū)智慧化評(píng)價(jià)導(dǎo)則
評(píng)論
0/150
提交評(píng)論