Microsoft Teams Operations In SPFx Webpart Using Graph API

Introduction

In this article, we will learn how to integrate with MS teams in SPFx using Graph API. The below three concepts will be explored here.
  • Getting Current Users Teams
  • Getting Channels of a particular team
  • Sending Messages to a particular channel
We will use the Teams Graph API endpoint to do these operations. Microsoft has provided many endpoints to access MS Teams data and do operations using Graph API endpoint. We can explore these in detail here.
Pre-requisites
  • SPFx web part created with React framework(you can also use No javascript framework or any other framework). For this sample, we are using a React-based webpart.
  • You have provided permission in SharePoint admin for accessing Graph API on behalf of your solution. So here, we are doing this before deployment as proactive steps, but you can also do this after deployment. You can refer to steps here about how to do this post-deployment. Basically you have to use API Access Page of SharePoint admin and add below permission for our use case.
  • User.Read.All
  • User.ReadWrite.All
  • Group.Read.All
  • Group.ReadWrite.All
Here are the details of the solution which we are using here in our article:
  • Solution Name – react-teams-message
  • Web part Name – MyTeams
Step – Passing WebPart context to React components
We need a Sharepoint site context to work with, hence we will pass it from our web part file to React components.
Open src\webparts\controls\components\IMyTeamsProps.ts
Modify the code to what’s shown below:
import { WebPartContext } from "@microsoft/sp-webpart-base";  
  
export interface IMyTeamsProps {  
  context: WebPartContext;  
}

 

Open src\webparts\controls\MyTeamsWebPart.ts
Modify the render method to pass the context.
public render(): void {  
   const element: React.ReactElement<IMyTeamsProps> = React.createElement(  
     MyTeams,  
     {  
       context: this.context  
     }  
   );  
  
   ReactDom.render(element, this.domElement);  
 }

 

Please note we have just added line ‘context:this.context’.
Step – Create a Service Provider class and add the required methods.
Create a file at src\shared\services\ServiceProvider.ts
Add the below code:
import { WebPartContext } from "@microsoft/sp-webpart-base";  
import { MSGraphClient } from "@microsoft/sp-http";  
  
export class ServiceProvider {  
  public _graphClient: MSGraphClient;  
  private spcontext: WebPartContext;  
  public constructor(spcontext: WebPartContext) {  
    this.spcontext = spcontext;  
  }  
  
  public getmyTeams = async (): Promise<[]> => {  
    this._graphClient = await this.spcontext.msGraphClientFactory.getClient(); //TODO  
  
    let myTeams: [] = [];  
    try {  
      const teamsResponse = await this._graphClient.api('me/joinedTeams').version('v1.0').get();  
      myTeams = teamsResponse.value as [];  
    } catch (error) {  
      console.log('Unable to get teams', error);  
    }  
    return myTeams;  
  }  
  
  public getChannel = async (teamID): Promise<[]> => {  
    this._graphClient = await this.spcontext.msGraphClientFactory.getClient(); //TODO  
  
    let myTeams: [] = [];  
    try {  
      const teamsResponse = await this._graphClient.api('teams/' + teamID + '/channels').version('v1.0').get();  
      myTeams = teamsResponse.value as [];  
    } catch (error) {  
      console.log('unable to get channels', error);  
    }  
    return myTeams;  
  }  
  
  public sendMessage = async (teamId, channelId, message): Promise<[]> => {  
    this._graphClient = await this.spcontext.msGraphClientFactory.getClient();  
    try {  
      // https://graph.microsoft.com/beta/teams/{team-id}/channels/{channel-id}/messages  
      var content = {  
        "body": {  
          "content": message  
        }  
      };  
      const messageResponse = await this._graphClient.api('/teams/' + teamId + '/channels/' + channelId + "/messages/")  
        .version("beta").post(content);  
      return messageResponse;  
  
    } catch (error) {  
      console.log('Unable to send message', error);  
      return null;  
    }  
  
  }  
}

 

You can see here that we have created 3 methods:
  • getmyTeams – To get teams of current logged in user
  • getChannel – To get channels of a particular team
  • sendMessage – To send messages to the team and a particular channel within that team.
Please note that the last endpoint to sendMessage is still in beta version and not advisable for production use until it is generally available.
Step – Modify React component
Below is what we will do on a high level:
  • Display a single button ‘Get My Teams’ on page load(component/webpart load)
  • On a click of the Get My Teams button, it calls the getmyTeams method of service provider class and sets it to the state object myteams
  • The render method will take care of looping through this myteams object creating radio buttons for every item in teams.
  • On a click of any radio button, the Get Channels button will be displayed.
  • On a click of the Get Channels button, we will call getChannel method of service provider class and set it to state object teamChannels
  • The render method will take care of looping through this teamChannels object and creating a radio button for every item in object
  • On the click of any radio button of displayed channels, it will show an input text box and Send message button.
  • On a click on Send message button, we are using selected team and channel id and calling sendMessage of service provider to post message to particualar channel.
  • On success, it displays an alert box success message.
Open src\webparts\controls\components\MyTeams.tsx
Modify the code to what’s shown below:
import * as React from 'react';  
import styles from './MyTeams.module.scss';  
import { IMyTeamsProps } from './IMyTeamsProps';  
import { escape } from '@microsoft/sp-lodash-subset';  
import { ServiceProvider } from '../../../shared/services/ServiceProvider';  
  
export interface IMyTeamsState {  
  
  myteams: any[];  
  selectedTeam: any;  
  teamChannels: any;  
  selectedChannel: any;  
}  
  
