关于使用V2.0 Flex-project-template构建插件及函数调用的咨询
在V2.0 Flex Project Template中使用预构建及自定义函数/动作
一、调用预构建函数/动作
预构建功能已集成在模板的src/features或src/components目录下,以下是常见场景示例:
1. 使用预构建任务操作动作
比如分配任务给指定坐席,可直接通过Flex内置动作调用:
import { Actions } from '@twilio/flex-ui'; // 在组件事件处理函数中执行 const assignTaskToAgent = (task, agentSid) => { Actions.invokeAction('AssignTask', { task: task, targetSid: agentSid }); };
AssignTask是Flex原生预构建动作,模板已完成基础集成,直接用Actions.invokeAction触发即可。
2. 调用预构建Twilio Functions
模板serverless/functions目录下的预构建函数,可通过模板封装的API客户端调用:
import { ApiClient } from '../services'; const fetchCustomerDetails = async (customerId) => { try { const response = await ApiClient.get(`/get-customer-details?customerId=${customerId}`); return response.data; } catch (error) { console.error('获取客户信息失败:', error); throw error; } };
ApiClient已配置好请求路径与认证,直接传入函数路径即可发起调用。
二、创建并调用自定义函数/动作
1. 创建自定义动作
在src/actions目录新建CustomActions.js:
import { ActionContext } from '@twilio/flex-ui'; export const registerCustomActions = () => { ActionContext.getInstance().registerAction('CustomUpdateTaskStatus', (payload, abort) => { const { task, newStatus } = payload; // 自定义逻辑:更新任务状态属性 task.setAttributes({ ...task.attributes, status: newStatus }); return true; }); };
在src/index.js中注册动作:
import { registerCustomActions } from './actions/CustomActions'; registerCustomActions();
之后在组件中调用:
import { Actions } from '@twilio/flex-ui'; Actions.invokeAction('CustomUpdateTaskStatus', { task: currentTask, newStatus: 'On-Hold' });
2. 创建自定义Twilio Function
在serverless/functions目录新建custom-function.protected.js:
exports.handler = async function(context, event, callback) { const response = new Twilio.Response(); response.appendHeader('Content-Type', 'application/json'); try { // 自定义业务逻辑,如查询数据库或调用第三方API const result = { message: '自定义函数执行成功', data: event.inputData }; response.setBody(result); response.setStatusCode(200); callback(null, response); } catch (error) { response.setBody({ error: error.message }); response.setStatusCode(500); callback(error, response); } };
部署Serverless函数后,通过ApiClient调用:
import { ApiClient } from '../services'; const callCustomFunction = async (inputData) => { try { const response = await ApiClient.post('/custom-function', { inputData }); return response.data; } catch (error) { console.error('调用自定义函数失败:', error); throw error; } };
三、关键注意事项
- 确保模板初始化配置正确,比如
ApiClient的基础URL已设置妥当 - 自定义函数需部署到Twilio Serverless环境后才能调用,部署命令:
twilio serverless:deploy - 调用动作时需严格匹配官方文档中对应动作的参数格式要求
内容的提问来源于stack exchange,提问作者sunilkumar t
相关产品推荐
相关产品推荐

