how to properly delete or update activities on bot framework? - botframework

I can't find a guide on documentation for make this possible.
I tried to use TurnContext.UpdateActivity, but I'm getting an error.
My code:
IMessageActivity responseActivity = MessageFactory.Text("Test ctm");
responseActivity.Id = userProfile.messageToDelete;
responseActivity.Conversation = turnContext.Activity.Conversation;
responseActivity.ServiceUrl = turnContext.Activity.ServiceUrl;
//await turnContext.DeleteActivityAsync(userProfile.messageToDelete, cancellationToken: cancellationToken);
await turnContext.UpdateActivityAsync(responseActivity, cancellationToken);
The last line throws the exception:
Microsoft.Bot.Schema.ErrorResponseException: 'Operation returned an invalid status code 'NotFound''
What could be wrong? Can you share any code sample?

The Emulator is built on top of Web Chat, and unfortunately, Web Chat does not support updating or deleting activities at the moment. For more details, take a look at this comment in Web Chat's source code and this open issue in the Web Chat repository for adding support for deleteActivity and updateActivity.
Hope this helps!

Related

MAUI authentication with MSAL for B2C shows black screen

I am working with the .NET MAUI starter project (calling it AuthTest) and adding the changes from this article, but when the android emulator tries to start the B2C process all I get back is black screen that just sits until the system gives me the 'AuthTest isn't responding' message. HAs anyone seen this and know what causes it?
The code works fine up to the AcquireTokenInteractive call and then just sits (presumably waiting for the B2C process to complete) with a black screen...no error message or any indication what it is looking for.
The code that stops at is:
public async Task<AuthenticationResult> LoginAsync(CancellationToken cancellationToken) {
AuthenticationResult result;
try {
result = await _authClient
.AcquireTokenInteractive(_constants.Scopes)
.WithPrompt(Prompt.ForceLogin)
#if ANDROID
.WithParentActivityOrWindow(Platform.CurrentActivity)
#endif
.ExecuteAsync(cancellationToken);
return result;
}
catch(MsalClientException) { return null; }
}
It just never reaches the return result;
Has anyone seen this and have some suggestions to try?
For anyone trying the same thing as above, I have found that this article works. I have not yet compared this to the one above to find the differences, but the sample code from the linked article (in this answer) allows a MAUI application to login against AAD B2C tenant.

Failed to connect (500) to bot framework using Direct Line

We have a bot running in Azure (Web App Bot) that I'm trying to embed on a website. The bot is based of the Bot Builder V4 SDK Tamplate CoreBot v4.9.2. At first I used the iframe to embed the bod. This worked but didn't provide the features we need, so now im changing it to use DirectLine.
My code on the webpage looks like this:
<script crossorigin="anonymous"
src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
<div id="webchat" role="main"></div>
<script>
(async function () {
const res = await fetch('https://[my bot name here].azurewebsites.net/.bot/v3/directline/tokens/generate',
{
method: 'POST',
headers: new Headers({
'Authorization': "Bearer [my token here]"
})
});
const { token } = await res.json();
window.WebChat.renderWebChat(
{
directLine: await window.WebChat.createDirectLineAppServiceExtension({
domain: 'https://[my bot name here].azurewebsites.net/.bot/v3/directline',
token
})
},
document.getElementById('webchat')
);
document.querySelector('#webchat > *').focus();
})().catch(err => console.error(err));
</script>
After some struggles I managed to fetch a token from https://[my bot name here].azurewebsites.net/.bot/v3/directline.
And I can see the chat window on my webpage, but is says connecting for a while then it changes to Taking longer than usual to connect, like this:
In the Chrome console there is an error saying Failed to connect Error: Connection response code 500. When I check Chrome's Network tab I can see that the token generated completed with status 200 and that the websocket connection is open, like this:
----------EDIT---------
I just noticed that when go to https://[my bot name here].azurewebsites.net/.bot using a webbrowser, the resulting json is
{"v":"1.0.0.0.55fa54091a[some key?]","k":true,"ib":false,"ob":false,"initialized":true}
ib and ob should be true but are false, maybe this is part of the problem.
----------EDIT 2---------
OK so now I'm starting to go crazy.
Ashish helped me and at some point the ib and ob were true. They were true for most of yesterday. At some point yesterday they turned false for a short while (no more than 2 hours). I checked if someone had triggered the release pipeline but no recent releases. After that ib and ob magically turned true again and connecting to the direct line worked again.
Now this morning ib and ob were false again. And again no recent releases. I don't know what is causing this.
Does anybody know what's going on here or how to fix this? How do I find what causes ib and ob to be false?
Any help is appreciated! Thanks in advance. If you need more information, just ask and I'll post it.
If the ib and ob values displayed by the *.bot endpoint are false this means the bot and the Direct Line app service extension are unable to connect to each other.
Make sure you verify below things:
Double check the code for using named pipes has been added to the
bot.
Confirm the bot is able to start up and run at all. Useful
tools are Test in WebChat, connecting an additional channel, remote
debugging, or logging.
Restart the entire Azure App Service the bot
is hosted within, to ensure a clean start up of all processes.
Please check troubleshooting guide, it seems updated today. (still old date reflected some how, not sure why)

