Proactive Messaging
In Sending Messages, you were shown how to respond to an event when it happens. However, there are times when you want to send a message to the user without them sending a message first. This is called proactive messaging. You can do this by using the send method in the app instance. This approach is useful for sending notifications or reminders to the user.
The main thing to note is that you need to have the conversationId of the chat or channel that you want to send the message to. It's a good idea to store this value somewhere from an activity handler so that you can use it for proactive messaging later.
- Minimal
app.OnInstall(async context =>
{
// Save the conversation id in
context.Storage.Set(activity.From.AadObjectId!, activity.Conversation.Id);
await context.Send("Hi! I am going to remind you to say something to me soon!");
notificationQueue.AddReminder(activity.From.AadObjectId!, Notifications.SendProactive, 10_000);
});
Then, when you want to send a proactive message, you can retrieve the conversationId from storage and use it to send the message.
public static class Notifications
{
public static async Task SendProactive(string userId)
{
var conversationId = (string?)storage.Get(userId);
if (conversationId is null) return;
await app.Send(conversationId, "Hey! It's been a while. How are you?");
}
}
In this example, you see how to get the conversationId using one of the activity handlers. This is a good place to store the conversation id, but you can also do this in other places like when the user installs the app or when they sign in. The important thing is that you have the conversation id stored somewhere so you can use it later.
Targeted Proactive Messages​
Targeted messages are currently in preview.
Targeted messages, also known as ephemeral messages, are delivered to a specific user in a shared conversation. From a single user's perspective, they appear as regular inline messages in a conversation. Other participants won't see these messages.
When sending targeted messages proactively, you must explicitly specify the recipient account.
// When sending proactively, you must provide an explicit recipient account
public static async Task SendTargetedNotification(string conversationId, Account recipient)
{
var teams = app.UseTeams();
await teams.Send(
conversationId,
new MessageActivity("This is a private notification just for you!")
.WithRecipient(recipient, isTargeted: true)
);
}