【问题标题】:Send message to microsoft teams channel using nodejs使用 nodejs 向微软团队频道发送消息
【发布时间】:2021-06-10 06:42:19
【问题描述】:

我能够获取访问令牌,但不确定如何发送消息,因为它需要一个用户并且我的应用程序是一个后端应用程序(nodejs 脚本)。在图形浏览器上,它可以工作。

graph explorer 上的代码 sn-p 是:

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);

如何在 nodejs 中获取 authProvider? 我尝试使用 MSALAuthenticationProviderOptions,但按照以下步骤似乎存在问题(如他们的 github 存储库中所述):https://www.npmjs.com/package/@microsoft/microsoft-graph-client

【问题讨论】:

    标签: javascript node.js oauth-2.0 microsoft-graph-api


    【解决方案1】:

    您需要在应用程序而不是用户的上下文中运行它。 Microsoft Graph JavaScript 库现在支持用于获取令牌的 Azure TokenCredential。

    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);
    });
    

    此样本来自:

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

    【讨论】:

    • 感谢您的回复,迈克尔。我收到错误Cannot find module '@microsoft/microsoft-graph-client/authProviders/azureTokenCredentials'。当我查看节点模块中的@microsoft/microsoft-graph-client 时,没有像 authProviders 这样的目录。
    猜你喜欢
    • 2020-03-23
    • 2021-04-18
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-07
    • 2020-08-11
    相关资源
    最近更新 更多