botframework-sdk icon indicating copy to clipboard operation
botframework-sdk copied to clipboard

Make bot send a message to a certain user in response to another user action

Open piffarettig opened this issue 9 years ago • 15 comments

To put this simple:

I have User A and User B. Both have added my bot in their corresponding Skype accounts. Whenever User A does some specific action, I want to trigger a message to User B, via Skype Bot as well. So basically this is an example of a bot messaging 'proactively' but not to the same user, to a different one. That is because User B will be receiving a message from his bot a consequence of some action User A did. Whenever the User B receives the message, he does some action in response that goes backwards to User A.

Any suggestions on how should I implement this? Any examples?

Bot Connector Service has any way of implementing this?

Thanks

piffarettig avatar Jan 03 '17 17:01 piffarettig

I found this: Starting Conversations, where this code is shown as an example for starting 1:1 conversations:

var userAccount = new ChannelAccount(name: "Larry", id: "@UV357341");
var connector = new ConnectorClient(new Uri(incomingMessage.ServiceUrl));
var conversationId = await connector.Conversations.CreateDirectConversationAsync(botAccount, userAccount);
IMessageActivity message =  Activity.CreateMessageActivity();
message.From = botAccount;
message.Recipient = userAccount;
message.Conversation = new ConversationAccount(id: conversationId.Id);
message.Text = "Hello";
message.Locale = "en-Us";
await connector.Conversations.SendToConversationAsync((Activity)message); 

However I still have some doubts:

  1. How can I get the ChannelAccount properties (name and id) for the user I want to message? In the example the values are hardcoded.
  2. botAccount:ChannelAccount was never initialized in that code. I guess var botAccount = activity.Recipient; would do the trick right?

Probably @willportnoy or @dandriscoll know this.

Thanks!

piffarettig avatar Jan 03 '17 18:01 piffarettig

