You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何向拉取请求作者发送Azure DevOps流水线Teams私信通知?

实现Azure DevOps拉取请求流水线结束后发送Teams私信通知给作者

核心思路

通过调用Microsoft Graph API创建一对一聊天并发送消息,结合Azure DevOps内置变量获取PR作者的Azure AD ID(与Teams用户ID一致),实现流水线结束后直接私信通知作者,避免团队频道被刷屏。

步骤1:配置Azure AD应用权限

  • 在Azure AD中注册新应用,添加应用权限:
    • User.Read.All(用于验证用户身份)
    • ChatMessage.Send(用于发送私信)
  • 为这些权限授予管理员同意,确保服务主体能正常调用Graph API。

步骤2:在Azure DevOps中存储敏感信息

  • 创建变量组,存入以下敏感值(设置为保密状态):
    • TenantId:你的Azure AD租户ID
    • ClientId:注册的Azure AD应用客户端ID
    • ClientSecret:Azure AD应用的客户端密钥
  • 将变量组关联到目标流水线,确保任务能访问这些变量。

步骤3:添加PowerShell任务到流水线

在流水线的最后阶段(设置为无论成功/失败都执行)添加PowerShell任务,使用以下脚本:

# 获取Graph API访问令牌
$tenantId = "$(TenantId)"
$clientId = "$(ClientId)"
$clientSecret = "$(ClientSecret)"
$resource = "https://graph.microsoft.com"

$tokenBody = @{
    Grant_Type    = "client_credentials"
    Scope         = "$resource/.default"
    Client_Id     = $clientId
    Client_Secret = $clientSecret
}

$tokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" -Method POST -Body $tokenBody
$accessToken = $tokenResponse.access_token

# 组装通知内容
$userId = "$(Build.RequestedForId)" # PR作者的Azure AD ID
$messageContent = @"
**PR流水线执行结果通知**
- 状态: *$(Build.Status)*
- PR标题: $(System.PullRequest.Title)
- PR链接: $(System.PullRequest.SourceRepositoryURI)/pullrequest/$(System.PullRequest.PullRequestId)
- 流水线详情: $(Build.Repository.Uri)/_build/results?buildId=$(Build.BuildId)
"@

# 创建一对一聊天(若已存在则返回现有聊天)
$chatRequestBody = @{
    chatType = "oneOnOne"
    members = @(
        @{
            "@odata.type" = "#microsoft.graph.aadUserConversationMember"
            roles = @("owner")
            user = @{ id = $userId }
        }
    )
} | ConvertTo-Json -Depth 3

$chatResponse = Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/chats" -Method POST -Headers @{ Authorization = "Bearer $accessToken" } -Body $chatRequestBody -ContentType "application/json"
$chatId = $chatResponse.id

# 发送私信
$messageRequestBody = @{
    body = @{ content = $messageContent }
} | ConvertTo-Json -Depth 3

Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/chats/$chatId/messages" -Method POST -Headers @{ Authorization = "Bearer $accessToken" } -Body $messageRequestBody -ContentType "application/json"

关键注意事项

  • 确保流水线由拉取请求触发,否则$(Build.RequestedForId)等PR相关变量会为空。
  • 若PR作者未开通Teams账号,API调用会失败,可在脚本中添加异常捕获逻辑。
  • 所有敏感变量需设置为保密,避免信息泄露。

内容的提问来源于stack exchange,提问作者kopolomo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 17:18:29