Bot Framework SDK を使用してメディア添付ファイルを送信する

適用対象: SDK v4

ユーザーとボットの間のメッセージ交換には、イメージ、ビデオ、オーディオ、ファイルなどのメディア添付ファイルを含めることができます。 Bot Framework SDK では、ユーザーにリッチ メッセージを送信するタスクがサポートされています。 チャネル (Facebook、Slack など) がサポートするリッチ メッセージの種類を確認するには、チャネルのドキュメントで制限事項に関する情報を参照してください。

前提条件

添付ファイルを送信する

イメージやビデオなどのユーザー コンテンツを送信するには、添付ファイルまたは添付ファイルのリストをメッセージに追加します。

使用可能なカードの例については、「 ユーザー エクスペリエンスの設計」 を参照してください。

FAQ の「 チャネルを使用して転送されるファイルのサイズ制限とは」 も参照してください。

このセクションに示すソース コードはすべて、 添付ファイルの処理 サンプルに基づいています。

Activity オブジェクトの Attachments プロパティには、メッセージに添付するメディア添付ファイルやリッチ カードを表す Attachment オブジェクトが格納されます。 メディア添付ファイルをメッセージに追加するには、reply アクティビティ用の Attachment オブジェクトを作成し、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",
        };
    }
}

添付ファイルがイメージ、オーディオ、またはビデオの場合、コネクタ サービスにより、チャネルでの会話内の添付ファイルがレンダリングできる方法で、添付ファイルのデータがチャネルに通信されます。 添付ファイルがファイルである場合は、ファイルの URL が会話内にハイパーリンクとしてレンダリングされます。

ヒーロー カードを送信する

シンプルなイメージ添付ファイルまたはビデオ添付ファイルだけでなく、ヒーロー カードを添付することもできます。これにより、1 つのオブジェクトに含まれるイメージとボタンを結合してユーザーに送信することができます。 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);

リッチ カード内のイベントを処理する

リッチ カード内のイベントを処理するには、 カード アクション オブジェクトを使用して、ユーザーがボタンを選択するか、カードのセクションをタップしたときの動作を指定します。 各カード アクションには、 のプロパティがあります。

正しく機能するには、ヒーロー カード上のクリック可能な各アイテムにアクションの種類を割り当てます。 この表では、使用できるアクションの種類と、関連付けられている value プロパティに含める内容を一覧にまとめ、説明しています。 カード アクションは messageBack 、他のカード アクションよりも一般化された意味を持ちます。 その他の カード アクション の種類の詳細については、 アクティビティ スキーマ のカード アクションセクションを messageBack 参照してください。

Type 説明
call 電話を発信します。 電話の発信先 (形式は tel:123123123123)。
downloadFile ファイルをダウンロードします。 ダウンロードするファイルの URL。
imBack ボットにメッセージを送信し、目に見える応答をチャットに投稿します。 送信するメッセージのテキスト。
messageBack チャット システム経由で送信されるテキスト応答を表します。 生成されたメッセージに含めるオプションのプログラム値。
openUrl 組み込みのブラウザーで URL を開きます。 開く URL。
playAudio オーディオを再生します。 再生するオーディオの URL。
playVideo ビデオを視聴します。 再生するビデオの URL。
postBack ボットにメッセージを送信します。目に見える応答はチャットに投稿できません。 送信するメッセージのテキスト。
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;
}

アダプティブ カードを送信する

メッセージ ファクトリを使用して (任意の種類の) 添付ファイルを含むメッセージを作成できますが、アダプティブ カードは特定の種類の添付ファイルの 1 つです。 一部のチャネルではアダプティブ カードがサポートされておらず、一部しかサポートされていないチャネルもあります。 たとえば、Facebook でアダプティブ カードを送信する場合、テキストと画像は適切に機能しますが、ボタンは機能しません。 メッセージ ファクトリは、作成手順を自動化するために使用される Bot Framework SDK ヘルパー クラスです。

アダプティブ カードは、カード交換のオープン フォーマットであり、開発者は一貫性のある共通した方法で UI コンテンツを交換できます。 ただし、すべてのチャネルでアダプティブ カードがサポートされているわけではありません。

アダプティブ カード デザイナーは、アダプティブ カードを作成するための豊富な対話型のデザイン時エクスペリエンスを提供します。

注意

ご自分のボットで使用されるチャネルにおいてこの機能をテストして、それらのチャネルでアダプティブ カードがサポートされているかどうかを判断する必要があります。

アダプティブ カードを使用するには、必ず 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);

次に、添付ファイルを追加し、レイアウトの種類をカルーセルに設定 します。 ここでは 1 つずつ追加しますが、必要に応じて、リストを使ってカードを追加することもできます。

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

アダプティブ カード入力を処理するためのコード サンプル

次の例は、ボット ダイアログ クラス内でアダプティブ カード入力を使用する 1 つの方法を示しています。 応答するクライアントからテキスト フィールドで受信した入力を検証することで、ヒーロー カードのサンプルを拡張します。 まず、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"
        }
      ]
    }
  }
]

テキスト入力フィールドの ID が に設定されていることに注意してください "text"。 ユーザーが [OK] を選択すると、アダプティブ カードによって生成されるメッセージには ユーザーがカードのテキスト入力フィールドに入力した情報を含むプロパティを "text" 持つ値プロパティが含まれます。

この検証コントロールでは 、Newtonsoft.json を使用して最初にこれを a JObjectに変換し、次に比較のためにトリミングされたテキスト文字列を作成します。 そのため、次のコードを

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

を MainDialog.cs にインストールし、Newtonsoft.Json の最新の安定した NuGet パッケージをインストールします。 検証コントロールのコードでは、コード コメントにロジック フローを追加しました。 この ChoiceValidator メソッドは、MainDialog の宣言用の閉じかっこパブリックの直後に 、Using カード のサンプルに配置されます。

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

これにより、バリデーターが呼び出され、新しい選択プロンプトが作成されるたびにアダプティブ カード入力が検索されます。

コードをテストするには、アダプティブ カードが表示されたら、[ テキスト ] ボタンを選択し、 ヒーロー カード などの有効な選択項目を入力し、[ OK] ボタンを選択します。

Test Adaptive Card

  1. 最初の入力は、新しいダイアログを開始するために使用されます。
  2. もう一度 [OK] ボタンを選択すると、この入力を使用して新しいカードが選択されます。

次のステップ