gpt4 book ai didi

c# - 在 v4 Bot Framework Bot(C# + .Net Core Web 应用程序)中显示欢迎消息

转载 作者:行者123 更新时间:2023-12-03 18:32:54 29 4
gpt4 key购买 nike

我使用 v3 (C#) SDK 创建了一个机器人,欢迎消息过去工作得很好,没有任何问题。它在生产中仍然对我有用。代码在 HandleSystemMessage 中是这样处理的——

.. v3 Code 为清楚起见删除了额外的代码...

else if (message.Type == ActivityTypes.ConversationUpdate)
{
// Handle conversation state changes, like members being added and removed
// Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
// Not available in all channels

//Code to show Welcome Message
if (message.MembersAdded.Any(o => o.Id == message.Recipient.Id))
{
var reply = message.CreateReply();
reply.Attachments = new List<Attachment>();
// Create the attachment.
Attachment attachment = new Attachment()
{
ContentType = AdaptiveCard.ContentType,
Content = AdaptiveCardHelper.GetOptionsCard()
};
reply.Attachments.Add(attachment);
ConnectorClient connector = new ConnectorClient(new Uri(message.ServiceUrl));
await connector.Conversations.ReplyToActivityAsync(reply);
}
}

我使用的 Web Chat 版本是 BotFramework-WebChat-0.11.4,我在其中做了一些定制以实现带有评论的 facebook Like/Unlike 功能。

现在我正在将机器人迁移到 v4 SDK(C# + .Net Core Web App),并且我打算使用相同的旧版本的网络聊天。但是我苦苦挣扎了两天才能在同一个网络聊天中显示一条欢迎消息,同时它在模拟器(给那两个 ConversationUpdate)事件上运行良好。

我已尝试使用本文提供的解决方案发送消息和事件,并尝试在 Bot 中使用不同的异步方法 OnEventAsync、OnEventActivityAsync、OnMessageActivityAsync 捕获它。

https://blog.botframework.com/2018/07/12/how-to-properly-send-a-greeting-message-and-common-issues-from-customers/

V4 代码如下所示:

 protected override async Task OnConversationUpdateActivityAsync(ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
{
if (turnContext.Activity.MembersAdded != null)
{
if (turnContext.Activity.MembersAdded.Any(m => m.Id != turnContext.Activity.Recipient?.Id))
{
//var welcomeCard = CreateAdaptiveCardAttachment();
//var response = CreateResponse(turnContext.Activity, welcomeCard);
//await turnContext.SendActivityAsync(response, cancellationToken);

await Utility.LogTraceAsync("Inside OnConversationUpdateActivityAsync");

var eventActivity = turnContext.Activity.AsConversationUpdateActivity();

ConnectorClient connector = new ConnectorClient(new Uri(eventActivity.ServiceUrl), Configuration.MicrosoftAppId, Configuration.MicrosoftAppPassword);

await Utility.LogTraceAsync("Service URL OnConversationUpdateActivityAsync" + eventActivity.ServiceUrl);

await Utility.LogTraceAsync("Recipient ID OnConversationUpdateActivityAsync" + turnContext.Activity.Recipient?.Id);

var welcomeCard = CreateAdaptiveCardAttachment();

var reply = ((Activity)eventActivity).CreateReply();
reply.Attachments.Add(welcomeCard);

//var response = CreateResponse(turnContext.Activity, welcomeCard);
await connector.Conversations.ReplyToActivityAsync(reply, cancellationToken);// turnContext.SendActivityAsync(response, cancellationToken);

await Utility.LogTraceAsync("OnConversationUpdateActivityAsync Response Returned.");

await Utility.LogTraceAsync("Exit OnConversationUpdateActivityAsync");
}
}
}

protected override async Task OnEventActivityAsync(ITurnContext<IEventActivity> turnContext, CancellationToken cancellationToken)
{
await Utility.LogTraceAsync("Inside OnEventActivityAsync");
if (turnContext.Activity.Type == ActivityTypes.Event)
{
var eventActivity = turnContext.Activity.AsEventActivity();

await Utility.LogTraceAsync("Event Activity from WebChat matched.");

ConnectorClient connector = new ConnectorClient(new Uri(eventActivity.ServiceUrl), Configuration.MicrosoftAppId, Configuration.MicrosoftAppPassword);

await Utility.LogTraceAsync("Service URL " + eventActivity.ServiceUrl);

var welcomeCard = CreateAdaptiveCardAttachment();

var reply = ((Activity)eventActivity).CreateReply();
reply.Attachments.Add(welcomeCard);

var members = await connector.Conversations.GetConversationMembersAsync(eventActivity.Conversation.Id.ToString());
var membernames = "";
foreach (var member in members) {
membernames += member.Name + ",";
}

await Utility.LogTraceAsync(membernames);

await connector.Conversations.SendToConversationAsync(reply, cancellationToken);

await connector.Conversations.ReplyToActivityAsync(reply, cancellationToken);// turnContext.SendActivityAsync(response, cancellationToken);

await Utility.LogTraceAsync("Event Response Returned.");
}

await Utility.LogTraceAsync("Exit OnEventActivityAsync");
}

但是好像一点作用都没有。我很紧张,不知道如何为 .Net Core App 做事。我很高兴知道是否有人解决了这个问题。

更新 - 我在客户端使用了@tdurnford 提供的 JS 代码,在 Bot 端使用了以下两种方法 -

//Required to Show Welcome Message on Emulator
protected override async Task OnMembersAddedAsync(IList<ChannelAccount> membersAdded, ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
{
foreach (var member in membersAdded ?? Array.Empty<ChannelAccount>())
{
// Greet anyone that was not the target (recipient) of this message.
// To learn more about Adaptive Cards, see https://aka.ms/msbot-adaptivecards for more details.
if (member.Id != turnContext.Activity.Recipient.Id)
{
Activity reply = ((Activity)turnContext.Activity).CreateReply();
AdaptiveCard card = AdaptiveCardHelper.GetWelcomeCard();
Attachment attachment = new Attachment()
{
ContentType = AdaptiveCard.ContentType,
Content = card
};
reply.Attachments.Add(attachment);
await turnContext.SendActivityAsync(reply, cancellationToken);
}
}
}

//Required to Show Welcome Message on Web Chat
protected override async Task OnEventActivityAsync(ITurnContext<IEventActivity> turnContext, CancellationToken cancellationToken)
{
if (turnContext.Activity.Name == "webchat/join")
{
Activity reply = ((Activity)turnContext.Activity).CreateReply();
AdaptiveCard card = AdaptiveCardHelper.GetWelcomeCard();
Attachment attachment = new Attachment()
{
ContentType = AdaptiveCard.ContentType,
Content = card
};
reply.Attachments.Add(attachment);
await turnContext.SendActivityAsync(reply, cancellationToken);
}
}

这两种方法都会在聊天窗口中显示两条欢迎消息 -

Bot Window with two Welcome Messages

然后我在 C# 中注释了 OnEventActivityAsync 方法并再次部署。现在它只显示一条从 OnMembersAddedAsync 返回的欢迎消息,如窗口中所示。

Bot Window with only one Welcome Message

如果我在网络聊天代码中注释以下代码行,即不发送后期事件 -

botConnection.postActivity({
from: {
id: 'myUserId',
name: 'myUserName'
},
type: 'event',
name: 'webchat/join',
value: {
locale: 'en-US'
}
}).subscribe(
id => console.log("Posted welcome event, assigned ID ", id),
error => console.log("Error posting activity", error)
);

在这种情况下,不会显示任何欢迎消息。 @tdurnford,请检查您是否能够复制此行为。

尽管这种方式存在另一个问题,即当用户在机器人中输入问题时,会再次显示欢迎消息。 Bot window with two welcome messages one on load and another after the first question

最佳答案

通常, channel 会在对话初始化时发送两个对话更新事件 - 一个用于机器人,另一个用于用户。第二个 - 用户事件 - 旨在触发欢迎消息。与其他一些 channel 不同,网络聊天会等待发送第二个对话更新事件,直到用户向机器人发送消息。显然,在第一条消息之后才会发送欢迎消息。要解决此问题,开发人员可以在建立 DirectLine 连接时向机器人发送反向 channel 欢迎事件,并从 onEventAsync 处理程序而不是 onMembersAdded 发送欢迎消息。有关详细信息,请查看下面的代码片段。

机器人聊天代码

<!DOCTYPE html>
<html>
<head>
<link href="https://cdn.botframework.com/botframework-webchat/0.11.4/botchat.css" rel="stylesheet" />
<style>
#webchat {
height: 100%;
width: 100%;
}
</style>

</head>
<body>
<div style="display: flex">
<div style="position: relative; height: 500px; width: 500px"><div id="bot" ></div></div>
</div>


<script src="https://cdn.botframework.com/botframework-webchat/0.11.4/botchat.js"></script>

<script>

(async function() {

const res = await fetch('/directline/token', { method: 'POST' });
const { token } = await res.json();

var userinfo = {
id: 'user-id',
name: 'user name',
locale: 'es'
};

var botConnection = new window.BotChat.DirectLine({ token });

botConnection.connectionStatus$
.subscribe(connectionStatus => {
switch(connectionStatus) {
case window.BotChat.ConnectionStatus.Online:
botConnection.postActivity({
from: { id: 'myUserId', name: 'myUserName' },
type: 'event',
name: 'webchat/join',
value: { locale: 'en-US' }
}).subscribe(
id => console.log("Posted welcome event, assigned ID ", id),
error => console.log("Error posting activity", error)
);
break;
}
});


BotChat.App({
botConnection: botConnection,
user: userinfo,
bot: { id: 'botid' },
resize: 'detect'
}, document.getElementById("bot"));

})().catch(err => console.log(err));

</script>
</body>
</html>

机器人代码 - C#

protected override async Task OnEventActivityAsync(ITurnContext<IEventActivity> turnContext, CancellationToken cancellationToken)
{
if (turnContext.Activity.Name == "webchat/join") {
await turnContext.SendActivityAsync("Welcome Message!");
}
}

protected override async Task OnMembersAddedAsync(IList<ChannelAccount> membersAdded, ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
{
if (turnContext.Activity.ChannelId != "webchat" && turnContext.Activity.ChannelId != "directline") {

foreach (var member in membersAdded)
{
if (member.Id != turnContext.Activity.Recipient.Id)
{
await turnContext.SendActivityAsync($"Hi there - {member.Name}. {WelcomeMessage}", cancellationToken: cancellationToken);
await turnContext.SendActivityAsync(InfoMessage, cancellationToken: cancellationToken);
await turnContext.SendActivityAsync(PatternMessage, cancellationToken: cancellationToken);
}
}
}
}

屏幕截图

enter image description here

另请注意,Web Chat v0.11.4 称为 Bot Chat 或 Web Chat v3。对不起,我被绊倒了。

希望这对您有所帮助!

关于c# - 在 v4 Bot Framework Bot(C# + .Net Core Web 应用程序)中显示欢迎消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56863203/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com