Programmatically sending a message to a bot in Microsoft Teams

Basically you want to message the user directly at a specific point in time (like 24 hours later). I’m doing this in a few different bots, so it’s definitely possible. The link that Wajeed has sent in the comment to your question is exactly what you need – when the user interacts with your bot, you need to save important information like the conversation id, conversation type, service url, and To and From info. You can store this, for instance, in a database, and then you can actually have a totally separate application make the call AS IF IT WAS your bot. In my bots, for example, I have the bot hosted in a normal host (e.g. Azure Website) but then have an Azure Function that sends the messages, for example, 24 hours later. It just appears to the user as if it was a message from the bot, like normal.

You will also need the Microsoft App ID and App Password for your bot, which you should have already (if not, it’s in the Azure portal).

In your “sending” application, you’re going to need to create an instance of Microsoft. Bot.Connector.ConnectorClient, like follows:

var Connector = new ConnectorClient(serviceUrl, microsoftAppId: credentialProvider.AppId, microsoftAppPassword: credentialProvider.Password);

You also need to “trust” the service url you’re calling, like this:

MicrosoftAppCredentials.TrustServiceUrl(serviceURL);

Then you create an instance of Microsoft.Bot.Schema.Activity, set the required properties, and send it via the connector you created:

 var activity = Activity.CreateMessageActivity();

 activity.From = new ChannelAccount([FromId], [FromName];
 activity.Recipient = new ChannelAccount([ToId], [ToName]);
 activity.Conversation = new ConversationAccount(false, [ConversationType], [ConversationId]);
 activity.Conversation.Id = [ConversationId];

 activity.Text = "whatever you want to send from the bot...";

 Connector.Conversations.SendToConversationAsync((activity as Activity)).Wait();

All the items in square braces are what you get from the initial conversation the user is having with the bot, except that the From and To are switched around (when the user sends your bot a message, the user is the FROM and your Bot is the TO, and when the bot is sending you switch them around.

Hope that helps

Leave a Comment

tech