Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel
Ezequiel Jadib 6b3df2c0b3
Update documentation links to point to new docs (#118)
6 years ago
..
6b3df2c0b3
Update documentation links to point to new docs (#118)
6 years ago
1cac51aaa5
Merge pull request #119
6 years ago
76ccf52f7a
[CSharp] DirectLine + WebSockets sample
7 years ago
76ccf52f7a
[CSharp] DirectLine + WebSockets sample
7 years ago
6b3df2c0b3
Update documentation links to point to new docs (#118)
6 years ago
76ccf52f7a
[CSharp] DirectLine + WebSockets sample
7 years ago

README.md

You have to be logged in to leave a comment. Sign In

Direct Line Bot Sample (using client WebSockets)

A sample bot and a custom client communicating to each other using the Direct Line API and WebSockets.

Deploy to Azure

Prerequisites

The minimum prerequisites to run this sample are:

  • The latest update of Visual Studio 2017. You can download the community version here for free.
  • The Bot Framework Emulator. To install the Bot Framework Emulator, download it from here. Please refer to this documentation article to know more about the Bot Framework Emulator.
  • Register your bot with the Microsoft Bot Framework. Please refer to this for the instructions. Once you complete the registration, update the Bot's Web.config file with the registered config values (Bot Id, MicrosoftAppId and MicrosoftAppPassword)

Direct Line API

Credentials for the Direct Line API must be obtained from the Bot Framework developer portal, and will only allow the caller to connect to the bot for which they were generated. In the Bot Framework developer portal, enable Direct Line in the channels list and then, configure the Direct Line secret and update its value in the client's App.config file alongside with the Bot Id. Make sure that the checkbox for version 3.0 [PREVIEW] is checked. Refer to this for more information on how to configure channels.

Configure Direct Line

Publish

Also, in order to be able to run and test this sample you must publish your bot, for example to Azure. Alternatively, you can use Ngrok to interact with your local bot in the cloud.

Code Highlights

The Direct Line API is a simple REST API for connecting directly to a single bot. This API is intended for developers writing their own client applications, web chat controls, or mobile apps that will talk to their bot. The Direct Line v3.0 Nuget package simplifies access to the underlying REST API.

Each conversation on the Direct Line channel must be explicitly started using the DirectLineClient.Conversations.StartConversationAsync. Check out the client's Program.cs class which creates a new DirectLineClient and starts a new conversation.

You'll see that we are using the Direct Line secret to obtain a token. This step is optional, but prevents clients from accessing conversations they aren't participating in.

// Obtain a token using the Direct Line secret
var tokenResponse = await new DirectLineClient(directLineSecret).Tokens.GenerateTokenForNewConversationAsync();

// Use token to create conversation
var directLineClient = new DirectLineClient(tokenResponse.Token);
var conversation = await directLineClient.Conversations.StartConversationAsync();

User messages are sent to the Bot using the Direct Line Client Conversations.PostActivityAsync method using the ConversationId generated in the previous step.

while (true)
{
    string input = Console.ReadLine().Trim();

    if (input.ToLower() == "exit")
    {
        break;
    }
    else
    {
        if (input.Length > 0)
        {
            Activity userMessage = new Activity
            {
                From = new ChannelAccount(fromUser),
                Text = input,
                Type = ActivityTypes.Message
            };

            await client.Conversations.PostActivityAsync(conversation.ConversationId, userMessage);
        }
    }
}

Messages from the Bot are being received using WebSocket protocol. For this, after the conversation was created a streamUrl is also returned and it will be the target for the WebSocket connection. Check out the client's WebSocket initialization in Program.cs.

Note: In this project we use websocket-sharp to implement the receiver client but as we have the WebSocket URL this functionality can be implemented according to the needs of the solution.

using (var webSocketClient = new WebSocket(conversation.StreamUrl))
{
    webSocketClient.OnMessage += WebSocketClient_OnMessage;
    webSocketClient.Connect();

We use the WebSocketClient_OnMessage method to handle the OnMessage event of the webSocketClient witch occurs when the WebSocket receives a message.

private static void WebSocketClient_OnMessage(object sender, MessageEventArgs e)
{
    var activitySet = JsonConvert.DeserializeObject<ActivitySet>(e.Data);
    var activities = from x in activitySet.Activities
        where x.From.Id == botId
        select x;

Direct Line v3.0 (unlike version 1.1) has support for Attachments (see Add media attachments to messages for more information about attachments). Check out the WebSocketClient_OnMessage method in Program.cs to see how the Attachments are retrieved and rendered appropriately based on their type.

if (activity.Attachments != null)
{
    foreach (Attachment attachment in activity.Attachments)
    {
        switch (attachment.ContentType)
        {
            case "application/vnd.microsoft.card.hero":
                RenderHeroCard(attachment);
                break;

            case "image/png":
                Console.WriteLine($"Opening the requested image '{attachment.ContentUrl}'");

                Process.Start(attachment.ContentUrl);
                break;
        }
    }
}

Outcome

To run the sample, you'll need to run both Bot and Client apps.

  • Running Bot app
    1. In the Visual Studio Solution Explorer window, right click on the DirectLineBot project.
    2. In the contextual menu, select Debug, then Start New Instance and wait for the Web application to start.
  • Running Client app
    1. In the Visual Studio Solution Explorer window, right click on the DirectLineSampleClient project.
    2. In the contextual menu, select Debug, then Start New Instance and wait for the Console application to start.

To test the Attachments type show me a hero card or send me a botframework image and you should see the following outcome.

Sample Outcome

More Information

To get more information about how to get started in Bot Builder for .NET and Conversations please review the following resources:

Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...