部署微信聊天机器人对接文心一言

最近微信群里看到有人引入了AI机器人,就想着自己也搞一个,废话不多说,下面是部署步骤

一、系统环境

1、Centos Stream 9
2、Nodejs 23.2.0
3、文心一言接口

二、获取百度文心一言接口

1
2
3
4

三、部署机器人

1、安装eggjs
1
2
3
4
5
6
mkdir -p /www/wxbot
cd /www/wxbot
npm init egg
npm i
npm i -s wechaty
npm i -s qrcode-terminal
2、修改配置文件
1
2
3
cd /www/wxbot/app
mkdir service
vi wechat.js
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
const { Service } = require('egg');
const { WechatyBuilder, ScanStatus } = require("wechaty");
const qrcode = require("qrcode-terminal");

let ctx;
let wechaty;
let startStatus = false;

const onMessage = async (message) => {
console.log(`收到消息: ${message}`);

// 判断是否是群聊消息且没有 @,如果是则忽略不回复
if (message.room() && !message.text().includes('@DeepOcean')) {
console.log('这是群聊消息,但没有 @,忽略回复');
return;
}

if (message.type() === wechaty.Message.Type.Text) {
const userMsg = await message.text();

try {
let msgRecord = [{
"role": "user",
"content": userMsg
}];
let res = await ctx.service.ernie.sendMsg(msgRecord);
if (res) {
if (res.error_code) {
message.say(JSON.stringify(res));
console.log(`报错: ${JSON.stringify(res)}`);
} else {
if (res.result) {
message.say(res.result);
console.log(`回复: ${res.result}`);
}
}
}
} catch (error) {
console.log(error);
message.say(JSON.stringify(error));
}
}
};

const onLogout = (user) => {
console.log(`用户 ${user} 退出成功`);
};

const onLogin = async (user) => {
console.log(`用户 ${user} 登录成功`);
};

const onError = console.error;

const onScan = (code, status) => {
if (status === ScanStatus.Waiting) {
qrcode.generate(code, { small: true }, console.log);
}
};

class WechatService extends Service {
async startBot() {
console.log('===================WechatService startBot=====================');
ctx = this.ctx;

if (startStatus && wechaty) {
if (wechaty.isLoggedIn) {
await wechaty.logout();
}
await wechaty.stop();
startStatus = false;
wechaty = null;
}

wechaty = await WechatyBuilder.build();
wechaty
.on("scan", onScan)
.on("login", onLogin)
.on("logout", onLogout)
.on("error", onError)
.on("message", onMessage);

await wechaty.start();
startStatus = true;
}
}

module.exports = WechatService;
1
2
3
cd /www/wxbot/config
mv config.default.js config.default.js
vi config.default.js
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
module.exports = appInfo => {
const config = exports = {};

// use for cookie sign key, should change to your own and keep security
config.keys = appInfo.name + '_1736224596802_9615';

// add your middleware config here
config.middleware = [];

// Ernie 配置
config.ernie = {
       client_id: 'dsa456d7sa89f6123', //这里填写刚才获取到的API Key
       client_secret: 'fsa456d7as89f456sad', //这里填写刚才获取到的Secret Key
       access_token: '', // 此字段不再需要在这里存储,已使用内存存储
expire_day: 30,
gpt_model: 'ERNIE-Speed',
gpt_list: [{
type: 'ERNIE-Speed',
url: 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie_speed'
}, {
type: 'ERNIE-Lite',
url: 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-lite-8k'
}, {
type: 'ERNIE-Tiny-8K',
url: 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-tiny-8k'
}]
};

return config;
};

//只需要该client_id和client_token的值,其他不用改,这里用的是不收费的接口,所以不用担心会扣费
1
2
cd /www/wxbot/app/service
vi ernie.js
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
const { Service } = require('egg');
const moment = require('moment');

