Sending Bot Reply Message With Attachment Using Bot Framework

Introduction

The Bot Framework enables you to build bots that support different types of interactions with users. You can design conversations in your bot to be freeform. Your bot can also have more guided interactions where it provides the user choices or actions. The conversation can use simple text strings, the message with an attachment like the image, File (pdf, word, excel, ppt), mp3, Video or more complex rich cards.
Bot Framework

In this article, I will help you to send a reply message with the different types of media file attachment.

Prerequisites

I have explained about Bot framework Installation, deployment, and implementation in the below articles.

  1. Getting Started with Chatbot Using Azure Bot Service
  2. Getting Started with Bots Using Visual Studio 2017
  3. Deploying A Bot to Azure Using Visual Studio 2017
  4. How to Create ChatBot In Xamarin
  5. Getting Started with Dialog Using Microsoft Bot Framework
  6. Getting Started with Prompt Dialog Using Microsoft Bot Framework
  7. Getting Started With Conversational Forms And FormFlow Using Microsoft Bot Framework
  8. Getting Started With Customizing A FormFlow Using Microsoft Bot Framework

Create a new Bot application

Let's create a new bot application using Visual Studio 2017. Open Visual Studio > Select File > Create New Project (Ctrl + Shift +N) > select Bot application.

Bot Framework

The Bot application template was created with all the components and all required NuGet references installed in the Solution.

Bot Framework

Create A New AttachmentDialog Class

Step 1

