首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >欢迎卡与直线通道集成时不会自动弹出。

欢迎卡与直线通道集成时不会自动弹出。
EN

Stack Overflow用户
提问于 2019-12-10 09:40:14
回答 2查看 221关注 0票数 0

我使用bot框架v4 c#在本地创建了一个bot。它有一个欢迎卡,自动弹出,当我连接我的本地网址与仿真器,但最近我部署了我的机器人在蔚蓝和整合它使用我的网站直线式通道。现在,每当我点击,它打开了机器人,但欢迎卡不是自己来的,当我从我的聊天机器人写东西时,它就出现了。我只想让欢迎卡自动在模拟器中显示出来。伙计们你们能帮帮我吗?下面是我在我的网站中集成的直线式代码。

代码语言:javascript
运行
复制
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<!-- Paste line 7 to 27 after the title tag in _Layout.cshtml -->
<link href="https://cdn.botframework.com/botframework-webchat/latest/botchat.css" rel="stylesheet" 
/>
<script src="https://cdn.botframework.com/botframework-webchat/latest/botchat.js"></script>
<style>
    #mychat {
        margin: 10px;
        position: fixed;
        bottom: 30px;
        left: 10px;
        z-index: 1000000;
    }

    .botIcon {
        float: left !important;
        border-radius: 50%;
    }

    .userIcon {
        float: right !important;
        border-radius: 50%;
    }
</style>
</head>
< body>
<!-- Paste line from 31 to 33 before the </body> tag at the end of code -->
<div id="container">
    <img id="mychat" src=""/>
</div>
</body>

代码语言:javascript
运行
复制
<!-- Paste line 38 to 88 after the </html> tag -->
<script>
(function () {
    var div = document.createElement("div");

    var user = {
                id: "",
                name: ''
            };

    var bot = {
                id: '',
                name: 'SaathiBot'
            };

    const botConnection = new BotChat.DirectLine({

                secret: '',

                webSocket: false 
            })        

    document.getElementsByTagName('body')[0].appendChild(div);

    div.outerHTML = "<div id='botDiv' style='width: 400px; height: 0px; margin:10px; position: 
fixed; bottom: 0; left:0; z-index: 1000;><div  id='botTitleBar' style='height: 40px; width: 400px; 

位置:固定;光标:指针;cursor>“;

代码语言:javascript
运行
复制
    BotChat.App({
                botConnection: botConnection, 
                user: user,
                bot: bot 
            }, document.getElementById("botDiv"));

    document.getElementsByClassName("wc-header")[0].setAttribute("id", "chatbotheader");
    document.querySelector('body').addEventListener('click', function (e) {
        e.target.matches = e.target.matches || e.target.msMatchesSelector;
        if (e.target.matches('#chatbotheader')) {
            var botDiv = document.querySelector('#botDiv');

            botDiv.style.height = "0px";

            document.getElementById("mychat").style.display = "block";
        };
    });

    document.getElementById("mychat").addEventListener("click", function (e) {

        document.getElementById("botDiv").style.height = '500px';

        e.target.style.display = "none";
    })
    }());
 </script>

这里还有我在c#中的欢迎卡代码

代码语言:javascript
运行
复制
namespace Microsoft.BotBuilderSamples
{
public class WelcomeUser : SaathiDialogBot<MainDialog>
{

    protected readonly string[] _cards =
    {
        Path.Combine(".", "Resources", "WelcomeCard.json"),

    };

    public WelcomeUser(ConversationState conversationState, UserState userState, MainDialog dialog, ILogger<SaathiDialogBot<MainDialog>> logger)
        : base(conversationState, userState, dialog, logger)
    {
    }

