nodejs實現聊天機器人

技術棧

服務端:

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

客戶端:

html、css、js、websocket。css

遠程聊天API:

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

 

客戶端展現

開發步驟

1.在桌面建立bbs文件夾,而後在文件夾內打開cmd,輸入:node

$ npm init

 

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

2.cmd輸入:npm

$ npm install koa --save

 

安裝koa。json

3.cmd輸入:api

$ 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

 

這樣服務端就已經啓動成功了。

直接右鍵瀏覽器打開index.html便可愉快地和機器人妹妹聊天了,告別單身狗了....

喜歡的麻煩點贊,謝謝

能夠關注下本人博客,本人會堅持時不時更新好的博客給你們哦。

相關文章
相關標籤/搜索