共用方式為


使用 Bot Framework SDK 傳送媒體附件

適用於: SDK v4

使用者與 Bot 之間交換的訊息可以包含媒體附件,例如影像、視訊、音訊和檔案。 Bot Framework SDK 支援將豐富訊息傳送給使用者的工作。 若要判斷通道支援的豐富訊息類型(Facebook、Slack 等等),請參閱通道的檔以取得限制的相關信息。

注意

Bot Framework JavaScript、C# 和 Python SDK 將會繼續受到支援,不過,Java SDK 即將淘汰,最終長期支援將於 2023 年 11 月結束。

使用 Java SDK 建置的現有 Bot 將繼續運作。

針對新的 Bot 建置,請考慮使用 Power Virtual Agents ,並閱讀 選擇正確的聊天機器人解決方案

如需詳細資訊,請參閱 Bot 建置的未來。

必要條件

傳送附件

若要傳送用戶內容,例如影像或視訊,您可以將附件或附件清單新增至郵件。

如需可用卡片的範例,請參閱 設計用戶體驗

請參閱常見問題中的檔案使用通道傳輸的大小限制為何?

本節中顯示的所有原始程式碼都是以處理附件範例為基礎

對象的 Attachments 屬性 Activity 包含 物件的數位 Attachment ,這些物件代表連結至訊息的媒體附件和豐富卡片。 若要將媒體附件新增至訊息,請建立Attachmentreply活動的物件,並設定ContentTypeContentUrlName 屬性。

若要建立回復訊息,請定義文字,然後設定附件。 將附件指派給回復的每個附件類型都相同,不過會以不同的方式設定和定義各種附件,如下列代碼段所示。 下列程式代碼會設定內嵌附件的回復:

Bots/AttachmentsBot.cs

{
    reply = MessageFactory.Text("This is an inline attachment.");

接下來,我們會查看附件的類型。 首先是內嵌附件:

Bots/AttachmentsBot.cs

{
    var imagePath = Path.Combine(Environment.CurrentDirectory, @"Resources", "architecture-resize.png");
    var imageData = Convert.ToBase64String(File.ReadAllBytes(imagePath));

    return new Attachment
    {
        Name = @"Resources\architecture-resize.png",
        ContentType = "image/png",
        ContentUrl = $"data:image/png;base64,{imageData}",
    };
}

然後,上傳的附件:

Bots/AttachmentsBot.cs

{
    if (string.IsNullOrWhiteSpace(serviceUrl))
    {
        throw new ArgumentNullException(nameof(serviceUrl));
    }

    if (string.IsNullOrWhiteSpace(conversationId))
    {
        throw new ArgumentNullException(nameof(conversationId));
    }

    var imagePath = Path.Combine(Environment.CurrentDirectory, @"Resources", "architecture-resize.png");

    var connector = turnContext.TurnState.Get<IConnectorClient>() as ConnectorClient;
    var attachments = new Attachments(connector);
    var response = await attachments.Client.Conversations.UploadAttachmentAsync(
        conversationId,
        new AttachmentData
        {
            Name = @"Resources\architecture-resize.png",
            OriginalBase64 = File.ReadAllBytes(imagePath),
            Type = "image/png",
        },
        cancellationToken);

    var attachmentUri = attachments.GetAttachmentUri(response.Id);

    return new Attachment
    {
        Name = @"Resources\architecture-resize.png",
        ContentType = "image/png",
        ContentUrl = attachmentUri,
    };
}

最後,因特網附件:

Bots/AttachmentsBot.cs

    {
        // ContentUrl must be HTTPS.
        return new Attachment
        {
            Name = @"Resources\architecture-resize.png",
            ContentType = "image/png",
            ContentUrl = "https://docs.microsoft.com/en-us/bot-framework/media/how-it-works/architecture-resize.png",
        };
    }
}

如果附件是影像、音訊或視訊,連線 or 服務會以讓通道在交談中轉譯該附件的方式,將附件數據傳達給通道。 如果附件是檔案,檔案 URL 將會轉譯為交談內的超連結。

傳送主圖卡片

除了簡單的影像或視訊附件之外,您還可以附加 主圖卡片,這可讓您在一個對象中結合影像和按鈕,並將其傳送給使用者。 大部分文字欄位都支援 Markdown,但支援可能會因通道而異。

若要使用主圖卡片和按鈕撰寫訊息,您可以將物件附加 HeroCard 至訊息。

下列原始碼來自 處理附件 範例。

