nodejs实现聊天机器人功能


Posted in NodeJs onSeptember 19, 2019

技术栈

服务端:

koa、koa-route、koa-websocket、request。

客户端:

html、css、js、websocket。

远程聊天API:

 http://api.qingyunke.com/api.php?key=free&appid=0&msg=msg。

客户端展示

nodejs实现聊天机器人功能

开发步骤

1.在桌面创建bbs文件夹,然后在文件夹内打开cmd,输入:

$ npm init

初始化箱项目,生成package.json包管理文件

2.cmd输入:

$ npm install koa --save

安装koa。

3.cmd输入:

$ npm install koa-route --save

安装koa路由模块。

4.cmd输入:

$ npm install koa-websocket --save

安装koawebsocket模块。

我的package.json:

{
 "name": "bbs",
 "version": "1.0.0",
 "description": "",
 "main": "server.js",
 "scripts": {
 "test": "echo \"Error: no test specified\" && exit 1",
 "start": "node server.js"
 },
 "author": "",
 "license": "ISC",
 "dependencies": {
 "koa": "^2.8.1",
 "koa-route": "^3.2.0",
 "koa-websocket": "^6.0.0"
 }
}

5.在bbs文件夹中新建server.js,项目启动入口文件。

添加内容如下:

const Koa = require('koa'),
  route = require('koa-route'),
  websockify = require('koa-websocket'),
  http = require('http'),
  app = websockify(new Koa());

app.ws.use(route.all('/', ctx => {
 // websocket作为“ctx.websocket”添加到上下文中。
 ctx.websocket.on('message', message => {
  startRequest(message, ctx);
 });
}));

function startRequest(message, ctx) {
 // 采用http模块向服务器发起一次get请求  
 http.get(`http://api.qingyunke.com/api.php?key=free&appid=0&msg=${encodeURI(message)}`, res => {
  // 防止中文乱码
  res.setEncoding('utf-8');
  // 监听data事件,每次取一块数据
  res.on('data', chunk => {
   ctx.websocket.send(JSON.parse(chunk).content);
  });
 }).on('error', err => {
  ctx.websocket.send('对不起,网络故障了');
 });}

// 监听端口、启动程序
app.listen(3000, err => {
 if (err) throw err;
 console.log('websocket服务器启动在3000端口');
})

假如对server.js还不清楚的,可以留言或者邮件咨询我。

6.在bbs文件夹中新建index.html文件,作为客户端展示文件。

添加内容如下:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>实时聊天室</title>
 <link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
 <div class="box">
  <div class="title">实时聊天室</div>
  <div class="input-box">
   <input class="input" placeholder="你想说什么..." type="text" id="pl" onkeydown="keyEnter()" />
   <div class="send" id="submit">发送</div>
  </div>
  <div class="view" id="ulView">
   <ul id="view"></ul>
  </div>
 </div>
 <script src="index.js"></script>
</body>
</html>

7.在bbs文件夹中新建index.css,客户端的样式。

内容如下:

