Search code examples
reactjsaxiosmicrosoft-graph-apimicrosoft-teamsmicrosoft-graph-teams

401 error while sending a message into a chat with microsoft teams Graph


I have a scenario for sending notification into a chat window from my microsoft teams custom tab. So, I am trying to call Microsoft Graph API for sending message into a specific chatId: Post https://graph.microsoft.com/beta/chats/${chatId}/messages I can get access_token successfully , but while calling post request for sending notification into a chatId , I get "401 UnAuthorized" error . what is wrong with my code?

var message = {
            "body": {
                   "content": "Hello World"
                }
               };
                    fetch(`https://graph.microsoft.com/beta/${context.userObjectId}/chats/${chatId}/messages`, {
                        method: "POST",
                        mode: "cors",
                        cache: "no-cache",
                        headers: {
                           
                            'Content-Type': "application/json;charset=utf-8",
                            'Authorization': `Bearer ${fetched_accessToken}`
                        },
                        body: JSON.stringify(message)
                    }).then((response) => {
                         alert(response.statusText);
                    }).catch((err) => {
                       alert(err);
                    });    
                } 

what is wrong with this code?


Solution

  • If you have a Teams app already, for your tab, and you want to ALSO communicate into the chat, you should look into creating a bot, and using Proactive messaging. See more at https://learn.microsoft.com/en-us/microsoftteams/platform/bots/how-to/conversations/send-proactive-messages?tabs=dotnet and https://learn.microsoft.com/en-us/graph/teams-proactive-messaging