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.
269 lines
8.8 KiB
JavaScript
269 lines
8.8 KiB
JavaScript
const {
|
|
makeWASocket,
|
|
Browsers,
|
|
DisconnectReason,
|
|
fetchLatestBaileysVersion,
|
|
makeCacheableSignalKeyStore,
|
|
makeInMemoryStore,
|
|
useMultiFileAuthState,
|
|
downloadMediaMessage,
|
|
} = require('@whiskeysockets/baileys');
|
|
const { writeFile } = require('fs/promises');
|
|
const waEmitter = require('../emitter');
|
|
|
|
const { formatPhoneNumber, parsePhoneNumber, formatStatus, formatTimestamp } = require('./common');
|
|
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();
|
|
|
|
const store = makeInMemoryStore({ logger });
|
|
store?.readFromFile('./baileys_store_multi.json');
|
|
// save every 10s
|
|
setInterval(() => {
|
|
store?.writeToFile('./baileys_store_multi.json');
|
|
}, 10_000);
|
|
|
|
waEmitter.on('message:updated', event => {
|
|
console.info('msg:event', event);
|
|
});
|
|
waEmitter.on('message:received', event => {
|
|
console.info('msg:event', event);
|
|
});
|
|
waEmitter.on('connection.open', event => {
|
|
console.info('msg:event', event);
|
|
});
|
|
|
|
const createWhatsApp = async phone => {
|
|
const channelId = generateId();
|
|
const whatsAppNo = phone;
|
|
const { state, saveCreds } = await useMultiFileAuthState('baileys_auth_info/' + phone);
|
|
// fetch latest version of WA Web
|
|
const { version, isLatest } = await fetchLatestBaileysVersion();
|
|
const waVersion = version.join('.') + ', ' + (isLatest ? 'latest' : 'out');
|
|
|
|
const sendTextMessage = (whatsAppNo, content) => {
|
|
const number = formatPhoneNumber(whatsAppNo);
|
|
try {
|
|
waSocket.sendMessage(number, { text: content });
|
|
} catch (ex) {
|
|
waEmitter.emit('message.error', {
|
|
messge: '发送文本消息出错',
|
|
error: ex
|
|
})
|
|
console.error('发送文本消息出错: ', ex);
|
|
}
|
|
};
|
|
|
|
const sendImageMessage = (whatsAppNo, imageUrl) => {
|
|
const number = formatPhoneNumber(whatsAppNo);
|
|
try {
|
|
waSocket.sendMessage(number, {
|
|
image: { url: imageUrl },
|
|
});
|
|
} catch (ex) {
|
|
waEmitter.emit('message.error', {
|
|
messge: '发送图片消息出错',
|
|
error: ex
|
|
})
|
|
console.error('发送图片消息出错: ', ex);
|
|
}
|
|
};
|
|
|
|
let waSocket = null;
|
|
|
|
const start = () => {
|
|
return new Promise(resolve => {
|
|
waSocket = makeWASocket({
|
|
version,
|
|
logger,
|
|
auth: {
|
|
creds: state.creds,
|
|
/** caching makes the store faster to send/recv messages */
|
|
keys: makeCacheableSignalKeyStore(state.keys, logger),
|
|
},
|
|
// https://github.com/WhiskeySockets/Baileys/blob/31bc8ab/src/Utils/generics.ts#L21
|
|
browser: Browsers.macOS('Desktop'),
|
|
msgRetryCounterCache,
|
|
generateHighQualityLinkPreview: false,
|
|
syncFullHistory: false,
|
|
});
|
|
|
|
// something about the connection changed
|
|
// maybe it closed, or we received all offline message or connection opened
|
|
waSocket.ev.on('connection.update', async update => {
|
|
console.log('connection update: ', update);
|
|
const { connection, lastDisconnect, qr, isOnline } = update;
|
|
|
|
if (connection === 'close') {
|
|
console.log('链接断开:', lastDisconnect);
|
|
if (lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut) {
|
|
console.log('正在重连:');
|
|
start();
|
|
} else {
|
|
waSocket.end(error => console.error('end.error: ', error));
|
|
waSocket.logout(msg => console.error('logout.msg: ', msg));
|
|
console.log('Connection closed. You are logged out.');
|
|
|
|
waEmitter.emit('connection:close', {
|
|
whatsAppNo,
|
|
status: 'offline',
|
|
});
|
|
}
|
|
} else if (connection === 'open') {
|
|
waEmitter.emit('connection:open', {
|
|
whatsAppNo,
|
|
status: 'online',
|
|
});
|
|
waEmitter.emit('connection:open', {
|
|
status: 'open', phone
|
|
});
|
|
} else if (qr !== undefined) {
|
|
// WebSocket 创建成功等待扫码,如果没有扫码会更新 qr
|
|
resolve(qr);
|
|
}
|
|
});
|
|
|
|
waSocket.ev.on('messages.upsert', async upsert => {
|
|
console.log('收到消息:', JSON.stringify(upsert, undefined, 2));
|
|
|
|
if (upsert.type === 'notify') {
|
|
for (const msg of upsert.messages) {
|
|
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);
|
|
|
|
try {
|
|
const ppUrl = await waSocket.profilePictureUrl(msg.key.remoteJid);
|
|
console.log('头像: ' + ppUrl);
|
|
} catch (ex) {
|
|
console.error('头像出错: ', ex);
|
|
}
|
|
|
|
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),
|
|
from: whatsAppNo,
|
|
to: fromWhatsAppNo,
|
|
type: 'text',
|
|
text: {
|
|
body: text,
|
|
},
|
|
customerProfile: {
|
|
id: parsePhoneNumber(msg.key.participant),
|
|
name: msg.pushName,
|
|
},
|
|
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,
|
|
},
|
|
customerProfile: {
|
|
id: parsePhoneNumber(msg.key.participant),
|
|
name: msg.pushName,
|
|
},
|
|
createTime: formatTimestamp(msg.messageTimestamp),
|
|
});
|
|
}
|
|
}
|
|
}
|
|
}
|
|
});
|
|
|
|
waSocket.ev.on('messages.update', async messageUpdate => {
|
|
console.info('messages.update: ', messageUpdate);
|
|
|
|
for (const msg of messageUpdate) {
|
|
waEmitter.emit('message:updated', {
|
|
id: msg.key.id,
|
|
status: formatStatus(msg.update.status),
|
|
from: msg.key.fromMe ? whatsAppNo : parsePhoneNumber(msg.key.remoteJid),
|
|
to: msg.key.fromMe ? parsePhoneNumber(msg.key.remoteJid) : whatsAppNo,
|
|
customerProfile: {
|
|
id: parsePhoneNumber(msg.key.participant),
|
|
name: msg.pushName,
|
|
},
|
|
updateTime: formatTimestamp(new Date().getTime() / 1000),
|
|
});
|
|
}
|
|
});
|
|
|
|
waSocket.ev.on('group-participants.update', async GroupMetadata => {
|
|
console.info('group-participants.update: ', GroupMetadata);
|
|
});
|
|
|
|
// 不绑定不会影响扫码登录
|
|
store?.bind(waSocket.ev);
|
|
|
|
// the process function lets you process all events that just occurred
|
|
// efficiently in a batch
|
|
waSocket.ev.process(
|
|
// events is a map for event name => event data
|
|
async events => {
|
|
// credentials updated -- save them
|
|
if (events['creds.update']) {
|
|
await saveCreds();
|
|
}
|
|
},
|
|
);
|
|
});
|
|
};
|
|
|
|
return {
|
|
createTimestamp: Date.now(),
|
|
status: 'offline',
|
|
version: waVersion,
|
|
channelId: channelId,
|
|
phone: phone,
|
|
start,
|
|
sendTextMessage,
|
|
sendImageMessage,
|
|
};
|
|
};
|
|
|
|
module.exports = {
|
|
createWhatsApp,
|
|
};
|