Download Transcript option in Botframework v4

This is a whistle stop tour for adding a method to allow the user to download their transcript.

Automatically record the transcript

You need to add the built-in transcript services. In this example I’ll use the In-Memory store, you’ll want to evaluate the others for production code. Add this to the startup.cs

 
var memoryTranscriptStore = new MemoryTranscriptStore();
…
options.Middleware.Add(new TranscriptLoggerMiddleware(memoryTranscriptStore));

Next we’ll create a component to expose the ITranscriptStore (memoryTranscriptStore) to the dialog context. We’ll do that via our own middleware;

public class TranscriptProvider : IMiddleware
{
    private readonly ITranscriptStore transcriptStore;

    public TranscriptProvider(ITranscriptStore transcriptStore)
    {
        this.transcriptStore = transcriptStore;
    }

    public async Task OnTurn(ITurnContext context, MiddlewareSet.NextDelegate next)
    {
        context.Services.Add(transcriptStore);
        await next();
    }
}

Now add this to the startup middleware;

options.Middleware.Add(new TranscriptProvider(memoryTranscriptStore));

Download the transcript

The middleware will now capture all the activity traffic too and from the bot and user. We can add a simple mechanism to request the transcript file. In your bot’s OnTurn method we can hardcode a ‘Transcript’ message/command;

if (context.Activity.Text.Equals("Transcript", StringComparison.InvariantCultureIgnoreCase))
{
    var transcriptStore = context.Services.Get();
    var transcripts = await transcriptStore.GetTranscriptActivities(context.Activity.ChannelId, context.Activity.Conversation.Id);

    var transcriptContents = new StringBuilder();
    foreach (var transcript in transcripts.Items.Where(i => i.Type == ActivityTypes.Message))
    {
        transcriptContents.AppendLine((transcript.From.Name == "Bot" ? "\t\t" : "") + transcript.AsMessageActivity().Text);
    }

    byte[] bytes = StringToBytes(transcriptContents.ToString());

    var contentType = "text/plain";
    var attachment = new Attachment
    {
        Name = "Transcript.txt",
        ContentUrl = $"data:{contentType};base64,{Convert.ToBase64String(bytes)}",
        ContentType = contentType
    };

    var activity = MessageFactory.Attachment(attachment);
    await context.SendActivity(activity);

    return;
}
...
private byte[] StringToBytes(string transcriptToSend)
{
    byte[] bytes = new byte[transcriptToSend.Length * sizeof(char)];
    System.Buffer.BlockCopy(transcriptToSend.ToCharArray(), 0, bytes, 0, bytes.Length);
    return bytes;
}

When your user types in ‘Transcript’ they’ll be provided with a download attachment called ‘Transcript.txt’.

Production Ready

The above code is great for early testing but you should probably consider using the Download Activity Type and providing a URL to the full transcript. The above code has a nasty weakness in that it must fit inside the maximum reply payload for the bot, ~94K. You could just truncate the body but I’ll leave that up to you. Note, as of writing the emulator has an issue where it will allow you to click on the download but then it gets into a pickle and launches Windows Store. If you try this on a webchat it works fine.

Advertisements

Manipulating waterfall steps Botframework v4

To be honest I’m not even sure that this is strictly supported or that it is even a good idea, but as a point of interest you can manipulate the waterfall steps in v4. E.g. The standard flow is; step 1 -> step 2 -> step 3 -> step n. If your code realises that the user should skip a step then it can invoke the ‘next’ function;

async (dc, args, next) =>
{
    if (someCondition)
    {
        await next(args);
        return;
    }
}

That’s pretty easy. The difficult question, and one that I’m not even sure is (or should be) a valid one, how do you go back a step? Well, it is possible but it’s messy and you can’t get back to the initial step (although that is just starting again). You can go back a step by manipulating the dialog state;

// at step n
async (dc, args, next) =>
{
    if (someCondition)
    {
        var targetStep = 1;
        dc.ActiveDialog.Step = targetStep - 1;
        await Step1Prompt();
        return;
    }
}

I don’t recommend this approach, it’s ugly, but you know…possible.

ChoicePrompt, how to always call the validator in Botframework v4

BotFramework v4 has a number of helper prompts, TextPrompt, ChoicePrompt, etc. One common mechanism they share is a Validator delegate. When the user enters a value the Validator is invoked and you have an opportunity to check/change the outcome

var obj = new ValidatingTextPrompt(async (context, toValidate) =>
    {
        if (toValidate.Text.Length < minimumLength)
        {
            toValidate.Status = null;
            await context.SendActivity(minimumLengthMessage);
        }
    }
    );

The presence of the RetryPromptString means the ChoicePrompt will automatically retry of the user enters the incorrect value, such as 'frog'. However, what happens if the user enters the value '3'? Unfortunately this is considered as the 3rd choice and 'quit' will be selected. If your UI is really serving up numbers like this, that could be a real problem. Imagine if the list was 2,4,6 and you entered '3' or even worse '2'!? So I really want to add a Validator delegate that all prompts support;

this.Dialogs.Add("choicePrompt", new ChoicePrompt(Culture.English, ValidateChoice));

private async Task ValidateChoice(ITurnContext context, ChoiceResult toValidate)
{
    var userMessage = context.Activity.Text;
    if (userMessage == "3")
    {
        toValidate.Status = null;
        await Task.Delay(1);
    }
}

Sorted right? Wrong. Unfortunately there are two problems with this solutions; a) this is only called when a value from the choices list is selected (really??) b) the resulting selected value is passed in and not the original, i.e. ‘quit’ is passed in rather than ‘3’. My solution is to derive a new ChoicePrompt that will always call the available Validator with the original values;

public class ChoicePromptAlwaysVerify : Microsoft.Bot.Builder.Dialogs.ChoicePrompt
{
    private readonly PromptValidatorEx.PromptValidator validator;

    public ChoicePromptAlwaysVerify(string culture, PromptValidatorEx.PromptValidator validator = null) : base(culture, validator)
    {
        this.validator = validator;
    }

    protected override async Task OnRecognize(DialogContext dc, PromptOptions options)
    {
        var recognize = await base.OnRecognize(dc, options);
        if (this.validator != null)
        {
            await this.validator.Invoke(dc.Context, recognize);
        }

        return recognize;
    }
}

The code works by forcing the recognize override to call the validator. The downside is that this code will be called twice when the user makes a good choice (sigh), but it’s a small sacrifice to regain some consistent control over the valid values. It also allows for more specialized messages as the RetryMessage is fixed and has no chance to give a contextual response.