通过C#中的Microsoft Graph API在Microsoft团队常规频道中发布消息时出现禁止错误

时间:2020-09-21 14:31:31

标签: c# microsoft-graph-api microsoft-teams microsoft-graph-sdks microsoft-graph-teams

我正在尝试使用C#代码通过Microsoft Graph API在Microsoft团队的常规渠道中发布消息,但出现以下错误:

代码:禁止消息:禁止内部错误:AdditionalData: 日期:2020-09-21T12:32:20请求ID: 242cabdf-da4f-4633-8161-621b8a27d4a0客户端请求ID: 242cabdf-da4f-4633-8161-621b8a27d4a0 ClientRequestId: 242cabdf-da4f-4633-8161-621b8a27d4a0

代码如下:

    string userName = ConfigurationManager.AppSettings["UserName"];
    string password = ConfigurationManager.AppSettings["Password"];

    System.Security.SecureString passWordSecureString = new System.Security.SecureString();

    foreach (char c in password.ToCharArray()) passWordSecureString.AppendChar(c);

    var clientId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
    var tenantId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

    string[] scopes = { "ChannelMessage.Send", "Group.ReadWrite.All", "User.Read" };

    IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder
      .Create(clientId)
      .WithTenantId(tenantId)
      .Build();

    //creating the graph user context.
    UsernamePasswordProvider authProvider = new UsernamePasswordProvider(publicClientApplication, scopes);

    GraphServiceClient graphServiceClient = new GraphServiceClient(authProvider);

    var user = await graphServiceClient.Me.Request()
                .WithUsernamePassword(userName, passWordSecureString)
                .GetAsync();

    var chatMessage = new ChatMessage
    {
        Body = new ItemBody
        {
            Content = "Hello world From Console App"
        },

        From = new IdentitySet()
        {
            User = new Identity()
            {
                Id = "{user_Id}",
                DisplayName = "FirstName LastName",

                AdditionalData = new Dictionary<string, object>()
                {
                  { "userIdentityType", "aadUser" }

                },
            }
        },
    };

    try
    {
        await graphServiceClient.Teams["{public_team_id}"].Channels["{channel_id}"].Messages
                                .Request()
                                .AddAsync(chatMessage);
    }
    catch (Exception exc)
    {
        Console.WriteLine("Error : " + exc.Message);
    }

实际上,用户不是该特定公共团队的成员,因此我认为这就是为什么它会出现此禁止的错误。有人可以建议代码在用户不是该团队的成员/所有者的特定团队频道中发布消息吗?

1 个答案:

答案 0 :(得分:1)

如果您想向团队发布信息,则肯定需要某种访问权限,但是incoming webhook绝对是您最简单的解决方案。