从嵌入式网络聊天发送事件 [英] Sending events from an embedded webchat

查看:94
本文介绍了从嵌入式网络聊天发送事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试发送和接收来自嵌入式网络聊天的事件,该网络聊天遵循此示例中的网站代码 https://github.com/ryanvolum/backChannelBot 和机器人实现了代码来自 Bot框架获取嵌入式聊天控制页面的ServiceUrl 由ezequiel回答



以下是我的设置中的所有内容
index.html

 <!DOCTYPE html> 
<! -
注意:此示例需要一个可以发送和接收特定事件消息的机器人。按照
https://github.com/ryanvolum/backChannelBot上的说明部署这样的机器人。
这是一个示例HTML文件,显示如何嵌入侦听事件活动的WebChat实例。为了
的演示,它专门监听名称为changeBackground的事件。使用backChannelBot示例
我们的页面可以侦听名称为changeBackground的事件并发送名称为buttonClicked的事件。这个
突出了机器人与通过WebChat嵌入机器人的页面进行通信的能力。

1.构建项目:npm run build
2.启动Web服务器:npm run start
3.将浏览器对准http:// localhost:8000 / samples / backchannel?[下面列出的参数]
为了便于测试,可以在查询字符串中设置几个参数:
* s =直线保密,或
* t =直线令牌(通过调用Direct Line的生成令牌获得)
* domain =可选,备用Direct Line端点的URL
* webSocket =设置为'true'以使用WebSocket接收消息(目前默认为false)
*用户ID,用户名= id(以及可选名称)的机器人用户
* botid,botname = id(和可选名称)机器人
- >
< html>

< head>
< meta charset =UTF-8/>
< title> Bot Chat< / title>
< link href =../../ botchat.css =stylesheet/>

< meta name =viewportcontent =width = device-width,initial-scale = 1.0,maximum-scale = 1.0,user-scalable = no/>
< style>
.wc-chatview-panel {
宽度:320px;
身高:500px;
头寸:相对;
}
.h2 {
font-family:Segoe UI;
}
< / style>
< / head>

< body>
< h2 style =font-family:Segoe UI;>在WebChat中键入颜色!< / h2>
< div id =BotChatGoesHereclass =wc-narrow>< / div>
< button onclick =postButtonMessage()style =width:120px; height:60px; padding:20px; margin-left:80px; margin-top:20px;> Click Me!< /按钮>

< script src =../../ botchat.js>< / script>
< script>
var params = BotChat.queryParams(location.search);
var user = {
id:params ['me'] || 'userid',
name:params [tester] || 'username'
};

var bot = {
id:params ['somebot'] || 'botid',
name:params [somebot] || 'botname'
};
window ['botchatDebug'] = params ['debug']&& params ['debug'] ===true;
var botConnection = new BotChat.DirectLine({
secret:params ['mysecret'],
token:params ['t'],
domain:params ['ngroktunneledurl。 com / api / messages'],
webSocket:params ['webSocket']&& params ['webSocket'] ===true//默认为true
});
BotChat.App({
botConnection:botConnection,
用户:user,
bot:bot
},document.getElementById(BotChatGoesHere));
botConnection.activity $
.filter(activity => activity.type ===event&& activity.name ===changeBackground)
.subscribe(activity => changeBackgroundColor(activity.value))
const changeBackgroundColor =(newColor)=> {
document.body.style.backgroundColor = newColor;
}
const postButtonMessage =()=> {
botConnection
.postActivity({type:event,value:,from:{id:me},name:buttonClicked})
.subscribe(id => console.log(成功));
}
< / script>
< / body>

< / html>

和bot文件
MessagesController.cs

 使用System; 
使用System.Linq;
使用System.Net;
使用System.Net.Http;
使用System.Threading.Tasks;
使用System.Web.Http;
使用Microsoft.Bot.Builder.Dialogs;
使用Microsoft.Bot.Connector;
使用Kaseya_AI_Kbot.LuisDialog;

