diff --git a/wai-server/api/channels/channel.controller.js b/wai-server/api/channels/channel.controller.js index cac5028..44b0668 100644 --- a/wai-server/api/channels/channel.controller.js +++ b/wai-server/api/channels/channel.controller.js @@ -34,35 +34,6 @@ exports.newConnect = async ctx => { } }; -exports.sendText = async ctx => { - const { from, to, msgcontent, content: _content, actionId } = ctx.request.body; - const content = _content || msgcontent.body || ''; - if (!from || !content) { - ctx.assert(from, 400, 'From and message are required'); - return; - } - const wsToSend = whatApp.instance; - // console.log('find wsToSend', wsToSend) - if (!wsToSend) { - ctx.assert(wsToSend, 400, 'Session not found'); // 404 - return; - } - try { - const fromWebId = generateId(); - console.info(`fromWebId: ${fromWebId};`); - wsToSend.sendTextMessage(to, content, fromWebId).then(({ messageId, externalId }) => { - console.info(`messageId: ${messageId}; externalId: ${externalId}`); - }).catch(ex => { - console.error('Error channel sending message:', error); - }); - // const sockMsg = await wsToSend.sendTextMessage(to, content, actionId); - return 'channel sent successfully'; // { wsToSend, ret: 'Message sent successfully' }; - } catch (error) { - console.error('Error sending message:', error); - ctx.assert(null, 500, 'Failed to send message'); - } -}; - exports.getAll = async () => { const findConnection = await getConnection({}); return findConnection; diff --git a/wai-server/api/channels/channel.routes.js b/wai-server/api/channels/channel.routes.js index 1597164..bf4ae7f 100644 --- a/wai-server/api/channels/channel.routes.js +++ b/wai-server/api/channels/channel.routes.js @@ -15,7 +15,6 @@ module.exports = Router => { // .get('/:id', controller.getOne) .get('/', controller.getAll) .get('/sessions', controller.getSessions); - // .post('/test', controller.testSend); // .post('/', controller.createOne) // router.post('/get-in', callController.getIn); // router.post('/send-msg', callController.sendMsg); diff --git a/wai-server/core/baileys/index.js b/wai-server/core/baileys/index.js index b63ec27..a472908 100644 --- a/wai-server/core/baileys/index.js +++ b/wai-server/core/baileys/index.js @@ -33,14 +33,15 @@ waEmitter.on('connection:close', event => { const createWhatsApp = async phone => { let waSocket = null; let qrCode = null; + let connectionStatus = 'offline' const channelId = generateId(); const whatsAppNo = phone; + // 储存键值对 msgId-externalId + // TODO 什么时候清理旧的? 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 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); @@ -57,33 +58,33 @@ const msgRetryCounterCache = new NodeCache(); const jid = formatPhoneNumber(number); return new Promise(() => { - waSocket.sendMessage(jid, { text: content }) - .then(msg => { - msgIdMap.set(msg.key.id, externalId); - waEmitter.emit('message:updated', { - id: msg.key.id, - externalId, - status: 'saved', - direction: 'outbound', - from: whatsAppNo, - to: number, - eventSource: 'sendMessage.promise.then', - updateTime: formatTimestamp(new Date().getTime() / 1000), - }) + waSocket.sendMessage(jid, { text: content }) + .then(msg => { + msgIdMap.set(msg.key.id, externalId); + waEmitter.emit('message:updated', { + id: msg.key.id, + externalId, + status: 'saved', + direction: 'outbound', + from: whatsAppNo, + to: number, + eventSource: 'sendMessage.promise.then', + updateTime: formatTimestamp(new Date().getTime() / 1000), }) - .catch(ex => { - waEmitter.emit('message:updated', { - id: generateId(), - externalId, - status: 'failed', - direction: 'outbound', - from: whatsAppNo, - to: number, - errro: `发送文本消息出错 ` + ex, - eventSource: 'sendMessage.promise.catch', - updateTime: formatTimestamp(new Date().getTime() / 1000), - }); + }) + .catch(ex => { + waEmitter.emit('message:updated', { + id: generateId(), + externalId, + status: 'failed', + direction: 'outbound', + from: whatsAppNo, + to: number, + errro: `发送文本消息出错 ` + ex, + eventSource: 'sendMessage.promise.catch', + updateTime: formatTimestamp(new Date().getTime() / 1000), }); + }); }); }; @@ -262,13 +263,13 @@ const msgRetryCounterCache = new NodeCache(); creds: state.creds, keys: makeCacheableSignalKeyStore(state.keys, logger), }, - connectTimeoutMs: 1000*60*1, + connectTimeoutMs: 1000*60*10, defaultQueryTimeoutMs: 1000*60*1, - keepAliveIntervalMs: 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.baileys('WEAR_OS'),//Browsers.macOS('SAFARI'),//Browsers.ubuntu('IOS_PHONE'),//Browsers.baileys('WEAR_OS'),// + browser: Browsers.macOS('SAFARI'),//Browsers.macOS('SAFARI'),//Browsers.ubuntu('IOS_PHONE'),//Browsers.baileys('WEAR_OS'),// msgRetryCounterCache, generateHighQualityLinkPreview: false, syncFullHistory: false, @@ -292,8 +293,13 @@ const msgRetryCounterCache = new NodeCache(); }); } } else if (connection === 'open') { - // 扫码成功后向这个群('120363363417115199@g.us')发消息,后续就能使用 API 发送了。 - sendTextMessage('120363363417115199@g.us', whatsAppNo + ' 登录成功:' + new Date().toString()); + if (connectionStatus === 'open') { + sendTextMessage('120363363417115199@g.us', whatsAppNo + ' 在线:' + new Date().toString()); + } else { + // 扫码成功后向这个群('120363363417115199@g.us')发消息,后续就能使用 API 发送了。 + sendTextMessage('120363363417115199@g.us', whatsAppNo + ' 登录成功:' + new Date().toString()); + } + connectionStatus = 'open'; waEmitter.emit('connection:open', { status: 'open', whatsAppNo, channelId, eventSource: 'connection.update.open', diff --git a/wai-server/core/baileys/test.js b/wai-server/core/baileys/test.js new file mode 100644 index 0000000..adb8e1f --- /dev/null +++ b/wai-server/core/baileys/test.js @@ -0,0 +1,100 @@ +function generateRandomString(length) { + const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + let result = ''; + const charactersLength = characters.length; + for (let i = 0; i < length; i++) { + result += characters.charAt(Math.floor(Math.random() * charactersLength)); + } + return result; +} + +const start = () => { + + setInterval(() => { + + const randomString = generateRandomString(10); + var myHeaders = new Headers(); + myHeaders.append("Content-Type", "application/json"); + myHeaders.append("Accept", "*/*"); + myHeaders.append("Host", "wai-server-01-qq4qmtq7wc9he4.chinahighlights.cn"); + myHeaders.append("Connection", "keep-alive"); + + var raw = JSON.stringify({ + "from": "8618777396951", + "to": "8613557032060", + "content": randomString + "-setInterval(2min) 发送:" + new Date().toString() + }); + + var requestOptions = { + method: 'POST', + headers: myHeaders, + body: raw, + redirect: 'follow' + }; + + fetch("http://wai-server-01-qq4qmtq7wc9he4.chinahighlights.cn/api/v1/channels/send", requestOptions) + .then(rsp => rsp.json()) + .then(json => console.info('8613557032060: ', json)) + .catch(ex => console.error(ex)); + }, 1000*60*2); + // + + setInterval(() => { + + const randomString = generateRandomString(10); + var myHeaders = new Headers(); + myHeaders.append("Content-Type", "application/json"); + myHeaders.append("Accept", "*/*"); + myHeaders.append("Host", "wai-server-01-qq4qmtq7wc9he4.chinahighlights.cn"); + myHeaders.append("Connection", "keep-alive"); + + var raw = JSON.stringify({ + "from": "8618777396951", + "to": "8613317835586", + "content": randomString + "-setInterval(3min) 发送:" + new Date().toString() + }); + + var requestOptions = { + method: 'POST', + headers: myHeaders, + body: raw, + redirect: 'follow' + }; + + fetch("http://wai-server-01-qq4qmtq7wc9he4.chinahighlights.cn/api/v1/channels/send", requestOptions) + .then(rsp => rsp.json()) + .then(json => console.info('8613317835586: ', json)) + .catch(ex => console.error(ex)); + }, 1000*60*3); + // + + setInterval(() => { + + const randomString = generateRandomString(10); + var myHeaders = new Headers(); + myHeaders.append("Content-Type", "application/json"); + myHeaders.append("Accept", "*/*"); + myHeaders.append("Host", "wai-server-01-qq4qmtq7wc9he4.chinahighlights.cn"); + myHeaders.append("Connection", "keep-alive"); + + var raw = JSON.stringify({ + "from": "8618777396951", + "to": "8617607735120", + "content": randomString + "-setInterval(5min) 发送:" + new Date().toString() + }); + + var requestOptions = { + method: 'POST', + headers: myHeaders, + body: raw, + redirect: 'follow' + }; + + fetch("http://wai-server-01-qq4qmtq7wc9he4.chinahighlights.cn/api/v1/channels/send", requestOptions) + .then(rsp => rsp.json()) + .then(json => console.info('8613317835586: ', json)) + .catch(ex => console.error(ex)); + }, 1000*60*5); +} + +start(); \ No newline at end of file