[BotFramework]:有没有办法在C#中使用SDK V4开发的BOT中显示英雄卡或自适应卡中的Oauth提示? [英] [BotFramework]: Is there a way to Display Oauth prompt in hero card or Adaptive card in a BOT Developed using SDK V4 in C#?

查看:20
本文介绍了[BotFramework]:有没有办法在C#中使用SDK V4开发的BOT中显示英雄卡或自适应卡中的Oauth提示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 C# 中的 V4 开发聊天机器人;我已经使用 OauthCard 提示在瀑布对话框中实现了身份验证功能,我希望此 oauth 卡提示显示在 Hero Card 或 Adaptive 卡或任何其他合适的卡中,以便登录功能在网络聊天频道中工作.

目前,oauth 卡提示没有显示在网络聊天频道中,导致我无法登录,所以想如果我可以在 Hero 卡或任何合适的卡中显示 oauth 提示的登录功能,那么我可以继续身份验证功能.

我使用以下链接启用了 Oauth Prompt,它在模拟器中完美运行:

如何在不输入任何内容的情况下使用 C# 创建的 SDK V4 bot 中的瀑布对话框中使用 oauth 提示修复下一步导航?

但无法在网络聊天频道中做到这一点,因此我认为如果我将其保存在英雄卡中,它就可以工作.

  • 语言:C#
  • SDK:V4
  • 频道:网络聊天频道

请以详细的指导方式逐步提供代码或程序,因为我对 BOT 和编码还很陌生,以便我可以解决我的问题.

请帮忙.

谢谢&问候-柴塔杨

我不知道该怎么做,所以我尝试在 index.html 中执行以下操作:https://github.com/microsoft/BotFramework-WebChat/tree/master/samples/18.customization-open-url

这对我也不起作用.

我也查看了以下链接,但根据我的理解,团队频道有评论,但网络聊天频道没有任何具体内容:

https://github.com/microsoft/botframework-sdk/issues/4768

我也查看了下面的链接,但由于它与 React 相关,我没有调查它,因为我正在网络聊天频道和 azure C# 中做聊天机器人:

https://github.com/microsoft/BotFramework-WebChat/tree/master/samples/10.a.customization-card-components

我还尝试在 Singin 卡中调用 oauth 提示,但它不起作用,因为它没有在模拟器或 Webchannel 中调用提示.

因此我需要帮助,因为即使按照上述链接信息,oauth 卡也没有加载到网络聊天频道中.所以想如果我们可以保留一些卡片,它可以完成,但也没有找到任何具体的事情要做.由于我是 BOT 和编码新手,我可能错过了一些东西,所以请帮助或提供有关如何操作的分步指南.

预期结果:需要在 HeroCard 或任何其他合适的卡片中显示 oauth 提示,因为它是代码不起作用或在网络聊天频道中加载 oauth 提示在模拟器中工作正常.实际结果:不知道如何实现.

根据 Richardson 的评论添加详细信息:理查森,

我在瀑布对话框中使用了 OauthPrompt,其中第 1 步:我在单击链接时显示 OAuthCard 提示,它会弹出一个新窗口以输入凭据,并提供一个魔术代码.我在浏览器中输入魔法代码第 2 步:这里我正在检索令牌并继续进行,因为我说这在模拟器中工作,如下链接所述:

如何在不输入任何内容的情况下使用 C# 创建的 SDK V4 bot 中的瀑布对话框中使用 oauth 提示修复下一步导航?

进入网络聊天时,它向我显示了以下内容:['application/vnd.microsoft.card.oauth'类型的文件]

而不是登录按钮或链接.

我使用的代码如下:

public class LoginDialog : WaterfallDialog{public LoginDialog(string dialogId, IEnumerablesteps = null):基础(对话ID,步骤){AddStep(async (stepContext, cancelToken) =>{await stepContext.Context.SendActivityAsync("请使用以下选项登录以继续其他选项...");return await stepContext.BeginDialogAsync("登录提示",取消令牌:取消令牌);//这实际上调用了名称在 EchoWithCounterBot.LoginPromptName 中的 OAuthPrompt 的对话.});AddStep(async (stepContext, cancelToken) =>{Tokenresponse = (TokenResponse)stepContext.Result;如果(令牌响应!= null){await stepContext.Context.SendActivityAsync($"登录成功...");返回等待 stepContext.BeginDialogAsync(DisplayOptionsDialog.Id);//这里转到另一个显示选项的对话类}别的{await stepContext.Context.SendActivityAsync("登录失败,请重试...", cancelToken: cancelToken);等待 stepContext.BeginDialogAsync("登录提示",取消令牌:取消令牌);}返回等待 stepContext.EndDialogAsync();});}公共静态新字符串 Id =>"登录对话框";公共静态登录对话框实例 { 获取;} = new LoginDialog(Id);}

在称为 Mainrootdialog 类的主对话框中:1. 我有一个变量 LoginPromptName = "loginprompt" 和另一个连接名称参数;public const string ConnectionName = "conname";

  1. 然后我有一个名为 prompt 的方法,它接受连接名称并具有如下所示的 oauthprompt 相关代码:

 private static OAuthPrompt Prompt(string connectionName){返回新的 OAuthPrompt("登录提示",新的 OAuthPromptSettings{连接名称 = 连接名称,文字 = "登录",title = "登录",Timeout = 300000,//用户有 5 分钟的时间登录 (1000 * 60 *});}

  1. 最后这个提示被添加到对话框或堆栈中,如下所示:

 public MainRootDialog(UserState userState):基地(根"){_userStateAccessor = userState.CreateProperty("result");添加对话框(提示(连接名称));AddDialog(LoginDialog.Instance);InitialDialogId = LoginDialog.Id;}

正如您在上面共享链接中的评论中所看到的那样,正如您之前所尝试的那样,在模拟器中可以很好地解释之前的工作

但是在网络聊天频道中没有加载按钮或链接给了我这个:['application/vnd.microsoft.card.oauth'类型的文件]

我尝试了以下 GitHub 链接,但无法粘贴或附加 HTML 文件以供参考:https://github.com/microsoft/BotFramework-WebChat/tree/master/samples/18.customization-open-url

<html lang="en-US"><头><title>网络聊天:自定义打开 URL 行为</title><meta name="viewport" content="width=device-width, initial-scale=1.0"><!--出于演示目的,我们使用位于/master/webchat.js"的网络聊天的开发分支.当您使用网络聊天进行生产时,您应该使用位于/latest/webchat.js"的最新稳定版本,或使用以下格式锁定特定版本:/4.1.0/webchat.js".--><script src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script><风格>html,正文{高度:100%}身体 {保证金:0}#网络聊天,#网络聊天>* {高度:100%;宽度:100%;}</风格><身体><div id="webchat" role="main"><iframe src='https://webchat.botframework.com/embed/TestBotForOauthPrompt?s=<<给定我的网络聊天频道秘钥>>'样式 = 最小宽度:400 像素;宽度:100%;最小高度:500px;'></iframe>

<脚本>(异步函数(){//在这个演示中,我们使用来自 MockBot 的 Direct Line 令牌.//要与您的机器人交谈,您应该使用使用 Direct Line 机密交换的令牌.//永远不要将 Direct Line 密码放在浏览器或客户端应用程序中.//https://docs.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authenticationconst res = await fetch('https://testbotforoauthprompt.azurewebsites.net//directline//token', { method: 'POST' });const { token } = await res.json();window.WebChat.renderWebChat({directLine: window.WebChat.createDirectLine({ token }),//我们正在添加一个新的中间件来处理卡片操作cardActionMiddleware: () =>下一个 =>异步 ({ car​​dAction, getSignInUrl }) =>{const { type, value } = cardAction;开关(类型){案例登录"://对于 OAuth 或登录弹出窗口,我们将直接打开 auth 对话框.const popup = window.open();const url = 等待 getSignInUrl();popup.location.href = url;休息;案例'openUrl':if (confirm(`你要打开这个网址吗? ${ value }`)) {window.open(value, '_blank');}休息;默认:return next({ car​​dAction, getSignInUrl });}}}, document.getElementById('webchat'));document.querySelector('#webchat > *').focus();})().catch(err => console.error(err));</html>

进入您提供的链接无法打开它给我 404 错误

<小时>

日期:2019 年 5 月 29 日原因:对 Richardson 提供的输入的进一步查询

我知道在生成令牌的控制器类中编写了一个 .NET 代码.有一个 html 页面可以加载我们的网络聊天,其中包含所需的脚本存储或公开令牌,然后每当我们打开此 HTML 文件时聊天机器人就会打开.但是,我有以下疑问.这些可能看起来很基本,但请耐心等待,因为我是编码新手:

  1. 代码应该写在哪里,如何调用,因为我没有在我的 html 脚本中指定或在任何地方调用 Controller 类 Index 方法来生成令牌并使用它?或者它会自动调用控制器内部的索引方法.如果没有,我应该在哪里自动指定你调用索引方法的这个?是否可以提供完整的解决方案,例如在解决方案中包含机器人代码和控制器类,以便我可以获得更好的图片,以便我可以询问任何其他进一步的查询(如果有)?

  2. 这个 .net 代码是一个单独的解决方案还是应该写在同一个机器人解决方案控制器类中?如果单独解决,那么如何将其发布到azure中的BOT资源?机器人和新解决方案如何在不提供任何连接的情况下自动交互?

  3. 我假设它应该在 Visual Studio 中的同一个 BOT 代码解决方案中创建一个新类.现在,我对此有进一步的疑问(基于此假设):

一个.根据我对您的解释的理解,post 方法不起作用,因为没有令牌生成器,因此它会给您一个错误.您可以使用下面的链接编写代码并获取令牌,这又带来了问题 1?

I am developing a chatbot using V4 in C#; I have implemented an authentication functionality inside a waterfall dialog using OauthCard prompt, I want this oauth card prompt to be displayed inside a Hero Card or Adaptive card or any other card that is suitable such that Login functionality works in Webchat Channel.

Currently, the oauth card prompt is not displayed in the webchat Channel as a result I am unable to login so thought if I can display the sign in functionality of oauth Prompt in Hero card or any suitable card then I can proceed it with authentication functionality.

I have enabled Oauth Prompt using the below link and it perfectly works fine in emulator:

How to fix next step navigation with oauth prompt in waterfall dialog in SDK V4 bot created using C# without typing anything?

But not able to do it in Webchat Channel hence thought if i keep this in hero card it can work.

  • Language: C#
  • SDK: V4
  • Channel: WebChat channel

Please provide the code or procedure in step by step in a detailed guide manner as I am fairly new to BOT and coding so that i can fix my issue.

Please help.

Thanks & Regards -ChaitayaNG

I do not know how to do it so i tried do the following in index.html: https://github.com/microsoft/BotFramework-WebChat/tree/master/samples/18.customization-open-url

This is did not work for me either.

I looked into the below links also but according to my understanding there was comments for Team Channel but nothing concrete for webchat channel:

https://github.com/microsoft/botframework-sdk/issues/4768

I also looked into belowlink but since it was related to React i did not investigate it as i am doing the chatbot in webchat channel and in azure C#:

https://github.com/microsoft/BotFramework-WebChat/tree/master/samples/10.a.customization-card-components

I also tried to call oauth prompt inside Singin card which did not work as it was not invoking the prompt either in Emulator or Webchannel.

Hence i need help as the oauth cards are not loading in Web Chat channel even after following above links information. So thought if we can keep in some cards it can be done but did not find any thing concrete to do also. Since i am new to BOT and coding i may have missed something so please help or provide step by step guide on how t do it.

Expected Result: Need the oauth prompt to be displayed inside a HeroCard or any other suitable card as it is code is not working or loading the oauth prompt in Webchat channel working fine in Emulator. Actual Result: Do not know how to achieve it.

Adding details as per the comments from Richardson: Hi Richardson,

I have used OauthPrompt in a Water fall dialog where in STEP 1: I display OAuthCard prompt where i click on link and it pops up a new window to enter credentials and it gives a magic code. I enter the magic code in browser it goes to STEP 2: Here i am retrieving token and proceeding further as i said this is working in Emulator as described in below link:

How to fix next step navigation with oauth prompt in waterfall dialog in SDK V4 bot created using C# without typing anything?

Coming to Webchat it displayed me the following: [File of type 'application/vnd.microsoft.card.oauth']

Instead of sign in button or link.

The code i used is the following:

public class LoginDialog : WaterfallDialog
{
    public LoginDialog(string dialogId, IEnumerable<WaterfallStep> steps = null)
         : base(dialogId, steps)
    {
        AddStep(async (stepContext, cancellationToken) =>
        {
            await stepContext.Context.SendActivityAsync("Please login using below option in order to continue with other options...");

            return await stepContext.BeginDialogAsync("loginprompt", cancellationToken: cancellationToken); // This actually calls the  dialogue of OAuthPrompt whose name is  in EchoWithCounterBot.LoginPromptName.  


        });

        AddStep(async (stepContext, cancellationToken) =>
        {
            Tokenresponse = (TokenResponse)stepContext.Result;

            if (Tokenresponse != null)
            {

                await stepContext.Context.SendActivityAsync($"logged in successfully... ");


                return await stepContext.BeginDialogAsync(DisplayOptionsDialog.Id); //Here it goes To another dialogue class where options are displayed
            }
            else
            {
                await stepContext.Context.SendActivityAsync("Login was not successful, Please try again...", cancellationToken: cancellationToken);


                await stepContext.BeginDialogAsync("loginprompt", cancellationToken: cancellationToken);
            }

            return await stepContext.EndDialogAsync();
        });
    }

    public static new string Id => "LoginDialog";

    public static LoginDialog Instance { get; } = new LoginDialog(Id);
}

In the maindialog called as Mainrootdialog class: 1. I have a variable LoginPromptName = "loginprompt" and another parameter for connection name; public const string ConnectionName = "conname";

  1. Then I have a method called prompt which accepts connection name and has oauthprompt related code as given below:

  private static OAuthPrompt Prompt(string connectionName)
        {
            return new OAuthPrompt(
               "loginprompt",
               new OAuthPromptSettings
               {
                   ConnectionName = connectionName,
                   Text = "signin",
                   Title = "signin",
                   Timeout = 300000, // User has 5 minutes to login (1000 * 60 * 
               });
        }

  1. Finally this prompt is added in the Dialogset or stack as below:

     public MainRootDialog(UserState userState)
            : base("root")
        {
            _userStateAccessor = userState.CreateProperty<JObject>("result");

            AddDialog(Prompt(ConnectionName));
            AddDialog(LoginDialog.Instance);            
            InitialDialogId = LoginDialog.Id;
        }

As tried to explain earlier works perfectly fine in emulator as you could see from my comments in the above shared link

But in webchat channel does not load button or link gives me this: [File of type 'application/vnd.microsoft.card.oauth']

I tried the following GitHub link which i did not work pasting or attaching the HTML file for reference: https://github.com/microsoft/BotFramework-WebChat/tree/master/samples/18.customization-open-url

<!DOCTYPE html>
<html lang="en-US">
<head>
    <title>Web Chat: Customize open URL behavior</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <!--
      For demonstration purposes, we are using the development branch of Web Chat at "/master/webchat.js".
      When you are using Web Chat for production, you should use the latest stable release at "/latest/webchat.js",
      or lock down on a specific version with the following format: "/4.1.0/webchat.js".
    -->
    <script src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
    <style>
        html, body {
            height: 100%
        }

        body {
            margin: 0
        }

        #webchat,
        #webchat > * {
            height: 100%;
            width: 100%;
        }
    </style>
</head>
<body>
    <div id="webchat" role="main">
        <iframe src='https://webchat.botframework.com/embed/TestBotForOauthPrompt?s=<<Given my secretkey of web chat channel>>' style='min-width: 400px; width: 100%; min-height: 500px;'></iframe>
    </div>
    <script>
      (async function () {
        // In this demo, we are using Direct Line token from MockBot.
        // To talk to your bot, you should use the token exchanged using your Direct Line secret.
        // You should never put the Direct Line secret in the browser or client app.
        // https://docs.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication
        const res = await fetch('https://testbotforoauthprompt.azurewebsites.net//directline//token', { method: 'POST' });
        const { token } = await res.json();
        window.WebChat.renderWebChat({
          directLine: window.WebChat.createDirectLine({ token }),
          // We are adding a new middleware to handle card action
          cardActionMiddleware: () => next => async ({ cardAction, getSignInUrl }) => {
            const { type, value } = cardAction;
            switch (type) {
              case 'signin':
                // For OAuth or sign-in popups, we will open the auth dialog directly.
                const popup = window.open();
                const url = await getSignInUrl();
                popup.location.href = url;
                break;
              case 'openUrl':
                if (confirm(`Do you want to open this URL?

${ value }`)) {
                  window.open(value, '_blank');
                }
                break;
              default:
                return next({ cardAction, getSignInUrl });
            }
          }
        }, document.getElementById('webchat'));
        document.querySelector('#webchat > *').focus();
      })().catch(err => console.error(err));
    </script>
</body>
</html>

Coming to the link you have provided it does not open it gives me 404 error


Date: 29-May-2019 Reason: Further queries on inputs provided by Richardson

I understand there is a .NET Code written inside a controller class which generates the Token. There is a html page to load our web chat which contains required scripts to store or expose tokens and then the chat bot opens whenever we open this HTML file. However, I have following queries. These might seem very basic but please bear with me as I am new to coding:

  1. Where the code should be written, how will it get called because I am not specifying in my html script or anywhere call the Controller class Index method to generate the token and use it? Or will it call automatically the index method inside controller. If not, automatically where should I specify this that u call index method? Is it possible to provide whole solution like having bot code and controller class at solution so that I can get a better picture so that I can ask any other further queries if any?

  2. Is this .net code is a separate solution or inside the same bot solution controller class should be written? If separate solution, then how to publish this to the BOT resource in azure? How bot and new solution will interact automatically without providing any connection?

  3. I am assuming it should a new class inside the same BOT Code solution in Visual Studio. Now, I have further queries on this(based on this assumption):

a. As per my understanding on your explanation the post method is not working because there is no Token generator, so it gives you an error. You can use the below link to write the code and get the token which again brings to question number 1?

What is the correct way to authenticate from JavaScript in an HTML file to the Microsoft Web Chat control for Bot Framework v4?

b. In the HTML file if I write the script given as per above link then should be in the same async function or we have to remove the async function?

c. Still the style options like BOT Avatar and etc work if kept as is ? same way other scripts for displaying welcome message?

d. In the GetElementByID('') we are passing bot as the value from the link above but in actual samples we pass web chat is it because we have changed the POST method to the new script?

e. Should the post method still be kept or can be removed? Instead of the post line:

const res = await fetch('https://examplebot.azurewebsites.net/directline/token', { method: 'POST' }); Write new one as below: the script given below (taken from above link):

@model ChatConfig
@{
    ViewData["Title"] = "Home Page";
}
<link href="https://cdn.botframework.com/botframework-webchat/latest/botchat.css" rel="stylesheet" />
<div id="bot" />
<script src="https://cdn.botframework.com/botframework-webchat/latest/botchat.js"></script>
<script>
      BotChat.App({
          directLine: {
              secret: '@Model.Token'
          },
        user: { id: @Model.UserId },
        bot: { id: 'botid' },
        resize: 'detect'
      }, document.getElementById("bot"));
</script>

  1. You have also explained that to avoid all these complications and make it simple just keep your secret in the file: Current: const { token } = await res.json(); To make it simple: const { token } = <>; Is my understanding, right?

  2. On top of 4th question: Then the POST method line should also be removed i.e. below line and we don’t have to write the new controller class or the script given above of Model config and rest keep as is: Something like below and the bot loads when I open the page and the OAuth prompts and adaptive cards work without any issue:

    Avanade D365 F&O Assets BOT

    <!--
      For demonstration purposes, we are using development branch of Web Chat at "/master/webchat.js".
      When you are using Web Chat for production, you should use the latest stable at "/latest/webchat.js".
      Or locked down on a specific version "/4.1.0/webchat.js".
    -->
    <script src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
    <style>
        html, body {
            height: 100%
        }
    
        body {
            margin: 0
        }
    
        #webchat {
            height: 100%;
            width: 100%;
        }
    </style>
    

    </div>
    <script>
      (async function () {
        // In this demo, we are using Direct Line token from MockBot.
        // To talk to your bot, you should use the token exchanged using your Direct Line secret.
        // You should never put the Direct Line secret in the browser or client app.
        // https://docs.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication
    
          const { token } = <<Directline secret from azure portal durect line channel>>;
    
          const styleOptions = {
           botAvatarImage: 'https://docs.microsoft.com/en-us/azure/bot-service/v4sdk/media/logo_bot.svg?view=azure-bot-service-4.0',
           botAvatarInitials: 'BF',
           userAvatarImage: 'https://avatars1.githubusercontent.com/u/45868722?s=96&v=4',
           userAvatarInitials: 'WC',
           bubbleBackground: 'rgba(0, 0, 255, .1)',
           bubbleFromUserBackground: 'rgba(0, 255, 0, .1)'
      };
        // We are using a customized store to add hooks to connect event
        const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
          if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
            // When we receive DIRECT_LINE/CONNECT_FULFILLED action, we will send an event activity using WEB_CHAT/SEND_EVENT
            dispatch({
              type: 'WEB_CHAT/SEND_EVENT',
              payload: {
                name: 'webchat/join',
                value: { language: window.navigator.language }
              }
            });
          }
          return next(action);
        });
        window.WebChat.renderWebChat({
          directLine: window.WebChat.createDirectLine({ token }),
          store
        }, document.getElementById('webchat'));
        document.querySelector('#webchat > *').focus();
      })().catch(err => console.error(err));
    </script>
    

Is my understanding, right?


30 May 2019 ChaitanyaNG Updates for the Comment: Screenshot: For reference on the findings of using the HTML file provided by Richardson as is and replacing it by my BOT Direct Channel secret key

解决方案

The real issue is in your comment here:

Coming to Webchat it displayed me the following: [File of type 'application/vnd.microsoft.card.oauth']

which is caused by:

<div id="webchat" role="main">
        <iframe src='https://webchat.botframework.com/embed/TestBotForOauthPrompt?s=<<Given my secretkey of web chat channel>>' style='min-width: 400px; width: 100%; min-height: 500px;'></iframe>
    </div>
    <script>
      (async function () {
        // In this demo, we are using Direct Line token from MockBot.
        // To talk to your bot, you should use the token exchanged using your Direct Line secret.
        // You should never put the Direct Line secret in the browser or client app.
        // https://docs.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication
        const res = await fetch('https://testbotforoauthprompt.azurewebsites.net//directline//token', { method: 'POST' });
        const { token } = await res.json();

First issue: You're using both the iframe (<iframe src='https://webchat...) and WebChat (<script> (async function ()...).

Fix: Remove the iframe and just use the WebChat code. This isn't really documented anywhere, but the iFrame uses botchat, which is an older version of WebChat, which doesn't work with OAuth and is what's giving you the [File of type... error.

Second issue: You aren't getting a valid token

const res = await fetch('https://testbotforoauthprompt.azurewebsites.net//directline//token', { method: 'POST' });

That code returns a 404 because https://testbotforoauthprompt.azurewebsites.net/directline/token doesn't exist.

You should follow the guide linked in the code comments, which would have you make a POST request to https://directline.botframework.com/v3/directline/tokens/generate with Authorization: Bearer <YourSecretFromAzurePortal> in the header.

Alternatively, you can use const token = <YourSecretFromAzurePortal> directly, instead. Note that it isn't a good idea to use your secret directly. You should really set up a token server. This should get you started (note: this is the link I intended to use in my comment above), but it's a little more complex. If you just want something simple and don't care if your app secret gets out, go with the const token = <YourSecretFromAzurePortal> method.

I just answered a similar question, here.


Regarding your updates

Token Generator

Regarding: this answer

If you want to keep your Secret private, you need to write your own token server. The first half of the linked answer explains a basic way to do this. You can either write your own, use the sample in that linked answer, or use the code from the blog posts that are linked in that answer.

Where to put the code is dependent on how you want it to run. The sample token server is entirely separate from the bot. The blog post samples show how to integrate it into your bot (although you can also host it separately).

The WebChat client makes a request to that token server, which makes a request to https://directline.botframework.com/v3/directline/tokens/generate and returns the response, which is a valid DirectLine token.

However, in many cases you don't need the extra security of writing your own token server. The second half of the linked answer explains that the security risks of exposing your secret are minimal for many simple bots.

I recommend, for you (since you said you're fairly new to coding), that you don't write your own token server and just leave the secret exposed in const token = <Directline secret from azure portal direct line channel>; (Note that I removed the {}, since your token is a string). If you really want to use a token server, you'll need to learn how to write a server in C#.

HTML File

The code you got from examplebot.azurewebsites... uses Angular (I think). It's old. Don't use it.

You should base your HTML code off of one of the WebChat Samples.

It looks like your last code block does. Since there's been a lot of confusion, just use this:

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <title>Web Chat: Custom style options</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!--
      For demonstration purposes, we are using the development branch of Web Chat at "/master/webchat.js".
      When you are using Web Chat for production, you should use the latest stable release at "/latest/webchat.js",
      or lock down on a specific version with the following format: "/4.1.0/webchat.js".
    -->
    <script src="https://cdn.botframework.com/botframework-webchat/master/webchat.js"></script>
    <style>
        html, body {
            height: 100%
        }

        body {
            margin: 0
        }

        #webchat {
            height: 100%;
            width: 100%;
        }
    </style>
  </head>
  <body>
    <div id="webchat" role="main"></div>
    <script>
      (async function () {
        // In this demo, we are using Direct Line token from MockBot.
        // To talk to your bot, you should use the token exchanged using your Direct Line secret.
        // You should never put the Direct Line secret in the browser or client app.
        // https://docs.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication

        // Token is found by going to Azure Portal > Your Web App Bot > Channels > Web Chat - Edit > Secret Keys - Show
        // It looks something like this: pD*********xI.8ZbgTHof3GL_nM5***********aggt5qLOBrigZ8
        const token = '<Directline secret from azure portal durect line channel>';

        // You can modify the style set by providing a limited set of style options
        const styleOptions = {
            botAvatarImage: 'https://docs.microsoft.com/en-us/azure/bot-service/v4sdk/media/logo_bot.svg?view=azure-bot-service-4.0',
            botAvatarInitials: 'BF',
            userAvatarImage: 'https://avatars1.githubusercontent.com/u/45868722?s=96&v=4',
            userAvatarInitials: 'WC',
            bubbleBackground: 'rgba(0, 0, 255, .1)',
            bubbleFromUserBackground: 'rgba(0, 255, 0, .1)'
        };

        // We are using a customized store to add hooks to connect event
        const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
        if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
            // When we receive DIRECT_LINE/CONNECT_FULFILLED action, we will send an event activity using WEB_CHAT/SEND_EVENT
            dispatch({
            type: 'WEB_CHAT/SEND_EVENT',
            payload: {
                name: 'webchat/join',
                value: { language: window.navigator.language }
            }
            });
        }
        return next(action);
        });

        window.WebChat.renderWebChat({
          directLine: window.WebChat.createDirectLine({ token }),
          styleOptions
        }, document.getElementById('webchat'));

        document.querySelector('#webchat > *').focus();
      })().catch(err => console.error(err));
    </script>
  </body>
</html>

Answering your questions

a. Correct. POST method is not working because there wasn't a token server at the link you were using.

b. Use the code I have above

c. Yes, you can style however you want. Welcome messages should work because of the 'DIRECT_LINE/CONNECT_FULFILLED' code. You can add additional code from the WebChat samples to accomplish other things, yes.

d. Don't use the code that passes "bot" in getElementById. Use the code from the WebChat samples or the code I posted

e. Remove the post method unless you're using a token server.

  1. That's mostly right. See above responses.

  2. Yes. Remove the POST method. Your code was very close!!


Ensure the token you use comes from here:

这篇关于[BotFramework]:有没有办法在C#中使用SDK V4开发的BOT中显示英雄卡或自适应卡中的Oauth提示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