[BotAuthentication]
公共类MessagesController:ApiController
{
public async Task< HttpResponseMessage>发布([FromBody]活动活动)
{
if(activity.Type == ActivityTypes.Event&&
string.Equals(activity.Name,buttonClicked,StringComparison.InvariantCultureIgnoreCase ))
{
ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

//返回我们对用户的回复
活动回复= activity.CreateReply(我看到你刚按下那个按钮);
await connector.Conversations.ReplyToActivityAsync(reply);
}

if(activity.Type == ActivityTypes.Message)
{
ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

//返回我们对用户的回复
var reply = activity.CreateReply();
reply.Type = ActivityTypes.Event;
reply.Name =changeBackground;
reply.Value = activity.Text;
await connector.Conversations.ReplyToActivityAsync(reply);
}
其他
{
HandleSystemMessage(活动);
}
var response = Request.CreateResponse(HttpStatusCode.OK);
返回回复;
}

私有异步任务HandleSystemMessage(活动消息)
{
if(message.Type == ActivityTypes.DeleteUserData)
{
//在这里实现用户删除
//如果我们处理用户删除,则返回真实消息
}
else if(message.Type == ActivityTypes.ConversationUpdate)
{
if(message.MembersAdded.Any(o => o.Id == message.Recipient.Id))
{
ConnectorClient client = new ConnectorClient(new Uri(message.ServiceUrl));

var reply = message.CreateReply();

reply.Text =欢迎来到机器人!;

await client.Conversations.ReplyToActivityAsync(reply);
}
}
else if(message.Type == ActivityTypes.ContactRelationUpdate)
{
//处理联系人列表中的添加/删除
// Activity.From + Activity.Action代表发生了什么
}
else if(message.Type == ActivityTypes.Typing)
{
//知道用户输入$的句柄b $ b}
else if(message.Type == ActivityTypes.Ping)
{
}
}

public async Task< HttpResponseMessage>发布([FromBody]活动活动)
{
if(activity.Type == ActivityTypes.Event&&
string.Equals(activity.Name,buttonClicked,StringComparison.InvariantCultureIgnoreCase ))
{
ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

//返回我们对用户的回复
活动回复= activity.CreateReply(我看到你刚按下那个按钮);
await connector.Conversations.ReplyToActivityAsync(reply);
}

if(activity.Type == ActivityTypes.Message)
{
ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

//返回我们对用户的回复
var reply = activity.CreateReply();
reply.Type = ActivityTypes.Event;
reply.Name =changeBackground;
reply.Value = activity.Text;
await connector.Conversations.ReplyToActivityAsync(reply);
}
其他
{
HandleSystemMessage(活动);
}
var response = Request.CreateResponse(HttpStatusCode.OK);
返回回复;
}
}

}



我已经测试了发送消息活动的工作正常,但是在收到消息后尝试从机器人发送到网页或从网页发送到机器人没有做任何事情。



