You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
330 lines
11 KiB
JavaScript
330 lines
11 KiB
JavaScript
const {
|
|
makeWASocket,
|
|
Browsers,
|
|
DisconnectReason,
|
|
fetchLatestBaileysVersion,
|
|
makeCacheableSignalKeyStore,
|
|
makeInMemoryStore,
|
|
useMultiFileAuthState,
|
|
downloadMediaMessage,
|
|
isJidUser
|
|
} = require('@whiskeysockets/baileys');
|
|
const { writeFile } = require('fs/promises');
|
|
const waEmitter = require('../emitter');
|
|
|
|
const { formatPhoneNumber, parsePhoneNumber, formatStatus, formatTimestamp } = require('./helper');
|
|
const generateId = require('../../utils/generateId.util');
|
|
const NodeCache = require('node-cache');
|
|
const P = require('pino');
|
|
|
|
const logger = P({ timestamp: () => `,"time":"${new Date().toJSON()}"` }, P.destination('./wa-logs.txt'));
|
|
logger.level = 'trace';
|
|
|
|
const msgRetryCounterCache = new NodeCache();
|
|
|
|
waEmitter.on('message:updated', event => {
|
|
console.info('msg:evt:updated', event);
|
|
});
|
|
waEmitter.on('message:received', event => {
|
|
console.info('msg:evt:received', event);
|
|
});
|
|
waEmitter.on('connection:open', event => {
|
|
console.info('con:evt.open', event);
|
|
});
|
|
waEmitter.on('connection:close', event => {
|
|
console.info('con:evt.close', event);
|
|
});
|
|
|
|
const createWhatsApp = async phone => {
|
|
let waSocket = null;
|
|
let qrCode = null;
|
|
const channelId = generateId();
|
|
const whatsAppNo = phone;
|
|
|
|
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 sendTextMessage = async (number, content) => {
|
|
const jid = formatPhoneNumber(number);
|
|
try {
|
|
const msgInfo = await waSocket.sendMessage(jid, { text: content });
|
|
waSocket.sendMessage(jid, { text: content })
|
|
return {
|
|
messageId: msgInfo?.key.id
|
|
};
|
|
} catch (ex) {
|
|
waEmitter.emit('message.error', {
|
|
messge: `[${whatsAppNo}->${number}]发送文本消息出错`,
|
|
from: whatsAppNo,
|
|
to: number,
|
|
error: ex
|
|
})
|
|
console.error(`[${whatsAppNo}->${number}]发送文本消息出错: `, ex);
|
|
}
|
|
};
|
|
|
|
const sendImageMessage = async (number, imageUrl) => {
|
|
const jid = formatPhoneNumber(number);
|
|
try {
|
|
const msgInfo = await waSocket.sendMessage(jid, {
|
|
image: { url: imageUrl },
|
|
});
|
|
return {
|
|
messageId: msgInfo?.key.id
|
|
};
|
|
} 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);
|
|
}
|
|
}
|
|
|
|
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);
|
|
if (messageType === 'imageMessage') {
|
|
// download the message
|
|
const buffer = await downloadMediaMessage(
|
|
msg,
|
|
'buffer',
|
|
{},
|
|
{
|
|
logger,
|
|
// pass this so that baileys can request a reupload of media
|
|
// that has been deleted
|
|
reuploadRequest: waSocket.updateMediaMessage,
|
|
},
|
|
);
|
|
// save to file
|
|
await writeFile('d:/my-download.jpeg', buffer);
|
|
}
|
|
|
|
const fromWhatsAppNo = parsePhoneNumber(msg.key.remoteJid);
|
|
|
|
if (msg.message?.conversation || msg.message?.extendedTextMessage?.text) {
|
|
const text = msg.message?.conversation || msg.message?.extendedTextMessage?.text;
|
|
|
|
if (text.indexOf('【发图】') > -1) {
|
|
sendImageMessage(fromWhatsAppNo, 'https://images.asiahighlights.com/allpicture/2022/07/8a7d9ced5936463bb904c82a_cut_750x850_349.webp');
|
|
} else if (text.indexOf('【发文】') > -1) {
|
|
sendTextMessage(fromWhatsAppNo, '这是文本消息:' + new Date().toString());
|
|
} else if (text.indexOf('【发群】') > -1) {
|
|
sendTextMessage('120363363417115199@g.us', '这是群消息:' + new Date().toString());
|
|
}
|
|
|
|
if (msg.key.fromMe) {
|
|
waEmitter.emit('message:updated', {
|
|
id: msg.key.id,
|
|
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,
|
|
},
|
|
eventSource: 'messages.upsert.notify',
|
|
updateTime: formatTimestamp(msg.messageTimestamp),
|
|
});
|
|
} else {
|
|
waEmitter.emit('message:received', {
|
|
id: msg.key.id,
|
|
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,
|
|
},
|
|
eventSource: '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);
|
|
if (msg.key.fromMe) {
|
|
waEmitter.emit('message:updated', {
|
|
id: msg.key.id,
|
|
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,
|
|
},
|
|
eventSource: '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) {
|
|
waEmitter.emit('message:updated', {
|
|
id: msg.key.id,
|
|
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,
|
|
},
|
|
eventSource: 'messages.updated',
|
|
updateTime: formatTimestamp(new Date().getTime() / 1000),
|
|
});
|
|
}
|
|
}
|
|
|
|
const handleCredsUpdate = async messageUpdate => {
|
|
await saveCreds();
|
|
}
|
|
|
|
const start = () => {
|
|
return new Promise(resolve => {
|
|
waSocket = makeWASocket({
|
|
version,
|
|
logger,
|
|
auth: {
|
|
creds: state.creds,
|
|
keys: makeCacheableSignalKeyStore(state.keys, logger),
|
|
},
|
|
// 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.ubuntu('IOS_PHONE'),//Browsers.baileys('WEAR_OS'),//Browsers.baileys('WEAR_OS'),//
|
|
msgRetryCounterCache,
|
|
generateHighQualityLinkPreview: false,
|
|
syncFullHistory: false,
|
|
});
|
|
|
|
store?.bind(waSocket.ev);
|
|
|
|
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 {
|
|
console.log('Connection closed: ', lastDisconnect);
|
|
|
|
waEmitter.emit('connection:close', {
|
|
whatsAppNo,
|
|
eventSource: 'connection.update.close',
|
|
status: 'offline',
|
|
});
|
|
}
|
|
} else if (connection === 'open') {
|
|
// 扫码成功后向这个群发消息,后续就能使用 API 发送了。
|
|
sendTextMessage('120363363417115199@g.us', whatsAppNo + ' 登录成功:' + new Date().toString());
|
|
waEmitter.emit('connection:open', {
|
|
status: 'open', whatsAppNo,
|
|
eventSource: 'connection.update.open',
|
|
});
|
|
} else if (qr !== undefined) {
|
|
// WebSocket 创建成功等待扫码,如果没有扫码会更新 qr
|
|
// 第一次一分钟,后面是 20 秒更新一次
|
|
if (qrCode === null) {
|
|
qrCode = qr;
|
|
resolve(qr);
|
|
} 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,
|
|
sendTextMessage,
|
|
sendImageMessage,
|
|
getProfilePicture,
|
|
};
|
|
};
|
|
|
|
module.exports = {
|
|
createWhatsApp,
|
|
};
|