Calling an external API from MS Teams chat bot

Copper Contributor

Hi

 

I'm working on integrating MS Teams chat bot with an external API via using websockets. The problem is that after I get the response, the bot doesn't send it back to the chat. I guess the problem lies in the asynchronism of the call. Here's a code snippet:  

 

 

 

const { TeamsActivityHandler, CardFactory, TurnContext, TeamsInfo } = require("botbuilder");
const rawWelcomeCard = require("./adaptiveCards/welcome.json");
const rawLearnCard = require("./adaptiveCards/learn.json");
const rawModelsCard = require("./adaptiveCards/models.json");
const rawResetCard = require("./adaptiveCards/reset.json");
const cardTools = require("@microsoft/adaptivecards-tools");
const WebSocket = require("ws");

class TeamsBot extends TeamsActivityHandler {
  constructor() {
    super();
    
    this.webSocket = new WebSocket("wss://7m1s3vep8g.execute-api.us-east-1.amazonaws.com/prod");
    this.modelObj = {model: "anthropic.claude-v2"};
    this.messagesArrays = [];

    this.webSocket.onopen = async (event) => {
      console.log("connection established")
    }

    this.onMessage(async (context, next) => {
      let txt = context.activity.text;
      const removedMentionText = TurnContext.removeRecipientMention(context.activity);

      console.log("websocket - ", this.webSocket.readyState)
      
      if (removedMentionText) {
        // Remove the line break
        txt = removedMentionText.toLowerCase().replace(/\n|\r/g, "").trim();
      }
      
      // Trigger command by IM text
      switch (txt) {
        case "models": {
          const card = cardTools.AdaptiveCards.declare(rawModelsCard).render(this.modelObj);
          await context.sendActivity({ attachments: [CardFactory.adaptiveCard(card)] });
          
          break;
        }

        case "reset": {
          this.messagesArrays = [];
          const card = cardTools.AdaptiveCards.declareWithoutData(rawResetCard).render();
          await context.sendActivity({ attachments: [CardFactory.adaptiveCard(card)] });
          
          break;
        }

        default: {
          const message = {
            "role":"user", "content": txt
          };
    
          this.messagesArrays.push(message)
    
          const data = {"modelId": this.modelObj.model, "prompt": this.messagesArrays}
          const string = JSON.stringify(data);
          this.webSocket.send(string)

          this.webSocket.onmessage = async (event) => {
            const msg = event["data"]
            const trimmedMessage = msg.replace(/\n|\r|"/g, "").trim();
            const message = {
              "role":"system", "content": trimmedMessage
            };
          
            this.messagesArrays.push(message);
            console.log(this.messagesArrays)
          
            let test = await context.sendActivity("trimmedMessage");
            console.log(test)
            
            await context.sendActivity(trimmedMessage);
          }
          
          
          break;
        }
      }
      
      // By calling next() you ensure that the next BotHandler is run.
      await next();
    });

    // Listen to MembersAdded event, view https://docs.microsoft.com/en-us/microsoftteams/platform/resources/bot-v3/bots-notifications for more events
    this.onMembersAdded(async (context, next) => {
      const membersAdded = context.activity.membersAdded;
      for (let cnt = 0; cnt < membersAdded.length; cnt++) {
        if (membersAdded[cnt].id) {
          const card = cardTools.AdaptiveCards.declareWithoutData(rawWelcomeCard).render();
          await context.sendActivity({ attachments: [CardFactory.adaptiveCard(card)] });
          break;
        }
      }
      await next();
    });
  }

  // Invoked when an action is taken on an Adaptive Card. The Adaptive Card sends an event to the Bot and this
  // method handles that event.
  async onAdaptiveCardInvoke(context, invokeValue) {
    // The verb "userlike" is sent from the Adaptive Card defined in adaptiveCards/learn.json
    switch (invokeValue.action.verb) {
      case "1": {
        this.modelObj.model = "anthropic.claude-v2";
        const card = cardTools.AdaptiveCards.declare(rawModelsCard).render(this.modelObj);
       
        await context.updateActivity({
          type: "message",
          id: context.activity.replyToId,
          attachments: [CardFactory.adaptiveCard(card)],
        });
        
        break;
      }

      case "2": {
        this.modelObj.model = "Model B";
        const card = cardTools.AdaptiveCards.declare(rawModelsCard).render(this.modelObj);
       
        await context.updateActivity({
          type: "message",
          id: context.activity.replyToId,
          attachments: [CardFactory.adaptiveCard(card)],
        });

        break;
      }

      case "3": {
        this.modelObj.model = "Model C";
        const card = cardTools.AdaptiveCards.declare(rawModelsCard).render(this.modelObj);
       
        await context.updateActivity({
          type: "message",
          id: context.activity.replyToId,
          attachments: [CardFactory.adaptiveCard(card)],
        });

        break;
      }
    }

    return { statusCode: 200 };
  }
}

module.exports.TeamsBot = TeamsBot;

 

 

1 Reply
I need help teamsbot oninstallationupdate is not firing