Search code examples
c#.netbotframeworkbots

MS Enterprise Bot (v4) - how to exactly do a user mention programatically


I'm really tired of microsoft incomplete documentation. I have been bangin my head for a few days just to create a user mention. Scanned the internet for bits of code and tried to combine, but i still havent made it work.

var reply = turnContext.Activity.CreateReply($"Test mention <at>@{name}</at>");
var entity = new Entity();
                entity.SetAs(new Mention()
                {
                    Text = $"<at>@{name}</at>",
                    Mentioned = new ChannelAccount()
                    {
                        Name = $"{name}",
                        Id = id
                    }
                });

if (turnContext.Activity.Entities == null || !turnContext.Activity.Entities.Any())
            {
                var list = new List<Entity> { entity };
                turnContext.Activity.Entities = list;
            }
            else
                turnContext.Activity.Entities.Add(entity);

await turnContext.SendActivityAsync(reply);

Anyone have thoughts on how to programatically post/send/reply message with a user mention?

Thanks in advance.


Solution

  • I apologize that documentation hasn't been easy to find. Mentions aren't fully-supported across both dotnet and Node SDKs yet. However, this is possible to do with the current dotnet SDK. Edit: this is now fully supported in both SDKs

    Your code looks pretty good except that you're adding the entity to TurnContext and not the reply I think this is your issue). Try this, which I've tested and works:

    var userId = "29:1lpScfExyzx-asdfasdfasdfasdf_fasdfasdfasdfasdfasdfasdfasdfasdfasdf";
    var userName = "YourName";
    
    var reply = turnContext.Activity.CreateReply();
    
    reply.Text = $"<at>{ userName }</at> testing....";
    
    var mentioned = new ChannelAccount()
    {
        Id = userId,
        Name = userName
    };
    
    var entity = new Mention()
    {
        Mentioned = mentioned,
        Text = $"<at>{ userName }</at>",
    };
    
    reply.Entities = new List<Entity>() { entity };
    
    await turnContext.SendActivityAsync(reply);
    

    Make sure that reply.Text contains entity.Text or this will not work (in the example, <at>{ userName }</at> is in both).

    If you run into issues, Visual Studio doesn't provide much error information. However, if you open Azure > Your Web App Bot > Channels and look at the Teams Channel Issues, it gives a little more information about what might be wrong.

    Teams also has a Botbuilder Teams Dotnet SDK that has additional documentation and methods. It acts as a wrapper around the Botbuilder SDk to make some Teams-specific things easier. Note that this one is kind of tricky to search for and is different from this SDK which only supports V3 bots.