class ErnieService extends Service {
// 存储 access_token 的变量
accessToken = '';

// 获取 AccessToken
async getAccessToken() {
console.log('===================ErnieService getAccessToken=====================');
let ctx = this.ctx;

try {
const res = await ctx.curl(
`https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${ctx.app.config.ernie.client_id}&client_secret=${ctx.app.config.ernie.client_secret}`, {
method: 'POST',
rejectUnauthorized: false,
data: {},
headers: {},
timeout: 30000,
contentType: 'json',
dataType: 'json',
}
);
console.log(res);

if (res.data.access_token) {
// 存储 access_token 到内存中
this.accessToken = res.data.access_token;
console.log('access_token:', this.accessToken);
return this.accessToken;
}

} catch (error) {
console.log(error);
}
return null;
}

// 发送消息
async sendMsg(msg) {
console.log('===================ErnieService sendMsg=====================');
console.log(JSON.stringify(msg));
let ctx = this.ctx;

let gpt_url;
for (let i of ctx.app.config.ernie.gpt_list) {
if (i.type === ctx.app.config.ernie.gpt_model) {
gpt_url = i.url;
break;
}
}
if (!gpt_url) {
console.log('您设置的gpt_model值不存在');
return null;
}

try {
const res = await ctx.curl(
`${gpt_url}?access_token=${this.accessToken}`, {
method: 'POST',
rejectUnauthorized: false,
data: {
"messages": msg
},
timeout: 30000,
contentType: 'json',
dataType: 'json',
}
);
console.log(res);

if (res.data) {
if (res.data.error_code == '111') { // token 过期
await this.checkAccessToken(true); // 强制刷新
}
return res.data;
}
return null;
} catch (error) {
console.log(error);
return null;
}
}

// 检查 AccessToken 是否有效,并根据需要刷新
async checkAccessToken(forceReflesh = false) {
console.log('===================ErnieService checkAccessToken=====================');
let ctx = this.ctx;

if (!this.accessToken || forceReflesh) {
console.log('AccessToken 失效,重新获取');
const accessTokenStr = await this.getAccessToken();
if (accessTokenStr) {
this.accessToken = accessTokenStr;
console.log('accessToken 更新成功');
} else {
console.log('accessToken 获取失败');
}
} else {
console.log('accessToken 在有效期内');
}
}
}

module.exports = ErnieService;
1
2
cd /www/wxbot/
vi app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
module.exports = app => {
app.beforeStart(async () => {
console.log("==app beforeStart==");
});

app.ready(async () => {
console.log("==app ready==");
let ctx = app.createAnonymousContext();
await ctx.service.ernie.checkAccessToken(true); // 强制刷新 AccessToken
await ctx.service.wechat.startBot(); // 初始化 BOT
});

app.beforeClose(async () => {
console.log("==app beforeClose==");
});
};
3、运行服务端
1
2
cd /www/wxbot
npm run dev

然后屏幕上会有个二维码,微信扫码登陆就可以聊天了。

4、文献参考

https://blog.csdn.net/sfsgtc/article/details/133686011?spm=1001.2014.3001.5502
https://blog.csdn.net/sfsgtc/article/details/133709793?spm=1001.2014.3001.5502
https://blog.csdn.net/sfsgtc/article/details/133752506?spm=1001.2014.3001.5502
https://blog.csdn.net/sfsgtc/article/details/133789938?spm=1001.2014.3001.5502
https://blog.csdn.net/sfsgtc/article/details/133989716?spm=1001.2014.3001.5502

四、微信扫一扫关注我吧

戴戴的Linux 戴戴的Linux

文章目录
  1. 1. 最近微信群里看到有人引入了AI机器人,就想着自己也搞一个,废话不多说,下面是部署步骤
  • 一、系统环境
  • 二、获取百度文心一言接口
  • 三、部署机器人
    1. 1、安装eggjs
    2. 2、修改配置文件
    3. 3、运行服务端
    4. 4、文献参考
  • 四、微信扫一扫关注我吧


  • 本站总访问量 本文总阅读量