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

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

Related

Teams: How to open Task Module from Adaptive Card in desktop app

I am sending an adaptive card to teams with the bot framework. That is working fine. The card should contain an action that opens a task module like explained here.
My code for the card looks like this:
AdaptiveCard card = new AdaptiveCard(new AdaptiveSchemaVersion(1, 3))
{
Body = new List<AdaptiveElement>() {
new AdaptiveTextBlock() {
Wrap = true,
Text = "test",
IsSubtle = false,
Size = AdaptiveTextSize.Large,
Weight = AdaptiveTextWeight.Bolder
}
},
Actions = new List<AdaptiveAction>() {
new AdaptiveSubmitAction()
{
Title = "In Teams",
DataJson = $"{{\"msteams\":{{\"type\":\"task/fetch\"}},\"Url\":\"{url}\",\"Title\": \"{title}\"}}"
}
}
};
The card is showing in teams, but the button is not working in the desktop client. It is just showing this message in red:
Something went wrong. Please try again.
In the web version the task module is just opening fine. Do I have to change something for the desktop version of teams? Tried to change my code a bit like in this example but that isn't working either.
Update:
So I tried the example and it did work one time. After that I had the same error message and no task module is showing. But when I pop out the App in a new window, everything is working fine. So it looks to me like a bug in teams.
I had the same problem with the message “Something went wrong. Try again.", when called Task Module from adaptive card. I installed the bot through a local upload of the manifest, but then I found out that it was also added to the list of applications for our organization, and apparently there was some kind of collision between them. After I uninstalled the application from my desktop Teams and installed it from the application pool - the error disappeared.
This might relate to how the platform is reading your json - the "" characters for example might not be handled properly on the desktop. To solve this, rather leave the json conversion up to the platform and, for your example in C#, create a strong type instead. The example you link to does exactly that - see this line:
new TaskModuleAction(cardType.ButtonTitle, new CardTaskFetchValue<string>() { Data = cardType.Id }
inside https://github.com/microsoft/BotBuilder-Samples/blob/448c5535cb6d6be8d7a61f78ef1902b55c1f0edb/samples/csharp_dotnetcore/54.teams-task-module/Bots/TeamsTaskModuleBot.cs, which is referencing this class: https://github.com/microsoft/BotBuilder-Samples/blob/901bc140f5aa300fbfa852e64afd7c65fceebff9/samples/csharp_dotnetcore/54.teams-task-module/Models/AdaptiveCardTaskFetchValue.cs

Is the MS Teams bot framework / botkit able to disable typing indicator?

Is the MS Teams Bot Framework or botkit support a function to disable a typing indicator?
What I know that if want to start typing indicator then can use below format with value type is typing but how can I disabled the typing indicator once it start. Sometimes has case that typing indicator take long time to hide after bot response the answer.
var data = {
'type':'typing',
conversation:
{
id: <channel>
}
};
Hi Muhammad Aiman Azizan,
As of now we cannot disable the typing indicator but you can raise your idea/voice in the link below,
https://microsoftteams.uservoice.com/forums/555103-public/filters/new

Customizing Adaptive Card appearance using RenderedAdaptiveCards inside bot framework SDK

I am developing a Bot using Microsoft Bot Framework. I am using Adaptive Cards for displaying flights to users but they have a lot of limitations on their appearance. I am trying to render the adaptive card from one of the dialogs within my bot framework by creating a adaptive card renderer using my own hostconfig.json and then attaching the Html of my adaptive card back to the chat window. But its not working :(
public static Attachment CreateFlight(Flight flight)
{
var renderedAdaptiveCard = AdaptiveCardRenderer
.RenderCard(new AdaptiveCard
{
Body = new List<AdaptiveElement>
{
new AdaptiveContainer {Items = CreateFlightAdaptiveElements(flight)}
},
Actions = new List<AdaptiveAction>
{
new AdaptiveShowCardAction
{
Card = new AdaptiveCard
{
Body = new List<AdaptiveElement>
{
},
Actions = new List<AdaptiveAction>
{
new AdaptiveSubmitAction
{
Title = "Select",
Data = flight.Segments.Select(x => $"{x.Airline} {x.FlightNo}")
.Aggregate((i, j) => i + "/" + j),
}
},
BackgroundImage = new Uri($"{DomainUrl}/Images/ac_background.jpg")
},
Title = "Select"
},
},
BackgroundImage = new Uri($"{DomainUrl}/Images/ECEFF1.png")
});
var attachment = new Attachment
{
ContentType = "application/html",
Content = renderedAdaptiveCard.Html
};
return attachment;
}
Am I trying something that is impossible here ? How to change the default grey looks of my bot ? My primary channels would be Skype, Slack etc so I don't have plans to integrate this to a Web Chat. Kindly help me with this regard.
The idea behind Adaptive Cards is to allow each channel to render the cards in a way that's specific to that channel. A card "adapts" to any environment that might support it. While Adaptive Cards offer a lot of flexibility, the bot can only do so much because it's ultimately the channel that's in charge of rendering the card.
Card Authors describe their content as a simple JSON object. That
content can then be rendered natively inside a Host Application,
automatically adapting to the look and feel of the Host.
For example, Contoso Bot can author an Adaptive Card through the Bot
Framework, and when delivered to Skype, it will look and feel like a
Skype card. When that same payload is sent to Microsoft Teams, it will
look and feel like Microsoft Teams. As more host apps start to support
Adaptive Cards, that same payload will automatically light up inside
these applications, yet still feel entirely native to the app.
Users win because everything feels familiar. Host apps win because
they control the user experience. And Card Authors win because their
content gets broader reach without any additional work.
As you probably know, the RenderedAdaptiveCard type is meant to be used in client-side code. That means it can help you if you want to make your own channel for example, but it's not really meant to be used in a bot. Your code isn't working because there is no HTML attachment type and most channels don't support HTML at all. You can find more information in this question and this GitHub issue.
Hopefully you can achieve the appearance you're looking for using the tools available to you, such as images and links.

How to switch Dialogs in BotFramework SDK3 C#

I'm trying to add a timeout Dialog using proactiveMessages. If user doesn't reply to [A dialog], [timeout dialog] comes out. So I think timeout dialog should be the current dialog. But do I to close other dialog [A dialog]?
According this, it seems context.EndConversation was not working in MS Teams. Of course I have tried again. It is still not working.
I also tried the way below. But it seems not working either.
using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, context.Activity.AsMessageActivity()))
{
var botData = scope.Resolve<IBotData>();
await botData.LoadAsync(default(CancellationToken));
var stack = scope.Resolve<IDialogStack>();
stack.Reset();
await botData.FlushAsync(default(CancellationToken));
}
Any suggestions about changing the dialog?
There are two methods of redirecting dialog flow within a C# bot.
you can use context.Forward() to send a user to a new dialog starting with a message that you are currently processing:
await context.Forward(new NewOrderDialog(), this.ResumeAfterNewOrderDialog, message, CancellationToken.None);
or you can use context.call() to send a user to a new dialog and start from scratch there:
context.Call(new AgeDialog(this.name), this.AgeDialogResumeAfter);
The "ResumeAfter" functions can be defined anywhere (including a function within the new dialog itself) and setting these to where you would like to redirect the user after they have finished with your timeout dialog will allow you to determine the flow.

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.

Resources