如何使用Teams JS SDK v2向Microsoft Teams用户/频道发送大文本消息?
解决TeamsJS v2向特定用户/频道发送大文本消息的问题
TeamsJS v2本身仅提供客户端交互能力(比如用selectPeople选择用户),不直接支持发送消息。要实现向选定用户/频道发送大文本消息,需要结合Microsoft Graph API完成后端消息推送操作,以下是具体实现方案:
核心思路
- 用TeamsJS v2的
selectPeople(选用户)或selectChannel(选频道)API获取收件人标识(用户ID/团队+频道ID)。 - 将这些标识传递给后端服务,通过后端调用Microsoft Graph API完成消息发送(前端直接调用Graph会存在跨域、权限安全问题)。
步骤1:前端获取收件人信息
选择用户(基于你已实现的selectPeople)
import { peoplePicker } from "@microsoft/teams-js"; async function pickRecipients() { try { // 调用选择用户组件 const selectedPeople = await peoplePicker.selectPeople({ title: "选择消息收件人", singleSelect: false }); // 提取选中用户的AAD ID const recipientIds = selectedPeople.map(person => person.id); // 传递给后端发送消息 await fetch("/api/sendTeamsDirectMessage", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ recipientIds, message: "这里是大文本消息内容,支持多行、HTML格式(比如<br>换行),长度无客户端限制(Graph支持最大4096字符)" }) }); alert("消息发送请求已提交"); } catch (err) { console.error("选择收件人失败", err); } }
选择频道(若需支持频道消息)
如果需要向频道发送消息,使用TeamsJS v2的selectChannelAPI:
import { teams } from "@microsoft/teams-js"; async function pickChannel() { try { const selectedChannel = await teams.selectChannel(); // 提取团队ID和频道ID const { teamId, channelId } = selectedChannel; // 传递给后端 await fetch("/api/sendTeamsChannelMessage", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ teamId, channelId, message: "频道大文本消息内容" }) }); alert("频道消息发送请求已提交"); } catch (err) { console.error("选择频道失败", err); } }
步骤2:后端调用Graph API发送消息
以下以Node.js为例,使用@microsoft/microsoft-graph-client实现:
依赖安装
npm install @microsoft/microsoft-graph-client @azure/identity
后端核心代码
const express = require("express"); const { Client } = require("@microsoft/microsoft-graph-client"); const { ClientSecretCredential } = require("@azure/identity"); const { ClientCredentialsAuthenticationProvider } = require("@microsoft/microsoft-graph-client/authProviders/azureTokenCredentials"); const app = express(); app.use(express.json()); // 配置Azure AD应用凭据(需提前在Azure门户注册应用并授予权限) const tenantId = "你的Azure租户ID"; const clientId = "你的应用ID"; const clientSecret = "你的应用密钥"; // 初始化Graph客户端(应用权限模式,适合后台自动发送) const credential = new ClientSecretCredential(tenantId, clientId, clientSecret); const authProvider = new ClientCredentialsAuthenticationProvider(credential, { scopes: ["https://graph.microsoft.com/.default"] }); const graphClient = Client.initWithMiddleware({ authProvider }); // 发送一对一消息接口 app.post("/api/sendTeamsDirectMessage", async (req, res) => { const { recipientIds, message } = req.body; try { for (const userId of recipientIds) { // 1. 获取或创建与目标用户的一对一聊天 const existingChats = await graphClient.api(`/users/${userId}/chats`) .filter(`chatType eq 'oneOnOne'`) .get(); let chatId; if (existingChats.value.length > 0) { chatId = existingChats.value[0].id; } else { // 创建新的一对一聊天 const newChat = await graphClient.api("/chats") .post({ chatType: "oneOnOne", members: [{ "@odata.type": "#microsoft.graph.aadUserConversationMember", roles: ["owner"], user@odata.bind: `https://graph.microsoft.com/v1.0/users/${userId}` }] }); chatId = newChat.id; } // 2. 发送大文本消息 await graphClient.api(`/chats/${chatId}/messages`) .post({ body: { content: message } }); } res.status(200).send("所有消息发送成功"); } catch (err) { console.error("消息发送失败", err); res.status(500).send("消息发送失败"); } }); // 发送频道消息接口 app.post("/api/sendTeamsChannelMessage", async (req, res) => { const { teamId, channelId, message } = req.body; try { await graphClient.api(`/teams/${teamId}/channels/${channelId}/messages`) .post({ body: { content: message } }); res.status(200).send("频道消息发送成功"); } catch (err) { console.error("频道消息发送失败", err); res.status(500).send("频道消息发送失败"); } }); app.listen(3000, () => console.log("后端服务运行在3000端口"));
权限配置说明
在Azure AD门户中为你的应用授予以下权限(需管理员同意):
- 发送一对一消息:
ChatMessage.Send(应用权限) - 发送频道消息:
ChannelMessage.Send(应用权限)
如果是用户发起的操作(委托权限模式),可替换为ChatMessage.Send(委托权限),此时Graph客户端需使用用户的访问令牌初始化。
内容的提问来源于stack exchange,提问作者Vinny P.
相关产品推荐
相关产品推荐

