Los ejemplos de código de esta sección se basan en 4,6 y versiones posteriores del SDK de bot Framework. Si está buscando documentación para versiones anteriores, vea la sección SDK de bots-V3 en la carpeta recursos de la documentación.
Microsoft Teams envía notificaciones al bot para eventos que se suceden en ámbitos donde el bot está activo. Puedes capturar estos eventos en el código y tomar medidas en ellos, como los siguientes:
Desencadenar un mensaje de bienvenida cuando el bot se agrega a un equipo
Desencadenar un mensaje de bienvenida cuando se agrega o quita un nuevo miembro del equipo
Desencadenar una notificación cuando se crea, se cambia el nombre o se elimina un canal
Cuando un usuario le gusta un mensaje de bot
Eventos de actualización de conversación
Importante
Se pueden agregar eventos nuevos en cualquier momento y el bot empezará a recibirlos.
Debe diseñar la posibilidad de recibir eventos inesperados.
Si usa el SDK de Bot Framework, el bot responderá automáticamente con un a cualquier evento 200 - OK que no elija controlar.
Un bot recibe un evento cuando se ha agregado a una conversación, se han agregado o quitado otros miembros de una conversación, o los metadatos de conversationUpdate la conversación han cambiado.
El evento se envía al bot cuando recibe información sobre las actualizaciones de pertenencia de los equipos a los que conversationUpdate se ha agregado. También recibe una actualización cuando se ha agregado por primera vez específicamente para conversaciones personales.
En la tabla siguiente se muestra una lista de eventos de actualización de conversaciones de Teams, con vínculos para obtener más detalles.
El evento restaurado del canal se envía al bot cada vez que se restaura un canal que se eliminó anteriormente en un equipo en el que el bot ya está instalado.
async def on_teams_channel_restored(
self, channel_info: ChannelInfo, team_info: TeamInfo, turn_context: TurnContext
):
return await turn_context.send_activity(
MessageFactory.text(
f"The restored channel is {channel_info.name}. The channel id is {channel_info.id}"
)
)
Se agregaron miembros del equipo
El evento se envía al bot la primera vez que se agrega a una conversación y cada vez que se agrega un nuevo usuario a un chat de grupo o equipo en el que está teamMemberAdded instalado el bot. La información de usuario (id.) es única para el bot y puede almacenarse en caché para que el servicio la use en el futuro (por ejemplo, enviar un mensaje a un usuario específico).
protected override async Task OnTeamsMembersAddedAsync(IList<TeamsChannelAccount> teamsMembersAdded , TeamInfo teamInfo, ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
{
foreach (TeamsChannelAccount member in teamsMembersAdded)
{
if (member.Id == turnContext.Activity.Recipient.Id)
{
// Send a message to introduce the bot to the team
var heroCard = new HeroCard(text: $"The {member.Name} bot has joined {teamInfo.Name}");
await turnContext.SendActivityAsync(MessageFactory.Attachment(heroCard.ToAttachment()), cancellationToken);
}
else
{
var heroCard = new HeroCard(text: $"{member.Name} joined {teamInfo.Name}");
await turnContext.SendActivityAsync(MessageFactory.Attachment(heroCard.ToAttachment()), cancellationToken);
}
}
}
async def on_teams_members_added(
self, teams_members_added: [TeamsChannelAccount], turn_context: TurnContext
):
for member in teams_members_added:
await turn_context.send_activity(
MessageFactory.text(f"Welcome your new team member {member.id}")
)
return
_ * *
Miembros del equipo eliminados
El evento se envía al bot si se quita de un equipo y cada vez que se quita un usuario de un equipo del que el teamMemberRemoved bot es miembro. Puede determinar si el nuevo miembro quitado era el propio bot o un usuario mirando el Activity objeto del turnContext archivo . Si el campo del objeto es el mismo que el campo del objeto, el miembro quitado es el bot; de lo IdMembersRemovedIdRecipient contrario, es un usuario. Por lo Id general, los bots serán: 28:<MicrosoftAppId>
[!Note] Cuando un usuario se elimina permanentemente de un inquilino, se membersRemoved conversationUpdate desencadena el evento.
protected override async Task OnTeamsMembersRemovedAsync(IList<ChannelAccount> membersRemoved, TeamInfo teamInfo, ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
{
foreach (TeamsChannelAccount member in membersRemoved)
{
if (member.Id == turnContext.Activity.Recipient.Id)
{
// The bot was removed
// You should clear any cached data you have for this team
}
else
{
var heroCard = new HeroCard(text: $"{member.Name} was removed from {teamInfo.Name}");
await turnContext.SendActivityAsync(MessageFactory.Attachment(heroCard.ToAttachment()), cancellationToken);
}
}
}
El objeto del siguiente ejemplo de carga se basa en agregar un miembro a un equipo en lugar de un chat en grupo o iniciar una nueva conversación uno channelData a uno:
async def on_teams_members_removed(
self, teams_members_removed: [TeamsChannelAccount], turn_context: TurnContext
):
for member in teams_members_removed:
await turn_context.send_activity(
MessageFactory.text(f"Say goodbye to {member.id}")
)
return
Se cambió el nombre del equipo
El bot recibe una notificación cuando se ha cambiado el nombre del equipo en el que se encuentra. Recibe un conversationUpdate evento con en el eventType.teamRenamedchannelData objeto.
protected override async Task OnTeamsTeamRenamedAsync(TeamInfo teamInfo, ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
{
var heroCard = new HeroCard(text: $"{teamInfo.Name} is the new Team name");
await turnContext.SendActivityAsync(MessageFactory.Attachment(heroCard.ToAttachment()), cancellationToken);
}
export class MyBot extends TeamsActivityHandler {
constructor() {
super();
this.onTeamsTeamRenamedEvent(async (teamInfo: TeamInfo, turnContext: TurnContext, next: () => Promise<void>): Promise<void> => {
const card = CardFactory.heroCard('Team Renamed', `${teamInfo.name} is the new Team name`);
const message = MessageFactory.attachment(card);
await turnContext.sendActivity(message);
await next();
});
}
}
async def on_teams_team_renamed(
self, team_info: TeamInfo, turn_context: TurnContext
):
return await turn_context.send_activity(
MessageFactory.text(f"The new team name is {team_info.name}")
)
Equipo archivado
El bot recibe una notificación cuando se archiva el equipo en el que está instalado. Recibe un conversationUpdate evento con en el eventType.teamarchivedchannelData objeto.
protected override async Task OnTeamsTeamArchivedAsync(TeamInfo teamInfo, ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
{
var heroCard = new HeroCard(text: $"{teamInfo.Name} is the team name");
await turnContext.SendActivityAsync(MessageFactory.Attachment(heroCard.ToAttachment()), cancellationToken);
}
async def on_teams_team_archived(
self, team_info: TeamInfo, turn_context: TurnContext
):
return await turn_context.send_activity(
MessageFactory.text(f"The team name is {team_info.name}")
)
Equipo restaurado
El bot recibe una notificación cuando se restaura el equipo en el que está instalado. Recibe un conversationUpdate evento con en el eventType.teamrestoredchannelData objeto.
protected override async Task OnTeamsTeamrestoredAsync(TeamInfo teamInfo, ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
{
var heroCard = new HeroCard(text: $"{teamInfo.Name} is the team name");
await turnContext.SendActivityAsync(MessageFactory.Attachment(heroCard.ToAttachment()), cancellationToken);
}
async def on_teams_team_restored(
self, team_info: TeamInfo, turn_context: TurnContext
):
return await turn_context.send_activity(
MessageFactory.text(f"The team name is {team_info.name}")
)
Eventos de reacción de mensajes
El evento se envía cuando un usuario agrega o quita las reacción messageReaction a un mensaje enviado por el bot. Contiene el identificador del mensaje específico y el tipo de reacción replyToIdType en formato de texto. Entre los tipos de reacción se incluyen: "resalte", "corazón", "desanualizado", "me gusta", "Lamentablemente", "sorpresa". Este evento no contiene el contenido del mensaje original, por lo que si el procesamiento de las reacción a los mensajes es importante para el bot, tendrá que almacenar los mensajes cuando los envíe.
protected override async Task OnReactionsAddedAsync(IList<MessageReaction> messageReactions, ITurnContext<IMessageReactionActivity> turnContext, CancellationToken cancellationToken)
{
foreach (var reaction in messageReactions)
{
var newReaction = $"You reacted with '{reaction.Type}' to the following message: '{turnContext.Activity.ReplyToId}'";
var replyActivity = MessageFactory.Text(newReaction);
var resourceResponse = await turnContext.SendActivityAsync(replyActivity, cancellationToken);
}
}
export class MyBot extends TeamsActivityHandler {
constructor() {
super();
this.onReactionsAdded(async (context, next) => {
const reactionsAdded = context.activity.reactionsAdded;
if (reactionsAdded && reactionsAdded.length > 0) {
for (let i = 0; i < reactionsAdded.length; i++) {
const reaction = reactionsAdded[i];
const newReaction = `You reacted with '${reaction.type}' to the following message: '${context.activity.replyToId}'`;
const resourceResponse = context.sendActivity(newReaction);
// Save information about the sent message and its ID (resourceResponse.id).
}
}
});
}
}
protected override async Task OnReactionsRemovedAsync(IList<MessageReaction> messageReactions, ITurnContext<IMessageReactionActivity> turnContext, CancellationToken cancellationToken)
{
foreach (var reaction in messageReactions)
{
var newReaction = $"You removed the reaction '{reaction.Type}' from the following message: '{turnContext.Activity.ReplyToId}'";
var replyActivity = MessageFactory.Text(newReaction);
var resourceResponse = await turnContext.SendActivityAsync(replyActivity, cancellationToken);
}
}
export class MyBot extends TeamsActivityHandler {
constructor() {
super();
this.onReactionsRemoved(async(context,next)=>{
const reactionsRemoved = context.activity.reactionsRemoved;
if (reactionsRemoved && reactionsRemoved.length > 0) {
for (let i = 0; i < reactionsRemoved.length; i++) {
const reaction = reactionsRemoved[i];
const newReaction = `You removed the reaction '${reaction.type}' from the message: '${context.activity.replyToId}'`;
const resourceResponse = context.sendActivity(newReaction);
// Save information about the sent message and its ID (resourceResponse.id).
}
}
});
}
}