@piffarettig For sending messages from Bot to a user on Skype, we are saving the ResumptionCookie from the "conversationUpdate" activity along with the Skype user Display Name in a SQL Azure DB (You can store this in any external database of your choice). This is then used for sending messages to a user from the bot. We have built on top of the Proactive Bot example (https://docs.botframework.com/en-us/azure-bot-service/templates/proactive/) in .NET.

This has worked for us, but may not be the most elegant (or best practice) way to do this. @dandriscoll - Kindly share your insight on this approach.

abhishan avatar Jan 03 '17 19:01 abhishan

UPDATE:

Some way I found of getting the ID of the certain user was this one:

  1. Created a new Skype user to act as User B. Made it send a random message to the Bot.
  2. Debugging the bot's logic, I saw its ChannelAccount info by doing activity.From.
  3. Copied both name and id values.
  4. Then I tested sending a message from User A to that User B (the one I ve just copied its values), changing the parameters in the userAccount (code above), for the ones I copied.

It worked and User B received the message.

That was just a hardcoded test to know if that could be achieved, although I am not sure of what could be the best option to store the user info I need to send messages proactively. What do you suggest? Another way ?

And, does that Id change? Or is it always the same?

piffarettig avatar Jan 03 '17 19:01 piffarettig

In order to send message to a User B I think you need to have some recipient info about User B and that can be only obtained once User B interacts with bot. Problem is platforms like Skype, and FB don't let you send message to people directly (if they have not interacted with bot before). I think it's possible in channels like Slack to do at mentions even if user have not interacted with bot before, but not everywhere else. @msft-shahins should be able to add more details.

maxpert avatar Jan 03 '17 21:01 maxpert

Yes, this is possible.

You need to have the user's channel account. On Skype, this account is obfuscated to bots, so the user must contact the bot first. On other channels, like email and SMS, the account is simply the user's contact information, and you can reach out to the user on your own.

If you have a conversation ID corresponding to a discussion with the user you want to contact, you can use that conversation ID directly. (Don't try to create a conversation ID on your own.)

If you don't have a conversation ID or if you want to start a new conversation (relevant for channels like email), call the CreateConversation API and specify the user in the parameters to that call. This will return a conversation ID and you can send activities as usual.

dandriscoll avatar Jan 04 '17 04:01 dandriscoll

@dandriscoll ok. Thanks. The channel I'm using is Skype. Supposing that in the interaction with the bot is carried out successful and I have the conversation ID between them:

  1. What is the best option to store that ID?
  2. How do I know is the first time the bot and the user started talking? Because I don't want to save the conversationId every time a message is sent.

piffarettig avatar Jan 04 '17 16:01 piffarettig

@abhishan thanks! Proactive bot uses Azure Queue and Azure functions... How re you using that? Seems a little bit too much for what I want to achieve. Why adding messages to queues?

EDIT:

Another question, if I just use an SQL Azure DB that I query from the Bot to get the Conversation Id, how do you know that is the one corresponding to your user? You say you use Display Name, but that is not unique, multiple users can have the same display name. Any workaround?

piffarettig avatar Jan 04 '17 17:01 piffarettig

Hello piffaretting, You can log user chat history in your DB, you can store field like conversation Id,bot ID, user name etc(all fields you will get it in botbuilder session). When you want to send a message from bot to user you can use DB data. Please refer below code for storing user chat history,

var bot = new builder.UniversalBot(connector);
bot.use({
    receive: function (event, next) {
        if (event.address.channelId !== 'emulator') {
            // GET CURRENT INVOICE ID
            var CurrentInvoiceID = '';
            if (event.text !== undefined) {

                var data = {
                    CustomerId: "CustomerId",
                    customerName: event.user.name,
                    invoiceId: CurrentInvoiceID,
                    id: event.user.id,
                    message: event.text,
                    messengerChannel: event.address.channelId,
                    timeStamp: event.timestamp,
                    botId: event.address.bot.id,
                    conversationId: event.address.conversation.id
                }
                dbhelper.insertUserChatDetails(data);
                //LOG DASH BOT
                bothelper.DashLogg(event, "incoming");
            }
        }
        next();
    },
    send: function (event, next) {

        if (event.address.channelId !== 'emulator') {
            // GET CURRENT INVOICE ID
            var CurrentInvoiceID = '';
            if (event.text !== undefined) {
                var startDate = new Date();
                var data = {
                    CustomerId: "CustomerId",
                    customerName: event.agent,
                    invoiceId: CurrentInvoiceID,
                    id: event.agent,
                    message: event.text,
                    messengerChannel: event.address.channelId,
                    timeStamp: startDate,
                    botId: event.address.bot.id,
                    conversationId: event.address.conversation.id
                }
                dbhelper.insertUserChatDetails(data);

                //SEND SMS 
                //LOG DASH BOT
                bothelper.DashLogg(event, "outgoing");
            }
        }
       // bothelper.SendTestSMS(event.text, function (res) {
       //     next();
      //  });

    }
});

chetanmekha avatar Jan 06 '17 06:01 chetanmekha

I solved it using doing mostly three things:

  1. Setting up an Azure Table Storage on Azure (due to its simplicity, and that I don't require a Relational database for this, but you could use any other database you wan't).

  2. Saving user channel info the first time they establish connection (in C# this is when the activity type is ContactRelationUpdate).

  3. Then using the code above (here), to send proactive messages from the bot to the user. As I stated:

botAccount:ChannelAccount was never initialized in that code. var botAccount = activity.Recipient did the trick. This would be the new 'From' in your message. Similarly, the new 'Recipient' is going to be the user you saved in Azure Table Storage (supplanting the one that appears hardcoded in the example). Here you can learn how to use Table Storage

piffarettig avatar Jan 06 '17 19:01 piffarettig

@abhishan How did you detect when to save the ResumptionCookie within the "ConversationUpdate" activity. I am using the Proactive template as a base as well and have noticed when using the "Trigger" activity that "ConversationUpdate" is firing first and I'm struggling to determine the right state to save the conversation id etc...

Thanks

mmacneil avatar Jan 25 '17 18:01 mmacneil

@piffarettig In your case, are you using Skype as the channel? I am working on a similar scenario, but using the Webchat. In case of Webchat, I cannot identify the user uniquely. Do you have any suggestions to take this forward?

dhinag avatar Jun 22 '18 20:06 dhinag

@chetanmekha do you have any example in nodejs? Is it possible to send a message to a specific Skype account?

I'm using nodejs, and Dialogflow.

Thanks!

alexandrenunes-cs avatar Oct 18 '18 21:10 alexandrenunes-cs

hi, I am using bot framework v3 and node. I am saving user address on the first interaction on conversationUpdate. bot.on('conversationUpdate', (message) => { insertaddresstoDB(message) }); function insertaddresstoDB(message) { DB.insertaddress(message.user.name, message.address) .then((result) => { // some code
}) .catch((error) => { //some code });
}

After this when I am trying to send any msg on this address I am getting Invalid channelID error.

 MainBotDB.getaddress(username)
  .then((result) => {
    var useraddress=JSON.parse(result);

var msg = new builder.Message() .text('some message') .address(useraddress); bot.send(msg, function (err, useraddress) { console.log('done'); }); });

error : Error: Invalid channelId='skype' at D:\home\site\wwwroot\node_modules\botbuilder\lib\bots\UniversalBot.js:216:31 at UniversalBot.tryCatch (D:\home\site\wwwroot\node_modules\botbuilder\lib\bots\UniversalBot.js:516:13) at D:\home\site\wwwroot\node_modules\botbuilder\lib\bots\UniversalBot.js:212:23 at D:\home\site\wwwroot\node_modules\botbuilder\lib\bots\UniversalBot.js:536:17 at D:\home\site\wwwroot\node_modules\async\lib\async.js:52:16 at replenish (D:\home\site\wwwroot\node_modules\async\lib\async.js:314:29) at D:\home\site\wwwroot\node_modules\async\lib\async.js:326:29 at D:\home\site\wwwroot\node_modules\async\lib\async.js:44:16 at D:\home\site\wwwroot\node_modules\botbuilder\lib\bots\UniversalBot.js:207:21 at D:\home\site\wwwroot\node_modules\botbuilder\lib\bots\UniversalBot.js:427:53

RohanSaini avatar Nov 10 '18 08:11 RohanSaini

@mmacneil @piffarettig ,can u help me how to make a chat bot to have conversation to two or more user under Ms teams or simple a azure chat bot

vijaiv avatar Jan 25 '19 02:01 vijaiv

@mmacneil @piffarettig and also how to get diff user ID and reply to them

vijaiv avatar Jan 25 '19 02:01 vijaiv