wechaty可以接入腾讯自己的聊天机器人api,来实现消息自动回复。腾讯聊天机器人业务在自然语言处理》对话机器人》闲聊下。
这里以自建的get方式php api为示例,
1 |
composer require tencentcloud/tencentcloud-sdk-php |
api.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<?php require_once 'vendor/autoload.php'; use TencentCloud\Common\Credential; use TencentCloud\Common\Profile\ClientProfile; use TencentCloud\Common\Profile\HttpProfile; use TencentCloud\Common\Exception\TencentCloudSDKException; use TencentCloud\Nlp\V20190408\NlpClient; use TencentCloud\Nlp\V20190408\Models\ChatBotRequest; //input if (isset($_GET['send'])) { $send = $_GET['send']; } else { die(); } try { $cred = new Credential("SecretId-change-it", "SecretKey-change-it"); $httpProfile = new HttpProfile(); $httpProfile->setEndpoint("nlp.tencentcloudapi.com"); $clientProfile = new ClientProfile(); $clientProfile->setHttpProfile($httpProfile); $client = new NlpClient($cred, "ap-guangzhou", $clientProfile); $req = new ChatBotRequest(); $params = array( "Query" => "$send" ); $req->fromJsonString(json_encode($params)); $resp = $client->ChatBot($req); print_r($resp->toJsonString()); } catch(TencentCloudSDKException $e) { echo $e; } |
bot.js
1 2 3 4 5 6 7 8 9 10 11 12 13 |
if (msg.type() == bot.Message.Type.Text) { // tencent chatbot await axios.get(`https://your-api-server-address-change-me/api.php?send=${encodeURIComponent(msg.text())}`) .then(res=>{ console.log(res.data) global.autoReplySay = res.data.Reply if(res.data.Confidence < 0.5){ global.autoReplySay = "..." } }) } await msg.say(global.autoReplySay) } |
这里实在不知道如何把.then的值带到外面,所以用了global变量。Confidence应该是回复的匹配指数,可以用这个值来判断是否要丢弃这次的回复内容,这里设定判断阈值为0.5。注意替换上方的msg为你自己的message实例对象名称。另外需要用到axios模块 import axios from 'axios' 。
腾讯chatbot的返回内容格式
1 2 3 4 5 |
{ Reply: '不是姑姑我不明白,这世界变化快', Confidence: 0, RequestId: 'fac765f1-580f-401d-b8db-f65f1a544df2' } |
There are no comments yet