Microsoft Bot Framework Direct Line JS Client

0.15.8 · active · verified Sun Apr 19

This package provides a client library for the Microsoft Bot Framework Direct Line 3.0 protocol, enabling JavaScript applications to communicate directly with bots. It is an official Microsoft-supported library, used internally by components like BotFramework-WebChat, the Bot Framework Emulator, and Azure Bot Service. The current stable version is 0.15.8. The library primarily uses RxJS Observables for handling asynchronous operations, a key differentiator from Promise-based alternatives. While considered largely complete for its protocol, updates are typically limited to dependency bumps, bug fixes, and minor enhancements rather than new feature development, indicating a maintenance-focused release cadence. It fully supports TypeScript.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to initialize the Direct Line client, monitor its connection status, receive messages from a bot using RxJS Observables, and send a message to the bot. It highlights secure token handling and proper cleanup.

import { DirectLine, ConnectionStatus, Activity } from 'botframework-directlinejs';
import { filter } from 'rxjs/operators';

// In a real application, retrieve this securely (e.g., from an environment variable or a server-side call)
const DIRECT_LINE_SECRET = process.env.DIRECT_LINE_SECRET ?? 'YOUR_DIRECT_LINE_SECRET_HERE';
const USER_ID = 'user123'; // A unique user ID for the conversation

console.log('Starting Direct Line client...');

const directLine = new DirectLine({
  secret: DIRECT_LINE_SECRET, // For production, exchange secret for a token via a backend service
  webSocket: true, // Use Web Sockets for real-time communication
  // token: 'YOUR_DIRECT_LINE_TOKEN_HERE' // Recommended for production
});

// Observe connection status changes
directLine.connectionStatus$.subscribe(connectionStatus => {
  const statusMessage = ConnectionStatus[connectionStatus];
  console.log(`Connection status: ${statusMessage}`);
  if (connectionStatus === ConnectionStatus.Uninitialized) {
    console.warn('Direct Line connection is uninitialized. Check your secret/token.');
  } else if (connectionStatus === ConnectionStatus.ExpiredToken) {
    console.error('Direct Line token expired. Reconnect with a new token.'); //
  }
});

// Subscribe to incoming activities from the bot
const activitySubscription = directLine.activity$
  .pipe(
    filter(activity => activity.type === 'message' && activity.from.id !== USER_ID)
  )
  .subscribe(activity => {
    console.log(`Received activity from bot:`);
    console.log(JSON.stringify(activity, null, 2));

    if (activity.text && activity.text.toLowerCase().includes('hello')) {
      console.log('Bot greeted us back!');
    }
  }, error => {
    console.error('Error receiving activities:', error);
  });

// Send a message to the bot after a brief delay
setTimeout(() => {
  const message: Activity = {
    from: { id: USER_ID, name: 'Test User' },
    type: 'message',
    text: 'Hello bot!',
    channelData: { clientActivityID: Date.now().toString() } // Unique ID for client activity
  };

  directLine.postActivity(message).subscribe(
    id => console.log(`Sent activity with ID: ${id}`),
    error => console.error('Error sending activity:', error)
  );
}, 3000);

// Disconnect after some time (e.g., when the user leaves the chat)
setTimeout(() => {
  console.log('Ending conversation and disconnecting...');
  activitySubscription.unsubscribe();
  directLine.end(); // Clean up Direct Line connection
}, 15000); // Disconnect after 15 seconds for this example

view raw JSON →