node.js实现聊天机器人功能并在vue中集成

技术栈

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

客户端:

html、css、js、websocket。

远程聊天API:

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

功能图如下:

服务端:在这里插入图片描述

开发步骤

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"
  }
}

新建一个server文件夹然后创建一个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端口');
})

vue项目中创建一个chat.vue文件

<template>
  <div class="box">
    <div class="title">卷皮客服</div>
    <div class="input-box">
      <input class="input" placeholder="你想说什么..."  v-model= inputtext type="text" id="pl" @keydown="keyEnter()" />
      <div class="send" id="submit" @click="submits()">{{msg}}</div>
    </div>
    <div class="view" id="ulView">
      <ul id="view"></ul>
    </div>
  </div>
</template>
<script>
export default {
  name: "wetchat",
  data() {
    return {
      webSocket: "",
      inputtext:"",
      msg: "发送"
    }
  },
  created() {
    // let submit = document.getElementById("submit");
    // 很重要 必须写,判断浏览器是否支持websocket
    let CreateWebSocket = (urlValue => {
      return urlValue => {
        if (window.WebSocket) return new WebSocket(urlValue);
        if (window.MozWebSocket) return new MozWebSocket(urlValue);
        return false;
      };
    })();
    // 实例化websoscket websocket有两种协议ws(不加密)和wss(加密)
    this.webSocket = CreateWebSocket(`ws://127.0.0.1:3002`);
    console.log(this.webSocket);
    this.webSocket.onopen = evt => {
      this.addMsg(1, "你好,欢迎光临卷皮商城,请问有什么可以帮到您的!");
    };
    this.webSocket.onmessage = evt => {
      // 这是服务端返回的数据
      this.addMsg(1, evt.data);
      this.msg = "发送";
    };
  },
  methods: {
    keyEnter() {
      if (event.keyCode == 13) {
        this.submits()
      }
    },
    submits() {
      if (this.msg == "回复中...") {
        return false;
      }
      this.msg = "回复中...";
      this.webSocket.send(this.inputtext);
      this.addMsg(2, this.inputtext);
    },
    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>`;
       this.inputtext = "";
      }
      document.getElementById("view").appendChild(li);
      document
        .getElementById("ulView")
        .scrollTo(0, document.getElementById("view").clientHeight);
    }
  }
};
</script>

<style >
* {
    padding: 0;
    margin: 0;
    -webkit-user-select: none;
    -moz-user-select: none;
}

html,
body {
    height: 100%;
    width: 100%;
    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;
}
</style>

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

$ npm install

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

启动程序:cmd输入:

$ node server.js

启动成功的效果:
在这里插入图片描述

如果想了解在html中实现方式可以点击查看https://www.cnblogs.com/it-xiong/p/11549264.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值