Unable to retrieve activities at the beginning of a conversation using directlinejs

Utilizing Azure Directlinejs for connecting to my bot has been successful. I am able to establish a connection with the bot, but facing issues with receiving activities once connected successfully. However, I have figured out that subscribing to `PostActivity` helps me get the activities.

  case ConnectionStatus.Online:           // Successful connection to the conversation. Connection is healthy based on our knowledge.
                                            console.log('Online');
                                            debugger;
                                            this.directLine.activity$
                                            .subscribe(
                                                activity => console.log("received activity ", activity),
                                                error => {
                                                    console.log(error);
                                                }
                                            );
                                            break;

Answer №1

It appears that you are utilizing the `connectionStatus$` observable to determine if Web Chat should subscribe to the `activity$` observable. This approach is not correct.

`ConnectionStatus` should only be used to monitor the changes in DirectLine's state. It is meant to trigger specific actions within the client based on different states ('online' for instance).

The proper setup should resemble the following example. The code snippet below is extracted from a basic custom DirectLine client I utilize during testing. By subscribing to `activity$`, I display incoming messages from either the bot or the user on the page. Subscribing to `connectionStatus$` allows me to log the state and DirectLine object in the console for examination.

const sendBox = document.querySelector( '#sendBox' );
const sendBtn = document.querySelector( '#sendButton' );
const transcriptWindow = document.querySelector( '.transcript_list' );

// A REMINDER: AVOID USING DIRECTLINE SECRET IN PRODUCTION ENVIRONMENTS
const DirectLine = window.DirectLine;
const directLine = new DirectLine.DirectLine({
  secret: <<SECRET>>
});

directLine.activity$
  .subscribe(
    activity => {
      console.log("received activity ", activity);

      if (activity.from.id === '<<BOT ID>>') {
        const messageToSend = activity.text || JSON.stringify(activity.attachments[0].content?.speak);
        const el = `<li>Bot: ${messageToSend}</li>`;
        transcriptWindow.innerHTML += el;
      } else {
        const messageToSend = sendBox.value;
        const el = `<li>User: ${messageToSend}</li>`;
        transcriptWindow.innerHTML += el;
      }
    }
  );

directLine.connectionStatus$
  .subscribe(async connectionStatus => {
    switch (connectionStatus) {
      case ConnectionStatus.Uninitialized:
        console.log('CONNECTION_STATUS => UNINITIALIZED ', directLine);
        break;
      case ConnectionStatus.Connecting:
        console.log('CONNECTION_STATUS => CONNECTING ', directLine);
        break;
      case ConnectionStatus.Online:
        console.log('CONNECTION_STATUS => ONLINE ', directLine);
        break;
      case ConnectionStatus.ExpiredToken:
        console.log('CONNECTION_STATUS => EXPIRED TOKEN ', directLine);
        break;
      case ConnectionStatus.FailedToConnect:
        console.log('CONNECTION_STATUS => FAILED TO CONNECT ', directLine);
        break;
      case ConnectionStatus.Ended:
        console.log('CONNECTION_STATUS => ENDED ', directLine);
        break;
    }
  });

I hope this explanation helps!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React: Updating a property in an array of objects causes properties to become undefined

My intention was simply to update a property within an object inside an array and then update the state of the array. However, I encountered an issue where all properties except the one that was updated became undefined. The code in question is as follows ...

Definition for intersecting types

