Bot不能直接在直接行中发送欢迎消息

问题描述 投票:0回答:2

我已经使用bot框架v4 c#在本地创建了一个bot。它有一个欢迎卡,当我将本地URL与模拟器连接后,该卡会自动弹出,但是最近我将我的机器人部署在Azure上,并使用直接通道将其集成到我的网站中。现在,每当我单击时,它都会打开该机器人,但是欢迎卡并不会自动出现,当我从聊天机器人中写一些东西时,它就会出现。我只希望欢迎卡自动出现在模拟器中。你们可以帮我吗?下面是我正在网站中集成的直线代码。

<!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>

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

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

    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#中的欢迎卡代码

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文件夹中的两个文件

namespace Microsoft.BotBuilderSamples
{
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);
        }

 }
}
javascript c# asp.net-mvc botframework direct-line-botframework
2个回答
0
投票

发送自定义事件活动。

有关更多信息,请检查此link


0
投票

[如果您使用的是WebChat或Directline,则在创建会话时会发送漫游器的ConversationUpdate,而在用户第一次发送消息时会发送用户端的ConversationUpdate。最初发送ConversationUpdate时,消息中没有足够的信息来构造对话框堆栈。之所以在模拟器中似乎起作用,是因为该模拟器模拟了一种伪DirectLine,但是两个对话更新都在模拟器中同时得到解决,而实际服务的执行情况并非如此。

代替使用ConversationUpdate,您可以在客户端代码中发布事件活动(用于Web聊天的嵌入式HTML),然后用欢迎消息响应事件。

  • 在嵌入式HTML中发布用于Web聊天的事件活动(客户端代码)。这里的.postActivity调用具有'event'类型的属性。
<!DOCTYPE html>
<html>
<head>
    <link href="https://cdn.botframework.com/botframework-webchat/latest/botchat.css" rel="stylesheet" />
</head>
<body>
    <div>
        <div id="bot" />
    </div>
    <script src="https://cdn.botframework.com/botframework-webchat/latest/botchat.js"></script>
    <script>
        var user = {
            id: 'user-id',
            name: 'user name'
        };
        var botConnection = new BotChat.DirectLine({
            token: '[DirectLineSecretHere]',
            user: user
        });
        BotChat.App({
            user: user,
            botConnection: botConnection,
            bot: { id: 'bot-id', name: 'bot name' },
            resize: 'detect'
        }, document.getElementById("bot"));
        botConnection
            .postActivity({
                from: user,
                name: 'requestWelcomeDialog',
                type: 'event',
                value: ''
            })
            .subscribe(function (id) {
                console.log('"trigger requestWelcomeDialog" sent');
            });
    </script>
</body>
</html>
  • 用机器人代码中的所需欢迎消息响应事件。
private async Task HandleSystemMessage(Activity message)
{
    await TelemetryLogger.TrackActivity(message);
    if (message.Type == ActivityTypes.DeleteUserData)
    {
        // Implement user deletion here
        // If we handle user deletion, return a real message
    }
    else if (message.Type == ActivityTypes.ConversationUpdate)
    {
    }
    else if (message.Type == ActivityTypes.ContactRelationUpdate)
    {
    }
    else if (message.Type == ActivityTypes.Typing)
    {
        // Handle knowing that the user is typing
    }
    else if (message.Type == ActivityTypes.Ping)
    {
    }
    else if (message.Type == ActivityTypes.Event)
    {
        var eventActivity = message.AsEventActivity();
        if (eventActivity.Name == "setUserIdEvent")
        {
            ConnectorClient connector = new ConnectorClient(new Uri(message.ServiceUrl));
            var userId = message.From.Id;
            var welcomeMessages = GreetingHelper.FormatWelcomeMessages(userProfile);
            foreach (var welcomeMessage in welcomeMessages)
            {
                var reply = message.CreateReply(welcomeMessage);
                await connector.Conversations.ReplyToActivityAsync(reply);
            }
        }
    }
}

希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.