基于图灵api实现微信聊天机器人
2017-03-31 12:17
351 查看
基于图灵api实现微信聊天机器人
尝试了一下最近很火的聊天机器人,记录下实现过程。微信公众平台提供的接口很简单,先看看消息交互流程:
说的通俗一些,用户使用微信发送消息 -> 微信将数据发送给开发者 -> 开发者处理消息并返回数据至微信 -> 微信把返回数据发送给用户,期间数据交互通过XML完成,就这么简单。
下面写个实例,开发微信智能聊天机器人:
1. 注册微信公众平台账号
微信公众平台:https://mp.weixin.qq.com/
注: 目前一张身份证只能注册两个账号,账号名称关乎加微信认证,请慎重注册。
2. 申请服务器/虚拟主机
没有服务器/虚拟主机的童鞋可以使用BAE和SAE,不多介绍。我自己是在搬瓦工上面购买的一个VPS,之前主要用来翻墙使用。3. 开启开发者模式
微信公众平台有两个模式,一个是编辑模式(傻瓜模式),简单但功能单一。另一个是开发者模式,可以通过开发实现复杂功能。两个模式互斥,显而易见,登录微信公众平台并通过“开发”菜单开启开发者模式。4. 填写接口配置信息
同样是在“开发”-“基本配置”- “服务器配置”菜单中配置,需要配置两项参数:URL: 服务器地址,目前仅支持80端口
TOKEN: 令牌,随意填写,以”hello2017”为例,用于生成签名
填写完把下面代码保存为index.php并上传至http://your.server.ip/chat/目录,最后点击“提交”完成验证。其中your.server.ip是你的服务器IP地址或者域名。
<?php /** * wechat php test */ //define your token define("TOKEN", "hello2017"); $wechatObj = new wechatCallbackapiTest(); $wechatObj->valid(); class wechatCallbackapiTest { public function valid() { $echoStr = $_GET["echostr"]; //valid signature , option if($this->checkSignature()){ echo $echoStr; exit; } } private function checkSignature() { // you must define TOKEN by yourself if (!defined("TOKEN")) { throw new Exception('TOKEN is not defined!'); } $signature = $_GET["signature"]; $timestamp = $_GET["timestamp"]; $nonce = $_GET["nonce"]; $token = TOKEN; $tmpArr = array($token, $timestamp, $nonce); // use SORT_STRING rule sort($tmpArr, SORT_STRING); $tmpStr = implode( $tmpArr ); $tmpStr = sha1( $tmpStr ); if( $tmpStr == $signature ){ return true; }else{ return false; } } } ?>
这玩意儿就是微信公众平台校验URL是否正确接入,研究代码没有实质性意义,验证完即可删除文件,就不详细说明了,有兴趣的童鞋可以查看官方文档。
微信公众平台API文档
5. 开发微信公众平台功能
OK,上面提到了,微信公众平台与开发者之间的数据交互是通过XML完成的,既然用到XML,当然得遵循规范,所以在着手开发之前先看看官方接口文档提供的XML规范,以文本消息为例:<xml> <!--开发者微信号--> <ToUserName><![CDATA[toUser]]></ToUserName> <!--发送方帐号(OpenID)--> <FromUserName><![CDATA[fromUser]]></FromUserName> <!--消息创建时间 (整型)--> <CreateTime>12345678</CreateTime> <!--消息类别 (text文本消息)--> <MsgType><![CDATA1]></MsgType> <!--消息内容--> <Content><![CDATA[content]]></Content> <!--消息ID (64位整型)--> <MsgId>1234567890123456</MsgId> </xml>
开发者在处理完消息后需要返回数据给微信服务器:
<xml> <!--接收方帐号(OpenID)--> <ToUserName><![CDATA[toUser]]></ToUserName> <!--开发者微信号--> <FromUserName><![CDATA[fromUser]]></FromUserName> <!--消息创建时间 (整型)--> <CreateTime>12345678</CreateTime> <!--消息类别 (text文本消息)--> <MsgType><![CDATA1]></MsgType> <!--回复消息内容--> <Content><![CDATA[content]]></Content> <!--星标操作(位0x0001被标志时 星标刚收到的消息)--> <FuncFlag>0</FuncFlag> </xml>
除文本消息外,微信公众平台还支持用户发送图片消息、地理位置消息、链接消息、事件推送,而开发者还可以向微信公众平台回复音乐消息和图文消息,各类消息XML规范也可以参见官方文档。
来看看官方提供的一个PHP示例,我结合图灵机器人接口做了一些修改:
<?php /** * wechat php test */ $wechatObj = new wechatCallbackapiTest(); $wechatObj->responseMsg(); class wechatCallbackapiTest { // the api key string of the tuling // Replace your own apikey here ! const tuling_apiKey = "d8cca87d4ec446629bd4750cf404d84233"; const tuling_apiUrl = "http://www.tuling123.com/openapi/api?key="; const tuling_userid = 0; // response the wechat user by tuling robot according to the keyword function responseByTulingRobot( $keyword ) { $responseStr = ""; $apiUrlStr = self::tuling_apiUrl . self::tuling_apiKey . '&userid=' . self::tuling_userid . '&info='; try{ $text = file_get_contents($apiUrlStr . urlencode($keyword)); $result = json_decode($text); switch ($result->code) { // text type case 100000 : $responseStr = $result -> text; break; // link type case 200000 : $responseStr = $result -> text . ": </br> " . "<a style=\"color='#000000';\" href=\"" . $result -> url . "\"> ---go---</a>"; break; // others default: $responseStr = "I don't know how to response you !"; break; } } catch(Exception $e) { $responseStr = "Sorry I don't know how to response you !"; } return $responseStr; } private function writeLog($content) { file_put_contents("/tmp/log.txg", $content, FILE_APPEND); } public function responseMsg() { //get post data, May be due to the different environments $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; $this->writeLog( $postStr ); //extract post data if (!empty($postStr)){ /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection, the best way is to check the validity of xml by yourself */ libxml_disable_entity_loader(true); $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!"; $contentStr = $this->responseByTulingRobot($keyword); $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); echo $resultStr; writeLog($resultStr); }else{ echo "Input something..."; } }else { echo ""; exit; } } } ?>
简单的测试了下效果如下:
希望本文所述对大家基于php的微信公众平台开发有所帮助。
相关文章推荐
- 聊天机器人的实现(基于C#和图灵API)
- 使用图灵api创建微信聊天机器人
- 快速实现基于Python的微信聊天机器人示例代码
- 使用图灵api创建微信聊天机器人
- Android微信扫描二维码登入实现 基于ZXing开源工程
- 实现基于 cookie 的储存 API
- 基于GoogleMap,Mapabc,51ditu基于GoogleMap,Mapabc,51ditu,VirtualEarth,YahooMap Api接口的Jquery插件的通用实现(含源代码下载)
- JPA核心API-基于Hibernate实现
- 基于GoogleMap,Mapabc,51ditu,VirtualEarth,YahooMap Api接口的Jquery插件的通用实现(含源代码下载)
- 基于google Zxing实现二维码、条形码扫描,仿微信二维码扫描效果
- 本应用是基于淘宝开放平台(TOP)API以及Google Map JavaScript API的基础上实现的一个自用型淘宝买家应用。
- 基于各类地图 Api接口的Jquery插件的通用实现(含源代码下载)
- 基于google Zxing实现二维码、条形码扫描,仿微信二维码扫描效果
- Android 基于google Zxing实现二维码、条形码扫描,仿微信二维码扫描效果
- 基于google Zxing实现二维码、条形码扫描,仿微信二维码扫描效果
- 基于新浪微博api的微博分享功能实现
- 基于Google API的全文翻译Web Service实现
- 基于GoogleMap,Mapabc,51ditu,VirtualEarth,YahooMap Api接口的Jquery插件的通用实现(含源代码下载)
- 基于PhoneGap+JQuery Mobile+ArcGISJavascript API实现
- 读书札记:基于RBAC的权限设计模型--权限API和权限的实现