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.
Global-sales/wai-server/api/messages/message.controller.js

42 lines
1.4 KiB
JavaScript

'use strict';
const { sessionStore } = require('../../core');
const { createOutboundMessage } = require('../../services/outbound_messages.service');
const waEmitter = require('../../core/emitter');
const logger = require('../../utils/logger.util');
const { ctxToSendBuilder, ctxToDB } = require('../../helper/wai.msg.helper');
const send = async ctx => {
const { msgtype, from, to, msgcontent, content: _content } = ctx.request.body;
const content = _content || msgcontent.body || '';
logger.info('send', msgtype, from, to, content);
if (!from) {
ctx.assert(from, 400, '请先到个人资料页扫码登录WhatsApp');
return;
}
const wsToSend = sessionStore.getSession(from);
// console.log('find wsToSend', wsToSend)
if (!wsToSend) {
ctx.assert(wsToSend, 401, '未登录WhatsApp, 请到个人资料页扫码登录'); // 404
return;
}
try {
const _data = ctx.request.body;
_data.to = _data.to.trim();
const toUpsert = ctxToDB(_data);
await createOutboundMessage({ ...toUpsert });
// wsToSend.sendTextMessage(to, content, actionId);
const messagePayload = ctxToSendBuilder(_data);
waEmitter.emit('request.' + from + '.send.message', messagePayload);
return 'Message sent successfully'; // { wsToSend, ret: 'Message sent successfully' };
} catch (error) {
console.error('Error sending message:', error);
ctx.assert(null, 500, 'Failed to send message');
}
};
module.exports = {
send,
};