|
|
|
const {
|
|
|
|
makeWASocket,
|
|
|
|
Browsers,
|
|
|
|
DisconnectReason,
|
|
|
|
fetchLatestBaileysVersion,
|
|
|
|
makeCacheableSignalKeyStore,
|
|
|
|
makeInMemoryStore,
|
|
|
|
useMultiFileAuthState,
|
|
|
|
downloadMediaMessage,
|
|
|
|
isJidUser
|
|
|
|
} = require('@whiskeysockets/baileys');
|
|
|
|
const { writeFile } = require('fs/promises');
|
|
|
|
const waEmitter = require('../emitter');
|
|
|
|
const serverConfig = require('../../config').server;
|
|
|
|
|
|
|
|
const { formatPhoneNumber, parsePhoneNumber, formatStatus, formatTimestamp } = require('./helper');
|
|
|
|
const generateId = require('../../utils/generateId.util');
|
|
|
|
const NodeCache = require('node-cache');
|
|
|
|
const P = require('pino');
|
|
|
|
|
|
|
|
const createWhatsApp = async phone => {
|
|
|
|
let qrCode = null;
|
|
|
|
const channelId = generateId();
|
|
|
|
const whatsAppNo = phone;
|
|
|
|
// 储存键值对 msgId-externalId
|
|
|
|
// TODO 使用 NodeCache 储存,设置有效期。⬇️
|
|
|
|
const msgIdMap = new Map();
|
|
|
|
const logger = P({ timestamp: () => `,"time":"${new Date().toJSON()}"` }, P.destination('./wa-logs-' + phone + '_' + channelId + '.txt'));
|
|
|
|
logger.level = 'trace';
|
|
|
|
const msgRetryCounterCache = new NodeCache();
|
|
|
|
const storeFilename = './baileys_auth_info/baileys_store_' + phone + '_' + channelId + '.json'
|
|
|
|
const store = makeInMemoryStore({ logger });
|
|
|
|
store?.readFromFile(storeFilename);
|
|
|
|
// save every 10s
|
|
|
|
setInterval(() => {
|
|
|
|
store?.writeToFile(storeFilename);
|
|
|
|
}, 10_000);
|
|
|
|
const { state, saveCreds } = await useMultiFileAuthState('baileys_auth_info/' + phone + '_' + channelId);
|
|
|
|
// fetch latest version of WA Web
|
|
|
|
const { version, isLatest } = await fetchLatestBaileysVersion();
|
|
|
|
const waVersion = version.join('.') + ', ' + (isLatest ? 'latest' : 'out');
|
|
|
|
|
|
|
|
const handleMessagesUpsert = async upsert => {
|
|
|
|
console.info('messages.upsert: ', JSON.stringify(upsert, undefined, 2));
|
|
|
|
|
|
|
|
if (upsert.type === 'notify') {
|
|
|
|
for (const msg of upsert.messages) {
|
|
|
|
|
|
|
|
// 没有类型的消息,先忽略
|
|
|
|
if (!msg.message) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
const messageType = Object.keys(msg.message)[0];
|
|
|
|
console.log('messageType', messageType);
|
|
|
|
|
|
|
|
const fromWhatsAppNo = parsePhoneNumber(msg.key.remoteJid);
|
|
|
|
|
|
|
|
if (msg.message?.conversation || msg.message?.extendedTextMessage?.text) {
|
|
|
|
|
|
|
|
const text = msg.message?.conversation || msg.message?.extendedTextMessage?.text;
|
|
|
|
const externalId = msgIdMap.get(msg.key.id);
|
|
|
|
|
|
|
|
if (msg.key.fromMe) {
|
|
|
|
waEmitter.emit('message:updated', {
|
|
|
|
id: msg.key.id,
|
|
|
|
externalId,
|
|
|
|
status: formatStatus(msg.status),
|
|
|
|
direction: 'outbound',
|
|
|
|
from: whatsAppNo,
|
|
|
|
to: fromWhatsAppNo,
|
|
|
|
type: 'text',
|
|
|
|
text: {
|
|
|
|
body: text,
|
|
|
|
},
|
|
|
|
conversation: {
|
|
|
|
type: isJidUser(msg.key.remoteJid) ? 'individual' : 'group',
|
|
|
|
},
|
|
|
|
customerProfile: {
|
|
|
|
id: parsePhoneNumber(msg.key.participant),
|
|
|
|
name: msg.pushName,
|
|
|
|
},
|
|
|
|
whatsAppNo,
|
|
|
|
fromMe: msg.key.fromMe,
|
|
|
|
eventSource: serverConfig.name + '.messages.upsert.notify',
|
|
|
|
updateTime: formatTimestamp(msg.messageTimestamp),
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
waEmitter.emit('message:received', {
|
|
|
|
id: msg.key.id,
|
|
|
|
externalId,
|
|
|
|
status: '',
|
|
|
|
direction: 'inbound',
|
|
|
|
from: fromWhatsAppNo,
|
|
|
|
to: whatsAppNo,
|
|
|
|
type: 'text',
|
|
|
|
text: {
|
|
|
|
body: text,
|
|
|
|
},
|
|
|
|
conversation: {
|
|
|
|
type: isJidUser(msg.key.remoteJid) ? 'individual' : 'group',
|
|
|
|
},
|
|
|
|
customerProfile: {
|
|
|
|
id: parsePhoneNumber(msg.key.participant),
|
|
|
|
name: msg.pushName,
|
|
|
|
},
|
|
|
|
whatsAppNo,
|
|
|
|
fromMe: msg.key.fromMe,
|
|
|
|
eventSource: serverConfig.name + '.messages.upsert.notify',
|
|
|
|
createTime: formatTimestamp(msg.messageTimestamp),
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else if (upsert.type === 'append') {
|
|
|
|
for (const msg of upsert.messages) {
|
|
|
|
if (msg.message?.conversation || msg.message?.extendedTextMessage?.text) {
|
|
|
|
const text = msg.message?.conversation || msg.message?.extendedTextMessage?.text;
|
|
|
|
const fromWhatsAppNo = parsePhoneNumber(msg.key.remoteJid);
|
|
|
|
|
|
|
|
const externalId = msgIdMap.get(msg.key.id);
|
|
|
|
if (msg.key.fromMe) {
|
|
|
|
waEmitter.emit('message:updated', {
|
|
|
|
id: msg.key.id,
|
|
|
|
externalId,
|
|
|
|
status: formatStatus(msg.status),
|
|
|
|
direction: 'outbound',
|
|
|
|
from: whatsAppNo,
|
|
|
|
to: fromWhatsAppNo,
|
|
|
|
type: 'text',
|
|
|
|
text: {
|
|
|
|
body: text,
|
|
|
|
},
|
|
|
|
conversation: {
|
|
|
|
type: isJidUser(msg.key.remoteJid) ? 'individual' : 'group',
|
|
|
|
},
|
|
|
|
customerProfile: {
|
|
|
|
id: parsePhoneNumber(msg.participant),
|
|
|
|
name: msg.pushName,
|
|
|
|
},
|
|
|
|
whatsAppNo,
|
|
|
|
fromMe: msg.key.fromMe,
|
|
|
|
eventSource: serverConfig.name + '.messages.upsert.append',
|
|
|
|
updateTime: formatTimestamp(msg.messageTimestamp),
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const handleMessagesUpdate = async messageUpdate => {
|
|
|
|
console.info('messages.update: ', JSON.stringify(messageUpdate, undefined, 2));
|
|
|
|
|
|
|
|
for (const msg of messageUpdate) {
|
|
|
|
|
|
|
|
// 没有明确标识状态的更新,忽略
|
|
|
|
const ignore = msg.update === undefined || msg.update.status === undefined;
|
|
|
|
|
|
|
|
if (ignore) continue;
|
|
|
|
|
|
|
|
const externalId = msgIdMap.get(msg.key.id);
|
|
|
|
waEmitter.emit('message:updated', {
|
|
|
|
id: msg.key.id,
|
|
|
|
externalId,
|
|
|
|
status: formatStatus(msg.update?.status),
|
|
|
|
direction: msg.key.fromMe ? 'outbound' : 'inbound',
|
|
|
|
from: msg.key.fromMe ? whatsAppNo : parsePhoneNumber(msg.key.remoteJid),
|
|
|
|
to: msg.key.fromMe ? parsePhoneNumber(msg.key.remoteJid) : whatsAppNo,
|
|
|
|
conversation: {
|
|
|
|
type: isJidUser(msg.key.remoteJid) ? 'individual' : 'group',
|
|
|
|
},
|
|
|
|
customerProfile: {
|
|
|
|
id: parsePhoneNumber(msg.key.participant),
|
|
|
|
name: msg.pushName,
|
|
|
|
},
|
|
|
|
whatsAppNo,
|
|
|
|
fromMe: msg.key.fromMe,
|
|
|
|
eventSource: serverConfig.name + '.messages.updated',
|
|
|
|
updateTime: formatTimestamp(new Date().getTime() / 1000),
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const handleCredsUpdate = async () => {
|
|
|
|
await saveCreds();
|
|
|
|
}
|
|
|
|
const start = () => {
|
|
|
|
|
|
|
|
const waSocket = makeWASocket({
|
|
|
|
version,
|
|
|
|
logger,
|
|
|
|
auth: {
|
|
|
|
creds: state.creds,
|
|
|
|
keys: makeCacheableSignalKeyStore(state.keys, logger),
|
|
|
|
},
|
|
|
|
// connectTimeoutMs: 1000*60*10,
|
|
|
|
// defaultQueryTimeoutMs: 1000*60*1,
|
|
|
|
// keepAliveIntervalMs: 1000*60*60,
|
|
|
|
//retryRequestDelayMs: 1000*25,
|
|
|
|
// https://github.com/WhiskeySockets/Baileys/blob/31bc8ab/src/Utils/generics.ts#L21
|
|
|
|
// https://github.com/WhiskeySockets/Baileys/blob/31bc8ab4e2c825c0d774875701ed07e20d05bdb6/WAProto/WAProto.proto
|
|
|
|
browser: Browsers.macOS('SAFARI'),//Browsers.macOS('SAFARI'),//Browsers.ubuntu('IOS_PHONE'),//Browsers.baileys('WEAR_OS'),//
|
|
|
|
msgRetryCounterCache,
|
|
|
|
generateHighQualityLinkPreview: false,
|
|
|
|
syncFullHistory: false,
|
|
|
|
});
|
|
|
|
|
|
|
|
store?.bind(waSocket.ev);
|
|
|
|
|
|
|
|
const sendTextMessage = async (number, content, externalId) => {
|
|
|
|
const jid = formatPhoneNumber(number);
|
|
|
|
waSocket.sendMessage(jid, { text: content })
|
|
|
|
.then(msg => {
|
|
|
|
msgIdMap.set(msg.key.id, externalId);
|
|
|
|
})
|
|
|
|
.catch(ex => {
|
|
|
|
console.error('sendTextMessage.error: ', ex)
|
|
|
|
waEmitter.emit('message:updated', {
|
|
|
|
id: generateId(),
|
|
|
|
externalId,
|
|
|
|
status: 'failed',
|
|
|
|
direction: 'outbound',
|
|
|
|
from: whatsAppNo,
|
|
|
|
to: number,
|
|
|
|
error: `发送文本消息出错 ` + ex,
|
|
|
|
eventSource: serverConfig.name + '.sendMessage.promise.catch',
|
|
|
|
updateTime: formatTimestamp(new Date().getTime() / 1000),
|
|
|
|
});
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
const sendImageMessage = async (number, imageUrl) => {
|
|
|
|
const jid = formatPhoneNumber(number);
|
|
|
|
try {
|
|
|
|
const msgInfo = await waSocket.sendMessage(jid, {
|
|
|
|
image: { url: imageUrl },
|
|
|
|
});
|
|
|
|
return {
|
|
|
|
messageId: msgInfo?.key?.id ?? generateId()
|
|
|
|
};
|
|
|
|
} catch (ex) {
|
|
|
|
waEmitter.emit('message.error', {
|
|
|
|
messge: `[${whatsAppNo}->${number}]发送图片消息出错`,
|
|
|
|
from: whatsAppNo,
|
|
|
|
to: number,
|
|
|
|
error: ex
|
|
|
|
})
|
|
|
|
console.error(`[${whatsAppNo}->${number}]发送图片消息出错: `, ex);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
const getProfilePicture = async (whatsAppNo) => {
|
|
|
|
const number = formatPhoneNumber(whatsAppNo);
|
|
|
|
try {
|
|
|
|
const ppUrl = await waSocket.profilePictureUrl(number);
|
|
|
|
console.log('头像: ' + ppUrl);
|
|
|
|
} catch (ex) {
|
|
|
|
console.error('头像出错: ', ex);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
waSocket.ev.on('connection.update', async update => {
|
|
|
|
console.log('connection update: ', update);
|
|
|
|
const { connection, lastDisconnect, qr } = update;
|
|
|
|
|
|
|
|
if (connection === 'close') {
|
|
|
|
if((lastDisconnect?.error)?.output?.statusCode !== DisconnectReason.loggedOut) {
|
|
|
|
start();
|
|
|
|
} else {
|
|
|
|
waEmitter.emit('connection:close', {
|
|
|
|
whatsAppNo, channelId,
|
|
|
|
eventSource: serverConfig.name + '.connection.update.close',
|
|
|
|
status: 'offline',
|
|
|
|
});
|
|
|
|
}
|
|
|
|
} else if (connection === 'open') {
|
|
|
|
waEmitter.emit('connection:open', {
|
|
|
|
status: 'open', whatsAppNo, channelId,
|
|
|
|
eventSource: serverConfig.name + '.connection.update.open',
|
|
|
|
});
|
|
|
|
// 考虑迁移到 connection.update 事件之外,测试看是否能发送消息?
|
|
|
|
waEmitter.on('request.' + whatsAppNo + '.send.text', event => {
|
|
|
|
const {to: number, externalId, content} = event;
|
|
|
|
console.info('request.' + whatsAppNo + '.send.text:', event)
|
|
|
|
// const jid = formatPhoneNumber(event.to);
|
|
|
|
waSocket.sendMessage(
|
|
|
|
number + '@s.whatsapp.net', { text: content }
|
|
|
|
).then(msg => {
|
|
|
|
msgIdMap.set(msg.key.id, externalId);
|
|
|
|
}).catch(ex => {
|
|
|
|
console.error('sendMessage.error: ', ex)
|
|
|
|
waEmitter.emit('message:updated', {
|
|
|
|
id: generateId(),
|
|
|
|
externalId,
|
|
|
|
status: 'failed',
|
|
|
|
direction: 'outbound',
|
|
|
|
from: whatsAppNo,
|
|
|
|
to: number,
|
|
|
|
error: `发送文本消息出错 ` + ex,
|
|
|
|
eventSource: serverConfig.name + '.sendMessage.catch',
|
|
|
|
updateTime: formatTimestamp(new Date().getTime() / 1000),
|
|
|
|
});
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
waEmitter.on('request.' + whatsAppNo + '.send.image', event => {
|
|
|
|
const {to: number, externalId, imageUrl} = event;
|
|
|
|
const jid = formatPhoneNumber(event.to);
|
|
|
|
waSocket.sendMessage(
|
|
|
|
jid, {image: { url: imageUrl }}
|
|
|
|
).then(msg => {
|
|
|
|
msgIdMap.set(msg.key.id, externalId);
|
|
|
|
}).catch(ex => {
|
|
|
|
console.error('sendMessage.error: ', ex)
|
|
|
|
waEmitter.emit('message:updated', {
|
|
|
|
id: generateId(),
|
|
|
|
externalId,
|
|
|
|
status: 'failed',
|
|
|
|
direction: 'outbound',
|
|
|
|
from: whatsAppNo,
|
|
|
|
to: number,
|
|
|
|
error: `发送图片消息出错 ` + ex,
|
|
|
|
eventSource: serverConfig.name + '.sendMessage.catch',
|
|
|
|
updateTime: formatTimestamp(new Date().getTime() / 1000),
|
|
|
|
});
|
|
|
|
});
|
|
|
|
});
|
|
|
|
} else if (qr !== undefined) {
|
|
|
|
// WebSocket 创建成功等待扫码,如果没有扫码会更新 qr
|
|
|
|
// 第一次一分钟,后面是 20 秒更新一次
|
|
|
|
if (qrCode === null) {
|
|
|
|
qrCode = qr;
|
|
|
|
waEmitter.emit('creds:update', {
|
|
|
|
id: generateId(),
|
|
|
|
qr, whatsAppNo,
|
|
|
|
server:serverConfig.name,
|
|
|
|
eventSource: 'creds.update',
|
|
|
|
createTime: formatTimestamp(new Date().getTime() / 1000),
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
// 第一次二维码时效后退出,不需要等待更新二维码
|
|
|
|
waSocket.logout(() => '二维码已过期');
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
waSocket.ev.on('creds.update', handleCredsUpdate);
|
|
|
|
waSocket.ev.on('messages.upsert', handleMessagesUpsert);
|
|
|
|
waSocket.ev.on('messages.update', handleMessagesUpdate);
|
|
|
|
};
|
|
|
|
|
|
|
|
return {
|
|
|
|
createTimestamp: Date.now(),
|
|
|
|
status: 'offline',
|
|
|
|
version: waVersion,
|
|
|
|
channelId: channelId,
|
|
|
|
phone: phone,
|
|
|
|
start,
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
createWhatsApp,
|
|
|
|
};
|