You can create a new AttachmentDialog class for showing the attachment dialog. Right-click Project > select Add New Item > create a class that is marked with the [Serializable] attribute (so the dialog can be serialized to state) and implement the IDialog interface.

  1. using System;  
  2. using System.Threading.Tasks;  
  3. using Microsoft.Bot.Builder.Dialogs;  
  4. using Microsoft.Bot.Connector;  
  5. using System.IO;  
  6. using System.Web;  
  7. using System.Collections.Generic;  
  8.   
  9. namespace BotAttachment.Dialogs  
  10. {  
  11.     [Serializable]  
  12.     public class AttachmentDialog : IDialog<object>  
  13.     {    

Step 2

IDialog interface has only StartAsync() method. StartAsync() is called when the dialog becomes active. The method passes the IDialogContext object, used to manage the conversation.

  1. public async Task StartAsync(IDialogContext context)  
  2.         {  
  3.             context.Wait(this.MessageReceivedAsync);  
  4.         }  

Step 3

Create a MessageReceivedAsync method and write the following code for the welcome message and show the list of demo options dialog.

  1. private readonly IDictionary<string, string> options = new Dictionary<string, string>  
  2. {  
  3.     { "1""1. Attach Local-Image " },  
  4.     { "2""2. Attach Internet Image" },  
  5.     {"3" , "3. File Attachment" },  
  6.     {"4" , "4. Get local PDF" },  
  7.     {"5" , "5. Video Attachment" },  
  8.     {"6" , "6. Youtube video Attachment" },  
  9.     {"7" , "7. MP3 Attachment" },  
  10.   
  11. };  
  12. public async virtual Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result)  
  13. {  
  14.     var message = await result;  
  15.     var welcomeMessage = context.MakeMessage();  
  16.     welcomeMessage.Text = "Welcome to bot Attachment Demo";  
  17.   
  18.     await context.PostAsync(welcomeMessage);  
  19.   
  20.     await this.DisplayOptionsAsync(context);  
  21. }  
  22.   
  23. public async Task DisplayOptionsAsync(IDialogContext context)  
  24. {  
  25.     PromptDialog.Choice<string>(  
  26.         context,  
  27.         this. SelectedOptionAsync,  
  28.         this.options.Keys,  
  29.         "What Demo / Sample option would you like to see?",  
  30.         "Please select Valid option 1 to 6",  
  31.         6,  
  32.         PromptStyle.PerLine,  
  33.         this.options.Values);  
  34. }  
  35.   
  36. public async Task SelectedOptionAsync(IDialogContext context, IAwaitable<string> argument)  
  37. {  
  38.     var message = await argument;  
  39.   
  40.     var replyMessage = context.MakeMessage();  
  41.       
  42.     Attachment attachment = null;  
  43.   
  44.     switch (message)  
  45.     {  
  46.         case "1":  
  47.             attachment = GetLocalAttachment();  
  48.             replyMessage.Text = "Attach Image from Local Machine";  
  49.             break;  
  50.         case "2":  
  51.             attachment = GetInternetAttachment();  
  52.             replyMessage.Text = "Attach Image from Internet";  
  53.             break;  
  54.         case "3":  
  55.             attachment = GetinternetFileAttachment();  
  56.             replyMessage.Text = "Click Link for navigate PDF internet location";  
  57.             break;  
  58.         case "4":  
  59.             attachment = GetLocalFileAttachment();  
  60.             replyMessage.Text = "Click Link for navigate PDF local location";  
  61.             break;  
  62.         case "5":  
  63.             attachment = GetinternetVideoAttachment();  
  64.             replyMessage.Text = "Click on play button ";  
  65.             break;  
  66.         case "6":  
  67.             attachment = GetinternetYoutubeAttachment();  
  68.             replyMessage.Text = "Showing video from Youtube ";  
  69.             break;  
  70.         case "7":  
  71.             attachment = GetinternetMP3Attachment();  
  72.             replyMessage.Text = "Showing MP3 from internet ";  
  73.             break;  
  74.   
  75.     }  
  76.     replyMessage.Attachments = new List<Attachment> { attachment };  
  77.   
  78.     await context.PostAsync(replyMessage);  
  79.   
  80.     await this.DisplayOptionsAsync(context);  
  81. }  

After user enters the first message, the Bot will reply with a welcome message and list of demo options, and wait for the user input like below.

Bot Framework

Step 4 Local Image Attachment

The following code is showing the reply message with an image. To add the image as an attachment to a message, create an Attachment object for the message activity and set the following.

  • ContentType
  • ContentUrl
  • Name
  1. /// <summary>  
  2.         /// dispaly local image  
  3.         /// </summary>  
  4.         /// <returns></returns>  
  5.         private static Attachment GetLocalAttachment()  
  6.         {  
  7.             var imagePath = HttpContext.Current.Server.MapPath("~/images/demo.gif");  
  8.   
  9.             var imageData = Convert.ToBase64String(File.ReadAllBytes(imagePath));  
  10.   
  11.             return new Attachment  
  12.             {  
  13.                 Name = "demo.gif",  
  14.                 ContentType = "image/gif",  
  15.                 ContentUrl = $"data:image/gif;base64,{imageData}"  
  16.             };  
  17.         }  

After the user provides input, the Bot will reply with a message with local image.

Bot Framework

Internet Image Attachment

The internet image option is the simplest but requires the image to be already on the Internet and be publicly accessible. Provide a content URL pointing to the image URL path.

  1. /// <summary>  
  2.         /// Dispaly image from internet  
  3.         /// </summary>  
  4.         /// <returns></returns>  
  5.         private static Attachment GetInternetAttachment()  
  6.         {  
  7.             return new Attachment  
  8.             {  
  9.                 Name = "architecture-resize.png",  
  10.                 ContentType = "image/png",  
  11.                 ContentUrl = "https://docs.microsoft.com/en-us/bot-framework/media/how-it-works/architecture-resize.png"  
  12.             };  
  13.         }  

The following output screen shows up. After the user provides the input, the bot will fetch the image from internet and display that in emulator.

Bot Framework

Internet File Attachment

You can refer to the following code for adding a hyperlink to fetch the file from the internet and attach to reply message. The same code will be reused for all the types of the document but we need to change the content type and content URL.

  1. /// <summary>  
  2.         /// attach internet file  
  3.         /// </summary>  
  4.         /// <returns></returns>  
  5.         public static Attachment GetinternetFileAttachment()  
  6.         {  
  7.             Attachment attachment = new Attachment();  
  8.             attachment.ContentType = "application/pdf";  
  9.             attachment.ContentUrl = "https://qconlondon.com/london-2017/system/files/presentation-slides/microsoft_bot_framework_best_practices.pdf";  
  10.             attachment.Name = "Microsoft Bot Framework Best Practices";  

The following is the output screen. After the user provides input, the bot will reply with a message with hyperlink for document. The user needs to click a hyperlink for opening the document.

Bot Framework

Local File Attachment

You can add pdf file into your project and add the following code for attaching a local pdf document in reply message.

  1. /// <summary>  
  2.       /// Get local file   
  3.       /// </summary>  
  4.       /// <returns></returns>  
  5.       public static Attachment GetLocalFileAttachment()  
  6.       {  
  7.           var pdfPath = HttpContext.Current.Server.MapPath("~/File/BotFramework.pdf");  
  8.           Attachment attachment = new Attachment();  
  9.           attachment.ContentType = "application/pdf";  
  10.           attachment.ContentUrl = pdfPath;  
  11.           attachment.Name = "Local Microsoft Bot Framework Best Practices";  
  12.           return attachment;  
  13.       }  

The following output shows the reply message with hyperlink with download link to the attached pdf document.

Bot Framework

Video Attachment

The following code is showing the reply message with attached video file.

  1. /// <summary>  
  2.         /// Dispaly video from internet  
  3.         /// </summary>  
  4.         /// <returns></returns>  
  5.         public static Attachment GetinternetVideoAttachment()  
  6.         {  
  7.   
  8.             Attachment attachment = new Attachment();  
  9.             attachment = new VideoCard("Build a great conversationalist""Bot Demo Video""Build a great conversationalist", media: new[] { new MediaUrl(@"https://bot-framework.azureedge.net/videos/skype-hero-050517-sm.mp4") }).ToAttachment();  
  10.             return attachment;  
  11.         } 

The following output gets showing. After the user provides an input, our bot will reply with a message with video attachment.

Bot Framework

YouTube Video Attachment

The following code shows the reply message with attached YouTube video. You need to provide the content type and content URL in the attachment property.

  1. /// <summary>  
  2.         /// Display Youtube Video  
  3.         /// </summary>  
  4.         /// <returns></returns>  
  5.         public static Attachment GetinternetYoutubeAttachment()  
  6.         {  
  7.             Attachment attachment = new Attachment();  
  8.             attachment.ContentType = "video/mp4";  
  9.             attachment.ContentUrl = "https://youtu.be/RaNDktMQVWI";  
  10.             return attachment;  
  11.         }  

The following output is showing a message with YouTube video attachment.

Bot Framework

MP3 File Attachment

The following code is showing the attached mp3 file in a reply message. The attachment type is in the Content Type property, which should be a valid mime type is “image/mpeg3” or “audio/mp3”.

  1.     /// <summary>  
  2. /// attach internet file  
  3. /// </summary>  
  4. /// <returns></returns>  
  5. public static Attachment GetinternetMP3Attachment()  
  6. {  
  7.     Attachment attachment = new Attachment();  
  8.     attachment.ContentType = "audio/mpeg3";  
  9.     attachment.ContentUrl = "http://video.ch9.ms/ch9/f979/40088849-aa88-45d4-93d5-6d1a6a17f979/TestingBotFramework.mp3";  
  10.     attachment.Name = "Testing the Bot Framework Mp3";  
  11.     return attachment;  
  12. }         

The output is showing a reply message with attached mp3 file.

Bot Framework

Run Bot Application

The emulator is a desktop application that lets us test and debug our bot on localhost. Now, you can click on "Run the application" in Visual Studio and execute in the browser.

Test Application on Bot Emulator

You can follow the below steps to test your bot application.

  1. Open Bot Emulator.
  2. Copy the above localhost url and paste it in emulator e.g. - http://localHost:3979
  3. You can append the /api/messages in the above url; e.g. - http://localHost:3979/api/messages.
  4. You won't need to specify Microsoft App ID and Microsoft App Password for localhost testing, so click on "Connect".



Summary

In this article, you learned how to create a Bot application using Visual Studio 2017 and send a reply message with the different type of media file attachments. If you have any questions/feedback/ issues, please write in the comment box.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now