    protected override async Task OnMembersAddedAsync(IList<ChannelAccount> membersAdded, ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
    {
        await SendWelcomeMessageAsync(turnContext, cancellationToken);
        Random r = new Random();
        var cardAttachment = CreateAdaptiveCardAttachment(_cards[r.Next(_cards.Length)]);
        await turnContext.SendActivityAsync(MessageFactory.Attachment(cardAttachment), cancellationToken);
    }


    private static async Task SendWelcomeMessageAsync(ITurnContext turnContext, CancellationToken cancellationToken)
    {
        foreach (var member in turnContext.Activity.MembersAdded)
        {
            if (member.Id != turnContext.Activity.Recipient.Id)
            {

                if (DateTime.Now.Hour < 12)
                {

                    await turnContext.SendActivityAsync(
                        $"Hi,Good Morning {member.Name}",
                        cancellationToken: cancellationToken);

                }
                else if (DateTime.Now.Hour < 17)
                {

                    await turnContext.SendActivityAsync(
                        $"Hi,Good Afternoon {member.Name}",
                        cancellationToken: cancellationToken);
                }
                else
                {

                    await turnContext.SendActivityAsync(
                        $"Hi,Good Evening {member.Name}",
                        cancellationToken: cancellationToken);


                }
            }
        }

    }
    private static Attachment CreateAdaptiveCardAttachment(string filePath)
    {
        var adaptiveCardJson = File.ReadAllText(filePath);
        var adaptiveCardAttachment = new Attachment()
        {
            ContentType = "application/vnd.microsoft.card.adaptive",
            Content = JsonConvert.DeserializeObject(adaptiveCardJson),
        };
        return adaptiveCardAttachment;
    }
    }
}

这里是在欢迎卡中继承的saathiDialog代码。这是我的bot文件夹中的两个文件

代码语言:javascript
运行
复制
public class SaathiDialogBot<T> : ActivityHandler where T : Dialog
{
    protected readonly BotState ConversationState;
    protected readonly Dialog Dialog;
    protected readonly ILogger Logger;
    protected readonly BotState UserState;
    private DialogSet Dialogs { get; set; }

    public SaathiDialogBot(ConversationState conversationState, UserState userState, T dialog, ILogger<SaathiDialogBot<T>> logger)
    {
        ConversationState = conversationState;
        UserState = userState;
        Dialog = dialog;
        Logger = logger;
    }

    public override async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
    {
        var activity = turnContext.Activity;

        if (string.IsNullOrWhiteSpace(activity.Text) && activity.Value != null)
        {
            activity.Text = JsonConvert.SerializeObject(activity.Value);
        }
        if (turnContext.Activity.Text == "Yes")
        {

            await turnContext.SendActivityAsync($"Good bye. I will be here if you need me. ", cancellationToken: cancellationToken);
            await turnContext.SendActivityAsync($"Say Hi to wake me up.", cancellationToken: cancellationToken);
        }
        else
        {
            await base.OnTurnAsync(turnContext, cancellationToken);
        }
        await ConversationState.SaveChangesAsync(turnContext, false, cancellationToken);
        await UserState.SaveChangesAsync(turnContext, false, cancellationToken);
    }

    protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            Logger.LogInformation("Running dialog with Message Activity.");
            await Dialog.RunAsync(turnContext, ConversationState.CreateProperty<DialogState>(nameof(DialogState)), cancellationToken);
        }

 }
}
here is main Dialog code

