botframeworkmicrosoft-teamsteams-ai

Teams AI Library - JS - Send proactive message


I'm trying to use app.sendProactiveActivity to send a message to the user (1:1 chat), based on the conversationReference I have stored before.

I would like to add a new route to the backend (different from /api/messages) to send the proactive message when this endpoint is called as a webhook from an external system.

When using only app.sendProactiveActivity with the following code:

// Listen for notification requests
server.post("/notify", async (req, res) => {
  // Get the conversationReference for the user
  var conversationReference = await getConversationReference("userId");

  // Send the proactive message
  await app.sendProactiveActivity(conversationReference, "This is the notification");
})

I'm getting the following error message:

{
    "code": "Internal",
    "message": "Error: You must configure the Application with an 'adapter' before calling Application.continueConversationAsync()"
}

When trying to wrap the call in a adapter.process call this way:

// Listen for notification requests
server.post("/notify", async (req, res) => {
  // Get the conversationReference for the user
  var conversationReference = await getConversationReference("userId");

  // Send the proactive message
  await adapter.process(req, res as any, async (context) => {
    await app.sendProactiveActivity(conversationReference, "This is the notification");
  });
})

I'm getting the following error message:

{
    "code": "Internal",
    "message": "Error: validateAndFixActivity(): missing activity type."
}

What should I do?


Solution

  • In Teams AI Library, to send proactive messages with the Application object, it needs to be configured with a TeamsAdapter and the id of the bot to target.

    Example:

    // Create adapter.
    // See https://aka.ms/about-bot-adapter to learn more about how bots work.
    export const adapter = new TeamsAdapter(
      {},
      new ConfigurationServiceClientCredentialFactory({
        MicrosoftAppId: process.env.BOT_ID,
        MicrosoftAppType: process.env.BOT_TYPE,
        MicrosoftAppTenantId: process.env.BOT_TENANT_ID,
        MicrosoftAppPassword: process.env.BOT_PASSWORD,
      })
    );
    
    export const app = new Application<ApplicationTurnState>({
      // Adapter and botAppId are required for the Application to send proactive messages.
      adapter: adapter,
      botAppId: config.MicrosoftAppId,
      storage: storage,
    });
    

    Then the notification can be sent with the app.sendProactiveActivity function.

    Example:

    // Listen for notification requests
    server.post("/notify", async (req, res) => {
      // Get the conversationReference for the user
      var conversationReference = await getConversationReference("userId");
    
      // Send the proactive message
      await app.sendProactiveActivity(conversationReference, "This is the notification");
    })