Precondition Failed Error while trying to send Message to Teams-Chat | Graph API | C#

Th3TV 46 Reputation points
2022-10-24T08:07:58.467+00:00

Hello, everytime I try to send a Teams-Message I recieve an error.
I couldn`t figure out how to fix it and hope someone here has a clue for me.

Error Message:

Microsoft.Graph.ServiceException: "Code: PreconditionFailed
Message: Requested API is not supported in application-only context
Inner error:
AdditionalData:
date: 2022-10-20T12:07:44
request-id: 88e01bd9-370c-4739-b0bd-0244892475e2
client-request-id: 88e01bd9-370c-4739-b0bd-0244892475e2
ClientRequestId: 88e01bd9-370c-4739-b0bd-0244892475e2
"

Permissions:

Delegated Permissions:
Chat.ReadBasic, Chat.Read, Chat.ReadWrite, Chat.Create, ChatMember.Read, ChatMember.ReadWrite, ChatMessage.Send, Chat.ReadWrite, Channel.Delete.All, Group.ReadWrite.All, Directory.ReadWrite.All

Application Permissions:
ChatMember.Read.All, ChatMember.ReadWrite.All, Chat.ReadBasic.All, Chat.Read.All, Chat.Create, Chat.ReadWrite.All, Channel.Delete.Group, Channel.Delete.All, Group.ReadWrite.All, Directory.ReadWrite.All

Code I am using:

    /* ------------------------------------------------------------- */  
    /// <summary>  
    ///   
    /// </summary>  
    /// <param name="userId"></param>  
    /// <param name="chatID"></param>  
    /// <param name="messageText"></param>  
    /// <param name="scopes"></param>  
    /// <returns></returns>  
    public ChatMessage SendMessageToChat(string userId, string chatID, string messageText, string[] scopes = null)  
    {  
      return SendMessageToChatAsync(userId, chatID, messageText, scopes).GetAwaiter().GetResult();  
    }  
  
    /* ------------------------------------------------------------- */  
  
    private async Task<ChatMessage> SendMessageToChatAsync(string userId, string chatID, string messageText, string[] scopes = null)  
    {  
      GraphServiceClient graphClient = this.GetAuthenticatedGraphClient(scopes);  
  
      var chatMessage = new ChatMessage  
      {  
        Body = new ItemBody  
        {  
          Content = messageText  
        }  
      };  
  
      return await graphClient.Users[userId].Chats[chatID].Messages  
        .Request()  
        .AddAsync(chatMessage);  
  
    }  
  }  
}  
Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
12,005 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,914 questions
{count} votes

Accepted answer
  1. CarlZhao-MSFT 41,941 Reputation points
    2022-10-24T08:41:33.377+00:00

    Hi @Th3TV

    Sending messages in a chat doesn't support application-only contexts, the endpoint only supports delegated permissions, so the user must sign in.

    253494-image.png

    using Microsoft.Graph;  
    using Azure.Identity;  
      
    var scopes = new[] { "Chat.ReadWrite" };  
      
    var tenantId = "tenant id";  
      
    // Value from app registration  
    var clientId = "YOUR_CLIENT_ID";  
      
    // using Azure.Identity;  
    var options = new TokenCredentialOptions  
    {  
        AuthorityHost = AzureAuthorityHosts.AzurePublicCloud  
    };  
      
    var userName = "user name";  
    var password = "password";  
      
    // https://learn.microsoft.com/dotnet/api/azure.identity.usernamepasswordcredential  
    var userNamePasswordCredential = new UsernamePasswordCredential(  
        userName, password, tenantId, clientId, options);  
      
    var graphClient = new GraphServiceClient(userNamePasswordCredential, scopes);  
      
    var chatMessage = new ChatMessage  
    {  
     Body = new ItemBody  
     {  
     Content = "Hello world"  
     }  
    };  
      
    await graphClient.Chats["{chat-id}"].Messages  
     .Request()  
     .AddAsync(chatMessage);  
    

    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.