如何在Twilio Flex中区分对话状态以管控自动短信回复?
解决Twilio Flex对话状态区分问题:优化自动回复与Agent对话互斥逻辑
问题核心
现有代码仅通过对话state判断是否活跃,导致两个关键问题:
- 用户发送
Please help me创建的待分配对话也是active状态,被误判为已有活跃对话,无法生成Flex任务; - 无法精准区分「待分配对话」和「Agent正在处理的对话」,导致用户与Agent实时对话时发送
order status,可能触发不该有的自动回复。
解决方案思路
核心逻辑从仅依赖对话状态改为检查对话中是否有Agent参与:
- 待分配的对话只有用户一个参与者;
- Agent正在处理的对话会带有Agent角色的参与者(通过
identity或roleSid识别)。
代码修改实现
1. 重构对话状态检查逻辑
替换原有的参与者遍历代码,先判断对话中是否存在Agent参与者,再按请求类型分支处理:
// 获取当前对话详情及所有参与者 const targetConversation = await twilioClient.conversations.v1.conversations(ConversationSid).fetch(); const allParticipants = await twilioClient.conversations.v1.conversations(ConversationSid).participants.list(); // 判断对话是否有Agent参与(根据你的实际Agent标识规则调整) const isAgentEngaged = allParticipants.some(participant => { // 方案1:通过Agent的identity前缀判断(比如你的Agent账号统一用agent_开头) return participant.identity?.startsWith('agent_'); // 方案2:通过Agent角色SID判断(在Twilio控制台的Conversations -> Roles中查看) // return participant.roleSid === 'YOUR_AGENT_ROLE_SID'; }); // 核心分支处理 if (isAgentEngaged) { console.log("用户正在和Agent对话,禁止自动回复"); return; } // 无Agent参与的情况,按用户请求类型处理 const userMessage = 此处替换为实际接收的用户短信内容; if (userMessage.includes('order status')) { // 用户查询订单状态,发送自动回复 await sendAutoReply(incomingNumber, "你的订单状态为XXX"); // 替换为你的回复逻辑 } else if (userMessage === 'Please help me') { // 用户请求人工帮助,检查是否已创建Flex任务(避免重复创建) const conversationAttrs = JSON.parse(targetConversation.attributes || '{}'); if (!conversationAttrs.hasFlexTask) { // 创建Flex任务 await createFlexSupportTask(ConversationSid, incomingNumber); // 更新对话属性,标记已创建任务 await twilioClient.conversations.v1.conversations(ConversationSid).update({ attributes: JSON.stringify({ ...conversationAttrs, hasFlexTask: true }) }); } }
2. 封装Flex任务创建函数
将原创建任务代码封装为可复用函数:
async function createFlexSupportTask(conversationSid, customerNumber) { try { const newInteraction = await twilioClient.flexApi.v1.interaction.create({ channel: { type: 'sms', initiated_by: 'customer', properties: { media_channel_sid: conversationSid } }, routing: { properties: { workspace_sid: workspaceSid, workflow_sid: workflowSid, task_channel_unique_name: 'SMS', attributes: { name: customerNumber, } } } }); console.log(`已创建Flex任务,SID:${newInteraction.sid}`); return newInteraction; } catch (err) { console.error("创建Flex任务失败:", err); throw err; } }
额外配置建议
- 统一Agent标识规则:创建Flex Agent账号时,给
identity添加固定前缀(如agent_张三),方便代码识别; - 对话属性标记:创建任务后更新对话
attributes,避免用户重复发送Please help me时重复创建任务; - 验证角色SID:若使用角色SID判断,前往Twilio控制台「Conversations -> Roles」获取默认Agent角色SID,替换代码中的
YOUR_AGENT_ROLE_SID。
最终效果
- 用户与Agent正在对话时,发送
order status不会触发自动回复; - 用户发送
Please help me时,仅在无Agent参与且未创建任务的情况下,生成Flex任务通知坐席; - 用户单独发送
order status时,正常返回自动回复。
内容的提问来源于stack exchange,提问作者aqib
相关产品推荐
相关产品推荐

