Himanshu Kumar
Himanshu Kumar

Reputation: 99

Send message to microsoft teams channel using nodejs

I am able to acquire access token but not sure how to send messages because it requires a user and my app is a backend app(nodejs script). On graph explorer, it works.

The code snippet on graph explorer is:

const options = {
    authProvider, //I need this value
};

const client = Client.init(options);

const chatMessage = {body: {content: '@.@@@@.@'}};

await client.api('/teams/my-team-id/channels/my-channel-id/messages')
    .post(chatMessage);

How do I get authProvider in nodejs? I tried using MSALAuthenticationProviderOptions but there seems to be an issue (as mentioned in their github repo) by following these steps: https://www.npmjs.com/package/@microsoft/microsoft-graph-client.

Upvotes: 2

Views: 5609

Answers (1)

Michael Mainer
Michael Mainer

Reputation: 3465

You need to run this in the context of an application instead of a user. The Microsoft Graph JavaScript library now supports Azure TokenCredential for acquiring tokens.

const { Client } = require("@microsoft/microsoft-graph-client");
const { TokenCredentialAuthenticationProvider } = require("@microsoft/microsoft-graph-client/authProviders/azureTokenCredentials");
const { ClientSecretCredential } = require("@azure/identity");
const { clientId, clientSecret, scopes, tenantId } = require("./secrets"); // Manage your secret better than this please.

require("isomorphic-fetch");

async function runExample() {
    const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
    const authProvider = new TokenCredentialAuthenticationProvider(credential, { scopes: [scopes] });
    const client = Client.initWithMiddleware({
        debugLogging: true,
        authProvider,
    });

    const chatMessage = {body: {content: '@.@@@@.@'}};
    const res = await client.api('/teams/my-team-id/channels/my-channel-id/messages')
                            .post(chatMessage);
    console.log(res);
}

runExample().catch((err) => {
    console.log("Encountered an error:\n\n", err);
});

This sample came from:

https://github.com/microsoftgraph/msgraph-sdk-javascript/tree/dev/samples/tokenCredentialSamples/ClientCredentialFlow

Upvotes: 3

Related Questions