Full project address: gitee.com/Tziq/withou…

One, foreword

This tutorial is aimed at developers who want to learn about Web robots, but don’t know where to start. This chapter realizes the text robot, the next article realizes the speech robot

Two, technology selection

The background

  1. springboot
  2. WebSocket
  3. Ali ASR (Real-time)
  4. Ali TTS
  5. Ali Cloud Xiaomei

The front desk

  1. Hzrecorder2.js (H5 recording function, decoding JS)
  2. h5websocket.js

3. Create a cloud Xiaomi account

  1. Ali Cloud created address: help.aliyun.com/document_de…

  2. Get the ID in robot administration

  3. Introduce the required SDK in the Maven project

    < the dependency > < groupId > com. Aliyun < / groupId > < artifactId > aliyun - Java - SDK - chatbot < / artifactId > < version > 1.0.0 < / version > </dependency>Copy the code

    < the dependency > < groupId > com. Aliyun < / groupId > < artifactId > aliyun - Java - SDK - core < / artifactId > < version > 4.5.2 < / version > </dependency> <dependency> <groupId>cn. Hutool </groupId> <artifactId>hutool-all</artifactId> <version>4.5.6</version> </dependency>Copy the code

  4. Called in the main method

    public static void main(String[] args) throws Exception { String accountAccessAK = "XXXXXXXXXXXXXXXXXX"; String accountAccessSK = "XXXXXXXXXXXXXXXXXX"; String popRegion = "cn-shanghai"; String popProduct = "Chatbot"; String popDomain = "chatbot.cn-shanghai.aliyuncs.com"; DefaultProfile.addEndpoint(popRegion, popProduct, popDomain); IClientProfile profile = DefaultProfile.getProfile(popRegion, accountAccessAK, accountAccessSK); DefaultAcsClient client = new DefaultAcsClient(profile); CommonRequest = new CommonRequest(); commonRequest.setSysProduct("Chatbot"); commonRequest.setSysMethod(MethodType.GET); / / change according to API commonRequest. SetSysAction (" Chat "); commonRequest.setSysVersion("2017-10-11"); commonRequest.putQueryParameter("Utterance", "hi"); / / robot id commonRequest. PutQueryParameter (" InstanceId ", "chatbot - cn - XXXXXXXXXXXX"); CommonResponse commonResponse = client.getCommonResponse(commonRequest); System.out.println(commonResponse.getData()); }Copy the code
  5. View return parameters

    {"Messages":[{"Type":"Text","Text":{"UserDefinedChatTitle":" hello ","Content":" Hello ", Is there anything I can help you with ~","AnswerSource":"USER_DEFINED_CHAT","HitStatement":"hi"},"Knowledge":{}}],"RequestId":" 96F2396B-b116-4F65-90F 7-AEBE9D027F65","SessionId":"43619053db654fe3a7e0bed73b9d9d5f","MessageId":"96F2396B-B116-4F65-90F7-AEBE9D027F65"}Copy the code
  6. Encapsulate the dialogue robot in factory mode (for docking with other robots)

  7. Create a generic dialog interface

    package com.withouther.robot.rainingrobot.util.ai.dialogue;
    
    import com.aliyuncs.exceptions.ClientException;
    import com.withouther.robot.rainingrobot.util.ai.dialogue.model.BotResult;
    
    import java.util.Map;
    
    public interface DialogueBot {
        BotResult getDialogue(Map<String, Object> paramMap) throws ClientException;
    }
    Copy the code
  8. Create cloud honey implementation class

    package com.withouther.robot.rainingrobot.util.ai.dialogue; import cn.hutool.http.HttpStatus; import cn.hutool.setting.dialect.Props; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.aliyuncs.CommonRequest; import com.aliyuncs.CommonResponse; import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.http.MethodType; import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.profile.IClientProfile; import com.withouther.robot.rainingrobot.util.ai.dialogue.model.BotResult; import lombok.extern.slf4j.Slf4j; import java.util.HashMap; import java.util.Map; /** * @ClassName BeeBot * @Auther: tzq * @Date: 2020/9/21 14:00 * @Description: */ @Slf4j public class BeeBot implements DialogueBot { private static DefaultAcsClient client = null; public BeeBot() { init(); } public void init(){ Props robotPro = new Props("robot.properties"); String accountAccessAK = robotPro.getStr("ali.accountAccessAK"); String accountAccessSK = robotPro.getStr("ali.accountAccessSK"); String popRegion = robotPro.getStr("ali.popRegion"); String popProduct = robotPro.getStr("ali.popProduct"); String popDomain = robotPro.getStr("ali.popDomain"); if (client == null) { DefaultProfile.addEndpoint(popRegion, popProduct, popDomain); IClientProfile profile = DefaultProfile.getProfile(popRegion, accountAccessAK, accountAccessSK); client = new DefaultAcsClient(profile); } } @Override public BotResult getDialogue(Map<String, Object> paramMap) throws ClientException {// The fixed entry parameter CommonRequest CommonRequest = new CommonRequest(); commonRequest.setSysProduct("Chatbot"); commonRequest.setSysMethod(MethodType.GET); / / change according to API commonRequest. SetSysAction (" Chat "); commonRequest.setSysVersion("2017-10-11"); commonRequest.putQueryParameter("Utterance", (String) paramMap.get("text")); String InstanceId = paramMap.get("InstanceId") == null ? "chatbot-cn-q6YfyVfq6e" : (String) paramMap.get("InstanceId"); commonRequest.putQueryParameter("InstanceId", InstanceId); CommonResponse commonResponse = post(commonRequest); BotResult botResult = new BotResult(); botResult.setSuccess(commonResponse.getHttpStatus() == HttpStatus.HTTP_OK); JSONObject data = JSON.parseObject(commonResponse.getData()); JSONArray messages = data.getJSONArray("Messages"); JSONObject textJson = messages.getJSONObject(0).getJSONObject("Text"); botResult.setText(textJson.getString("Content")); botResult.setRequestId(data.getString("RequestId")); botResult.setMessage(textJson.getString("AnswerSource")); return botResult; } public CommonResponse post(CommonRequest commonRequest) throws ClientException { CommonResponse commonResponse = client.getCommonResponse(commonRequest); System.out.println(commonResponse.getData()); log.debug("dialogueRequest: {}", commonRequest); log.debug("dialogueResponse: {}", commonResponse); return commonResponse; }}Copy the code
  9. Creating a Factory Class

    package com.withouther.robot.rainingrobot.util.ai.dialogue; import com.aliyuncs.exceptions.ClientException; import com.withouther.robot.rainingrobot.util.ai.dialogue.model.BotResult; import java.util.HashMap; import java.util.Map; /** * @ClassName RobotFactory * @Auther: tzq * @Date: 2020/9/21 15:10 * @Description: */ public class RobotFactory { private static RobotFactory tools = null; private static Map<Integer, DialogueBot> strategyMap = new HashMap<>(); /** * public static final int BEEBOT = 1; static { strategyMap.put(BEEBOT, new BeeBot()); } private RobotFactory() { init(); Public void init() {} public void reset() {init(); Public static RobotFactory getFactory() {if (tools == null) {create(); } return tools; } /** * thread-safe creation method, */ private static synchronized void create() {if (tools == null) {tools = new RobotFactory(); } } public BotResult botAction(Map<String, Object> paramMap, int type) throws ClientException { DialogueBot dialogueBot = strategyMap.get(type); return dialogueBot.getDialogue(paramMap); }}Copy the code
  10. Create a generic receiving entity

    package com.withouther.robot.rainingrobot.util.ai.dialogue.model; import lombok.Data; import java.io.Serializable; /** * @ClassName BotResult * @Auther: tzq * @Date: 2020/9/21 14:08 * @Description: */ @data public class BotResult implements Serializable {private String text; private String requestId; private String message; private boolean isSuccess; }Copy the code
  11. To create a robot. The properties

    ali.accountAccessAK = LTAI4G1oyqgD7pZcnrPMZCMj
    ali.accountAccessSK = cEnXSJocB2O4AkAnki9s7L5QXSX5Ve
    ali.popRegion = cn-shanghai
    ali.popProduct = Chatbot
    ali.popDomain = chatbot.cn-shanghai.aliyuncs.com
    Copy the code

Create a dialog interface

  1. Create a controller

    package com.withouther.robot.rainingrobot.rest; import com.withouther.robot.rainingrobot.core.result.CallResult; import com.withouther.robot.rainingrobot.service.RobotRecordService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; /** * @ClassName RobotRecordController * @Auther: tzq * @Date: 2020/7/30 21:31 * @Description: */ @RestController @RequestMapping({"/robotRecord"}) public class RobotRecordController { @Autowired private RobotRecordService robotRecordService; @GetMapping("/dialogue") public CallResult getDialogue(@RequestParam("text") String text) { return CallResult.success(robotRecordService.getDialogue(text)); }}Copy the code
  2. Create a service

    package com.withouther.robot.rainingrobot.service.impl; import cn.hutool.core.util.StrUtil; import com.aliyuncs.exceptions.ClientException; import com.withouther.robot.rainingrobot.service.RobotRecordService; import com.withouther.robot.rainingrobot.util.ai.dialogue.RobotFactory; import com.withouther.robot.rainingrobot.util.ai.dialogue.model.BotResult; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; /** * @ClassName RobotRecordServiceImpl * @Auther: tzq * @Date: 2020/9/21 15:08 * @Description: */ @Service @Slf4j public class RobotRecordServiceImpl implements RobotRecordService { @Override public BotResult getDialogue(String text) { Map<String, Object> paramMap = new HashMap<>(); paramMap.put("text", text); BotResult botResult = null; try { botResult = RobotFactory.getFactory().botAction(paramMap, 1); } catch (ClientException e) { e.printStackTrace(); } if (strutil.isempty (botresult.gettext ())) {log.error(" no answer found: {}", botResult); Botresult. setText(" Oh, you want to ask the question, I don't know for a while." ); } return botResult; }}Copy the code
  3. CallResult can be obtained from the code cloud address

5. Create h5 project

  1. Create a Chat room page

    <html lang="zh-cn" ><head><meta charset="utf-8" /><meta HTTP-EQUIV="pragma" CONTENT="no-cache"><meta HTTP-EQUIV="Cache-Control" CONTENT="no-cache, must-revalidate"><meta HTTP-EQUIV="expires" CONTENT="0"><meta name="apple-touch-fullscreen" content="yes" /><meta name="format-detection" content="telephone=no" /><meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" /><meta name="viewport" content="width=device-width, Initial-scale =1.0 user-scalable=no" media="screen" /><title> <link rel="stylesheet" type="text/ CSS" href="css/main.css"></head><body><div class="speak_window"> <div class="speak_box"> <div class="answer"> <div Class ="heard_img left"><img SRC ="images/service.jpg"></div> <div class="answer_text"> <p>Hey, your own guide is here! You can ask me questions! Sometimes wechat will make a little temper with me, try to close the current page to re-enter ok! </p> <i></i> </div> </div> </div></div><div class="saying"> <img src="images/saying.gif"/></div><div class="wenwen-footer"> <div class="wenwen_text left"> <div class="write_box"> <input type="text" class="left" /> </div> <div class="wenwen_help right"> <button onClick="up_say()" </button> </div> <div style="opacity:0;" Class = "clear" > < / div > < / div > < script type = "text/javascript" SRC = "js/jquery - 3.2.1. Min. Js" > < / script > < div style="text-align:center;" ></div></body><script src="js/ajaxUtil.js"></script><script src="js/robot.js"></script></html>Copy the code
  2. The rest of the JS and CSS can be obtained from the code cloud

Six, the demonstration effect

Seven, conclusion

At present, the text robot of H5 chat room is realized, the next article will comb out how to realize the voice robot, please look forward to!