ajxs实现移动端聊天机器人(附源码含注释)
1、首先看图成品
我们使用谷歌浏览器上的移动端调式程序,直接进行代码编辑与调式
这个是目录结构
2、HTML与css设计样式
HTML代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>聊天机器人</title>
<link rel="stylesheet" href="./css/index.css">
</head>
<body>
<div class="header">人工智能机器人</div>
<div id="mainContainer" class="main">
<div class="chat-container robot-container">
<img src="./img/robot.jpg" alt="">
<div class="chat-txt">
您好!我是腾讯机器人,非常欢迎您的到来,有什么想和我聊聊的吗?
</div>
</div>
<!-- <div class="chat-container self-container">
<img src="./img/avatar.jpg" alt="">
<div class="chat-txt">
你好
</div>
</div> -->
</div>
<div class="footer">
<input id="inputNode" class="input" type="text" placeholder="请在这里输入聊天信息">
<span id="sendBtn" class="send-btn">发送</span>
</div>
<script src="./js/ajax.js"></script>
<script src="./js/index.js"></script>
</body>
</html>
css代码
*{
margin: 0;
padding: 0;
}
html,
body {
height: 100%;
font-size: 14px;
}
/* 头部文件 */
.header {
height: 56px;
line-height: 56px;
background-color: #3b3a3f;
text-align: center;
font-size: 18px;
color: #fff;
font-weight: bold;
}
/* 主体样式 */
.main {
overflow-y: scroll;
height: calc(100% - 108px);
padding: 20px;
box-sizing: border-box;
}
.main img {
width: 40px;
border-radius: 50%;
}
.chat-container {
margin-bottom: 20px;
}
.chat-container>* {
float: left;
}
.chat-container.self-container>* {
float: right;
}
.chat-container.self-container>.chat-txt {
margin-right: 10px;
background-color: #98e855;
}
.chat-container.self-container>.chat-txt:after {
content: "";
width: 0;
height: 0;
border: 6px solid transparent;
border-left-color: #98e855;
position: absolute;
top: 50%;
transform: translateY(-50%);
right: -12px;
}
.chat-container:after {
content: "";
display: block;
clear: both;
}
.chat-txt {
max-width: 251px;
padding: 8px;
background-color: #fff;
box-sizing: border-box;
border: 1px solid #d8d8d8;
color: #333;
border-radius: 6px;
margin-left: 10px;
position: relative;
}
/* footer样式 */
.footer {
position: absolute;
width: 100%;
left: 0;
bottom: 0;
height: 52px;
line-height: 52px;
background-color: #ebebeb;
box-sizing: border-box;
box-shadow: 0 -2px 5px #d8d8d8;
text-align: center;
}
.input {
width: 270px;
height: 36px;
margin: 0;
padding: 5px 10px;
border: 1px solid #d8d8d8;
color: #333;
box-sizing: border-box;
background-color: #fff;
border-radius: 18px;
outline: none;
}
.send-btn {
width: 54px;
height: 34px;
line-height: 34px;
display: inline-block;
text-align: center;
color: #fff;
background-color: #02cb0b;
}
3、结构样式代码不是重点,接下来我们来看看js代码块
1、初始化获取按钮,绑定事件
2、获取输入的value值,实现内容的渲染(判断一下用户是否输入了文字,如果为空,禁止的动作)
3、实现内容的渲染操作
3-1: 渲染我们自己输入的内容
3-2: 发送数据请求,获取机器人的响应内容
3-3: 渲染机器人的内容
3-4 定义一个公共的渲染函数
4、 滚动条每一次都有触底的操作
(function() {
var sendBtn = document.getElementById('sendBtn')
var inputNode = document.getElementById('inputNode')
var mainContainer = document.getElementById('mainContainer')
/* 程序的入口函数 */
var init = function() {
initEvent()
}
/* 事件绑定入口函数 */
var initEvent = function() {
sendBtn.addEventListener('click', onSendBtnClick)
}
/* 按钮的事件绑定函数 */
var onSendBtnClick = function() {
var txt = inputNode.value.trim()
if (!txt) return
renderHtml(txt, 'right')
sendChatInfo(txt)
inputNode.value = ''
}
/* 发送数据请求,获取后端的响应内容 */
var sendChatInfo = function(txt) {
ajax({
url: 'https://api.hyfarsight.com/test/testRequest/robotChat',
method: "POST",
data: {
txt: txt
},
type: "json",
onSuccess: function(res) {
renderHtml(res.responseTxt, 'left')
}
})
}
/* 渲染函数 */
var renderHtml = function(txt, direction) {
var parentDiv = document.createElement('div')
parentDiv.className = direction === 'right' ? 'chat-container self-container' :
'chat-container robot-container'
var img = document.createElement('img')
img.src = direction === 'right' ? './img/avatar.jpg' : './img/robot.jpg'
var childDiv = document.createElement('div')
childDiv.className = 'chat-txt'
childDiv.innerHTML = txt
parentDiv.appendChild(img)
parentDiv.appendChild(childDiv)
mainContainer.appendChild(parentDiv)
var bottomDistance = parentDiv.offsetTop
console.log(bottomDistance)
mainContainer.scrollTo(0, bottomDistance)
}
init();
})()
4、我们直接调用腾讯的接口
router.post('/robotChat', async ctx => {
/* 获取前端的请求的参数 */
let {
txt: question
} = ctx.request.body
question = question.replace(/\s+/g, '')
/* 注册了腾讯账号,免费获取的key,自己找 */
const app_key = '你的API';
/* 准备请求腾讯ai 的参数 */
const params = {
'app_id': 2170573887,
'nonce_str': stringRandom(5, 'abcdefghijklmnopqrstuvwxyz'),
question,
'session': '10001',
'time_stamp': Math.floor(Date.now() / 1000)
}
/* 生成腾讯需要的签名 */
params.sign = generateFn(params, app_key)
/* 真正的调用腾讯的接口 */
const response = await axios.post(`https://api.ai.qq.com/fcgi-bin/nlp/nlp_textchat`, qs.stringify(
params))
/* 返回给同学们 */
if (response.data.ret !== 0) {
ctx.body = {
code: 1,
responseTxt: '我不知道你在讲什么!!!'
}
} else {
ctx.body = {
code: 0,
responseTxt: response.data.data.answer
}
}
})
/* 生成md5函数 */
const generateFn = (params, app_key) => {
let str = '';
Object.keys(params).forEach(key => {
str += `${key}=${urlencode(params[key])}&`
})
str += `app_key=${app_key}`
return md5(str).toUpperCase()
}
因为目前腾讯接口申请不了了,我直接把自己的源码全部拿出来,可以直接使用,实现聊天功能,需要的直接提取
链接:https://pan.baidu.com/s/16SxB53QsLc3_Uc6DMZSNBA
提取码:79ek