export default class MyTeams extends React.Component<IMyTeamsProps, IMyTeamsState> {  
  private serviceProvider;  
  private messageTextRef;  
  
  public constructor(props: IMyTeamsProps, state: IMyTeamsState) {  
    super(props);  
    this.serviceProvider = new ServiceProvider(this.props.context);  
    this.state = {  
      myteams: [],  
      selectedTeam: null,  
      selectedChannel: null,  
      teamChannels: []  
    };  
  }  
  
  private GetmyTeams() {  
  
    this.serviceProvider.  
      getmyTeams()  
      .then(  
        (result: any[]): void => {  
          console.log(result);  
          this.setState({ myteams: result });  
        }  
      )  
      .catch(error => {  
        console.log(error);  
      });  
  }  
  
  public render(): React.ReactElement<IMyTeamsProps> {  
    return (  
      <React.Fragment>  
         <div className={ styles.myTeams }>  
        <h1>Teams Operations Demo using Graph API</h1>  
          
        <div>  
          <button className={styles.buttons} onClick={() => this.GetmyTeams()}>Get My Teams</button>  
        </div>  
        { this.state.myteams.length>0 &&  
        <React.Fragment>  
         <h3>Below is list of your teams</h3>  
         <h4>Select any team and click on Get Channels</h4>  
        </React.Fragment>  
        }  
        {this.state.myteams.map(  
          (team: any, index: number) => (  
            <React.Fragment>  
              <input className={styles.radio} onClick={() => this.setState({ selectedTeam: team })} type="radio" id={team.id} name="myteams" value={team.id} />  
              <label >{team.displayName}</label><br />  
            </React.Fragment>  
          )  
        )  
        }  
  
        {this.state.selectedTeam &&  
        <React.Fragment>  
            <br></br>  
            <button  className={styles.buttons} onClick={() => this.getChannels()}>Get Channels</button>  
          </React.Fragment>  
        }  
        { this.state.teamChannels.length>0 &&  
        <React.Fragment>  
        <h3>Below is list of your channels for selected team : {this.state.selectedTeam.displayName}</h3>  
        <h4>Select any channel, enter message and click 'Send Message' to Post Message on MS teams</h4>  
        </React.Fragment>  
        }  
  
        {this.state.teamChannels.map(  
          (channel: any, index: number) => (  
            <React.Fragment>  
              <input className={styles.radio} onClick={() => this.setState({ selectedChannel: channel })} type="radio" id={channel.id} name="teamchannels" value={channel.id} />  
              <label >{channel.displayName}</label><br />  
            </React.Fragment>  
          )  
        )  
        }  
  
        {this.state.selectedChannel &&  
          <React.Fragment>  
          <br></br>  
          <div>  
            <input className={styles.textbox}  ref={(elm) => { this.messageTextRef = elm; }} type="text" id="message" name="message" />  
            <br></br>  
            <br></br>  
            <button  className={styles.buttons} onClick={() => this.sendMesssage()}>Send Message</button>  
              
          </div>  
          </React.Fragment>  
        }  
        </div>  
      </React.Fragment>  
    );  
  }  
  
  private getChannels() {  
  
    this.serviceProvider.  
      getChannel(this.state.selectedTeam.id)  
      .then(  
        (result: any[]): void => {  
          console.log(result);  
          this.setState({ teamChannels: result });  
        }  
      )  
      .catch(error => {  
        console.log(error);  
      });  
  }  
  
  private sendMesssage() {   
    this.serviceProvider.  
      sendMessage(this.state.selectedTeam.id, this.state.selectedChannel.id, this.messageTextRef.value)  
      .then(  
        (result: any[]): void => {  
          alert("message posted sucessfully");  
        }  
      )  
      .catch(error => {  
        console.log(error);  
      });  
  }  
}

 

Step – Add styling
Open src\webparts\controls\components\MyTeams.module.scss
Modify the code to below, we have removed any classes that are not used.
@import '~office-ui-fabric-react/dist/sass/References.scss';  
  
.myTeams {  
  label{  
    font-size: 16px;  
    line-height: 1.5;  
  }  
  .radio{  
    width: 16px;  
    height: 16px;  
  }  
  
  .textbox{  
    height: 30px;  
    width: 300px;    
  }  
   
  h4{  
    font-style: italic;  
    font-weight: normal;  
  }  
  
  .buttons{  
    background-color: $ms-color-themePrimary;  
    width: 200px;  
    height: 40px;  
    color: white;  
    font-size: 18px;  
  
   }  
}

 

Now we are done with our code changes. Let’s see this web part in the action. Run gulp serve.
gulp serve

 

Open SharePoint workbench
https://covid19.com/sites/stayhome/_layouts/15/workbench.aspx

 

Add your target webpart, and on On-Page load, we will see the below output.
Click on Get My Teams, we will see below output:

Select any team, I selected the MyFirstTeam:

Click on Get Channels, we will see below output. In my case, I have 2 channels one general channel(which is created by default for every team) and DemoChannel1 which I have created manually.

Click on DemoChannel1, type in some message and click on Send Message.

If everything goes well, we will see the below message.

Now, go to teams. Below is what we see in my tenant. You can see team names and channel matches as it was displayed in the web part and as in teams.

Conclusion

This example describes how to call Teams Graph API endpoints to integrate your SPFx web part with MS Teams. Attached is the source code for this sample. You can download and run NPM install to try this out. Please remember to allow permissions in SharePoint Admin API Access.
I hope this helps, happy coding!!!!
Note – This article was originally published at this link.
(Visited 5 times, 1 visits today)