如何在MS Bot Framework服务端发送IEventActivity控制WebChat文件上传按钮?
实现通过Bot发送事件控制WebChat文件上传按钮的方向
我来帮你梳理下具体的实现思路,核心分为Bot端发送事件、WebChat端监听事件并修改按钮状态两个关键步骤:
一、Bot端构造并发送IEventActivity
IEventActivity本质就是Bot Framework中类型为"event"的Activity,不需要特殊的API,用常规的发送Activity方法即可。你只需要指定好事件名称和携带的状态参数:
示例代码(C#)
var eventActivity = Activity.CreateEventActivity(); eventActivity.Name = "toggleFileUpload"; // 自定义事件名称,方便WebChat识别 eventActivity.Value = new { Enabled = false }; // 携带开关状态:true启用,false禁用 await turnContext.SendActivityAsync(eventActivity, cancellationToken);
示例代码(Node.js)
await context.sendActivity({ type: 'event', name: 'toggleFileUpload', value: { enabled: false } // 传递开关状态 });
只要构造的Activity符合type: 'event',并包含自定义的name和value,就属于标准的IEventActivity,Bot会正常发送给WebChat客户端。
二、WebChat端监听事件并控制文件上传按钮
WebChat提供了store middleware机制,可以监听Bot发送的所有Activity,我们可以在这里捕获自定义的事件,然后修改文件上传按钮的状态:
1. 配置WebChat的Store监听事件
const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => { if (action.type === 'DIRECT_LINE/INCOMING_ACTIVITY') { const activity = action.payload.activity; // 捕获自定义的toggleFileUpload事件 if (activity.type === 'event' && activity.name === 'toggleFileUpload') { const isEnabled = activity.value.enabled; // 方式一:直接操作DOM控制按钮(适合快速验证) const uploadButton = document.querySelector('[aria-label="Upload file"]'); if (uploadButton) { uploadButton.disabled = !isEnabled; uploadButton.style.opacity = isEnabled ? 1 : 0.5; } // 方式二:更新WebChat的自定义状态,供组件使用(更优雅) dispatch({ type: 'TOGGLE_FILE_UPLOAD', payload: { enabled: isEnabled } }); } } return next(action); }); // 将store传入WebChat渲染 window.WebChat.renderWebChat({ directLine: window.WebChat.createDirectLine({ token: 'YOUR_DIRECT_LINE_TOKEN' }), store: store }, document.getElementById('webchat'));
2. 自定义SendBox组件(推荐方式)
如果不想直接操作DOM,可以自定义SendBox组件,通过store的状态来控制文件上传按钮的禁用状态:
const CustomSendBox = props => { const { enabled } = props.store.getState().toggleFileUpload || { enabled: true }; return ( <window.WebChat.SendBox {...props} uploadButtonProps={{ disabled: !enabled }} /> ); }; // 渲染WebChat时传入自定义SendBox window.WebChat.renderWebChat({ directLine: window.WebChat.createDirectLine({ token: 'YOUR_DIRECT_LINE_TOKEN' }), store: store, components: { SendBox: CustomSendBox } }, document.getElementById('webchat'));
这样,当Bot发送toggleFileUpload事件时,WebChat就能实时切换文件上传按钮的启用/禁用状态了。
内容的提问来源于stack exchange,提问作者sk2andy
相关产品推荐
相关产品推荐

