March 6, 2025

Step-by-Step Guide: Building, Integrating, and Deploying a Microsoft Teams Bot Using Visual Studio, OpenAI, and Azure - Part 2


What is a Bot and Its Advantages?
A bot is a software application designed to automate tasks, often simulating human interaction. Bots are widely used in customer support, data retrieval, and task automation, making workflows efficient and reducing manual effort. With advancements in AI, bots can now engage in intelligent conversations and provide personalized assistance.

Advantages of Bots:
  • Efficiency: Automates repetitive tasks, saving time and resources.
  • 24/7 Availability: Provides uninterrupted support to users.
  • Scalability: Handles multiple interactions simultaneously.
  • Cost-Effective: Reduces the need for extensive human resources.

This tutorial is part of a series. To understand it fully, make sure to check out Part 1: Azure Configuration for Your Bot.

  1. Add the Bot Framework v4 SDK Templates to Visual Studio.
  2. Bot Framework SDK(Software Development Kit): This SDK provides essential tools and configurations for building bots. Visual Studio makes it easy to integrate and manage your bot's development.|

    1. Click on the 'Download' link to open the Bot Framework v4 SDK page.
    2. Once the page opens, find the green "Download" button.
    3. Click the green button to download the Bot SDK. 
    4. After the download is complete, install the SDK on your system.


    5. This template includes default bot configurations, making it easier to get started with your bot development.


  3. Create an Echo Bot Solution in Visual Studio.
    1. Open Visual Studio and choose "Create a new project.
    2. Search bar in search ‘bot’. 
    3. Select template  ‘Echo Bot (Bot Framework V4) 


    4. Add a Project name and create a project.



  4. Configure the OpenAI API in the Echo Bot Solution.
    • Add Dependencies: Install the System.Net.Http and Newtonsoft.Json packages via NuGet for handling HTTP requests and JSON.
    • Implement the ChatGPT Service: 
      1. Go to solution explore and Open file EchoBot.cs
      2. Add a new method in the following code to interact with the OpenAI API
        // New method to implement for retrieving OpenAI API responses and  returning them in the
        //proper format

         private async Task<string> GPTResponseAsync(string userQuery)
         {
            // API key for accessing Azure OpenAI service (replace this with your actual key)
            string apiKey = "API_KEY";
         
            // Endpoint URL of the Azure OpenAI deployment with the correct API version
            string endPoint = "AZURE_API";
         
            // Creating an HttpClient to send HTTP requests to the API
            var client = new HttpClient();
         
            // Preparing an HTTP POST request with the specified endpoint
            var request = new HttpRequestMessage(HttpMethod.Post, endPoint);
         
            // Adding the API key to the request header for authentication
            request.Headers.Add("api-key", apiKey);
         
            // Constructing the request body in JSON format
            // - `messages`: Contains the conversation with roles (`system`, `user`, `assistant`)
            // - `max_tokens`: Defines the maximum response length
            // - `temperature`: Controls the randomness of the response (higher values make output
            //    more creative)
            // - `top_p`, `frequency_penalty`, `presence_penalty`: Other parameters to fine-tune
            //    the response generation
             var content = new StringContent($@"{{
             ""messages"": [{{
               ""role"": ""system"",
               ""content"": ""You are an AI assistant designed to help people discover information.""
             }}, {{
               ""role"": ""user"",
               ""content"": ""{userQuery}""
             }}, {{
               ""role"": ""assistant"",
               ""content"": ""Hello! How can I assist you today?""
             }}],
             ""max_tokens"": 800,
             ""temperature"": 0.7,
             ""frequency_penalty"": 0,
             ""presence_penalty"": 0,
             ""top_p"": 0.95,
             ""stop"": null
           }}", null, "application/json");
         
            // Setting the content of the request to the JSON string prepared above
            request.Content = content;
         
            // Sending the request asynchronously and awaiting the response
            var response = await client.SendAsync(request);
         
            // Ensuring the response status code is successful (2xx), throwing an error if not
            response.EnsureSuccessStatusCode();
         
            // Reading the response content as a string
            var result = await response.Content.ReadAsStringAsync();

            // Parsing the result string into a JSON object    
            var resultObject = JObject.Parse(result);      

            // Returning the assistant's response from the JSON object    
             return Convert.ToString(resultObject["choices"][0]["message"]["content"]);
         }
        Note:
         Please double-check your API and API key to ensure they are working. (This code uses the Azure OpenAI API.)

    • Integrate ChatGPT with the Bot: 
      1. In your bot's main dialogue or message handler (e.g., EchoBot.cs), integrate the ChatGPT service: 
      2. Method Purpose: This method is triggered whenever a user sends a message in the conversation (e.g., in Microsoft Teams). It takes the message, forwards it to OpenAI's GPT API, and sends the response back to the user.
      3. TurnContext: This object contains all the relevant details about the conversation, including the message sent by the user. turnContext.Activity.Text gets the message text that the user sent. 
      4. GPTResponseAsync: The method sends the user's message to the GPT model hosted on Azure OpenAI and waits for the AI's response. It returns the response, which will be sent back to the user. 
      5. MessageFactory.Text: This creates a new message to be sent back to the user. The same text is passed twice; the first parameter is what will be displayed, and the second is for any formatting or processing. 
      6. CancellationToken: This parameter is used to manage the cancellation of asynchronous tasks. It ensures that the operation can be cancelled if needed without blocking the application. 
          protected override async Task OnMessageActivityAsync(
            ITurnContext<IMessageActivity> turnContext,
             CancellationToken cancellationToken)
         {
             //var replyText = $"Echo: {turnContext.Activity.Text}";
             var gptResponse = await GPTResponseAsync(turnContext.Activity.Text);
             await turnContext.SendActivityAsync(
                    MessageFactory.Text(gptResponse, gptResponse),
                    cancellationToken);
         }


  5. Test the Bot Locally in BotFramework-Emulator.
    1.  Go to the following link to directly 'download' BotFramework-Emulator exe file.
    2. Once the Bot Framework Emulator is downloaded, install it.
    3. Run your Project When successfully running the solution open the Bot window and copy the URL. 

    4. Open the Emulator > “Open Bot” > set your URL plus “api/messages” > Connect

    5. Test your bot.



  6. Deploy the Bot to Azure App Service.
    • Prerequisite
      • Azure Tenant ID
      • MicrosoftAppId
      • MicrosoftAppPassword

    1. Azure Tenant ID: Azure Portal > Azure Active Directory > Overview > Directory ID (copy this value)
    2. Microsoft App ID: Azure Portal > All services > Bot Services (or Azure Bot) > [Your Bot] > Settings > Microsoft App ID (copy this value)
    3. Microsoft App Password: Azure Portal > All services > Bot Services (or Azure Bot) > [Your Bot] > Settings > Manage > Certificates & secrets > New client secret > Add (copy the value of the newly created client secret)
    4. Open the Visual Studio solution(6) for your Echo Bot and navigate to the appsettings.json file. Add the following configuration (paste the IDs)


    5. Visual Studio > Solution Explorer > Right-click on your project > Publish > Add New Profile > Azure 


    6. Sign in to Azure (if required) and select Created app service for the bot. then Finish

    7. Click on 'Publish' to deploy the app to Azure App Service.

  7. Create a manifest.json for Microsoft Teams.
    1. Create a new file named manifest.json in your project folder.
    2. Add the following basic structure to your manifest.json file: Need more information click manifest.json

          {
              "$schema": "https://developer.microsoft.com/en-us/json-schemas/teams/v1.16/MicrosoftTeams.schema.json",
              "manifestVersion": "1.16",
              "version": "1.0.9",
              "id": "<YOUR_TEAMS_APP_ID>",
              "packageName": "com.microsoft.teams.extension",
              "developer": {
                  "name": "Teams App, Inc.",
                  "websiteUrl": "<YOUR_WEBSITE_URL>",
                  "privacyUrl": "<YOUR_WEBSITE_URL>",
                  "termsOfUseUrl": "<YOUR_WEBSITE_URL>"
              },
              "icons": {
                  "color": "color.png",
                  "outline": "outline.png"
              },
              "name": {
                  "short": "Gangbox ChatBot",
                  "full": "Gangbox ChatBot"
              },
              "description": {
                  "short": "This is AI Chatbot.",
                  "full": "This is AI Chatbot."
              },
              "accentColor": "#FFFFFF",
              "bots": [
                  {
                      "botId": "<YOUR_TEAMS_APP_ID>",
                      "scopes": [
                          "personal",
                          "team",
                          "groupchat"
                      ],
                      "supportsFiles": false,
                      "isNotificationOnly": false,
                      "commandLists": [
                          {
                              "scopes": [
                                  "personal",
                                  "team",
                                  "groupchat"
                              ],
                              "commands": [
                                  {
                                      "title": "welcome",
                                      "description": "Resend welcome card of this Bot"
                                  },
                                  {
                                      "title": "learn",
                                      "description": "Learn about Adaptive Card and Bot Command"
                                  }
                              ]
                          }
                      ]
                  }
              ],
              "composeExtensions": [],
              "configurableTabs": [],
              "staticTabs": [],
              "permissions": [
                  "identity",
                  "messageTeamMembers"
              ],
              "validDomains": []
          }
         

    3. Replace Placeholders
      • id: Your bot's Microsoft App ID.
      • developer: Fill in details about your name/company and URLs for your website, privacy policy, and terms of use.
      • botId: The same as your Microsoft App ID.
      • icons: Add the paths to your bot's icon images (color and outline versions).

        Add two images (icon files) in your folder:
        - color.png (192x192 pixels)
        - outline.png (32x32 pixels)

    4. Compress Files into a Zip
      Include the following files in a zip file:
      - manifest.json
      - color.png
      - outline.png

      The zip file will be your Teams app package.



  8. Add the App to Microsoft Teams.
    1. Go to Microsoft Teams > Apps > Upload a custom app > Upload for me or my teams.



    2. Upload your .zip file, and your bot will be added to Microsoft Teams.

    Thank you for reading! We hope this guide helped you successfully configure your bot. Feel free to share your thoughts or questions in the comments below!

    If you have any questions you can reach out our SharePoint Consulting team here.

    No comments:

    Post a Comment