WhatsApp 自动回复机器人
WhatsApp 自动回复机器人
·
WhatsApp 自动回复机器人 实现扫码登录 监听所有聊天对接ai问答 实现自动回复
const { Client, LocalAuth } = require('whatsapp-web.js');
const qrcode = require('qrcode-terminal');
const axios = require('axios');
const NodeCache = require('node-cache');
const cache = new NodeCache();
const corpId = xxxxx;
const corpSecret = "xxxx";
const hid = "x x x x x x";
async function getToken() {
const key = "SingerMindServiceApi-getToken";
const expirationTime = 3600; // Cache expiration time in seconds
let result = cache.get(key);
if (result) {
return result;
}
const url = `https://xxxxxxx/api/gettoken?corp_secret=${corpSecret}&corp_id=${corpId}`;
try {
const response = await axios.get(url);
const token = response.data.access_token;
cache.set(key, token, expirationTime);
return token;
} catch (error) {
console.error('Error fetching token:', error);
throw error;
}
}
async function QAChat(message, user) {
try {
const token = await getToken();
const url = `https://xxxxxxxx/api/chat?access_token=${token}`;
const response = await axios.post(url, {
hid: hid,
user: user,
channel: "wechat",
message: message,
max_tokens: 1500,
stream: false
});
return response.data;
} catch (error) {
console.error('Error in QAChat:', error);
throw error;
}
}
// 初始化 WhatsApp 客户端
const client = new Client({
authStrategy: new LocalAuth()
});
// 生成 QR 码以进行扫描
client.on('qr', (qr) => {
qrcode.generate(qr, { small: true });
});
client.on('authenticated', () => {
console.log('认证成功');
});
client.on('auth_failure', (msg) => {
console.error('认证失败:', msg);
});
client.on('disconnected', (reason) => {
console.log('客户端断开连接:', reason);
});
client.on('message_create', (msg) => {
// 如果消息是自己发出的
if (msg.fromMe) {
console.log('发送给自己的消息:', msg.body);
}
});
client.on('state_changed', (state) => {
console.log('客户端状态变更:', state);
});
client.on('change_state', (newState) => {
console.log('新的客户端状态:', newState);
});
// 客户端已准备就绪
client.on('ready', () => {
console.log('Client is ready!');
// 在准备好之后给自己发送消息
const myNumber = '6282220557438@c.us';
client.getChatById(myNumber).then(chat => {
chat.sendMessage('这是一条发给我自己的消息!');
console.log('这是一条发给我自己的消息!');
}).catch(err => {
console.error('无法获取聊天:', err);
});
});
client.on('message', message => {
console.log('收到新消息:', message.body);
});
client.on('message_ack', (message, ack) => {
/*
ack 值:
- 0 = 消息已被服务器接收
- 1 = 消息已被设备接收
- 2 = 消息已被设备阅读
*/
console.log('消息确认状态:', ack);
});
client.on('group_join', (notification) => {
console.log('有人加入群组:', notification);
});
client.on('group_leave', (notification) => {
console.log('有人离开群组:', notification);
});
// 处理接收到的消息
// client.on('message', async (message) => {
// console.log('收到新消息:', message.body); // 增加日志,打印收到的消息内容
// console.log('消息来自:', message.from); // 打印消息发送者
// if (message.hasMedia) {
// const media = await message.downloadMedia();
// console.log(`收到媒体文件:${media.mimetype}`);
// message.reply('感谢您的媒体文件!');
// } else {
// console.log('处理文本消息');
// if (message.body.startsWith('/')) {
// handleCommand(message);
// } else {
// const response = await getCustomAPIResponse(message.body);
// message.reply(response);
// }
// }
// });
// 调用自定义 API 生成回复
async function getCustomAPIResponse(prompt) {
try {
const response = await axios.post('https://your-api.com/generate-response', {
text: prompt
});
return "generated response"; // 假设 API 返回 { reply: "generated response" }
} catch (error) {
console.error('Error getting response from custom API:', error);
return 'Sorry, I am unable to process your request at the moment.';
}
}
function handleCommand(message) {
const command = message.body.substring(1).split(' ')[0];
switch (command) {
case 'hello':
message.reply('Hello! How can I assist you today?');
break;
case 'weather':
message.reply('I can tell you the weather. Please provide a location.');
break;
default:
message.reply('Unknown command. Try /hello or /weather.');
break;
}
}
client.initialize();

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐
所有评论(0)