网页上说BotChat没有定义,但我不确定为什么

  var params = BotChat.queryParams(location.search); 

  var botConnection = new BotChat.DirectLine({

in index.html



我的所有应用机密/身份和直接线密码都已添加。我觉得问题可能是我在index.html中添加我的秘密和网址但我不确定我将如何设置它

解决方案

我重新创建了你的项目并将其发布到Azure: http://QuickBackChannelEventTest.AzureWebsites.net/index.html



<我在 GitHub 上发布了代码。您需要在网络中更改MicrosoftAppId和MicrosoftAppPassword .config,并将你的机器人的 Direct Line 秘密添加到index.html页面的BotChat.DirectLine创建中:

  var b otConnection = new BotChat.DirectLine({
secret:'** DIRECT_LINE_SECRET **',// params ['mysecret'],
// token:params ['t'],
// domain:params ['ngroktunneledurl.com/api/messages'],
webSocket:params ['webSocket']&& params ['webSocket'] ===true//默认为true
});

我还添加了一个名为TestStandAlone的文件夹,其中只包含Index.html,botchat.css和botchat.js : https://github.com/EricDahlvang/BackChannelEventTest/tree/master/TestStandalone一旦设置了机器人的直线密码,这将按预期工作。


I'm trying to send and receive events from an embedded webchat which follows the code for the website from this example https://github.com/ryanvolum/backChannelBot and the bot implements the code from Bot framework get the ServiceUrl of embedded chat control page answered by ezequiel

Here's how it all looks in my setup index.html

<!DOCTYPE html>
<!-- 
NOTE: This sample requires a bot which can send and receive specific event messages. Follow the instructions on 
https://github.com/ryanvolum/backChannelBot to deploy such a bot. 
This is a sample HTML file which shows how to embed an instance of WebChat which listens for event activities. For the sake
of demonstration it specifically listens for events of name "changeBackground". Using the backChannelBot sample 
our page can listen for events of name "changeBackground" and send events of name "buttonClicked". This 
highlights the ability for a bot to communicate with a page that embeds the bot through WebChat. 

1. Build the project: "npm run build"
2. Start a web server: "npm run start"
3. Aim your browser at "http://localhost:8000/samples/backchannel?[parameters as listed below]"
For ease of testing, several parameters can be set in the query string:
    * s = Direct Line secret, or
    * t = Direct Line token (obtained by calling Direct Line's Generate Token)
    * domain = optionally, the URL of an alternate Direct Line endpoint
    * webSocket = set to 'true' to use WebSocket to receive messages (currently defaults to false)
    * userid, username = id (and optionally name) of bot user
    * botid, botname = id (and optionally name) of bot
-->
<html>

<head>
    <meta charset="UTF-8" />
    <title>Bot Chat</title>
    <link href="../../botchat.css" rel="stylesheet" />

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <style>
        .wc-chatview-panel {
            width: 320px;
            height: 500px;
            position: relative;
        }
        .h2{
            font-family: Segoe UI;
        }
    </style>
</head>

<body>
    <h2 style="font-family:Segoe UI;">Type a color into the WebChat!</h2>
    <div id="BotChatGoesHere" class="wc-narrow"></div>
    <button onclick="postButtonMessage()" style="width:120px;height:60px;padding:20px;margin-left:80px;margin-top:20px;">Click Me!</button>

    <script src="../../botchat.js"></script>
    <script>
            var params = BotChat.queryParams(location.search);
            var user = {
                id: params['me'] || 'userid',
                name: params["tester"] || 'username'
                };

            var bot = {
                id: params['somebot'] || 'botid',
                name: params["somebot"] || 'botname'
            };
            window['botchatDebug'] = params['debug'] && params['debug'] === "true";
            var botConnection = new BotChat.DirectLine({
                secret: params['mysecret'],
                token: params['t'],
                domain: params['ngroktunneledurl.com/api/messages'],
                webSocket: params['webSocket'] && params['webSocket'] === "true" // defaults to true
            });
            BotChat.App({
                botConnection: botConnection,
                user: user,
                bot: bot
            }, document.getElementById("BotChatGoesHere"));
            botConnection.activity$
                .filter(activity => activity.type === "event" && activity.name === "changeBackground")
                .subscribe(activity => changeBackgroundColor(activity.value))
            const changeBackgroundColor = (newColor) => {
                document.body.style.backgroundColor = newColor;
            }
            const postButtonMessage = () => {
                botConnection
                    .postActivity({type: "event", value: "", from: {id: "me" }, name: "buttonClicked"})
                    .subscribe(id => console.log("success"));
            }
        </script>
</body>

</html>

And the bot file MessagesController.cs

using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;
using Kaseya_AI_Kbot.LuisDialog;

[BotAuthentication]
public class MessagesController : ApiController
{
   public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
    {
        if (activity.Type == ActivityTypes.Event &&
            string.Equals(activity.Name, "buttonClicked", StringComparison.InvariantCultureIgnoreCase))
        {
            ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

            // return our reply to the user
            Activity reply = activity.CreateReply("I see that you just pushed that button");
            await connector.Conversations.ReplyToActivityAsync(reply);
        }

        if (activity.Type == ActivityTypes.Message)
        {
            ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

            // return our reply to the user
            var reply = activity.CreateReply();
            reply.Type = ActivityTypes.Event;
            reply.Name = "changeBackground";
            reply.Value = activity.Text;
            await connector.Conversations.ReplyToActivityAsync(reply);
        }
        else
        {
            HandleSystemMessage(activity);
        }
        var response = Request.CreateResponse(HttpStatusCode.OK);
        return response;
    }

    private async Task HandleSystemMessage(Activity 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)
        {
            if (message.MembersAdded.Any(o => o.Id == message.Recipient.Id))
            {
                ConnectorClient client = new ConnectorClient(new Uri(message.ServiceUrl));

                var reply = message.CreateReply();

                reply.Text = "Welcome to the bot!";

                await client.Conversations.ReplyToActivityAsync(reply);
            }
        }
        else if (message.Type == ActivityTypes.ContactRelationUpdate)
        {
            // Handle add/remove from contact lists
            // Activity.From + Activity.Action represent what happened
        }
        else if (message.Type == ActivityTypes.Typing)
        {
            // Handle knowing tha the user is typing
        }
        else if (message.Type == ActivityTypes.Ping)
        {
        }
    }

    public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
    {
        if (activity.Type == ActivityTypes.Event &&
            string.Equals(activity.Name, "buttonClicked", StringComparison.InvariantCultureIgnoreCase))
        {
            ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

            // return our reply to the user
            Activity reply = activity.CreateReply("I see that you just pushed that button");
            await connector.Conversations.ReplyToActivityAsync(reply);
        }

        if (activity.Type == ActivityTypes.Message)
        {
            ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

            // return our reply to the user
            var reply = activity.CreateReply();
            reply.Type = ActivityTypes.Event;
            reply.Name = "changeBackground";
            reply.Value = activity.Text;
            await connector.Conversations.ReplyToActivityAsync(reply);
        }
        else
        {
            HandleSystemMessage(activity);
        }
        var response = Request.CreateResponse(HttpStatusCode.OK);
        return response;
    }
}

}

I've tested sending message activities which works fine, however trying to send an event from the bot to the webpage or from the webpage to the bot after receiving a message doesn't do anything.

The webpage says that BotChat is not defined at both but I'm not sure why

var params = BotChat.queryParams(location.search);

and

var botConnection = new BotChat.DirectLine({

in index.html

All of my app secrets/id and directline secret are added. I feel like the problem might be how I'm adding my secret and url in index.html but I'm not sure how I would set it all up

解决方案

I re-created your project and published it to Azure: http://QuickBackChannelEventTest.AzureWebsites.net/index.html

I posted the code on GitHub. You'll need to change the MicrosoftAppId and MicrosoftAppPassword in the web.config, and add your bot's Direct Line secret to the index.html page's BotChat.DirectLine creation:

var botConnection = new BotChat.DirectLine({
            secret: '**DIRECT_LINE_SECRET**',//params['mysecret'],
            //token: params['t'],
            //domain: params['ngroktunneledurl.com/api/messages'],
            webSocket: params['webSocket'] && params['webSocket'] === "true" // defaults to true
    });

I also added a folder called TestStandAlone that contains only Index.html, botchat.css and botchat.js: https://github.com/EricDahlvang/BackChannelEventTest/tree/master/TestStandalone This works as expected once the the Direct Line secret for the bot is set.

这篇关于从嵌入式网络聊天发送事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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