如何使用botFramework NodeJs通过outlook发送自适应卡片

问题描述 投票:0回答:1

我构建了一个机器人,可以通过团队发送自适应卡片。我能够成功地与该卡进行交互。不过,我想扩展该功能并使其能够通过 Outlook 发送卡片。我已按照此步骤 并将频道添加到 azure 机器人服务。但是,我不知道如何开始发送卡,因为文档中没有解释。这是我如何将卡片发送给团队的片段。

// HTTP trigger to send notification. You need to add authentication / authorization for this API. Refer https://aka.ms/teamsfx-notification for more details.
server.post(
  "/api/notificationByTeams",
  restify.plugins.queryParser(),
  restify.plugins.bodyParser(), // Add more parsers if needed
  async (req, res) => {
    let continuationToken = undefined;
    do {
      const pagedData = await notificationApp.notification.getPagedInstallations();
      let adaptiveCardData = req.body;
      const { MerlinUser, MerlinPassword, Receivers, TemplateType } = adaptiveCardData;

      //Here we get all the users receiving the notification
      const usersReceivingCardInformation = await getNotificationMembersInfoByEmail(Receivers)
      const installations = pagedData.data;
      continuationToken = pagedData.continuationToken;

      //Here we encrypt the data of the admin user
      adaptiveCardData.MerlinUser = encryptData(MerlinUser);
      adaptiveCardData.MerlinPassword = encryptData(MerlinPassword);
      adaptiveCardData.Originator = process.env.Originator;
      console.info("Llegamos a setear el originator ", adaptiveCardData.Originator);
      adaptiveCardData.UserIds = usersReceivingCardInformation.map(x => x.id);

      for (const target of installations) {
       
        if (target.type === "Person" && usersReceivingCardInformation.some(x => x.id === target.conversationReference.user.id)) {
          let selectedTemplate = selectTemplate(TemplateType);
          await target.sendAdaptiveCard(
            AdaptiveCards.declare(selectedTemplate).render({
              ...adaptiveCardData
            })
          );
        }
      }
    } while (continuationToken);

    res.json({});
  }
);

我将 Outlook 频道添加到我的 Azure 机器人服务中。

node.js botframework azure-bot-service
1个回答
0
投票

我想扩展该功能并使其能够通过 Outlook 发送卡片。

通过使用 Microsoft Graph API,我们可以通过 Outlook 通过电子邮件发送自适应卡片。

在这里,我已将 Outlook 频道添加到我的 azure 机器人服务中。

enter image description here

  • 创建应用程序注册并导航到 API 权限

enter image description here

  • 单击 Microsoft graph 并选择应用程序权限,然后搜索
    Mail.send
    以授予您的应用程序权限。

enter image description here

  • 为自适应卡创建一个 JSON 结构,如下所示。
{
    "type": "AdaptiveCard",
    "body": [
        {
            "type": "TextBlock",
            "text": "Hello!",
            "size": "large"
        },
        {
            "type": "TextBlock",
            "text": "This is an adaptive card sent via email."
        },
        {
            "type": "Image",
            "url": "https://adaptivecards.io/content/cats/1.png"
        }
    ],
    "actions": [
        {
            "type": "Action.OpenUrl",
            "title": "Learn More",
            "url": "https://adaptivecards.io"
        }
    ],
    "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
    "version": "1.2"
}

enter image description here

  • 我已将此 MS 文档提交给进行身份验证,并使用 Microsoft Graph API 发送附有自适应卡的电子邮件。
const msal = require('@azure/msal-node');
const { Client } = require('@microsoft/microsoft-graph-client');
require('isomorphic-fetch');

// MSAL configuration
const msalConfig = {
    auth: {
        clientId: 'YOUR_CLIENT_ID',
        authority: 'https://login.microsoftonline.com/YOUR_TENANT_ID',
        clientSecret: 'YOUR_CLIENT_SECRET'
    }
};

const cca = new msal.ConfidentialClientApplication(msalConfig);

async function getToken() {
    const clientCredentialRequest = {
        scopes: ['https://graph.microsoft.com/.default'],
    };
    const response = await cca.acquireTokenByClientCredential(clientCredentialRequest);
    return response.accessToken;
}

async function sendAdaptiveCardEmail() {
    const accessToken = await getToken();

    const client = Client.init({
        authProvider: (done) => {
            done(null, accessToken);
        }
    });

    const adaptiveCardJson = require('./adaptiveCard.json');

    const email = {
        message: {
            subject: 'Adaptive Card Email',
            body: {
                contentType: 'HTML',
                content: 'Please see the adaptive card below.'
            },
            toRecipients: [
                {
                    emailAddress: {
                        address: '[email protected]'
                    }
                }
            ],
            attachments: [
                {
                    '@odata.type': '#microsoft.graph.fileAttachment',
                    name: 'adaptiveCard.json',
                    contentType: 'application/json',
                    contentBytes: Buffer.from(JSON.stringify(adaptiveCardJson)).toString('base64')
                }
            ]
        }
    };

    await client.api('/me/sendMail')
        .post({ message: email.message, saveToSentItems: 'true' });

    console.log('Email sent successfully.');
}

sendAdaptiveCardEmail().catch(console.error);

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.