c# - 如何在自定义网络聊天实现机器人框架中更改用户名/用户 ID
问题描述
我需要在自定义网络聊天控件中动态填充用户名。我知道网络聊天会呈现脚本中存在的用户名,但我该如何更改呢?我什至尝试使用 .NET SDK 从服务器端发送具有不同用户名的活动,但仍然无法实现。
<script>
var user = {
id: 'user-id',
name: 'user name'
};
var botConnection = new BotChat.DirectLine({
token: '[directlinesecret]',
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>
解决方案
我需要在自定义网络聊天控件中动态填充用户名。
我假设您想将Web Chat嵌入您的网站并user: { id: user_id, name: user_name }
根据当前用户(登录用户)动态指定,您可以尝试在用户登录您的网站时将用户信息保留在cookie中,然后您可以检索信息从 cookie 中获取当前用户并发起网络聊天。
例子:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<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>
.wc-chatview-panel {
width: 350px;
height: 500px;
position: relative;
}
</style>
</head>
<body onload="initiatewebchat()">
<div id="chat"></div>
</body>
</html>
<script>
function initiatewebchat() {
var botuser = getCookie("botuser");
if (botuser!=null) {
var userinfo = JSON.parse(botuser);
var botConnection = new BotChat.DirectLine({
secret: '{directline_secret_here}',
});
var user = {
id: userinfo.user_id,
name: userinfo.user_name
};
var bot = {
id: 'fehanbasicbot',
name: 'botname'
};
BotChat.App({
botConnection: botConnection,
user: user,
bot: bot,
}, document.getElementById('chat'));
} else {
alert("do not find user identity for web chat! please login to our website.");
}
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
</script>
测试结果:
笔记:
在上面的测试样本中,我保留"{"user_id":"0001","user_name":"user1"}"
在 cookie 中。
推荐阅读
- java - 如何在java中读取文本文件?
- mysql - Mysql百分比计算
- animation - 如何在 SVG.js 中暂停循环动画?
- vaadin - 带图像的 Vaadin 水平菜单栏
- makefile - Makefile递归安装?
- scala - 使用两个不同目录中的 Header 和 Data 创建 DataFrame / Dataset
- java - 来自 CameraUpdateFactory 的空对象引用导致的致命错误
- c++ - 使用 Clion 编译 SOIL
- qt - 对于基于 qt 的项目,我真的需要一个“./configure”脚本吗?
- python - python脚本在目录和子目录中的文件中搜索字符串