Я создал приложение Teams с ботом для уведомлений, использующим адаптивные карточки. Взаимодействие с адаптивной картой отлично работает в моей локальной среде, но не работает при развертывании в Службе приложений Azure (ОС Windows). Локально взаимодействие срабатывает onInvokeActivity, но в облаке оно проходит onMessage.
Вот соответствующий код:
const { TeamsActivityHandler, StatusCodes, MessageFactory, CardFactory } = require("botbuilder");
const { updateInstanceState } = require("./merlinOperations");
// An empty teams activity handler.
// You can add your customization code here to extend your bot logic if needed.
class TeamsBot extends TeamsActivityHandler {
constructor() {
super();
this.onMessage(async (context, next) => {
console.info("llegamos hasta el onMessage ", context.activity);
if (context.activity.name === "adaptiveCard/action") {
console.info("Activity information ", context.activity);
let invokeResponse = await this.onInvokeActivity(context);
console.info("invokeResponse information ", invokeResponse);
let message = MessageFactory.attachment(CardFactory.adaptiveCard(invokeResponse.body.value));
message.id = context.activity.replyToId;
console.info("new message information ", message);
await context.updateActivity(message);
}
else {
await context.sendActivity("Este bot es solo para generar notificaciones desde merlin");
}
//This next calls the next event(Middleware) in case we have many of them.
await next();
});
}
//This is the action triggered when interaction with an adaptive card.
async onAdaptiveCardInvoke(context) {
try {
let invokeResponse = { statusCode: StatusCodes.OK };
//if trigger === manual means that the action is a result of an user interaction.
if (context.activity.name === "adaptiveCard/action" && context.activity.value.trigger === "manual") {
//Here we go to Merlin an update the instance.
const successInteractionTemplate = await updateInstanceState(context.activity);
invokeResponse = InvokeResponseFactory.adaptiveCard(successInteractionTemplate);
await context.sendActivity({
type: ActivityTypes.InvokeResponse,
value: invokeResponse,
});
}
//if trigger === automatic means that the action is a result of an automatic refresh action
else if (context.activity.name === "adaptiveCard/action" && context.activity.value.trigger === "automatic") {
//If the validation result is undefined it means that the card has not been used yet.
const successInteractionTemplate = await validateAdaptiveCardInteraction(context.activity);
if (typeof (successInteractionTemplate) !== "undefined") {
//If the card had been used we replace it with the updated information.
invokeResponse = InvokeResponseFactory.adaptiveCard(successInteractionTemplate);
await context.sendActivity({
type: ActivityTypes.InvokeResponse,
value: invokeResponse,
});
}
}
return invokeResponse;
} catch (error) {
console.error("###ERROR ocurrió en el invoke ", error);
const errorResponse = InvokeResponseFactory.errorResponse(StatusCodes.BAD_REQUEST, `An error occurred while processing the action. ${error.message || error}`);
console.error("Error response", JSON.stringify(errorResponse, null, 2));
await context.sendActivity({
type: ActivityTypes.InvokeResponse,
value: errorResponse,
});
return errorResponse;
}
};
}
module.exports.TeamsBot = TeamsBot;
Поскольку облако context.activity.name приходит пустым, я прокомментировал if в этом операторе, чтобы проверить, работает ли оно, я могу подтвердить, что адаптивная карта для замены приходит в тело invokeResponse, но на карте просто отображается сообщение, в котором говорится:
Что-то пошло не так. Пожалуйста, попробуйте еще раз.
Будем признательны за любую информацию о том, почему взаимодействие работает локально, но не работает в Azure.
Я также попробовал это, которое работает локально (фокус на событии onAdaptiveCardInvoke)
const { TeamsActivityHandler, StatusCodes, MessageFactory, CardFactory, ActivityTypes } = require("botbuilder");
const { updateInstanceState } = require("./merlinOperations");
const { successInteractionStatusChange } = require('./adaptiveCards/templates');
const { InvokeResponseFactory } = require("@microsoft/teamsfx");
const { HttpStatusCode } = require("axios");
const { AdaptiveCard } = require("@microsoft/adaptivecards-tools");
// An empty teams activity handler.
// You can add your customization code here to extend your bot logic if needed.
class TeamsBot extends TeamsActivityHandler {
constructor() {
super();
this.onMessage(async (context, next) => {
if (context.activity.name === "adaptiveCard/action") {
let invokeResponse = await this.onInvokeActivity(context);
await context.sendActivity({
type: ActivityTypes.InvokeResponse,
value: invokeResponse,
});
}
else {
await context.sendActivity("Este bot es solo para generar notificaciones desde merlin");
}
//This next calls the next event(Middleware) in case we have many of them.
await next();
});
}
async onAdaptiveCardInvoke(context) {
try {
//Here we confirm the interaction came from an adaptive card
if (context.activity.name === "adaptiveCard/action") {
let invokeResponse = InvokeResponseFactory.adaptiveCard(successInteractionStatusChange);
invokeResponse.statusCode = StatusCodes.OK;
await context.sendActivity({
type: ActivityTypes.InvokeResponse,
value: invokeResponse,
});
return invokeResponse;
}
} catch (error) {
//If there was any error we go ahead an throw a toaster with saying an erro has occured
console.info("###ERROR ocurrió en el invoke ", error)
const cardRes = {
statusCode: StatusCodes.OK,
type: 'application/vnd.microsoft.error',
value: { message: `ha ocurrido un error ${error.message}` }
};
const res = {
status: StatusCodes.OK,
body: cardRes
};
return res;
}
};
}
module.exports.TeamsBot = TeamsBot;
@PAPIRATA перейдите по этой ссылке, чтобы предоставить и опубликовать бота в Azure.
@RajeeshMenoth совместим, фактически карта рендерится в командах, единственная проблема — при попытке взаимодействия с ней.
@Sampath, спасибо за документ, но это не то, что мне нужно.
@PAPIRATA вы выполняли развертывание в Azure Web для Windows или Linux? Какой тип приложения вы развернули: Node, Express и т. д.? развернут с помощью кода vs или git?
@Sampath Это веб-приложение для Windows, приложение построено на узле, и я развернул его с помощью набора инструментов Teams с кодом VS.





Я обнаружил, что причина, по которой карта не рендерилась в облаке, заключалась в том, что у новой карты было 3 пустых контейнера, которые каким-то образом вылетали в ответ при попытке рендеринга.
До: После:
Вывод: я удалил пустые контейнеры и поток начал работать в облаке.
Сначала проверьте, совместима ли протестированная вами адаптивная карта с каналом Teams. Я надеюсь, что вы провели локальное тестирование в канале эмулятора, но для поддержки в Teams может потребоваться дополнительное кодирование.