Error sending message to WebChat via DirectLine

I have a bot deployed in Azure. Uses the latest >net bot framework, (v3).
The front-end uses the vanilla WebChat. I am trying to send an event from the BOT TO THE CLIENT, in order to trigger a wipe of the webchat visible history.
I'm getting the more than useless 502 error when my bot tries to send the event message.
The JS to setup the web chat and directline on my front end is:
var botConnection = new BotChat.DirectLine({
secret: {secret removed..becuase secret},
//token: params['t'],
//domain: params['domain'],
webSocket: "true" // defaults to true
});
BotChat.App({
bot: bot,
botConnection: botConnection,
resize: 'detect',
user: user,
chatTitle: false,
showUploadButton: false
}, document.getElementById('bot'));
//backchannel communication setup
botConnection.activity$
.filter(function (activity) {
return activity.type === 'event' && activity.name === 'clearChatHistory';
})
.subscribe(function (activity) {
console.log('"clearChatHistory" received');
clearChatHistory();
});
function clearChatHistory() {
$(".wc-message-wrapper").remove();
}
The idea here is that my bot code will create a message of type 'activity' with the value = 'clearChatHistory'. This fire the code on my client.
The code for sending this message is:
internal static async Task SendClearChatHistoryEvent(Activity activity)
{
Trace.TraceInformation($"Utility::SendClearChatHistoryEvent");
Activity clearMessage = activity.CreateReply();
clearMessage.Type = "event";
clearMessage.Value = "clearChatHistory";
Trace.TraceInformation(JsonConvert.SerializeObject(clearMessage));
Trace.TraceInformation($"Utility::SendClearChatHistoryEvent::ServiceURL:{activity.ServiceUrl}");
var connector = new ConnectorClient(new Uri(activity.ServiceUrl));
await connector.Conversations.SendToConversationAsync(clearMessage);
}
The bot fail is happening at the 'SendToConversationAsync' call
The closest thing I get to an error is on the client side
"https://directline.botframework.com/v3/directline/conversations/5OSJJILizNqGG4H7SaV6fQ/activities 502 (Bad Gateway)"
The Visual Studio output window displays
'Microsoft.Rest.TransientFaultHandling.HttpRequestWithStatusException'
and 'Microsoft.Bot.Connector.ErrorResponseException
exceptions
Any insights on what I might be doing wrong or whats happening otherwise here would be greatly appreciated.
You're setting the value on the event but checking the name. If you use this as the filter it should work:
.filter(activity => activity.type === 'event' && activity.value === 'clearChatHistory')
Regarding the bad gateway however, I am not sure, as I was not seeing this occur with your code on my system.
I figured out what the problem is. First, there was a bug in my code example which Mark B pointed out. However, that was not the source of the problem but it did help me to get to the real issue.
The Bad Gateway problem wasn't really a good indicator of the problem either. I had to do a lot of Trace writing and stepping through code to finally notice what was happening. I'll try to describe the problem so you all can learn from my boneheaded mistake.
The understand the problem, you need to understand what this line of code is doing
Activity clearMessage = activity.CreateReply();
CreateReply() creates a new Activiy from an existing one. When it does that, it swaps the values of From and Recipient. This is because you want to reply to the person the original message comes from. Make 100% total sense.
The problem, for me, was my original message was ALSO created by calling CreateReaply() in a previous dialog. SO, I basically created a new message to be sent to myself (or the bot in this case). I need the message to to to the chatbot user, not the bot.
When the bot framework attempted to send itself a message it excepted and failed. Why it got the bad gateway error I dont exactly know and will continue to research that.
To fix this, I changed my upstream code to use
var newMessage = context.MakeMessage()
instead of the CreateReaply(). This does not swap From and Recipient.
Everything is now flowing along very nicely. My code will now force a wipe of the visible chat history in my WebChat client.

