基于JQ使用原生js构造一个自动回复随机消息的机器人
某些业务会使用到页面里存在一个机器人,类似于假客服一样,可以回复游客的问题.
那么如何自己写一个自动回复消息的机器人呢?
源码献上
/**
* 基于jq的自动对话机器人
* @param {Object} parmas 初始化配置
* parmas.talkModal 对话框弹出主体 classname
* parmas.talkBox 对话框内容区域 classname
* parmas.awakeBtn 唤醒按钮 用于显示对话框主体 classname
* parmas.exitBtn 隐藏按钮 用户隐藏对话框按钮 classname
* parmas.sendBtn 发送消息按钮 classname
* parmas.autoConent 自动对话框内容 Array
* parmas.input 内容输入框 classname
* parmas.openReply 在打开的时候自动回复一句 true or false 默认true
* parmas.replyName 自动回复的dom类名 classname
* parmas.userName 用户回复的dom类名 classname
* parmas.isChangeBtnStatus 是否在点击 唤醒和隐藏的时候隐藏相反的按钮 true or false 默认true
* parmas.fixedMsg 固定回复语句 string or dom
*
*/
function Talk(parmas) {
if (typeof $ === "undefined") {
throw new Error("Please load JQ API before use the Talk function!")
}
this.talkModal = $('.' + parmas.talkModal);
this.talkContent = $("." + parmas.talkBox)
this.awakeBtn = $("." + parmas.awakeBtn)
this.autoConent = parmas.autoConent || ['你好', "欢迎你", "谢谢", "再见"]
this.exitBtn = $("." + parmas.exitBtn)
this.input = $("." + parmas.input)
this.sendBtn = $("." + parmas.sendBtn)
this.contentDefaultHeight = 0 // 对话框内容区域高度
this.autoTimer = null; // 自动回复定时器
this.autoIndexArr = Array.from({ length: this.autoConent.length }, (v, k) => k) //随机索引,先默认数组索引下标排列
this.contentIndex = 0;
this.openReply = parmas.openReply !== undefined ? parmas.openReply : true;
this.fixedMsg = parmas.fixedMsg || "收到";
this.isFixedReply = false;
this.changeBtnStatus = parmas.isChangeBtnStatus !== undefined ? parmas.isChangeBtnStatus : true
this.replyClassName = parmas.replyName || 'reply'
this.userClassName = parmas.userName || 'customer-txt'
// 检查绑定的dom是否符合规范
this.isInvalid()
// 绑定监听事件
this.addEvent()
// 生成自动回复索引
this.randomIndex()
}
// 检查绑定的dom是否符合规范
Talk.prototype.isInvalid = function () {
if (this.talkModal.length === 0) {
throw new Error('The TalkModal is not found.Please check out the binding TalkModel.')
}
if (this.talkContent.length === 0) {
throw new Error("The TalkModal's contentBox is not found.Please check out the binding TalkModal's contentBox.")
}
if (this.awakeBtn.length === 0) {
throw new Error("The TalkModal's awake Button is not found.Please check out the binding TalkModal's awake Button.")
}
if (this.input.length === 0) {
throw new Error("The TalkModal's input is not found.Please check out the binding TalkModal's input.")
} if (this.talkModal.length !== 1) {
throw new Error("The TalkModal is not unique classname,Please check out the dom's classname.")
}
if (this.talkContent.length !== 1) {
throw new Error("The TalkModal's contentBox is not unique classname,Please check out the dom's classname.")
}
if (this.awakeBtn.length !== 1) {
throw new Error("The TalkModal's awake Button is not unique classname,Please check out the dom's classname.")
}
if (this.input.length !== 1) {
throw new Error("The TalkModal's input is not unique classname,Please check out the dom's classname.")
}
} // 绑定事件
Talk.prototype.addEvent = function () {
// 唤醒对话框按钮绑定事件
this.awakeBtn.click(function (e) {
e.stopPropagation || e.stopPropagation()
this.showModal()
}.bind(this))
// 关闭对话框按钮 绑定事件
this.exitBtn.click(function (e) {
e.stopPropagation || e.stopPropagation()
this.hiddenModal()
}.bind(this))
// 发送消息按钮 绑定事件
this.sendBtn.click(function (e) {
e.stopPropagation || e.stopPropagation()
this.sendMsg()
}.bind(this))
// 输入框按钮监听回车
this.input.on("keypress", function (event) {
if (event.keyCode == "13") {
this.sendMsg()
}
}.bind(this))
} // 显示对话框
Talk.prototype.showModal = function () {
this.talkModal.fadeIn(300)
if (this.changeBtnStatus) {
this.awakeBtn.hide()
this.exitBtn.show()
}
if (this.openReply) {
this.autoReply()
}
if (this.contentDefaultHeight === 0) {
this.contentDefaultHeight = this.talkContent.height()
}
} // 隐藏对话框
Talk.prototype.hiddenModal = function () {
clearTimeout(this.autoTimer)
this.talkModal.fadeOut(0)
if (this.changeBtnStatus) {
this.exitBtn.hide()
this.awakeBtn.show()
}
} // 用户主动发送消息
Talk.prototype.sendMsg = function () {
var val = this.input.val()
if (!val || !val.trim()) {
return
}
this.appendContent(this.userClassName, val)
this.input.val('')
this.isFixedReply = false
// ...这里可以判断用户输入信息进行其他处理
this.dealMsg(val) }
/**
* 处理用户输入信息 根据信息来回复
* @param {String} msg 用户输入信息
*/
Talk.prototype.dealMsg = function (msg) {
// ...do Ajax or on the msg,according to directed reply
if (msg === "你好") {
var str = '我不好'
this.autoReply(str)
return
}
if (msg === "18888888888") {
this.isFixedReply = true
}
// auto reply
this.autoReply()
} /**
* 追加文本,每次聊天后滚动聊天区域
* @param {String} classname 回复的类名 用于显示不同的对话
* @param {String} content 内容,即聊天内容
*/
Talk.prototype.appendContent = function (classname, content) {
this.talkContent.append('<div><p class="' + classname + '">' + content + '</p></div>')
this.srcollContent()
} // 滚动聊天内容区域
Talk.prototype.srcollContent = function () {
var height = this.talkContent.prop("scrollHeight")
if (this.contentDefaultHeight > height) {
return
}
this.talkContent.animate({ scrollTop: height }, 400);
} /**
* 机器人自动回复
* @param {String} str 需要回复的内容 若没有则自动回复
*/
Talk.prototype.autoReply = function (str) {
clearTimeout(this.autoTimer)
this.autoTimer = setTimeout(function () {
if (this.isFixedReply) {
return this.appendContent(this.replyClassName, this.fixedMsg)
}
if (str) {
return this.appendContent(this.replyClassName, str)
}
var content = this.autoConent[this.autoIndexArr[this.contentIndex]]
this.contentIndex += 1
this.appendContent(this.replyClassName, content)
if (this.contentIndex === this.autoConent.length) {
this.randomIndex()
this.contentIndex = 0
}
}.bind(this), 1500)
} // 生成随机的消息索引数组
Talk.prototype.randomIndex = function () {
var len = this.autoConent.length;
var temp = this.autoIndexArr
for (var i = 0; i < len + 10; i++) {
var rdm = Math.floor(Math.random() * temp.length)
temp.push(temp[rdm])
temp.splice(rdm, 1)
}
if (temp[0] === this.autoIndexArr[len - 1]) {
this.randomIndex()
} else {
this.autoIndexArr = temp
}
}
如何自己定制机器人回复内容
只需要重写Talk函数的dealMsg函数即可,默认第一个参数是用户输入的内容,根据第一个参数进行判断去调用this.autoReply(str)即可,若不传str则默认是以预设的自动回复语句去回复.
若你是否重写dealMsg,在Talk构造函数之后去实例化
- 实例化
var talk = new Talk({
talkModal: "modal", // 对话框主体
talkBox: "talk-content", // 对话框内容区域
awakeBtn: "awake", // 唤醒对话框按钮
exitBtn: "exit", // 关闭对话框按钮
input: "ipt", // 对话框input
sendBtn: "send", // 发送信息按钮 // 自动回复的语句可以包含html字符
replyName: "reply", //回复的类名 用于样式
userName: "msg", // 用户使用的类名 用于样式
openReply: false, // 打开自动回复一句
})
案例
<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Talk</title>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<!-- 请在jq加载后,加载Talk,引入文件方式 ,或者 直接把函数复制到script里即可-->
<script src="./Talk.js"></script>
<style>
* {
margin: 0;
padding: 0;
border: 0;
} .header {
padding: 20px;
text-align: center;
font-size: 24px;
background-color: antiquewhite;
} .content {
text-align: center;
font-size: 24px;
height: 1000px;
line-height: 500px;
background-color: aquamarine;
} .fixed-wrap {
position: fixed;
right: 0;
top: 50%;
transform: translateY(-50%);
width: 30px;
height: 100px;
background-color: blanchedalmond;
} .btn {
text-align: center;
padding: 3px 5px;
font-size: 14px;
cursor: pointer;
} .exit {
display: none;
} .modal {
position: absolute;
display: none;
left: -300px;
top: -70px;
padding: 10px;
width: 300px;
height: 240px;
box-sizing: border-box;
background-color: burlywood;
} .talk-content {
height: 200px;
overflow-y: auto;
} .talk-content div {
overflow: hidden;
} .talk-content p {
margin-bottom: 10px;
padding: 8px;
max-width: 80%;
word-break: break-all;
font-size: 12px;
color: #000;
border-radius: 10px;
} .talk-content span {
color: red;
} .msg {
float: right;
background-color: #b7e6e7;
} .reply {
float: left;
background-color: #fff;
} .control {
position: absolute;
left: 10px;
bottom: 5px;
height: 25px;
} .control input,
.control button {
outline: none;
height: 100%;
padding: 0 10px;
}
</style>
</head> <body>
<div class="header">header</div>
<div class="content">content</div>
<div class="fixed-wrap">
<div class="awake btn">展开机器人</div>
<div class="exit btn">关闭机器人</div>
<div class="modal">
<div class="talk-content">
</div>
<div class="control">
<input type="text" class="ipt">
<button class="send">发送</button>
</div>
</div>
</div>
</body>
<script>
var talk = new Talk({
talkModal: "modal", // 对话框主体
talkBox: "talk-content", // 对话框内容区域
awakeBtn: "awake", // 唤醒对话框按钮
exitBtn: "exit", // 关闭对话框按钮
input: "ipt", // 对话框input
sendBtn: "send", // 发送信息按钮 // 自动回复的语句可以包含html字符
replyName: "reply", //回复的类名 用于样式
userName: "msg", // 用户使用的类名 用于样式
openReply: false, // 打开自动回复一句
})
</script> </html>
基于JQ使用原生js构造一个自动回复随机消息的机器人的更多相关文章
- jq与原生js实现收起展开效果
jq与原生js实现收起展开效果 (jq需自己加载) <!DOCTYPE html> <html> <head> <meta charset="UTF ...
- 原生js实现一个DIV的碰撞反弹运动,并且添加重力效果
继上一篇... 原生js实现一个DIV的碰撞反弹运动,并且添加重力效果 关键在于边界检测,以及乘以的系数问题,实现代码并不难,如下: <!DOCTYPE html> <html la ...
- 原生js实现一个DIV的碰撞反弹运动
原生js实现一个DIV的碰撞反弹运动: 关键在于DIV的边界检测,进而改变运动方向,即可实现碰撞反弹效果. <!DOCTYPE html> <html lang="en& ...
- 用原生js写一个"多动症"的简历
用原生js写一个"多动症"的简历 预览地址源码地址 最近在知乎上看到@方应杭用vue写了一个会动的简历,觉得挺好玩的,研究一下其实现思路,决定试试用原生js来实现. 会动的简历实现 ...
- 原生js实现一个简单的轮播图
想锻炼一下自己的原生js能力可以从写一个轮播图开始,轮播图的运用想必大家都知道吧,好了废话不多说,开始记笔记了,一些需要注意的点,我都在代码中标注了 首先是构造html: <div id=&qu ...
- 原生js写一个无缝轮播图插件(支持vue)
轮播图插件(Broadcast.js) 前言:写这个插件的原因 前段时间准备用vue加上网易云的nodejs接口,模拟网易云音乐移动端.因为想自己写一遍所有的代码以及加固自己的flex布局,所以没有使 ...
- 使用原生JS实现一个风箱式的demo,并封装了一个运动框架
声明,该DEMO依托于某个培训机构中,非常感谢这个培训结构.话不多说,现在开始改demo的制作. 首先,在前端的学习过程中,轮播图是我们一定要学习的,所以为了更加高效的实现各种轮播图,封装了一个运动的 ...
- 导航栏中各按钮在点击当前按钮变色其他按钮恢复为原有色的实现方法(vue、jq、原生js)
一.vue如何实现? 代码: <!DOCTYPE html> <html lang="en"> <head> <meta charset= ...
- 用原生JS实现一个轮播(包含全部代码和详细思路)
在我看来要想实现轮播主要是要知道当前位于的页面和即将位于的页面.这个案例是通过改变图片的透明度来实现轮播的效果. 我把涉及的知识点分为两个方面,分别是HTML+css和JS. 第一部分(html+cs ...
- 用原生JS写一个网页版的2048小游戏(兼容移动端)
这个游戏JS部分全都是用原生JS代码写的,加有少量的CSS3动画,并简单的兼容了一下移动端. 先看一下在线的demo:https://yuan-yiming.github.io/2048-online ...
随机推荐
- 传统css布局方案(position,float,line-height等配合)
一.display display 是 css 布局中很重要的一个属性,它定义了元素生成的显示框类型,常见的几个属性值有:block.inline.inline-block.inherit.none. ...
- 当字符遇上 scanf() 要当心
当字符遇上 scanf() 要当心 看一下程序 char ch1,ch2; printf("请输入ch1,ch2的值:"); scanf("%c %c",&am ...
- 数据库—SQL语言学习
文章目录 SQL 数据类型 重要的关键字 定义数据库 数据库的文件 table创建与删除 表的定义 表的alter 表的删除 视图 定义视图 删除视图 更新视图 插入视图 视图总结 索引 SQL单表查 ...
- C#.Net筑基-类型系统①基础
C#.Net的BCL提供了丰富的类型,最基础的是值类型.引用类型,而他们的共同(隐私)祖先是 System.Object(万物之源),所以任何类型都可以转换为Object. 01.数据类型汇总 C#. ...
- RCTF 2024 WEB wp
RCTF 2024 WEB wp 前言 赛后复现,proxy发现自己真是个呆b... what_is_love 首先拿key1,sql语句处有注入,可以盲注拿key1的值 import request ...
- matplotlib学习:搞明白plt. /ax./ fig
原文章一:https://zhuanlan.zhihu.com/p/93423829,原文章二:https://jishuin.proginn.com/p/763bfbd23e20 感谢作者的讲 ...
- 滴滴面试:谈谈你对Netty线程模型的理解?
Netty 线程模型是指 Netty 框架为了提供高性能.高并发的网络通信,而设计的管理和利用线程的策略和机制. Netty 线程模型被称为 Reactor(响应式)模型/模式,它是基于 NIO 多路 ...
- 使用python在k8s中创建一个pod
要在Kubernetes (k8s) 中使用Python创建一个Pod,你可以使用Kubernetes Python客户端库(通常称为kubernetes或kubernetes-client).以下是 ...
- GNU GDB
1 说明 本文主要介绍一些简单的.常用的gdb调试技巧. 环境:GNU gdb (GDB) Red Hat Enterprise Linux (7.2-60.el6_4.1) 参考文档:<gdb ...
- css3 浏览器前缀 线型渐变 过渡属性
css3:没有形成正式版 每个浏览器商,为了能对css3属性形成一个更好的支持,浏览器形成自己一套语法规范,一些css属性,如果想在浏览器上形成支持,有时候需要添加浏览器前缀 谷歌前缀:-webkit ...