'use strict'; const generateId = require('../../utils/generateId.util'); const plannerEvents = require('../emitter'); // const createAsyncQueueProcessor = require('../emitter/queueProcessor'); const { getConnection } = require('../../services/connections.service') const { getAgentSession, createAgentSession, update: updateAgentSession } = require('../../services/agent_sessions.service'); // const { getOutboundMessage, upsertOutboundMessage } = require('../../services/outbound_messages.service'); const { isEmpty } = require('../../utils/commons.util'); const { logger, getUserLogger } = require('../../utils/logger.util'); const { callAgentRounds } = require('../vendor/bailian.aliyun'); const { sendMessage } = require('../handler/whatsappHandler'); const userMessageEventNames = ['user:message:received']; const agentMessageEventNames = ['agent:message:received']; // const AGENT_PHONE_NO = ['8613557032060']; const AGENT_PHONE_NO = require('../../config').agentHosted.split(','); /** * 接收客人的回复 * - 发送给agent */ const setupUserMessageHandler = async () => { const messageListner = async ({ eventName, msgRow }) => { const { from, to, direction } = msgRow; const _whatsAppNo = to; const _contact = from; getUserLogger(_whatsAppNo).info({ eventName, msgRow }); const hostedUser = await getConnection({ wa_id: _whatsAppNo, status: 'hosted' }); if ((!AGENT_PHONE_NO.includes(_whatsAppNo) && isEmpty(hostedUser)) || direction !== 'inbound') { // logger.info({ eventName, msgRow }, 'ignore message'); return false; } try { const agentSession = await getAgentSession({ hosted: _whatsAppNo, contact: _contact }); // if (isEmpty(agentSession) || isEmpty(savedMsg?.text_body)) { // 只处理文本 if (isEmpty(msgRow?.text_body)) { return false; } // contact -> agent const agentPost = { agent_session_id: agentSession?.agent_session_id || '', content: msgRow.text_body, }; const agentRes = await callAgentRounds(agentPost); plannerEvents.emit('agent:message:received', { msgRow, agentSession, agentRes }); // # } catch (error) { logger.error({ messageData: msgRow, error }, 'error call agent'); } }; userMessageEventNames.forEach(eventName => { plannerEvents.on(eventName, async msgRow => messageListner({ eventName, msgRow })); }); }; const setupAgentMessageHandler = async () => { const messageListner = async ({ eventName, payload }) => { const { msgRow, agentSession, agentRes } = payload; const { from, to, whatsAppNo, direction } = msgRow; const _whatsAppNo = whatsAppNo || to; const _contact = from; const { output: agentMsg } = agentRes; const { session_id: agentSessionId } = agentMsg; getUserLogger(_whatsAppNo).info({ eventName, agentRes }); try { const now = new Date(new Date().getTime() + 60 * 60 * 1000).toISOString(); // 号码直接托管 // - todo: 按会话托管时另外处理 if (isEmpty(agentSession)) { await createAgentSession({ agent_session_id: agentSessionId, hosted: _whatsAppNo, contact: _contact, agent_id: agentRes.agent.id, agent_name: agentRes.agent.name, model_id: agentRes.usage.models[0].model_id, }); } else { // 更新 await updateAgentSession( { agent_session_id: agentSessionId, hosted: _whatsAppNo, contact: _contact, agent_id: agentRes.agent.id, agent_name: agentRes.agent.name, model_id: agentRes.usage.models[0].model_id, }, { hosted: _whatsAppNo, contact: _contact, }, ); } // agent -> contact const msgReady = { from: _whatsAppNo, to: _contact, msgcontent: { body: agentMsg.text }, msgtype: 'text', actionId: `.${generateId()}.${agentSessionId}` }; await sendMessage(msgReady); // # } catch (error) { logger.error({ msgRow, agentRes, error }, 'error call agent'); } }; agentMessageEventNames.forEach(eventName => { plannerEvents.on(eventName, async payload => messageListner({ eventName, payload })); }); }; async function startAgentSession(messageData) { // const now = new Date(new Date().getTime() + 60 * 60 * 1000).toISOString(); // const { from, to, whatsAppNo, direction } = messageData; // const _whatsAppNo = whatsAppNo || to; // const _contact = from; // // -> agent // const agentRes = await callAgentFirst({ // // agent_session_id: agentSession.agent_session_id, // content: messageData.text_body, // }); // const { text: agentMsg, session_id: agentSessionId } = agentRes; // await createAgentSession({ agent_session_id: agentSessionId, hosted: _whatsAppNo, contact: _contact, created_at: now }); // const msgReady = { from: _whatsAppNo, to: _contact, body: agentMsg, msgtype: 'text', actionId: `.${generateId()}` }; // await sendMessage(msgReady); // // } function setupAgentHandler() { setupAgentMessageHandler(); setupUserMessageHandler(); } module.exports = { setupAgentHandler, startAgentSession };