Using MS Teams as Channel: Authentification Dialog (GetTokenDialog class from Microsoft.Bot.Builder.Dialogs) doesn't popup

How can I use the new authentification feature in Bot Builder with MS Teams?
There seems to be an issue with Teams (see Login user with MS Teams bot or https://github.com/Microsoft/BotBuilder/issues/2104), seems if this is not considered in GetTokenDialog?
Is there any chance to get around this?
Just found the reason why it won't work with Teams. In method Microsoft.Bot.Connector.Activity.CreateOAuthReplyAsync(), Parameter asSignInCard has to be set to True for MSTeams, then, the line new CardAction() { Title = buttonLabel, Value = link, Type = ActionTypes.Signin } has to be changed to new CardAction() { Title = buttonLabel, Value = link, Type = ActionTypes.OpenUrl } because MS Teams can obviously not deal with Action type Signin. Hope, the MS developers will fix that method soon.
There are a few things you need to do to get this to work. First you need to create a manifest file for your bot in teams and whitelist token.botframework.com. That is the first problem.
From teams itself in AppStudio you create a Manifest. I had to play around with this a little bit. In AppDetails... Let it generate a new ID. Just hit the button. The URLs really don't matter much for testing. The package name just needs to be unique so something like com.ilonatag.teams.test
In the bots section you plug in your MS AppId and a bot name. This is a the real MSAPPID from your bots MicrosoftAppId" value=" from web.config in your code.
Ok now in "finish->valid domains" I added token.botframework.com and also the URL for my bot just in case. so something like franktest.azurewebsites.net
This part is done but you are not quite done... in your messages controller you need to add this since Teams sends a different verification than the other clients.
if (message.Type == ActivityTypes.Invoke)
{
// Send teams Invoke along to the Dialog stack
if (message.IsTeamsVerificationInvoke())
{
await Conversation.SendAsync(message, () => new Dialogs.RootDialog());
}
}
It took me a bunch of going back and forth with Microsoft to get this sorted out.
This is a known problem using OAuthCard in MS Teams. To solve it, you can change the Button ActionType from signIn to openUrl using this solution on github

Remote name could not be resolved "facebook.botframework.com"

I am building facebook bot using Microsoft bot framework and api.ai but am facing the following errors
Remote name could not be resolved for following urls
facebook.botframework.com
api.api.ai
Could anyone suggest something
#Eric Dahlvang, please find details below
Both errors are frequent but not always
For facebook.botframework.com
the line of code which gives the error is 4th line in below code, sending the typing reply
var connector = new ConnectorClient(new Uri(activity.ServiceUrl));
Activity isTypingReply = activity.CreateReply();
isTypingReply.Type = ActivityTypes.Typing;
// error in line below
await connector.Conversations.ReplyToActivityAsync(isTypingReply);

Resources