* {
 padding: 0;
 margin: 0;
 -webkit-user-select: none;
 -moz-user-select: none;
}
html,
body {
 height: 100%;
 width: 100%;
 background-color: #333;
 position: relative;
 font-size: 12px;
}
.box {
 position: absolute;
 top: 50%;
 left: 50%;
 transform: translate(-50%, -50%);
 background-color: #eee;
 width: 320px;
 height: 564px;
 box-sizing: border-box;
}
.title {
 height: 40px;
 line-height: 40px;
 text-align: center;
 background-color: #000;
 color: #fff;
 position: relative;
 font-size: 16px;
}
.input-box {
 margin-top: 10px;
 position: absolute;
 bottom: 0;
 background-color: #fff;
 width: 100%;
 height: 40px;
 line-height: 32px;
 padding: 4px;
 padding-right: 0;
 box-sizing: border-box;
 display: -webkit-flex;
 display: -moz-flex;
 display: -ms-flex;
 display: -o-flex;
 display: flex;
 -ms-align-items: center;
 align-items: center;
 justify-content: space-between;
 border-top: 1px solid #eee;
}
.input {
 vertical-align: top;
 height: 32px;
 line-height: 32px;
 outline: none;
 border: 1px solid #ccc;
 padding: 0 4px;
 box-sizing: border-box;
 flex: 1;
 background-color: #eee;
 border-radius: 4px;
 margin-right: 10px;
 margin-left: 4px;
}
.input:focus {
 border: 1px solid #ccc;
}
.send {
 width: 80px;
 text-align: center;
 height: 32px;
 line-height: 32px;
 cursor: pointer;
 background-color: green;
 color: #fff;
 margin-right: 10px;
 font-size: 14px;
}
.send:active {
 opacity: 0.6;
}
li {
 list-style: none;
 padding: 6px 10px;
 box-sizing: border-box;
}
.my-say {
 text-align: right;
}
.say {
 display: inline-block;
 background-color: #fff;
 font-size: 12px;
 padding: 6px 4px;
 border-radius: 4px;
 margin-top: 1px;
 vertical-align: top;
 max-width: 220px;
}
.computer-say .sayman {
 background-color: #40E0D0;
}
.my-say .sayman {
 background-color: #FFA500;
}
.my-say .say {
 text-align: left;
}
.sayman {
 font-size: 10px;
 display: inline-block;
 height: 30px;
 width: 30px;
 background-color: #ccc;
 border-radius: 50%;
 text-align: center;
 line-height: 30px;
 overflow: hidden;
 text-overflow: ellipsis;
 white-space: nowrap;
 padding: 0 4px;
 box-sizing: border-box;
 margin: 0 4px;
 color: #fff;
}
.view {
 position: absolute;
 top: 40px;
 bottom: 40px;
 left: 0;
 width: 100%;
 padding: 10px 0;
 box-sizing: border-box;
 overflow-y: auto;
}

8.在bbs文件夹中创建index.js文件,作为客户端js处理文件。

内容如下:

let submit = document.getElementById("submit"),
 pl = document.getElementById("pl");
// 很重要 必须写,判断浏览器是否支持websocket
let CreateWebSocket = (() => {
 return (urlValue) => {
  if (window.WebSocket) return new WebSocket(urlValue);
  if (window.MozWebSocket) return new MozWebSocket(urlValue);
  return false;
 }
})()
// 实例化websoscket websocket有两种协议ws(不加密)和wss(加密)
let webSocket = CreateWebSocket(`ws://127.0.0.1:3000`);
webSocket.onopen = evt => {
 addMsg(1, '你好,欢迎进入实时聊天室!')
}
webSocket.onmessage = evt => {
 // 这是服务端返回的数据
 addMsg(1, evt.data);
 submit.innerHTML = '发送';
}
// input事件发送数据
submit.onclick = (e) => {
 if (e.target.innerHTML == '回复中...') {
  return false
 }
 e.target.innerHTML = '回复中...';
 const str = document.getElementById("pl").value;
 webSocket.send(str);
 addMsg(2, str);
}
// 绑定回车事件
function keyEnter() {
 if (event.keyCode == 13) {
  document.getElementById("submit").click();
 }
}
// 添加消息
function addMsg(type, msg) {
 let li = document.createElement('li');
 // 1机器人/2自己
 if (type == 1) {
  li.classList.add('computer-say');
  li.innerHTML = `<span class="sayman">机器人</span><span class="computer say">${msg}</span>`;
 } else {
  li.classList.add('my-say');
  li.innerHTML = `<span class="computer say">${msg}</span><span class="sayman">我</span>`;
  pl.value = '';
 }
 document.getElementById('view').appendChild(li);
 document.getElementById('ulView').scrollTo(0, document.getElementById('view').clientHeight);
}

为了保证服务端包都可以加载进来,可以在bbs文件夹中打开cmd,然后输入:

$ npm install

到这里,程序就已经搭建完成了。

启动程序:

cmd输入:

$ node server.js

nodejs实现聊天机器人功能

这样服务端就已经启动成功了。

直接右键浏览器打开index.html即可愉快地和机器人妹妹聊天了,告别单身狗了....

喜欢的麻烦点赞,谢谢

可以关注下本人博客,本人会坚持时不时更新好的博客给大家哦。

总结

以上所述是小编给大家介绍的nodejs实现聊天机器人功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

