从嵌入式网络聊天发送事件
Sending events from an embedded webchat
我正在尝试从嵌入式网络聊天发送和接收事件,该网络聊天遵循此示例中网站的代码 https://github.com/ryanvolum/backChannelBot and the bot implements the code from 由 ezequiel 回答
这是我的设置中的样子
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>
和机器人文件
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;
}
}
}
我已经测试了发送消息活动,效果很好,但是在收到消息后尝试将事件从 bot 发送到网页或从网页发送到 bot 没有做任何事情。
网页上说 BotChat 在这两个地方都没有定义,但我不确定为什么
var params = BotChat.queryParams(location.search);
和
var botConnection = new BotChat.DirectLine({
在index.html
我所有的应用程序 secrets/id 和直线密码都已添加。我觉得问题可能出在我如何在 index.html 中添加我的秘密和 url 但我不确定我将如何设置它
我重新创建了你的项目并将其发布到 Azure:http://QuickBackChannelEventTest.AzureWebsites.net/index.html
我在 GitHub 上发布了代码。您需要更改 web.config 中的 MicrosoftAppId 和 MicrosoftAppPassword,并将机器人的 Direct Line
密码添加到 index.html 页面的 BotChat.DirectLine 创建:
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
});
我还添加了一个名为 TestStandAlone 的文件夹,该文件夹仅包含 Index.html、botchat.css 和 botchat.js:https://github.com/EricDahlvang/BackChannelEventTest/tree/master/TestStandalone 一旦 Direct Line 密码为机器人已设置。
我正在尝试从嵌入式网络聊天发送和接收事件,该网络聊天遵循此示例中网站的代码 https://github.com/ryanvolum/backChannelBot and the bot implements the code from
这是我的设置中的样子 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>
和机器人文件 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;
}
}
}
我已经测试了发送消息活动,效果很好,但是在收到消息后尝试将事件从 bot 发送到网页或从网页发送到 bot 没有做任何事情。
网页上说 BotChat 在这两个地方都没有定义,但我不确定为什么
var params = BotChat.queryParams(location.search);
和
var botConnection = new BotChat.DirectLine({
在index.html
我所有的应用程序 secrets/id 和直线密码都已添加。我觉得问题可能出在我如何在 index.html 中添加我的秘密和 url 但我不确定我将如何设置它
我重新创建了你的项目并将其发布到 Azure:http://QuickBackChannelEventTest.AzureWebsites.net/index.html
我在 GitHub 上发布了代码。您需要更改 web.config 中的 MicrosoftAppId 和 MicrosoftAppPassword,并将机器人的 Direct Line
密码添加到 index.html 页面的 BotChat.DirectLine 创建:
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
});
我还添加了一个名为 TestStandAlone 的文件夹,该文件夹仅包含 Index.html、botchat.css 和 botchat.js:https://github.com/EricDahlvang/BackChannelEventTest/tree/master/TestStandalone 一旦 Direct Line 密码为机器人已设置。