如何通过Microsoft Graph向Teams频道发送公告类型聊天消息
问题根因
你遇到这个报错是三个配置错误导致的,和附件ID只读的说法没有关系:
Attachments参数要求传入数组类型,你原代码里传的是单个哈希表对象,接口无法正确解析附件的顶层结构- 附件ID是附件对象的顶层属性,和
contentType、content平级,你原代码里把id注释/放在了content子对象内部,接口识别不到 - 公告附件的ID不需要系统生成,你自己生成随机GUID即可,只要保证附件对象的id值,和HTML正文里
<attachment>标签的id属性值完全一致就可以正常识别。
修正后的PowerShell(Microsoft.Graph模块)实现
Select-MgProfile beta Connect-MgGraph -Scopes "ChannelMessage.Send" # 生成随机GUID作为附件匹配ID $announcementAttachmentId = [guid]::NewGuid().ToString() # 注意Attachments是数组,id放在附件对象顶层 $attachments = @( @{ id = $announcementAttachmentId contentType = "application/vnd.microsoft.teams.messaging-announcementBanner" content = @{ title = "This is an important announcement" cardImageType = "colorTheme" cardImageDetails = @{ colorTheme = "periwinkleBlue" } | ConvertTo-Json -Compress } } ) $bodyContent = @" <attachment id="$announcementAttachmentId"></attachment> <div>Hi all, 这里填写公告正文内容</div> "@ $params = @{ ChannelId = "替换为实际频道ID" TeamId = "替换为实际团队ID" Attachments = $attachments Importance = "high" Body = @{ ContentType = "html" Content = $bodyContent } } New-MgTeamChannelMessage @params
原生REST接口调用示例
如果不用PowerShell模块,可以直接向beta版Graph接口发POST请求,请求地址为https://graph.microsoft.com/beta/teams/{team-id}/channels/{channel-id}/messages,请求体结构如下:
{ "importance": "high", "body": { "contentType": "html", "content": "<attachment id=\"e5718d51-22a3-4c28-9978-1f3aexample\"></attachment><div>Hi all, 公告正文内容</div>" }, "attachments": [ { "id": "e5718d51-22a3-4c28-9978-1f3aexample", "contentType": "application/vnd.microsoft.teams.messaging-announcementBanner", "content": "{\"title\":\"This is an important announcement\",\"cardImageType\":\"colorTheme\",\"cardImageDetails\":\"{\\\"colorTheme\\\":\\\"periwinkleBlue\\\"}\"}" } ] }
补充说明
- 内置可选的公告主题色除了
periwinkleBlue,还支持red、green、orange、purple、darkBlue - 如果需要使用自定义图片作为公告头图,把
cardImageType改为uploadedImage,在cardImageDetails中传入图片的托管URL、宽高参数即可 - 公告类型消息目前仅在beta版本Graph中支持,v1.0版本暂未开放对应能力
- 权限除了委派权限
ChannelMessage.Send,使用应用权限ChannelMessage.Send.All也可正常调用
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

