微信公众号开发(python+werobot)-自动回复
生活随笔
收集整理的這篇文章主要介紹了
微信公众号开发(python+werobot)-自动回复
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
環(huán)境準備
有一臺外網(wǎng)可以訪問的云服務(wù)器
微信公眾號端的配置
如下圖所示的配置,請?zhí)顚?#xff0c;其中
- URL: 填寫你服務(wù)器的地址,即使http://your_address/weixin/index.php
- 令牌:隨便填一個即可
在/var/www/html 下建weixin目錄,并將以下代碼保存到index.php中,然后拷貝到/var/www/html/路徑。注意文中的xxxxxx環(huán)境你自己的token
<?php/*** wechat php test*///define your tokendefine("TOKEN", "xxxxxx");$wechatObj = new wechatCallbackapiTest();$wechatObj->valid();class wechatCallbackapiTest{public function valid(){$echoStr = $_GET["echostr"];//valid signature , optionif($this->checkSignature()){echo $echoStr;exit;}}public function responseMsg(){//get post data, May be due to the different environments$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];//extract post dataif (!empty($postStr)){$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);$fromUsername = $postObj->FromUserName;$toUsername = $postObj->ToUserName;$keyword = trim($postObj->Content);$time = time();$textTpl = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[%s]]></MsgType><Content><![CDATA[%s]]></Content><FuncFlag>0</FuncFlag></xml>"; if(!empty( $keyword )){$msgType = "text";$contentStr = "Welcome to wechat world!";$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);echo $resultStr;}else{echo "Input something...";}}else {echo "";exit;}}private function checkSignature(){$signature = $_GET["signature"];$timestamp = $_GET["timestamp"];$nonce = $_GET["nonce"];$token = TOKEN;$tmpArr = array($token, $timestamp, $nonce);sort($tmpArr);$tmpStr = implode( $tmpArr );$tmpStr = sha1( $tmpStr );if( $tmpStr == $signature ){return true;}else{return false;}}}?>以上完成之后點擊提交。
編寫測試代碼
記得安裝 pip3 install werobot
示例代碼
import werobotrobot = werobot.WeRoBot(token='xxxxxx')@robot.handler def hello(msg):return 'Hello World!'robot.config['HOST'] = '0.0.0.0' robot.config['PORT'] = 80 robot.run()注意,代碼中的token后的xxxxx要和"微信公眾號端的配置"中的一致
效果展示:
參考文檔
WeRoBot開發(fā)文檔
(backup)
前面是基于python + WeRoBot開發(fā)的公眾號自動回復,其實如果單純是聊天,可以點擊自動回復菜單欄中開啟自動回復,然后接入圖靈機器人即可。
接入圖靈機器人的效果展示:
(您也可以關(guān)注此公眾進行測試)
總結(jié)
以上是生活随笔為你收集整理的微信公众号开发(python+werobot)-自动回复的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 思想解读:optee中的多线程处理
- 下一篇: TF-A代码阅读: 双系统切换时是如何保