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

使用Direct Line API在Teams中添加代理用户至终端用户机器人遇404错误求助

问题分析与解决方案

核心问题

你当前使用Direct Line API尝试添加代理到Teams机器人对话的思路有误——Direct Line API仅用于自定义客户端与机器人的交互,无法操作Teams原生的聊天会话。Teams中的聊天会话由Microsoft Teams平台管理,必须通过Microsoft Graph API来修改成员。

正确实现步骤

1. 获取正确的Teams聊天ID

当终端用户发送“咨询专家”指令时,在OnMessageActivityAsync方法中,从传入的turnContext里获取终端用户与机器人的1对1聊天ID:

string teamsChatId = turnContext.Activity.Conversation.Id;

注意:这个ID是Teams平台生成的聊天会话ID,不是机器人的ID(botId)。

2. 配置Azure AD应用权限

要调用Graph API修改Teams聊天成员,需要注册一个Azure AD应用并授予相应权限:

  • 在Azure门户的“Azure Active Directory”→“应用注册”中创建新应用
  • 为应用添加应用权限:ChatMember.ReadWrite.All(或Chat.ReadWrite,根据场景选择)
  • 授予管理员同意
  • 记录应用的客户端ID、租户ID和客户端密钥,用于获取Graph API的访问令牌

3. 修改代码使用Graph API

替换原有的Direct Line调用,改为调用Graph API的添加聊天成员接口。以下是修正后的AgentHandler类示例:

using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

public class AgentHandler
{
    private readonly string _tenantId;
    private readonly string _clientId;
    private readonly string _clientSecret;

    public AgentHandler(string tenantId, string clientId, string clientSecret)
    {
        _tenantId = tenantId;
        _clientId = clientId;
        _clientSecret = clientSecret;
    }

    // 获取Graph API访问令牌
    private async Task<string> GetGraphAccessTokenAsync()
    {
        using var client = new HttpClient();
        var requestBody = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("grant_type", "client_credentials"),
            new KeyValuePair<string, string>("client_id", _clientId),
            new KeyValuePair<string, string>("client_secret", _clientSecret),
            new KeyValuePair<string, string>("scope", "https://graph.microsoft.com/.default")
        });

        var response = await client.PostAsync($"https://login.microsoftonline.com/{_tenantId}/oauth2/v2.0/token", requestBody);
        response.EnsureSuccessStatusCode();
        var tokenData = JsonConvert.DeserializeObject<dynamic>(await response.Content.ReadAsStringAsync());
        return tokenData.access_token;
    }

    // 添加代理到Teams聊天
    public async Task AddUserAsAgentAsync(string teamsChatId, string agentUserId)
    {
        var accessToken = await GetGraphAccessTokenAsync();
        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

        // 构造Graph API请求体
        var participantData = new
        {
            "@odata.type" = "#microsoft.graph.aadUserConversationMember",
            user@odata.bind = $"https://graph.microsoft.com/v1.0/users('{agentUserId}')",
            roles = new[] { "member" }
        };

        var content = new StringContent(JsonConvert.SerializeObject(participantData), Encoding.UTF8, "application/json");
        var response = await client.PostAsync($"https://graph.microsoft.com/v1.0/chats/{teamsChatId}/members", content);
        
        // 可选:处理响应,检查是否成功
        if (!response.IsSuccessStatusCode)
        {
            var errorContent = await response.Content.ReadAsStringAsync();
            // 这里可以添加错误日志或处理逻辑
            throw new HttpRequestException($"添加代理失败:{response.StatusCode} - {errorContent}");
        }
    }
}

4. 在机器人中调用修正后的方法

在OnMessageActivityAsync中调用时,传入正确的Teams聊天ID和代理的Azure AD用户ID:

// 初始化AgentHandler(使用你的Azure AD应用信息)
var agentHandler = new AgentHandler("你的租户ID", "你的客户端ID", "你的客户端密钥");
// 获取终端用户与机器人的聊天ID
string chatId = turnContext.Activity.Conversation.Id;
// 代理的Azure AD用户ID
string agentUserId = "代理的用户ID";
// 调用添加方法
await agentHandler.AddUserAsAgentAsync(chatId, agentUserId);

原404错误原因

你之前使用的Direct Line API端点仅适用于Direct Line创建的会话,而终端用户与Teams机器人的会话是由Teams平台管理的,并非Direct Line会话,因此该端点不存在,返回404错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 21:35:26