Bots/AttachmentsBot.cs


      private static async Task DisplayOptionsAsync(ITurnContext turnContext, CancellationToken cancellationToken)
      {
          // Create a HeroCard with options for the user to interact with the bot.
          var card = new HeroCard
          {
              Text = "You can upload an image or select one of the following choices",
              Buttons = new List<CardAction>
              {
                  // Note that some channels require different values to be used in order to get buttons to display text.
                  // In this code the emulator is accounted for with the 'title' parameter, but in other channels you may
                  // need to provide a value for other parameters like 'text' or 'displayText'.
                  new CardAction(ActionTypes.ImBack, title: "1. Inline Attachment", value: "1"),
                  new CardAction(ActionTypes.ImBack, title: "2. Internet Attachment", value: "2"),
                  new CardAction(ActionTypes.ImBack, title: "3. Uploaded Attachment", value: "3"),
              },
          };

          var reply = MessageFactory.Attachment(card.ToAttachment());
          await turnContext.SendActivityAsync(reply, cancellationToken);

處理豐富卡片內的事件

若要處理豐富卡片內的事件,請使用 卡片動作 物件來指定當使用者選取按鈕或點選卡片區段時應該會發生什麼事。 每個卡片動作都有類型和屬性。

若要正確運作,請將動作類型指派給主圖卡片上的每個可點選專案。 下表列出並描述可用的動作類型,以及關聯值屬性中應包含的內容。 卡片 messageBack 動作比其他卡片動作更具一般意義。 如需其他卡片動作類型的詳細資訊messageBack,請參閱活動架構卡片動作一節。

類型 描述
call 起始通話。 以下列格式撥打電話的目的地: tel:123123123123
downloadFile 下載檔案。 要下載之檔案的 URL。
imBack 將訊息傳送至 Bot,並在聊天中張貼可見的回應。 要傳送之訊息的文字。
messageBack 表示要透過聊天系統傳送的文字回應。 選擇性的程式設計值,要包含在產生的訊息中。
openUrl 在內建瀏覽器中開啟URL。 要開啟的 URL。
playAudio 播放音訊。 要播放之音訊的 URL。
playVideo 播放影片。 要播放的視訊 URL。
回傳 將訊息傳送至 Bot,且可能不會在聊天中張貼可見的回應。 要傳送之訊息的文字。
showImage 顯示影像。 要顯示的映像 URL。
signin 起始 OAuth 登入程式。 要起始之 OAuth 流程的 URL。

使用各種事件類型的主圖卡片

下列程式代碼示範使用各種豐富卡片事件的範例。

如需所有可用卡片的範例,請參閱 使用卡片 範例。

Cards.cs

public static HeroCard GetHeroCard()
{
    var heroCard = new HeroCard
    {
        Title = "BotFramework Hero Card",
        Subtitle = "Microsoft Bot Framework",
        Text = "Build and connect intelligent bots to interact with your users naturally wherever they are," +
               " from text/sms to Skype, Slack, Office 365 mail and other popular services.",
        Images = new List<CardImage> { new CardImage("https://sec.ch9.ms/ch9/7ff5/e07cfef0-aa3b-40bb-9baa-7c9ef8ff7ff5/buildreactionbotframework_960.jpg") },
        Buttons = new List<CardAction> { new CardAction(ActionTypes.OpenUrl, "Get Started", value: "https://docs.microsoft.com/bot-framework") },
    };

    return heroCard;
}

Cards.cs

public static SigninCard GetSigninCard()
{
    var signinCard = new SigninCard
    {
        Text = "BotFramework Sign-in Card",
        Buttons = new List<CardAction> { new CardAction(ActionTypes.Signin, "Sign-in", value: "https://login.microsoftonline.com/") },
    };

    return signinCard;
}

傳送調適型卡片

雖然您可以使用 訊息處理站 來建立包含附件的訊息(任何類型的), 調適型卡片 是一種特定的附件類型。 並非所有通道都支援調適型卡片,有些通道可能只部分支援調適型卡片。 例如,如果您在Facebook中傳送調適型卡片,則當文字和影像正常運作時,按鈕將無法運作。 訊息處理站是 Bot Framework SDK 協助程式類別,用來為您自動化建立步驟。

調適型卡片是一種開放卡片交換格式,可讓開發人員以通用且一致的方式交換 UI 內容。 不過,並非所有通道都支援調適型卡片。

調 適型卡片設計工具 提供豐富的互動式設計時間體驗來撰寫調適型卡片。

注意

您應該使用 Bot 將用來判斷這些通道是否支援調適型卡片的通道來測試此功能。

若要使用調適型卡片,請務必新增 AdaptiveCards NuGet 套件。

下列原始碼來自 使用卡片 範例。

Cards.cs

此範例會從檔案讀取調適型卡片 JSON,並將其新增為附件。

public static Attachment CreateAdaptiveCardAttachment()
{
    // combine path for cross platform support
    var paths = new[] { ".", "Resources", "adaptiveCard.json" };
    var adaptiveCardJson = File.ReadAllText(Path.Combine(paths));

    var adaptiveCardAttachment = new Attachment()
    {
        ContentType = "application/vnd.microsoft.card.adaptive",
        Content = JsonConvert.DeserializeObject(adaptiveCardJson),
    };

    return adaptiveCardAttachment;
}

郵件也可以在浮動切換版面配置中包含多個附件,將附件並排放置,並允許使用者捲動。

下列原始碼來自 使用卡片 範例。

Dialogs/MainDialog.cs

首先,建立回復,並將附件定義為清單。

// Cards are sent as Attachments in the Bot Framework.
// So we need to create a list of attachments for the reply activity.
var attachments = new List<Attachment>();

// Reply to the activity we received with an activity.
var reply = MessageFactory.Attachment(attachments);

然後新增附件,並將版面配置類型設定為 浮動切換。 在這裡,我們會一次新增一個卡片,但您可以隨意操作清單,以視您偏好新增卡片。

// Display a carousel of all the rich card types.
reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
reply.Attachments.Add(Cards.CreateAdaptiveCardAttachment());
reply.Attachments.Add(Cards.GetAnimationCard().ToAttachment());
reply.Attachments.Add(Cards.GetAudioCard().ToAttachment());
reply.Attachments.Add(Cards.GetHeroCard().ToAttachment());
reply.Attachments.Add(Cards.GetOAuthCard().ToAttachment());
reply.Attachments.Add(Cards.GetReceiptCard().ToAttachment());
reply.Attachments.Add(Cards.GetSigninCard().ToAttachment());
reply.Attachments.Add(Cards.GetThumbnailCard().ToAttachment());
reply.Attachments.Add(Cards.GetVideoCard().ToAttachment());

新增附件之後,您可以像任何其他一樣傳送回復。

// Send the card(s) to the user as an attachment to the activity
await stepContext.Context.SendActivityAsync(reply, cancellationToken);

處理調適型卡片輸入的程式碼範例

下列範例示範在 Bot 對話類別中使用調適型卡片輸入的其中一種方式。 它會驗證回應用戶端在文字欄位中收到的輸入,藉此擴充主圖卡片範例。 您必須先將文字輸入和按鈕功能新增至現有的調適型卡片,方法是將下列程式代碼新增至位於 resources 資料夾中adaptiveCard.json的最後括弧之前:

"actions": [
  {
    "type": "Action.ShowCard",
    "title": "Text",
    "card": {
      "type": "AdaptiveCard",
      "body": [
        {
          "type": "Input.Text",
          "id": "text",
          "isMultiline": true,
          "placeholder": "Enter your comment"
        }
      ],
      "actions": [
        {
          "type": "Action.Submit",
          "title": "OK"
        }
      ]
    }
  }
]

文字輸入欄位的識別碼會設定為 「text」。 當使用者選取 [ 確定] 時,調適型卡片產生的訊息會有一個 屬性,其具有名為 text 的屬性,其中包含使用者在卡片文字輸入字段中輸入的資訊。

驗證程式會使用 Newtonsoft.json 先將此轉換成 JObject,然後建立修剪后的文字字串進行比較。 因此,請新增:

using System;
using System.Linq;
using Newtonsoft.Json.Linq;

MainDialog.cs並安裝Newtonsoft.Json的最新穩定 NuGet 套件。 在驗證程式程式代碼中,我們已將邏輯流程新增至程式代碼批注。 這個 ChoiceValidator 方法會放在 MainDialog 宣告的封閉大括弧公開之後的 Using card 範例中:

private async Task ChoiceValidator(
    PromptValidatorContext promptContext,
    CancellationToken cancellationToken)
{
    // Retrieves Adaptive Card comment text as JObject.
    // looks for JObject field "text" and converts that input into a trimmed text string.
    var jobject = promptContext.Context.Activity.Value as JObject;
    var jtoken = jobject?["text"];
    var text = jtoken?.Value().Trim();

    // Logic: 1. if succeeded = true, just return promptContext
    //        2. if false, see if JObject contained Adaptive Card input.
    //               No = (bad input) return promptContext
    //               Yes = update Value field with JObject text string, return "true".
    if (!promptContext.Recognized.Succeeded && text != null)
    {
        var choice = promptContext.Options.Choices.FirstOrDefault(
        c => c.Value.Equals(text, StringComparison.InvariantCultureIgnoreCase));
        if (choice != null)
        {
            promptContext.Recognized.Value = new FoundChoice
            {
                Value = choice.Value,
            };
            return true;
        }
    }
    return promptContext.Recognized.Succeeded;
}

現在,宣告中的 MainDialog 上方變更:

// Define the main dialog and its related components.
AddDialog(new ChoicePrompt(nameof(ChoicePrompt)));

變更為:

// Define the main dialog and its related components.
AddDialog(new ChoicePrompt(nameof(ChoicePrompt), ChoiceValidator));

這將會叫用驗證程式,以在每次建立新的選擇提示時尋找調適型卡片輸入。

測試 Using Card Bot

  1. 在本機 執行 Using card 範例,並在 Bot Framework 模擬器中開啟 Bot。
  2. 遵循 Bot 中的提示來顯示卡片類型,例如調適型卡片。

下一步