Search code examples
asp.net-corebotframeworkmicrosoft-teams

Send message to ms teams bot from api


I have created ms teams Bot using Microsoft documentation https://learn.microsoft.com/en-us/microsoftteams/platform/bots/how-to/create-a-bot-for-teams

Bot is working fine but communication started if i do message from ms teams bot and OnMessageActivityAsync get called.

All good but i want to initiate communication from my api, i want to send message to team bot when data is added to database. how can i create instance of ITurnContext?

private static async Task SendMessage()
 {
   ITurnContext<IMessageActivity> turnContext;// how can i get this object?
   var message = MessageFactory.Text("Hi!");
   await turnContext.SendActivityAsync(message);
 } 

Thanks


Solution

  • What you are looking for is how to send proactive messages.

    Sending a proactive message is different from replying to a message received from a user because there is no turnContext object available.

    Instead, what you can do is create a new conversation. This could be a one-to-one chat or a new conversational thread in a channel.

    When a user initially adds the bot or sends a message to the bot, the bot will be notified, and you can access and store the conversation reference for that user. Later, when you are ready to send a proactive message, you can use the stored conversation reference to create a new conversation.

    Proactive messages are explained with code samples in detail here - https://learn.microsoft.com/en-us/microsoftteams/platform/bots/how-to/conversations/send-proactive-messages?tabs=typescript