DEV Community

Cover image for Building Interactive Chat Applications with Microsoft DirectLine API: A Complete Guide with Code Examples
Vivek Yadav
Vivek Yadav

Posted on

Building Interactive Chat Applications with Microsoft DirectLine API: A Complete Guide with Code Examples

The DirectLine API is a part of Microsoft Bot Framework that facilitates communication between a bot and custom client applications. With the DirectLine API, developers can integrate bot conversations into their applications, whether it's a web, mobile, or desktop app.

This article will walk you through the essential steps of using the DirectLine API, including sample code to get started.

Overview of DirectLine API

DirectLine API provides a WebSocket or REST-based interface for real-time communication between bots and clients. Key features include:

  • Starting conversations.
  • Sending and receiving activities (messages).
  • Handling reconnections.
  • Managing conversations and retrieving history.

Prerequisites

  1. Bot Framework Registration: A bot must be registered in the Azure Bot Service.
  2. Direct Line Channel: Enable the DirectLine channel in the bot settings.
  3. DirectLine Secret: Obtain the secret key from the DirectLine configuration in Azure.

Setting Up a DirectLine Client

Step 1: Installation

Install the botframework-directlinejs package for Node.js or React-based applications:

npm install botframework-directlinejs
Enter fullscreen mode Exit fullscreen mode

Step 2: Initialize the DirectLine Client

Use the secret key from the DirectLine channel to create a DirectLine instance.

import { DirectLine } from 'botframework-directlinejs';

const directLine = new DirectLine({
  token: 'YOUR_DIRECT_LINE_SECRET',
});
Enter fullscreen mode Exit fullscreen mode

Alternatively, generate a token dynamically via REST API:

fetch('https://directline.botframework.com/v3/directline/tokens/generate', {
  method: 'POST',
  headers: {
    Authorization: `Bearer YOUR_DIRECT_LINE_SECRET`,
  },
})
  .then((response) => response.json())
  .then((data) => {
    const directLine = new DirectLine({ token: data.token });
  });
Enter fullscreen mode Exit fullscreen mode

Step 3: Starting a Conversation

A new conversation starts automatically when a DirectLine instance is initialized. However, to start manually or reconnect, use:

directLine.startConversation().subscribe({
  next: (response) => console.log('Conversation started:', response),
  error: (err) => console.error('Error starting conversation:', err),
});
Enter fullscreen mode Exit fullscreen mode

Step 4: Sending Messages

To send a message to the bot, use the postActivity method:

directLine
  .postActivity({
    from: { id: 'user1', name: 'User' },
    type: 'message',
    text: 'Hello, Bot!',
  })
  .subscribe({
    next: (id) => console.log('Message sent with id:', id),
    error: (err) => console.error('Error sending message:', err),
  });
Enter fullscreen mode Exit fullscreen mode

Step 5: Receiving Messages

Listen for messages and activities from the bot using the activity$ observable:

directLine.activity$.subscribe((activity) => {
  if (activity.type === 'message') {
    console.log('Received message:', activity.text);
  }
});
Enter fullscreen mode Exit fullscreen mode

Step 6: Reconnection

Handle reconnections in case the connection drops:

directLine.reconnect({ conversationId: 'your-conversation-id' }).subscribe({
  next: () => console.log('Reconnected to conversation'),
  error: (err) => console.error('Error reconnecting:', err),
});
Enter fullscreen mode Exit fullscreen mode

Advanced Features

Fetching Chat History

Retrieve previous messages using REST API:

fetch(`https://directline.botframework.com/v3/directline/conversations/${conversationId}/activities`, {
  method: 'GET',
  headers: {
    Authorization: `Bearer YOUR_DIRECT_LINE_SECRET`,
  },
})
  .then((response) => response.json())
  .then((data) => console.log('Chat history:', data.activities));
Enter fullscreen mode Exit fullscreen mode

Using WebSockets

For real-time communication, DirectLine supports WebSockets. WebSocket support is built-in when initializing DirectLine:

const directLine = new DirectLine({
  token: 'YOUR_DIRECT_LINE_SECRET',
  webSocket: true, // Default: true
});
Enter fullscreen mode Exit fullscreen mode

Formatting Chat Output

Customize how the client displays bot messages:

const renderMessage = (activity) => {
  if (activity.type === 'message') {
    return activity.text.split('\n').map((line, index) => (
      <p key={index}>{line}</p>
    ));
  }
};
Enter fullscreen mode Exit fullscreen mode

React Example

Here’s a full example of a React component using DirectLine API:

import React, { useEffect, useState } from 'react';
import { DirectLine } from 'botframework-directlinejs';

const ChatApp = () => {
  const [messages, setMessages] = useState([]);
  const directLine = new DirectLine({ token: 'YOUR_DIRECT_LINE_SECRET' });

  useEffect(() => {
    const subscription = directLine.activity$.subscribe((activity) => {
      if (activity.type === 'message') {
        setMessages((prev) => [...prev, activity]);
      }
    });

    return () => subscription.unsubscribe();
  }, [directLine]);

  const sendMessage = (text) => {
    directLine
      .postActivity({
        from: { id: 'user1', name: 'User' },
        type: 'message',
        text,
      })
      .subscribe();
  };

  return (
    <div>
      <div>
        {messages.map((msg, index) => (
          <p key={index}>
            <strong>{msg.from.name}:</strong> {msg.text}
          </p>
        ))}
      </div>
      <input
        type="text"
        onKeyDown={(e) => {
          if (e.key === 'Enter') {
            sendMessage(e.target.value);
            e.target.value = '';
          }
        }}
      />
    </div>
  );
};

export default ChatApp;
Enter fullscreen mode Exit fullscreen mode

Conclusion

The DirectLine API is a powerful way to bring bot conversations into custom apps. Using its WebSocket or REST-based interfaces, developers can build dynamic and responsive chat applications across platforms. Integrate with React for an interactive experience, and explore advanced features like reconnection and message formatting to enhance your bot-driven apps.

Top comments (0)