抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

机器人协议库

本文使用OICQ机器人协议库进行机器人开发,github仓库地址

克隆

1
git clone https://github.com/takayama-lily/oicq.git

你可以下载我已经写好的源码运行,目前已有签到、发送服务器状态、关键字回复、小爱同学聊天等功能

启动

创建nodejs项目,在index.js文件里输入下面的代码

1
2
3
4
5
6
7
8
9
10
11
12
const oicq = require('oicq');
const account = 123456789;//此处换成你的QQ号
const client = oicq.createClient(account);

client.on('system.online',()=>{
console.log('XICQ Start!');
});
client.on('system.login.qrcode',function (e){
process.stdin.once('data',()=>{
this.login();
});
}).login();

运行后会在项目根目录的data文件夹下生成以你QQ号命名的文件夹,其中有一个"qrcode.png"图片,使用手机扫码登录,然后在控制台按下回车,此时会显示登录成功

DearXuan

对话

为了便于管理,在项目根目录下创建"plugins"文件夹,专门用于存放功能代码

创建"message.js"文件.写入下面的代码

1
2
3
4
5
6
7
module.exports = {
OnMessageReceive
}

function OnMessageReceive(msg){
msg.reply("hello", false);//false表示不引用原消息
}

在"index.js"中调用该函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const oicq = require('oicq');
const account = 123456789;
const client = oicq.createClient(account);
const OnMessageReceive = require('./plugins/message.js').OnMessageReceive;

client.on('system.online',()=>{
console.log('XICQ Start!');
});
client.on('message',OnMessageReceive);
client.on('system.login.qrcode',function (e){
process.stdin.once('data',()=>{
this.login();
});
}).login();

上面的代码将使机器人在收到任意信息后立即回复"hello"

DearXuan

更多有关消息的结果,请前往原仓库查看

项目示例

下面将使用该QQ机器人实现查看服务器负载信息的功能

定义相关函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
module.exports = {
OnMessageReceive
}

const os = require('os');

function OnMessageReceive(msg){
switch (msg.toString()){
case '服务器':
SendServerState(msg);
}
}

/** 发送服务器状态 */
function SendServerState(msg){
let CpuUsage = 0;
//获取CPU信息
let cpus = os.cpus();
cpus.forEach((cpu, idx, arr)=>{
let times = cpu.times;
CpuUsage += (1-times.idle/(times.idle+times.user+times.nice+times.sys+times.irq))*100;
})
//计算CPU使用率
CpuUsage = (CpuUsage / cpus.length).toFixed(1);
//内存总量
let totalMemory = Math.round(os.totalmem() / 1048576);
//剩余内存
let freeMemory = Math.round(os.freemem() / 1048576);
//计算内存使用率
let MemoryUsage = (freeMemory * 100 / totalMemory).toFixed(1);
let s =
"CPU使用率:\n" + CpuUsage + "%" +
"\n内存使用率:\n" + MemoryUsage + "%" +
"\n内存使用量:\n" + freeMemory + "MB/" + totalMemory + "MB";
msg.reply(s, false);
}

创建监听

1
client.on('message',OnMessageReceive);

DearXuan

部署

在服务器上直接运行"index.js"即可,下面介绍如何在面板上运行(以宝塔为例)

创建一个文件夹用于存放项目文件

DearXuan

先在本地扫码登录一次,再上传全部文件到该目录

添加Node项目,项目目录为刚才创建的文件夹

DearXuan

点击"提交"后,会自动运行,如果你已经在本地登陆过,会生成设备信息,这样就能在服务器上自动登录

DearXuan

评论