一、为什么需要聊天机器人
(一)公众号、客服自动回复 ×
(二)在线闲聊 ×
(三)拓宽功能 ×
(四)应付对象 ✔
二、那么在哪里才能搞得到
机器人汇总:
https://blog.csdn.net/wenxuhonghe/article/details/100703398
这个帖子里列出了常见的一些机器人API,提供了各机器人的官网及其特点,简明扼要。
三、我搞到了,该怎么用
这里给各位介绍青云客、图灵机器人、海知智能三种机器人的使用和调用流程。
青云客机器人:作为公共机器人,调用方式较为容易,无需其他jar或工具类,可直接复制以下代码使用
图灵机器人、海知智能机器人:均为私有机器人,需要申请个人账户创建个人机器人,调用方式较为复杂,需要使用到一些jar包与工具类,这些工具类因代码过长未在本文贴出。
整个项目已经发布至github,欢迎各位看客下载交流
地址:https://github.com/Nannan78/talking_robot
以下方式中,字符编码均使用UTF-8,数据格式均采用JSON
(一)青云客(初学者强推)
1、特点:
轻便:调用简单,完全免费,无需注册,不需要申请密钥,可直接调用,因此响应的内容也较为简洁。
2、调用方式:
这里有三个需要注意的地方:请求地址、请求方式与参数传入
请求地址:即请求调用的机器人API接口
请求方式:GET
参数:
①、key:"free"字符串,固定值,必填
②、appid:若传入"0"字符串,表示对消息智能识别,选填
③、msg:即发给机器人的消息,必填
3、代码实现:
在官网案例中,采用以GET方式进行URL拼接发起请求,我们这里也依葫芦画瓢照着做。
(1)创建URL连接
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
public class QingYunKeRobot {
public static String getQingYunKe(String generalUrl, String key,String msg)
throws Exception {
key= URLEncoder.encode(key, "UTF-8");
msg= URLEncoder.encode(msg, "UTF-8");
generalUrl=generalUrl+"?key="+key+"&"+"appid=0"+"&"+"msg="+msg;
URL url = new URL(generalUrl);
// 打开和URL之间的连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
// 设置通用的请求属性
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true);
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> headers = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String info : headers.keySet()) {
System.err.println(info + "--->" + headers.get(info));
}
// 定义 BufferedReader输入流来读取URL的响应
BufferedReader in = null;
in = new BufferedReader(
new InputStreamReader(connection.getInputStream(), "UTF-8"));
String result = "";
String getLine;
while ((getLine = in.readLine()) != null) {
result += getLine;
}
in.close();
System.err.println("result:" + result);
return result;
}
}
(2)传入参数
import com.nan.robots.QingYunKeRobot;
public class QingYunKeConnection {
private static final String url = "http://api.qingyunke.com/api.php";
private static final String key = "free";
public static String getResponse(String msg) throws Exception {
String response = QingYunKeRobot.getQingYunKe(url, key,msg);
return response;
}
}
(3)测试
import com.nan.connection.HaiZhiConnection;
import com.nan.connection.QingYunKeConnection;
import com.nan.connection.TuLingConnection;
import com.nan.util.JsonFormatTool;
public class TestRobots {
public static void main(String[] args) throws Exception {
String response = QingYunKeConnection.getResponse("你好啊");
System.out.println(new JsonFormatTool().formatJson(response));
}
}
执行OK!
(二)图灵机器人
1、特点:
基本功能完善,可创建自己专属的机器人。需要注册,每日限定100次调用
2、注册
(1)来我们首先打开官网,点击注册
(2)注册完成后,点击创建机器人,设置相应的属性,就可以得到我们自己的一个机器人啦。
这里两个重要的参数:
用户ID:右上角的数字
apikey:机器人的API密钥
这两个参数在我们发起请求的时候需要用上。
3、调用方式
API调用官方文档:
https://www.kancloud.cn/turing/www-tuling123-com/718227
(1)使用方式
这里我们注意到:
编码:代码中的编码方式应全部设置为UTF-8
数据:数据的格式采用JSON
请求方式:POST
请求接口:http://openapi.tuling123.com/openapi/api/v2
(2)参数设置
官网给出的是参数是表格形式,但我还是觉得图片好理解一点,所以做了下图:
大家别被这么多参数项吓怕了,其实其中要求我们填写的并没有那么多,
发起一个简单的请求只需要三个参数:perception、apiKey与userId。
①reqType:说明输入的数据类型,0-文本(默认)、1-图片、2-音频,选填
②perception:用户输入的数据,大部分情况下都使用文本形式,必填
③userInfo:标识机器人的信息,需要使用到刚刚提及的apiKey与用户ID,必填
官方请求示例:
{
"reqType":0,
"perception": {
"inputText": {
"text": "附近的酒店"
},
"inputImage": {
"url": "imageUrl"
},
"selfInfo": {
"location": {
"city": "北京",
"province": "北京",
"street": "信息路"
}
}
},
"userInfo": {
"apiKey": "",
"userId": ""
}
}
3、代码实现
(1)建立URL连接
import com.nan.util.HttpUtil;
import org.json.JSONArray;
import org.json.JSONObject;
public class TuLingRobot {
public static String getResponse(String request,String requestUrl,String apiKey,String userId,String contentType){
JSONObject perception = new JSONObject();
JSONObject inputText = new JSONObject();
inputText.put("text", request);
perception.put("inputText", inputText);
JSONObject userInfo = new JSONObject();
userInfo.put("apiKey", apiKey);
userInfo.put("userId", userId);
JSONObject root = new JSONObject();
root.put("reqType", 0);
root.put("perception", perception);
root.put("userInfo", userInfo);
String params = root.toString();
System.out.println(params);
try {
String resultString = HttpUtil.postGeneralUrl(requestUrl, contentType, params, "UTF-8");
System.out.println(resultString);
JSONObject resultJson = new JSONObject(resultString);
JSONArray results = resultJson.getJSONArray("results");
JSONObject values = ((JSONObject)(results.get(0))).getJSONObject("values");
String text = values.getString("text");
return text;
} catch (Exception e) {
e.printStackTrace();
return "我不知道怎么回答你";
}
}
}
(2)传入参数
注意:将此处的apiKey与userId替换为自己创建的机器人时得到信息
import com.nan.robots.TuLingRobot;
public class TuLingConnection {
private static final String requestUrl = "http://openapi.tuling123.com/openapi/api/v2";
/**
* 在图灵机器人官网注册登陆后,在右上角产生你的useId;
* 创建机器人后,生成apiKey
*/
private static final String apiKey = "apiKey";
private static final String userId = "userId";
private static final String contentType = "application/json";
public static String getResponse(String request) {
String response = TuLingRobot.getResponse(request,requestUrl,apiKey,userId,contentType);
return response;
}
}
(3)测试
import com.nan.connection.HaiZhiConnection;
import com.nan.connection.QingYunKeConnection;
import com.nan.connection.TuLingConnection;
import com.nan.util.JsonFormatTool;
public class TestRobots {
public static void main(String[] args) throws Exception {
String response = TuLingConnection.getResponse("你好啊");
System.out.println(new JsonFormatTool().formatJson(response));
}
}
测试OK!
(三)海知智能机器人
官网:
https://ruyi.ai/official.html
1、特点:
功能强大,覆盖面广,免费,不限调用次数,需注册,可定制高
2、注册
(1)首先还是得来到我们的官网进行注册登录
(2)注册完成后登录,点击创建机器人
(3)选择机器人的类型及功能
(4)然后我们就可以得到自己的机器人啦
此处的AppKey需要在调用的时候使用到
接下来我们就可以愉快的调用我们的机器人啦!
3、调用方式
API调用官方文档:
http://docs.ruyi.ai/502931
(1)使用方式
好像也没说到啥…注意三个点
数据:数据的格式采用JSON
请求方式:POST
请求接口:http://api.ruyi.ai/v1/message
(2)参数设置
官网怎么总喜欢给出表格形式的参数呀,我还是画个图吧
①q:用户输入的数据,大部分情况下都使用文本形式,必填
②app_key:标识机器人的信息,需要使用到刚刚提及机器人的AppKey,必填
③user_id:用来标识用户的ID,官方建议建议开发者使用UUID字符,必填
④reset_session:如果为true,重置当前对话session,忘记短期对话记忆,选填
⑤context:用户当前上下文信息。JSON字符串格式,选填
官方请求示例:
curl 命令
> curl -H "Content-Type: application/json" -X POST --data @content.json http://api.ruyi.ai/v1/message
content.json 内容
> cat content.json
{
"q": "你好",
"app_key": "xxxx",
"user_id": "xxxx",
"reset_session": true,
"context": {
"location": {
"latitude": "39.92",
"longitude": "116.46"
}
}
}
4、代码实现
(1)建立URL连接
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
public class HaiZhiZhiNengRobot {
public static String postHaiZhi(String generalUrl, String params)
throws Exception {
URL url = new URL(generalUrl);
// 打开和URL之间的连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
// 设置通用的请求属性
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded ");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true);
// 得到请求的输出流对象
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.write(params.getBytes("UTF-8"));
out.flush();
out.close();
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> headers = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : headers.keySet()) {
System.err.println(key + "--->" + headers.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
BufferedReader in = null;
in = new BufferedReader(
new InputStreamReader(connection.getInputStream(), "UTF-8"));
String result = "";
String getLine;
while ((getLine = in.readLine()) != null) {
result += getLine;
}
in.close();
System.err.println("result:" + result);
return result;
}
}
(2)传入参数
注意:将此处的app_key替换为自己创建的机器人时得到AppKey
import com.nan.robots.HaiZhiZhiNengRobot;
import com.nan.util.GsonUtils;
import com.nan.util.JsonFormatTool;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class HaiZhiConnection {
private static final String url = "http://api.ruyi.ai/v1/message";
private static final String app_key = "app_key";
private static final String user_id = UUID.randomUUID().toString();
public static String getResponseByPost(String q){
try {
Map<String, Object> map = new HashMap<>();
map.put("q", q);
map.put("app_key", app_key);
map.put("user_id", user_id);
String param = GsonUtils.toJson(map);
String result = HaiZhiZhiNengRobot.postHaiZhi(url,param);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String getResponseByGet(String q){
try {
String result = HaiZhiZhiNengRobot.getHaiZhi(url,q,app_key,user_id);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
(3)测试
import com.nan.connection.HaiZhiConnection;
import com.nan.connection.QingYunKeConnection;
import com.nan.connection.TuLingConnection;
import com.nan.util.JsonFormatTool;
public class TestRobots {
public static void main(String[] args) throws Exception {
String response = HaiZhiConnection.getResponseByPost("你好啊");
System.out.println(new JsonFormatTool().formatJson(response));
}
}
测试OK!
四、使用总结
青云客机器人:其简易型十分受用于初学者,但作为公共接口,响应内容较少,响应时间略长。
图灵机器人:较青云客机器人而言,功能更加齐全,响应速度较快,但需要注册创建机器人,并且一天最多只能调用100次。
海知智能机器人:功能十分完善的一款机器人,定制度很高,相应内容丰富,而且调用次数不限,但需要注册创建机器人。
项目地址:https://github.com/Nannan78/talking_robot
参考:https://blog.csdn.net/haoranhaoshi/article/details/87992548