DEV Community

Cover image for Using Direct Line botframework in a React Native Application to connect to Copilot Studio Agent
Vivek Yadav
Vivek Yadav

Posted on

Using Direct Line botframework in a React Native Application to connect to Copilot Studio Agent

  1. Overview
  2. Pre-requisites
  3. Authentication
  4. Starting a Conversation with Copilot Agent Bot
  5. Reconnecting the Conversation
  6. Using Existing Conversation ID
  7. Sending Activity to a Copilot Agent Bot
  8. Receiving Activity from Copilot Chat Bot
  9. Ending the Conversation
  10. Checking Connection Status and Reconnecting
  11. Conclusion
  12. References

1. Overview

This documentation provides a detailed guide for integrating and using Microsoft Bot Framework's Direct Line API in a React Native application. It covers all the essential steps, from setting up prerequisites to managing WebSocket connections and handling conversations with a Copilot Agent bot. The objective is to enable seamless communication between your React Native app and the bot using Direct Line JS and WebSocket, ensuring efficient and reliable interactions.


2. Pre-requisites

  1. A React Native development environment set up.
  2. Node.js installed on your system.
  3. A valid Microsoft Bot Framework Copilot Studio bot.
  4. A Direct Line secret key, available from the Azure Bot Service configuration.
  5. Basic understanding of WebSocket and REST APIs.
  6. Installed dependencies:
    • botframework-directlinejs

Install Direct Line JS:

npm install botframework-directlinejs
Enter fullscreen mode Exit fullscreen mode

3. Authentication

The Direct Line secret is used to authenticate your React Native application with the bot framework. Avoid exposing the secret in your client application; instead, use a backend service to generate a token.

To get a token:

  • Use your backend service to send a request to the Direct Line API endpoint with your secret:
POST https://directline.botframework.com/v3/directline/tokens/generate
Authorization: Bearer <YOUR_DIRECT_LINE_SECRET>
Enter fullscreen mode Exit fullscreen mode
  • The response will include the token, which can then be securely passed to the client application for use.

4. Starting a Conversation with Copilot Agent Bot

Use the token obtained during authentication to start a conversation with the bot.

Sample Code:

import { DirectLine } from 'botframework-directlinejs';

const directLine = new DirectLine({
  token: '<YOUR_GENERATED_TOKEN>'
});

directLine.activity$.subscribe(
  activity => console.log("Received activity: ", activity),
  error => console.error("Error: ", error)
);
Enter fullscreen mode Exit fullscreen mode

Ensure the token used here is obtained using the backend service as described in the Authentication section.


5. Reconnecting the Conversation

Using Existing Conversation ID

const directLine = new DirectLine({
  token: '<YOUR_GENERATED_TOKEN>',
  conversationId: '<EXISTING_CONVERSATION_ID>'
});
Enter fullscreen mode Exit fullscreen mode

6. Sending Activity to a Copilot Agent Bot

Sample Code:

directLine.postActivity({
  from: { id: 'user1' },
  type: 'message',
  text: 'Hello, Copilot!'
}).subscribe(
  id => console.log("Posted activity, assigned ID: ", id),
  error => console.error("Error posting activity: ", error)
);
Enter fullscreen mode Exit fullscreen mode

7. Receiving Activity from Copilot Chat Bot

Subscribe to the activity stream:

directLine.activity$.subscribe(
  activity => console.log("Received activity: ", activity),
  error => console.error("Error receiving activity: ", error)
);
Enter fullscreen mode Exit fullscreen mode

8. Ending the Conversation

End the conversation gracefully by stopping the activity subscription:

directLine.end();
Enter fullscreen mode Exit fullscreen mode

9. Checking Connection Status and Reconnecting

Handle WebSocket errors and fallback to polling:

const directLine = new DirectLine({
  token: '<YOUR_GENERATED_TOKEN>',
  webSocket: true
});

directLine.connectionStatus$.subscribe(status => {
  switch (status) {
    case 0: // Uninitialized
      console.log('Connection uninitialized');
      break;
    case 1: // Connecting
      console.log('Connecting...');
      break;
    case 2: // Online
      console.log('Connected');
      break;
    case 4: // Failed to connect
      console.log('Failed to connect, switching to polling.');
      directLine = new DirectLine({ token: '<YOUR_GENERATED_TOKEN>', webSocket: false });
      break;
    case 5: // Ended
      console.log('Conversation ended');
      break;
    default:
      console.log('Unknown status');
  }
});
Enter fullscreen mode Exit fullscreen mode

10. Conclusion

Integrating Microsoft Bot Framework's Direct Line API into a React Native application provides a powerful way to interact with bots, enabling features like real-time messaging and enhanced user engagement. By following this documentation, developers can efficiently authenticate, manage tokens, and establish seamless conversations with the bot. Robust error handling ensures a reliable user experience, even under challenging network conditions. This integration offers a scalable solution for implementing conversational AI in mobile applications.


11. References

Bot Framework Documentation

Direct Line API Reference

Bot Framework Direct Line JS GitHub

Top comments (0)