nodejs實現(xiàn)聊天機器人功能
技術(shù)棧
服務(wù)端:
koa、koa-route、koa-websocket、request。
客戶端:
html、css、js、websocket。
遠程聊天API:
http://api.qingyunke.com/api.php?key=free&appid=0&msg=msg。
客戶端展示

開發(fā)步驟
1.在桌面創(chuàng)建bbs文件夾,然后在文件夾內(nèi)打開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,項目啟動入口文件。
添加內(nèi)容如下:
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模塊向服務(wù)器發(fā)起一次get請求
http.get(`http://api.qingyunke.com/api.php?key=free&appid=0&msg=${encodeURI(message)}`, res => {
// 防止中文亂碼
res.setEncoding('utf-8');
// 監(jiān)聽data事件,每次取一塊數(shù)據(jù)
res.on('data', chunk => {
ctx.websocket.send(JSON.parse(chunk).content);
});
}).on('error', err => {
ctx.websocket.send('對不起,網(wǎng)絡(luò)故障了');
});}
// 監(jiān)聽端口、啟動程序
app.listen(3000, err => {
if (err) throw err;
console.log('websocket服務(wù)器啟動在3000端口');
})
假如對server.js還不清楚的,可以留言或者郵件咨詢我。
6.在bbs文件夾中新建index.html文件,作為客戶端展示文件。
添加內(nèi)容如下:
<!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">發(fā)送</div> </div> <div class="view" id="ulView"> <ul id="view"></ul> </div> </div> <script src="index.js"></script> </body> </html>
7.在bbs文件夾中新建index.css,客戶端的樣式。
內(nèi)容如下:
* {
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文件夾中創(chuàng)建index.js文件,作為客戶端js處理文件。
內(nèi)容如下:
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有兩種協(xié)議ws(不加密)和wss(加密)
let webSocket = CreateWebSocket(`ws://127.0.0.1:3000`);
webSocket.onopen = evt => {
addMsg(1, '你好,歡迎進入實時聊天室!')
}
webSocket.onmessage = evt => {
// 這是服務(wù)端返回的數(shù)據(jù)
addMsg(1, evt.data);
submit.innerHTML = '發(fā)送';
}
// input事件發(fā)送數(shù)據(jù)
submit.onclick = (e) => {
if (e.target.innerHTML == '回復(fù)中...') {
return false
}
e.target.innerHTML = '回復(fù)中...';
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);
}
為了保證服務(wù)端包都可以加載進來,可以在bbs文件夾中打開cmd,然后輸入:
$ npm install
到這里,程序就已經(jīng)搭建完成了。
啟動程序:
cmd輸入:
$ node server.js

這樣服務(wù)端就已經(jīng)啟動成功了。
直接右鍵瀏覽器打開index.html即可愉快地和機器人妹妹聊天了,告別單身狗了....
喜歡的麻煩點贊,謝謝
可以關(guān)注下本人博客,本人會堅持時不時更新好的博客給大家哦。
總結(jié)
以上所述是小編給大家介紹的nodejs實現(xiàn)聊天機器人功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
相關(guān)文章
前端自動化開發(fā)之Node.js的環(huán)境搭建教程
這篇文章主要介紹了前端自動化開發(fā)之Node.js環(huán)境搭建的相關(guān)資料,文中介紹的非常詳細,對大家學(xué)習(xí)或者使用node.js具有一定的參考價值,需要的朋友們下面來一起看看吧。2017-04-04
Node.js?操作本地文件及深入了解fs內(nèi)置模塊
這篇文章主要介紹了Node.js?操作本地文件及深入了解fs內(nèi)置模塊,node.js作為服務(wù)端應(yīng)用,肯定少不了對本地文件的操作,像創(chuàng)建一個目錄、創(chuàng)建一個文件、讀取文件內(nèi)容等都是我們開發(fā)中經(jīng)常需要用到的功能2022-09-09
Node.js Stream ondata觸發(fā)時機與順序的探索
今天小編就為大家分享一篇關(guān)于Node.js Stream ondata觸發(fā)時機與順序的探索,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03
詳解基于Node.js的微信JS-SDK后端接口實現(xiàn)代碼
本篇文章主要介紹了詳解基于Node.js的微信JS-SDK后端接口實現(xiàn)代碼,具有一定的參考價值,有興趣的可以了解一下2017-07-07
詳解基于node.js的腳手架工具開發(fā)經(jīng)歷
這篇文章主要介紹了詳解基于node.js的腳手架工具開發(fā)經(jīng)歷,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-01-01
node.js使用http模塊創(chuàng)建服務(wù)器和客戶端完整示例
這篇文章主要介紹了node.js使用http模塊創(chuàng)建服務(wù)器和客戶端,結(jié)合完整示例形式分析了node.js基于http模塊實現(xiàn)客戶端與服務(wù)器端交互的相關(guān)操作技巧,需要的朋友可以參考下2020-02-02