I am trying to define a function that can take two objects of different types but with the same keys: function myFunc(left, right, keys) { // simplified: for (const key of keys) { console.log(key, left[key] === right[key]) } return { left, rig ...

Validating dates in TypeScript

Currently, I am studying date handling and have an object that contains both a start and end date. For example: Startdate = "2019-12-05" and Enddate = "2020-05-20" My goal is to establish a condition that first verifies the dates are not empty. After tha ...

Step-by-step guide on transitioning code to utilize @use instead of @import

Currently, I am in the process of revamping a clubs app from Angular 9 to 18, as it has not been well maintained. My goal is to preserve as much of the frontend as possible and maintain the design more or less the same. Within the code, I have identified ...

Ways to conceal a div when the array length is zero

I am faced with an issue regarding filtering a table of objects (Bills => Bill => Products => Product) using pipes. The pipe filtering works correctly, but even after the arrays have been filtered, the names (bill.name) are still visible when they ...

In Angular, the template view does not update when data is removed from property bindings while using a custom pipe transform function

I am working with an array of items that undergo a custom pipe transform function before being displayed to the user. Here is an example: ` <mat-chip [removable]="true" (removed)="onRemoveImage(storeImage)" ...

Unable to apply styling to table cells that are dynamically added using JQuery within an Angular

Currently working on setting up a form using Angular. Within the hotel.view.html file, there is a table that looks like this: <table id="rooms"> <tr> <td>Room Type</td><td>Beds</td><td>Q.ty</td ...

What is the process for embedding images in Angular that are stored in a directory other than assets?

I am working on an Angular Application with a particular structure outlined below: Structure Within the structure, there is a directory labeled backend (highlighted in yellow) containing other directories. An example of a valid path within this structure ...

Utilizing props in React results in the introduction of an array

One of my components sends an array of movies to a child component: const films: IMovie[] = data.movies; console.log(films); return ( <React.Fragment> <DashboardMovieOverviewMenu /> { films.length > 0 ? <MovieOverview movies={f ...

Encountering compilation issues in Angular 9 following the transition from Angular 8

I recently upgraded my Angular application from version 8 to version 9. When I try to run ng serve --open, the app opens in the browser but gets stuck on the loading screen. The console displays an error message that says: core.js:610 Uncaught Error: Ang ...

Buffer Overflow - Security Audit - Node JS TypeScript Microservice Vulnerability Scan Report

Person Data Schema: import JoiBase from '@hapi/joi'; import JoiDate from '@hapi/joi-date'; const Joi = JoiBase.extend(JoiDate); const personDataSchema = Joi.object().keys({ person: Joi.object().keys({ personId: Joi.string().max( ...

What is the process for specifying an input for a component?

When defining an input for a component like this: @Input() person: Person, some encountered the error message saying, "property 'person' has no initializer and is not definitely assigned in the constructor" even though the Person model has been i ...

Having trouble with testing an Angular directive?

This is a snippet from my directive spec file for Angular 6. import { Component, DebugElement, NO_ERRORS_SCHEMA } from '@angular/core'; import { TestBed, ComponentFixture, async } from '@angular/core/testing'; import { By } from ' ...

What is the process for exporting libraries in TypeScript?

Encountering an error when attempting to export socket.io using this method import socketIOClient from 'socket.io-client';. The error message is TS1192: Module '"***/node_modules/socket.io-client/build/index"' has no default e ...

What is the rationale behind assigning a random value to the `(keyup)` event in order to update template local variables in Angular2?

To update #box in <p>, I need to give a random value to the (keyup) attribute. Here's an example: <!-- The value on the right of equality sign for (keyup) doesn't matter --> <input #box (keyup)="some_random_value" placeholder ...

Angular4 - Implementing a Masterpage with Parent-child components for Header, Content, and Footer structures

When clicking on a link in the header component, the corresponding data should be displayed in the app-Content component. However, currently the data is only displaying in the header component and not in the content component. The goal is to create a Mast ...

What methods can be used to accurately display the data type with TypeOf()?

When working with the following code: const data = Observable.from([{name: 'Alice', age: 25}, {name: 'Bob', age: 35}]); console.log(typeof(data)); The type is displayed as Object(). Is there a way to obtain more specific information? ...

Is there a method to automatically select or deselect a checkbox based on the incoming value in Angular?

When new data comes in, the table gets populated and I can't specify that "A" should be checked while "D" shouldn't. re(ref: getrefactormodel, count:number){ let data= this.fb.group({ word_to_rename: [ref.word_to_rename, Vali ...

Issues encountered when attempting to use ngModel within ngFor (Angular version 5.1.2)

Encountering some unusual behavior with the combination of ngFor and ngModel. Allow me to illustrate with an example: heroes = [ { "name": "Deadpool" }, { "name": "Thor" }, { "name": "Superman" }, { "name": "Ba ...

Please ensure that the Angular Input field only allows for numbers to be entered, with the exception that the

My input should only allow numbers, with the exception of the first digit being zero. I have attempted to use regex in this directive, but it is not functioning as expected. import { Directive ,ElementRef, HostListener} from '@angular/core'; @Di ...