mui的官方demo是点击进入聊天界面后,在对话框输入消息,系统接入图灵api每天返回有次数限制。
现在要做的功能是1、列表页面有几条数据,点击则跳转聊天界面,自动发送该条点击的数据,机器人自动回复设置好的消息。类似于以前QQ设置离线时,对方给你发送消息,自动提示您好不在线上。
效果图如下:
2、直接点击聊天界面,发送任意消息,调用接口在数据库查询,有值就返回相应内容,否则提示您说的话听不懂。
参考文档:https://www.jianshu.com/p/3ef8ff92d3f8 每个方法作用讲解得比较详细
CSS大同小异,直接上JS部分吧。
先贴所有代码上来:
<script type="text/javascript" charset="utf-8">
(function($, doc) {
var MIN_SOUND_TIME = 800;
$.init({
gestureConfig: {
tap: true, //默认为true
doubletap: true, //默认为false
longtap: true, //默认为false
swipe: true, //默认为true
drag: true, //默认为true
hold: true, //默认为false,不监听
release: true //默认为false,不监听
}
});
template.config('escape', false);
if(mui.os.ios) {
// 解决在ios上fixed元素focusin时位置出现错误的问题
document.addEventListener('DOMContentLoaded', function() {
var footerDom = document.querySelector('footer');
document.addEventListener('focusin', function() {
footerDom.style.position = 'absolute';
});
document.addEventListener('focusout', function() {
footerDom.style.position = 'fixed';
});
});
}
$.plusReady(function() {
plus.webview.currentWebview().setStyle({
softinputMode: "adjustResize"
});
var showKeyboard = function() {
if($.os.ios) {
var webView = plus.webview.currentWebview().nativeInstanceObject();
webView.plusCallMethod({
"setKeyboardDisplayRequiresUserAction": false
});
} else {
var Context = plus.android.importClass("android.content.Context");
var InputMethodManager = plus.android.importClass("android.view.inputmethod.InputMethodManager");
var main = plus.android.runtimeMainActivity();
var imm = main.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
//var view = ((ViewGroup)main.findViewById(android.R.id.content)).getChildAt(0);
imm.showSoftInput(main.getWindow().getDecorView(), InputMethodManager.SHOW_IMPLICIT);
//alert("ll");
}
};
var record = [{
sender: 'zs',
type: 'text',
content: '欢迎使用智能语音福宝,您有什么问题可以问我!'
}];
var ui = {
body: doc.querySelector('body'),
footer: doc.querySelector('footer'),
footerRight: doc.querySelector('.footer-right'),
footerLeft: doc.querySelector('.footer-left'),
btnMsgType: doc.querySelector('#msg-type'),
boxMsgText: doc.querySelector('#msg-text'),
boxMsgSound: doc.querySelector('#msg-sound'),
btnMsgImage: doc.querySelector('#msg-image'),
areaMsgList: doc.querySelector('#msg-list'),
boxSoundAlert: doc.querySelector('#sound-alert'),
h: doc.querySelector('#h'),
content: doc.querySelector('.mui-content')
};
ui.h.style.width = ui.boxMsgText.offsetWidth + 'px';
//alert(ui.boxMsgText.offsetWidth );
var footerPadding = ui.footer.offsetHeight - ui.boxMsgText.offsetHeight;
var msgItemTap = function(msgItem, event) {
var msgType = msgItem.getAttribute('msg-type');
var msgContent = msgItem.getAttribute('msg-content')
if(msgType == 'sound') {
player = plus.audio.createPlayer(msgContent);
var playState = msgItem.querySelector('.play-state');
playState.innerText = '正在播放...';
player.play(function() {
playState.innerText = '点击播放';
}, function(e) {
playState.innerText = '点击播放';
});
}
};
var imageViewer = new $.ImageViewer('.msg-content-image', {
dbl: false
});
//绑定消息节点
var bindMsgList = function() {
ui.areaMsgList.innerHTML = template('msg-template', {
"record": record
});
var msgItems = ui.areaMsgList.querySelectorAll('.msg-item');
[].forEach.call(msgItems, function(item, index) {
item.addEventListener('tap', function(event) {
msgItemTap(item, event);
}, false);
});
imageViewer.findAllImage();
ui.areaMsgList.scrollTop = ui.areaMsgList.scrollHeight + ui.areaMsgList.offsetHeight;
};
bindMsgList();
window.addEventListener('resize', function() {
ui.areaMsgList.scrollTop = ui.areaMsgList.scrollHeight + ui.areaMsgList.offsetHeight;
}, false);
var Question,
Answer;
function GetTitle() {
mui.Validation_Api("irr/fag/answerList", {
"faqQuestion": decodeURI(mui.GetQueryString("_faqQuestion"))
}, function(data) {
if(data.respCode == "200") {
if(data.data.rows != 0) {
Question = data.data.rows[0].faqQuestion;
Answer = data.data.rows[0].faqAnswer;
record.push({
sender: 'self',
type: 'text',
content: Question
});
record.push({
sender: 'zs',
type: 'text',
//机器人返回的数据
content: Answer
});
bindMsgList();
}
} else {
mui.toast("错误:" + data.message);
}
});
}
GetTitle();
//发送对象声明
var send = function(msg) {
//将消息内容体push进record
record.push(msg);
//绑定消息节点
bindMsgList();
toRobot(msg.content);
};
var toRobot = function(info) {
mui.Validation_Api("irr/fag/answerList", {
"faqQuestion": info
}, function(data) {
if(data.respCode == "200") {
if(data.data.rows.length == 0) {
record.push({
sender: 'zs',
type: 'text',
//机器人返回的数据
content: "您说什么我听不懂!问福宝点别的东西吧 "
});
bindMsgList();
} else if(data.data.rows.length == 1) {
Answer = data.data.rows[0].faqAnswer;
record.push({
sender: 'zs',
type: 'text',
//机器人返回的数据
content: Answer
});
bindMsgList();
} else {
var area_val = "";
Answer = data.data.rows[0].faqAnswer;
for(var i = 1; i < data.data.rows.length; i++) {
area_val += "<div class=\"listtext1\"></div><div class=\"listtext2\" attrtext=" + data.data.rows[i].faqAnswer + ">" + data.data.rows[i].faqQuestion + "</div></br>"
}
record.push({
sender: 'zs',
type: 'text',
//机器人返回的数据
content: "<div style=\"padding-bottom:10px\">" + Answer + "</div><div class=\"listtext\">您可能想了解:</div>" + area_val
});
bindMsgList();
}
} else {
mui.toast("错误:" + data.message);
}
});
};
mui('body').on('tap', '.listtext2', function() {
record.push({
sender: 'self',
type: 'text',
content: this.innerHTML
});
record.push({
sender: 'zs',
type: 'text',
//机器人返回的数据
content: this.getAttribute("attrtext")
});
bindMsgList();
});
function msgTextFocus() {
ui.boxMsgText.focus();
setTimeout(function() {
ui.boxMsgText.focus();
}, 150);
}
//解决长按“发送”按钮,导致键盘关闭的问题;
ui.footerRight.addEventListener('touchstart', function(event) {
if(ui.btnMsgType.classList.contains('mui-icon-paperplane')) {
msgTextFocus();
event.preventDefault();
}
});
//解决长按“发送”按钮,导致键盘关闭的问题;
ui.footerRight.addEventListener('touchmove', function(event) {
if(ui.btnMsgType.classList.contains('mui-icon-paperplane')) {
msgTextFocus();
event.preventDefault();
}
});
//长按离开屏幕时触发
ui.footerRight.addEventListener('release', function(event) {
//当是文字时
if(ui.btnMsgType.classList.contains('mui-icon-paperplane')) {
//showKeyboard();
ui.boxMsgText.focus();
setTimeout(function() {
ui.boxMsgText.focus();
}, 150);
send({
sender: 'self',
type: 'text',
content: ui.boxMsgText.value.replace(new RegExp('\n', 'gm'), '<br/>')
});
ui.boxMsgText.value = '';
$.trigger(ui.boxMsgText, 'input', null);
}
//当是语音时
else if(ui.btnMsgType.classList.contains('mui-icon-mic')) {
ui.btnMsgType.classList.add('mui-icon-compose');
ui.btnMsgType.classList.remove('mui-icon-mic');
ui.boxMsgText.style.display = 'none';
ui.boxMsgSound.style.display = 'block';
ui.boxMsgText.blur();
document.body.focus();
}
//当是文本状态时
else if(ui.btnMsgType.classList.contains('mui-icon-compose')) {
ui.btnMsgType.classList.add('mui-icon-mic');
ui.btnMsgType.classList.remove('mui-icon-compose');
ui.boxMsgSound.style.display = 'none';
ui.boxMsgText.style.display = 'block';
//--
//showKeyboard();
ui.boxMsgText.focus();
setTimeout(function() {
ui.boxMsgText.focus();
}, 150);
}
}, false);
ui.footerLeft.addEventListener('tap', function(event) {
var btnArray = [{
title: "拍照"
}, {
title: "从相册选择"
}];
plus.nativeUI.actionSheet({
title: "选择照片",
cancel: "取消",
buttons: btnArray
}, function(e) {
var index = e.index;
switch(index) {
case 0:
break;
case 1:
var cmr = plus.camera.getCamera();
cmr.captureImage(function(path) {
send({
sender: 'self',
type: 'image',
content: "file://" + plus.io.convertLocalFileSystemURL(path)
});
}, function(err) {});
break;
case 2:
plus.gallery.pick(function(path) {
send({
sender: 'self',
type: 'image',
content: path
});
}, function(err) {}, null);
break;
}
});
}, false);
var setSoundAlertVisable = function(show) {
if(show) {
ui.boxSoundAlert.style.display = 'block';
ui.boxSoundAlert.style.opacity = 1;
} else {
ui.boxSoundAlert.style.opacity = 0;
//fadeOut 完成再真正隐藏
setTimeout(function() {
ui.boxSoundAlert.style.display = 'none';
}, 200);
}
};
var recordCancel = false;
var recorder = null;
var audio_tips = document.getElementById("audio_tips");
var startTimestamp = null;
var stopTimestamp = null;
var stopTimer = null;
//按住说话时候触发
ui.boxMsgSound.addEventListener('hold', function(event) {
recordCancel = false;
if(stopTimer) clearTimeout(stopTimer);
audio_tips.innerHTML = "手指上划,取消发送";
ui.boxSoundAlert.classList.remove('rprogress-sigh');
setSoundAlertVisable(true);
recorder = plus.audio.getRecorder();
if(recorder == null) {
plus.nativeUI.toast("不能获取录音对象");
return;
}
startTimestamp = (new Date()).getTime();
recorder.record({
filename: "_doc/audio/"
}, function(path) {
if(recordCancel) return;
send({
sender: 'self',
type: 'sound',
content: path
});
}, function(e) {
plus.nativeUI.toast("录音时出现异常: " + e.message);
});
}, false);
//监听drag(拖动中)事件 上滑;下滑事件
ui.body.addEventListener('drag', function(event) {
//console.log('drag');
if(Math.abs(event.detail.deltaY) > 50) {
if(!recordCancel) {
recordCancel = true;
if(!audio_tips.classList.contains("cancel")) {
audio_tips.classList.add("cancel");
}
audio_tips.innerHTML = "松开手指,取消发送";
}
} else {
if(recordCancel) {
recordCancel = false;
if(audio_tips.classList.contains("cancel")) {
audio_tips.classList.remove("cancel");
}
audio_tips.innerHTML = "手指上划,取消发送";
}
}
}, false);
//长按离开录音节点时执行
ui.boxMsgSound.addEventListener('release', function(event) {
//console.log('release');
if(audio_tips.classList.contains("cancel")) {
audio_tips.classList.remove("cancel");
audio_tips.innerHTML = "手指上划,取消发送";
}
//
stopTimestamp = (new Date()).getTime();
if(stopTimestamp - startTimestamp < MIN_SOUND_TIME) {
audio_tips.innerHTML = "录音时间太短";
ui.boxSoundAlert.classList.add('rprogress-sigh');
recordCancel = true;
stopTimer = setTimeout(function() {
setSoundAlertVisable(false);
}, 800);
} else {
setSoundAlertVisable(false);
}
recorder.stop();
}, false);
//阻止浏览器默认的事件冒泡
ui.boxMsgSound.addEventListener("touchstart", function(e) {
//console.log("start....");
e.preventDefault();
});
//监听用户输入时触发
ui.boxMsgText.addEventListener('input', function(event) {
ui.btnMsgType.classList[ui.boxMsgText.value == '' ? 'remove' : 'add']('mui-icon-paperplane');
ui.btnMsgType.setAttribute("for", ui.boxMsgText.value == '' ? '' : 'msg-text');
ui.h.innerText = ui.boxMsgText.value.replace(new RegExp('\n', 'gm'), '\n-') || '-';
ui.footer.style.height = (ui.h.offsetHeight + footerPadding) + 'px';
ui.content.style.paddingBottom = ui.footer.style.height;
});
var focus = false;
//监听用户点击发送时触发
ui.boxMsgText.addEventListener('tap', function(event) {
ui.boxMsgText.focus();
setTimeout(function() {
ui.boxMsgText.focus();
}, 0);
focus = true;
setTimeout(function() {
focus = false;
}, 1000);
event.detail.gesture.preventDefault();
}, false);
//点击消息列表,关闭键盘
ui.areaMsgList.addEventListener('click', function(event) {
if(!focus) {
ui.boxMsgText.blur();
}
})
});
}(mui, document));
</script>
单个代码块详解:
1、列表页面有几条数据,点击则跳转聊天界面,自动发送该条点击的数据,机器人自动回复设置好的消息。
GetTitle()方法就是由外部数据点击进入聊天页面加载时调用的方法,调用后端方法获取到要显示的用户发送消息和机器人回复消息后,push进record中,这里重要的点在record.push方法上。
function GetTitle() {
mui.Validation_Api("XXX/XXX/XXX", { //调用后端方法
"faqQuestion": decodeURI(mui.GetQueryString("_faqQuestion"))
}, function(data) {
if(data.respCode == "200") {
if(data.data.rows != 0) {
Question = data.data.rows[0].faqQuestion;
Answer = data.data.rows[0].faqAnswer;
record.push({
sender: 'self',
type: 'text',
content: Question //设置用户主动发送的消息
});
record.push({
sender: 'zs',
type: 'text',
//机器人返回的数据
content: Answer
});
bindMsgList();//一定要记得绑定数据
}
} else {
mui.toast("错误:" + data.message);
}
});
}
GetTitle();
2、直接点击聊天界面,发送任意消息,调用接口在数据库查询,有值就返回相应内容,否则提示您说的话听不懂。
//发送对象声明
var send = function(msg) {
//将消息内容体push进record
record.push(msg);
//绑定消息节点
bindMsgList();
//输入框输入的消息
toRobot(msg.content);
};
var toRobot = function(info) {
mui.Validation_Api("XXX/XXX/XXX", { //把输入框的发送的消息传给后台接口
"faqQuestion": info
}, function(data) {
if(data.respCode == "200") {
if(data.data.rows.length == 0) { //如果后台返回的数据为0 表示未查询到数据 提示听不懂
record.push({
sender: 'zs',
type: 'text',
//机器人返回的数据
content: "您说什么我听不懂!问福宝点别的东西吧 "
});
bindMsgList();
} else if(data.data.rows.length == 1) { //如果后台返回的数据为1条说明只有单条信息 没有列表
Answer = data.data.rows[0].faqAnswer;
record.push({
sender: 'zs',
type: 'text',
//机器人返回的数据
content: Answer
});
bindMsgList();
} else { //返回多条信息 就加载猜您还想搜的列表
var area_val = "";
Answer = data.data.rows[0].faqAnswer;
for(var i = 1; i < data.data.rows.length; i++) {
area_val += "<div class=\"listtext1\"></div><div class=\"listtext2\" attrtext=" + data.data.rows[i].faqAnswer + ">" + data.data.rows[i].faqQuestion + "</div></br>"
}
record.push({
sender: 'zs',
type: 'text',
//机器人返回的数据
content: "<div style=\"padding-bottom:10px\">" + Answer + "</div><div class=\"listtext\">您可能想了解:</div>" + area_val
});
bindMsgList();
}
} else {
mui.toast("错误:" + data.message);
}
});
};
//点击相应的猜您想搜列表 自动发送点击的消息和设置好的回答
mui('body').on('tap', '.listtext2', function() {
record.push({
sender: 'self',
type: 'text',
content: this.innerHTML
});
record.push({
sender: 'zs',
type: 'text',
//机器人返回的数据
content: this.getAttribute("attrtext")
});
bindMsgList();
});