NodeJs 相关文章推荐
用nodejs访问ActiveX对象,以操作Access数据库为例。
Dec 15 NodeJs
使用Nodejs开发微信公众号后台服务实例
Sep 03 NodeJs
使用nodejs中httpProxy代理时候出现404异常的解决方法
Aug 15 NodeJs
Highcharts+NodeJS搭建数据可视化平台示例
Jan 01 NodeJs
深入nodejs中流(stream)的理解
Mar 27 NodeJs
详解如何在NodeJS项目中优雅的使用ES6
Apr 22 NodeJs
Nodejs进阶:express+session实现简易登录身份认证
Apr 24 NodeJs
nodejs批量下载图片的实现方法
May 19 NodeJs
NodeJS自定义模块写法(详解)
Jun 27 NodeJs
NodeJS收发GET和POST请求的示例代码
Aug 25 NodeJs
nodejs实现大文件(在线视频)的读取
Oct 16 NodeJs
nodejs实现简单的gulp打包
Dec 21 NodeJs
图解NodeJS实现登录注册功能
Sep 16 #NodeJs
详解NodeJs项目 CentOs linux服务器线上部署
Sep 16 #NodeJs
nodejs一个简单的文件服务器的创建方法
Sep 13 #NodeJs
nodejs的安装使用与npm的介绍
Sep 11 #NodeJs
5分钟教你用nodeJS手写一个mock数据服务器的方法
Sep 10 #NodeJs
NodeJS 文件夹拷贝以及删除功能
Sep 03 #NodeJs
纯异步nodejs文件夹(目录)复制功能
Sep 03 #NodeJs
You might like
本地机apache配置基于域名的虚拟主机详解
2013/08/10 PHP
PHP中的事务使用实例
2015/05/26 PHP
浅谈PHP中new self()和new static()的区别
2017/08/11 PHP
php实现微信公众平台发红包功能
2018/06/14 PHP
tp5递归 无限级分类详解
2019/10/18 PHP
繁简字转换功能
2006/07/19 Javascript
Javascript 设计模式(二) 闭包
2010/05/26 Javascript
各浏览器对click方法的支持差异小结
2011/07/31 Javascript
jQuery源码分析-01总体架构分析
2011/11/14 Javascript
jQuery 网易相册鼠标移动显示隐藏效果实现代码
2013/03/31 Javascript
jquery简单实现鼠标经过导航条改变背景图
2013/12/17 Javascript
jQuery判断checkbox是否选中的3种方法
2014/08/12 Javascript
Javascript基础之数组的使用
2016/05/13 Javascript
原生JS实现-星级评分系统的简单实例
2016/08/21 Javascript
Vue2.0如何发布项目实战
2017/07/27 Javascript
[57:18]DOTA2上海特级锦标赛主赛事日 - 1 败者组第一轮#3VP VS VG
2016/03/03 DOTA
Python多线程编程(五):死锁的形成
2015/04/05 Python
用python实现简单EXCEL数据统计的实例
2017/01/24 Python
python编程通过蒙特卡洛法计算定积分详解
2017/12/13 Python
将Python字符串生成PDF的实例代码详解
2019/05/17 Python
Python内置random模块生成随机数的方法
2019/05/31 Python
远程部署工具Fabric详解(支持Python3)
2019/07/04 Python
python对矩阵进行转置的2种处理方法
2019/07/17 Python
Pycharm如何运行.py文件的方法步骤
2020/03/03 Python
Python按照list dict key进行排序过程解析
2020/04/04 Python
Selenium关闭INFO:CONSOLE提示的解决
2020/12/07 Python
CSS3模块的目前的状况分析
2010/02/24 HTML / CSS
环法自行车赛官方商店:Le Tour de France
2017/08/27 全球购物
土耳其时尚购物网站:Morhipo
2017/09/04 全球购物
新西兰最大的在线设计师眼镜店:SmartBuyGlasses新西兰
2017/10/20 全球购物
英语师范专业毕业生自荐信
2013/09/21 职场文书
销售代理协议书
2014/09/30 职场文书
给上级领导的感谢信
2015/01/22 职场文书
酒店温馨提示语
2015/07/14 职场文书
2016年3月份红领巾广播稿
2015/12/21 职场文书
Python尝试实现蒙特卡罗模拟期权定价
2022/04/21 Python