命名空间Microsoft.BotBuilderSamples { public class MainDialog : ComponentDialog {私有const string UserInfo = "value-userInfo";受保护的只读ILogger _logger;受保护的只读string[] _cards ={ Path.Combine(".","Resources","ValidationCard.json"),};public MainDialog(ILogger记录器):base(nameof(MainDialog)) { _logger = logger;AddDialog(新的Path.Combine)新ProductIssue($"{nameof(Confirm)}.fromConfirm"));AddDialog(新ProductIssue($"{ nameof(决议)}.resolution“);AddDialog(新确认();AddDialog(${nameof(MainDialog)}.issue));AddDialog(new NumberPrompt(${nameof(MainDialog)}.num,valinatiotionAsync));新WaterfallDialog($"{nameof(MainDialog)}.mainFlow",新WaterfallStep[]

代码语言:javascript
运行
复制
            {
            MoblieNumberAsync,
            ChoiceCardStepAsync,
            ShowCardStepAsync,
            CallingDialogsAsync
          }));
        AddDialog(new TextPrompt(nameof(TextPrompt)));

        InitialDialogId = $"{nameof(MainDialog)}.mainFlow";

    }

    private async Task<DialogTurnResult> MoblieNumberAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
    {
        stepContext.Values[UserInfo] = new UserInput();
        var options = new PromptOptions()
        {

            Prompt = MessageFactory.Text("Kindly enter your 10 digit mobile number without any spaces, dashes and country code. We will be sending an OTP later to this number "),
            RetryPrompt = MessageFactory.Text("Incorrect mobile number entered. Please only enter the 10 digits of your mobile without any spaces, dashes and country code.")

        };

        return await stepContext.PromptAsync($"{nameof(MainDialog)}.num", options, cancellationToken);
    }

    private async Task<DialogTurnResult> ChoiceCardStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
    {
        BotAPIBLL botApiBLL = new BotAPIBLL();

        var response =   botApiBLL.GetCustomerDetail(stepContext.Context.Activity.Text);

        await stepContext.Context.SendActivityAsync(MessageFactory.Text("Fetching your details from our systems. This may take a moment"), cancellationToken);
        var options = new PromptOptions()
        {

            Prompt = MessageFactory.Text("Welcome user, How can we serve you ? "),
            RetryPrompt = MessageFactory.Text("That was not a valid choice, please select a option between 1 to 4."),
            Choices = GetChoices(),
        };

        return await stepContext.PromptAsync($"{nameof(MainDialog)}.issue", options, cancellationToken);
    }

    private async Task<DialogTurnResult> ShowCardStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
    {
        var attachments = new List<Attachment>();
        var reply = MessageFactory.Text("");
        var user_choice = ((FoundChoice)stepContext.Result).Value;
        switch (user_choice)
        {
            case "Product issue":
                reply.Attachments.Add(Cards.CreateAdaptiveCardAttachment3());
                break;

            case "Register Product":

                reply.Attachments.Add(Cards.GetHeroCard1().ToAttachment());
                break;
            case "Online Purchase":

                reply.Attachments.Add(Cards.GetHeroCard2().ToAttachment());
                break;
            case "Customer Grivance":

                reply.Attachments.Add(Cards.GetHeroCard3().ToAttachment());
                break;

            default:
                reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                reply.Attachments.Add(Cards.CreateAdaptiveCardAttachment3());
                reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                reply.Attachments.Add(Cards.GetHeroCard1().ToAttachment());
                break;
        }
        if (user_choice == "Register Product" || user_choice == "Online Purchase" || user_choice == "Customer Grivance")
        {
            await stepContext.Context.SendActivityAsync(reply, cancellationToken);
            Random r = new Random();
            var validationcard = Cards.CreateAdaptiveCardAttachment2(_cards[r.Next(_cards.Length)]);
            await stepContext.Context.SendActivityAsync(MessageFactory.Attachment(validationcard), cancellationToken);
            return await stepContext.EndDialogAsync(null, cancellationToken);
        }
        else
        {
            var options2 = new PromptOptions() { Prompt = reply, RetryPrompt = MessageFactory.Text("Retry") };
            return await stepContext.PromptAsync($"{nameof(MainDialog)}.callDialog", options2, cancellationToken);
        }
    }

    private async Task<DialogTurnResult> CallingDialogsAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
    {
        string choice = stepContext.Result.ToString();
        if (choice.ToLower() == "no")
        {
            return await stepContext.BeginDialogAsync($"{nameof(MainDialog)}.fromMain", null, cancellationToken);

        }
        else
            return await stepContext.BeginDialogAsync(nameof(Confirm), null, cancellationToken);
    }

    private IList<Choice> GetChoices()
    {
        var cardOptions = new List<Choice>()
            {

                new Choice() { Value = "Product issue", Synonyms = new List<string>() { "adaptive" } },
                new Choice() { Value = "Register Product", Synonyms = new List<string>() { "hero" } },
                new Choice() { Value = "Online Purchase", Synonyms = new List<string>() { "hero" } },
                new Choice() { Value = "Customer Grivance", Synonyms = new List<string>() { "hero" } },
            };

        return cardOptions;
    }

    private Task<bool> valinatiotionAsync(PromptValidatorContext<int> promptContext, CancellationToken cancellationToken)
    {
        string value = (string)promptContext.Context.Activity.Text;
        if (Regex.IsMatch(value, "^[0-9]{10}$"))
        {
            return Task.FromResult(true);
        }
        else
        {
            return Task.FromResult(false);
        }
    }




}
}
EN

Stack Overflow用户

发布于 2019-12-10 10:09:53

您必须使用ConversationUpdate事件ActivityTypes.ConversationUpdate

这是开关语句中的一个示例,我在其中检查我得到的不同的ActivityTypes,conversationUpdate用于显示欢迎消息。

代码语言:javascript
运行
复制
       case ActivityTypes.ConversationUpdate:
                        {
                            if (activity.MembersAdded?.Count > 0)
                            {
                              await innerDc.BeginDialogAsync(nameof(dialog));  
                            }

                            break;
                        }

更新

查看这个工作示例,并解释如何从欢迎讯息事件发送WebChat。

票数 1
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59264217

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档