Teams Toolkit v4通知Bot自动触发欢迎自适应卡问题求助
解决方案建议
1. 监听标签页激活事件触发卡片发送
在你的notification bot标签页前端,借助Teams JavaScript SDK监听页面激活/聚焦事件,每当用户切换到该标签页时,调用后端接口发送欢迎自适应卡。
先引入Teams JS SDK:
<script src="https://res.cdn.office.net/teams-js/2.21.0/js/MicrosoftTeams.min.js"></script>初始化SDK并绑定事件:
microsoftTeams.initialize(); // 页面首次加载完成时触发 microsoftTeams.registerOnLoadHandler(() => { triggerWelcomeCard(); }); // 标签页被重新选中(切换回来)时触发 microsoftTeams.registerOnFocusHandler(() => { triggerWelcomeCard(); }); function triggerWelcomeCard() { // 获取当前用户上下文信息 microsoftTeams.getContext(context => { const userInfo = { userId: context.userObjectId, tenantId: context.tenant.id }; // 调用后端接口发送卡片 fetch('/api/send-welcome-card', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(userInfo) }).catch(err => console.error('发送欢迎卡失败:', err)); }); }
2. 后端restify接口实现
在你的restify服务中添加接口,接收用户信息后调用Teams Bot API发送自适应卡:
server.post('/api/send-welcome-card', async (req, res) => { const { userId, tenantId } = req.body; const botToken = process.env.TEAMS_BOT_TOKEN; // 从环境变量获取Bot令牌 // 你的欢迎自适应卡内容 const welcomeCard = { type: 'AdaptiveCard', version: '1.0', body: [ { type: 'TextBlock', text: '欢迎使用通知机器人!', size: 'Large' }, { type: 'TextBlock', text: '这里是你的专属通知中心,将为你推送重要消息。' } ] }; try { const response = await fetch( `https://smba.trafficmanager.net/amer/v3/conversations/users/${userId}/activities`, { method: 'POST', headers: { 'Authorization': `Bearer ${botToken}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ type: 'message', attachments: [{ contentType: 'application/vnd.microsoft.card.adaptive', content: welcomeCard }], channelData: { tenant: { id: tenantId } } }) } ); res.status(response.ok ? 200 : response.status).send({ success: response.ok, message: response.ok ? '卡片发送成功' : '卡片发送失败' }); } catch (err) { res.status(500).send({ success: false, message: err.message }); } });
3. 优化:避免重复发送卡片
如果不需要每次切换都发送,可以通过以下方式控制:
- 前端方案:用
localStorage标记已发送状态function triggerWelcomeCard() { if (localStorage.getItem('hasReceivedWelcomeCard')) return; microsoftTeams.getContext(context => { // 调用接口发送卡片 fetch('/api/send-welcome-card', ...) .then(() => localStorage.setItem('hasReceivedWelcomeCard', 'true')); }); } - 后端方案:在数据库中记录用户是否已接收过欢迎卡,接口调用时先查询再决定是否发送。
内容的提问来源于stack exchange,提问作者catBuddy
相关产品推荐
相关产品推荐

