Send a message to Microsoft Teams using Microsoft Graph in SPFx

A few days ago, I got a challenge that required me to send a message from a SharePoint page into a Microsoft Teams chat and that can be achieved using Microsoft Graph. I created a blank SPFx project and this post will go to the most important elements. You can also take a look at a sample webpart that I built using this process.

First, you need to add to the package-solution.json the required scopes for the Microsoft Graph can make the required calls. These are the scopes:

{
    "resource": "Microsoft Graph",
    "scope": "ChatMessage.Send"
},
{
    "resource": "Microsoft Graph",
    "scope": "Chat.Create"
},
{
    "resource": "Microsoft Graph",
    "scope": "Chat.ReadWrite"
},
{
    "resource": "Microsoft Graph",
    "scope": "User.Read"
},
{
    "resource": "Microsoft Graph",
    "scope": "User.ReadWrite.All"
},
{
    "resource": "Microsoft Graph",
    "scope": "Directory.Read.All"
},
{
    "resource": "Microsoft Graph",
    "scope": "Directory.ReadWrite.All"
}

For this webpart to be able to make the calls, you will need to approve this scopes on your SharePoint. Then we need to make 4 calls to Microsoft Graph:

  1. Get the user Id of the user that is sending the message. Get a user – Microsoft Graph v1.0 | Microsoft Docs
    • GET => https://graph.microsoft.com/v1.0/me
  2. Get the user Id of the user that will receive the message. Get a user – Microsoft Graph v1.0 | Microsoft Docs
    • GET => https://graph.microsoft.com/v1.0/users/ {id | userPrincipalName}
  3. Get the chat Id, behind the scenes, a connection between 2 users contains a chat, and we need to get their chat Id. Note that if a chat already exists it will add a message on top of the existing chat. Create chat – Microsoft Graph beta | Microsoft Docs
    • POST => https://graph.microsoft.com/beta/chats
  4. Send the message to the user. Send chatMessage in a channel or a chat – Microsoft Graph beta | Microsoft Docs
    • POST => https://graph.microsoft.com/beta/chats/{id}/messages

You can check all the required code on the following link.

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *