Trigger a specific dialog in Bot via Directline API - node.js

I'm working on breaking my bot repo into 2 separate repos
A repo to purely handle bot logic
A repo to handle custom chat via directline
Currently , we have a feature where we can trigger the bot to start a specific dialog if its mentioned as a parameter in the URL. So something like
https://foo.com/?param=bar
would trigger the bar dialog
This is the code that handles it
function(userId, conversationId, params, token){
return new Promise((resolve, reject)=>{
var _directlineAddress = {
bot: {"id":config.BOT.ID, "name": config.BOT.HANDLE},
channelId: "directline",
serviceUrl: config.BOT.DIRECTLINE_URL,
useAuth: true,
user:{"id": userId},
"conversation": {"id": conversationId}
}
if(params.options){
var _re = /^\?(\w+)*=(\w+)*/
var _programType = _re.exec(params.options);
if (_programType[1] === "foo") {
var _dialogId = "*:/foo";
}
else {
var _dialogId = "*:/" + _programType[1];
}
} else {
var _dialogId = "*:/";
var _specialParams = {"sessionId":token};
}
bot.beginDialog(_directlineAddress, _dialogId, _specialParams, function(err){
else{
resolve();
}
});
})
};
Since i'm splitting the directline from the bot logic , i will no longer be having access to the bot object. therefore bot.beginDialog would not work here
Is there a way i can trigger the dialog by posting to the Directline API?

No. With Direct Line you will be able to send messages to the bot. I guess that a way to go here will be to define a convention message that you will send via Direct Line and that the bot logic will know that it will have to start a dialog based on it.

Related

Cannot find documentation for botframework-connector functions examples

I'm using the botframework-connector npm package. And I want to use the sendOperationRequest & sendRequest methods from the ConnectorClient instance.
I have searched for the method examples here but can not find them.
Can anyone help me, please?
Edit:
I know how to use the create/update conversations via Conversations methods. I'm trying to scope whether I can use the package for other operations such as createChannel, add members to a group etc.
You should explore code samples in
https://github.com/microsoft/BotBuilder-Samples/tree/main/samples
rather than trying to understand how to use the SDK through the class references.
sendOperationRequest & sendRequest aren't really meant to be used explicitly, ConnectorClient uses it to send the request.
In order to send your message you first need a conversation reference (otherwise, how would the bot know which conversation to send the message to?) For example, look at the sample code on the documentation page of the NPM package you linked :
var { ConnectorClient, MicrosoftAppCredentials } = require('botframework-connector');
async function connectToSlack() {
var credentials = new MicrosoftAppCredentials('<your-app-id>', '<your-app-password>');
var botId = '<bot-id>';
var recipientId = '<user-id>';
var client = new ConnectorClient(credentials, { baseUri: 'https://slack.botframework.com' });
var conversationResponse = await client.conversations.createConversation({
bot: { id: botId },
members: [
{ id: recipientId }
],
isGroup: false
});
var activityResponse = await client.conversations.sendToConversation(conversationResponse.id, {
type: 'message',
from: { id: botId },
recipient: { id: recipientId },
text: 'This a message from Bot Connector Client (NodeJS)'
});
console.log('Sent reply with ActivityId:', activityResponse.id);
}
The botID and recipientID is dependent on the channel you use.
Edit : As I misunderstood the intent of the question.
If you want to create a channel, check out
https://github.com/howdyai/botkit/blob/main/packages/docs/core.md
There are officially supported channels with adapters that you can utilize. But if you are looking to connect to a custom app, look at https://github.com/howdyai/botkit/blob/main/packages/docs/reference/web.md#webadapter
for the generic web adapter that you can use to send and receive messages.

Sending proactive messages to a channel in Teams

So,
I searched far and wide, read everything I could find on the topic and I am still failing at this. I have managed to send proactive message to user, reply to a topic in team, etc. but I am unable to send a proactive message (create new post) in a team channel.
Is there an available example (I was unable to find any)? MS Docs for NodeJS seem to show an example of messaging each user in the team, but not the channel itself.
I explored the source code, and channelData is hardcoded to null inside botFrameworkAdapter.js, which only adds to the confusion.
So, basic code is:
const builder = require('botbuilder');
const adapter = new builder.BotFrameworkAdapter({
appId: 'XXX',
appPassword: 'YYY'
});
const conversation = {
channelData: {
//I have all this (saved from event when bot joined the Team)
},
...
// WHAT THIS OBJECT NEEDS TO BE TO SEND A SIMPLE "HELLO" TO A CHANNEL?
// I have all the d
};
adapter.createConversation(conversation, async (turnContext) => {
turnContext.sendActivity('HELLO'); //This may or may not be needed?
});
Has anyone done this with Node ? If so, can anyone show me a working example (with properly constructed conversation object)?
* EDIT *
As Hilton suggested in the answer below, I tried using ConnectorClient directly, but it returns resource unavailable (/v3/conversations)
Here is the code that I am using (it's literally only that, just trying to send demo message):
const path = require('path');
const { ConnectorClient, MicrosoftAppCredentials } = require('botframework-connector');
const ENV_FILE = path.join(__dirname, '.env');
require('dotenv').config({ path: ENV_FILE });
const serviceUrl = 'https://smba.trafficmanager.net/emea/';
async function sendToChannel() {
MicrosoftAppCredentials.trustServiceUrl(serviceUrl);
var credentials = new MicrosoftAppCredentials(process.env.MicrosoftAppId, process.env.MicrosoftAppPassword);
var client = new ConnectorClient(credentials, { baseUri: serviceUrl });
var conversationResponse = await client.conversations.createConversation({
bot: {
id: process.env.MicrosoftAppId,
name: process.env.BotName
},
isGroup: true,
conversationType: "channel",
id: "19:XXX#thread.tacv2"
});
var acivityResponse = await client.conversations.sendToConversation(conversationResponse.id, {
type: 'message',
from: { id: process.env.MicrosoftAppId },
text: 'This a message from Bot Connector Client (NodeJS)'
});
}
sendToChannel();
What am I doing wrong?
Okay, so, this is how I made it work. I am posting it here for future reference.
DISCLAIMER: I still have no idea how to use it with botbuilder as was asked in my initial question, and this answer is going to use ConnectorClient, which is acceptable (for me, at least). Based on Hilton's directions and a GitHub issue that I saw earlier ( https://github.com/OfficeDev/BotBuilder-MicrosoftTeams/issues/162#issuecomment-434978847 ), I made it work finally. MS Documentation is not that helpful, since they always use context variable which is available when your Bot is responding to a message or activity, and they keep a record of these contexts internally while the Bot is running. However, if your Bot is restarted for some reason or you want to store your data in your database to be used later, this is the way to go.
So, the code (NodeJS):
const path = require('path');
const { ConnectorClient, MicrosoftAppCredentials } = require('botframework-connector');
const ENV_FILE = path.join(__dirname, '.env');
require('dotenv').config({ path: ENV_FILE });
const serviceUrl = 'https://smba.trafficmanager.net/emea/';
async function sendToChannel() {
MicrosoftAppCredentials.trustServiceUrl(serviceUrl);
var credentials = new MicrosoftAppCredentials(process.env.MicrosoftAppId, process.env.MicrosoftAppPassword);
var client = new ConnectorClient(credentials, { baseUri: serviceUrl });
var conversationResponse = await client.conversations.createConversation({
bot: {
id: process.env.MicrosoftAppId,
name: process.env.BotName
},
isGroup: true,
conversationType: "channel",
channelData: {
channel: { id: "19:XXX#thread.tacv2" }
},
activity: {
type: 'message',
text: 'This a message from Bot Connector Client (NodeJS)'
}
});
}
sendToChannel();
NOTE: As Hilton pointed out, serviceUrl also needs to be loaded from your database, along with the channel id. It is available inside the activity which you receive initially when your Bot is added to team / channel / group along with channelId which you will also need, and you need to store those for future reference (do not hardcode them like in the example).
So, there is no separate createConversation and sendActivity, it's all in one call.
Thanks Hilton for your time, and a blurred image of my hand to MS Docs :)
Hope this helps someone else
(I'm replacing my previous answer as I think this fits the situation much better).
I've looked more into this and done a Fiddler trace to get you a more complete answer. I'm not a Node guy, so I'm not sure this will translate 100%, but let's see.
Basically, you're wanting to send to the following endpoint:
https://smba.trafficmanager.net/emea/v3/conversations/19:[RestOfYourChannelId]/activities
and you'll be posting a message like the following:
{
"type": "message",
"from": {
"id": "28:[rest of bot user id]",
"name": "[bot name]"
},
"conversation": {
"isGroup": true,
"conversationType": "channel",
"id": "19:[RestOfYourChannelId]"
},
"text": "Test Message"
}
However, to post to that endpoint, you need to authenticate to it properly. It's possible to do that, and communicate with the endpoint directly, but it's actually easier to just use the built-in mechanisms. This means getting and storing the conversationreference when the bot is first installed to the channel. This file shows how to do that (see how it gets and stores the conversationReference in the this.onConversationUpdate function). In that same sample, in a different file, it shows how to use that conversation reference to actually send the pro-active message - see here, where it uses adapter.continueConversation.
One of the Microsoft bot team members also shows this in similar detail over here. He also adds MicrosoftAppCredentials.trustServiceUrl(ref.serviceUrl); which can be necessary under certain circumstances (if you're having security issues, give that a try).
That -should- cover what you need, so give it a go, and let me know if you're still having difficulties.

How to trigger a customised welcome message from Dialogflow bot using kommunicate.io?

I have just started creating a bot using dialogflow and kommunicate.io. So, I created a simple bot and integrated it with kommunicate and finally copied the kommunicatesettings script in my HTML page. I am able to get simple responses from the bot. But now I want to set a different welcome message for every HTML page. So can this be done using kommunicatesettings? I tried :
var kommunicateSettings = {"appId":"7519ee060abee2b532e8565aa0527ae","popupWidget":true,"automaticChatOpenOnNavigation":true,
"appSettings": {
"chatWidget": {
"popup": true
},
"chatPopupMessage": [{
"message": "Wanna ask something related to "+document.title+ "?",
"delay": 3000
}],
"text": {
"text": ["My welcome message!"]
}
}
};
var s = document.createElement("script"); s.type = "text/javascript"; s.async = true;
s.src = "https://widget.kommunicate.io/v2/kommunicate.app";
var h = document.getElementsByTagName("head")[0]; h.appendChild(s);
window.kommunicate = m; m._globals = kommunicateSettings;
})(document, window.kommunicate || {});
"text" in settings. But it is not able to do anything.
I want to show just the document title in the welcome message. So if some nodejs code for fulfillment can do that, it will be fine(document.title and window.location are not working in fulfillment code).
When a new conversation started and routed through the Dialogflow bot, Kommunicate triggers the Default Welcome Intent configured in Dialogflow console. However, You can customize a welcome message and set a different welcome message for your conversations dynamically. You have to create the events on the Dialogflow console and pass the event in customWelcomeEvent parameter. Below is the complete script :
(function (d, m) {
var kommunicateSettings = {
"appId": "your-app-Id",
onInit: function (status, data) {
if (status == "success") {
Kommunicate.updateSettings({ "customWelcomeEvent": "welcome_event_for_home_page" });
}
}
};
var s = document.createElement("script"); s.type = "text/javascript"; s.async = true;
s.src = "https://widget.kommunicate.io/v2/kommunicate.app";
var h = document.getElementsByTagName("head")[0]; h.appendChild(s);
window.kommunicate = m; m._globals = kommunicateSettings;
})(document, window.kommunicate || {});
You can update this setting dynamically when certain events occur on your website.
This setting will be applied to all the new conversations that started after the update i.e. The conversation started after the setting is updated will trigger the new welcome event.
Also, this setting can be used to show different welcome messages on different pages of your website.
I hope it helps.
you can enable and customise the default welcome intent in DialogFlow which Kommunicate triggers when a conversation is routed through the bot (for example upon page reload and the init of the Kommunicate plugin).
I am not sure you can customise the Welcome page for each page, at least not easily.
One approach to try is to pass some custom data to DialogFlow
var chatContext = {
"key1":"value1",
"key2":"value2"
}
Kommunicate.updateSettings({"KM_CHAT_CONTEXT":chatContext})
which is then passed on to the webhook
"originalDetectIntentRequest": {
"payload": {
"key1": "value1",
"key2": "value2"
}
}
I think it can eventually be used to personalise your welcome message.

How to tell Alexa to jump to a specific intent from LaunchRequest based on user input

I am quite new in Alexa development so please excuse my ignorance. The Alexa skill I am developing requires the following:
Users will awake the skill along with a question, e.g.
Alexa, ask marketing platform about result of last campaign
I am referring to https://developer.amazon.com/docs/custom-skills/understanding-how-users-invoke-custom-skills.html#cert-invoke-specific-request but not quite understand how to jump to a specific intent from LaunchRequest.
Where marketing platform is the skill invocation and result of last campaign is the utterance for skill intent named CampaignIntent.
There are more intents like this, which I want to call based on user's question, e.g.
Alexa, ask marketing platform to give me messaging details
I am using Lambda for the skill. At the moment it looks like the following:
exports.handler = (event, context, callback) => {
try {
if (event.request.type === 'LaunchRequest') {
var welcomeMessage = '<speak>';
welcomeMessage = welcomeMessage + 'Welcome to XYZ agency.';
welcomeMessage = welcomeMessage + '</speak>';
callback(null, buildResponse(welcomeMessage, false));
//How can I tell Alexa to jump to CampaignIntent?
}
else if (event.request.type === 'IntentRequest') {
const intentName = event.request.intent.name;
if (intentName === 'CampaignIntent') {
var ssmlConfirm = "<speak>";
ssmlConfirm = ssmlConfirm + 'Hello Auto.';
ssmlConfirm = ssmlConfirm + "</speak>";
callback(null, buildResponse(ssmlConfirm, true));
}
}
}
catch (e) {
context.fail(`Exception: ${e}`);
}
};
function buildResponse(response, shouldEndSession) {
return {
version: '1.0',
response: {
outputSpeech: {
type: 'SSML',
ssml: response,
},
shouldEndSession: shouldEndSession,
},
sessionAttributes: {},
};
}
CampaignIntent does not have any slot. It simply fetches records from a third party platform API.
I also referred https://stackoverflow.com/a/48032367/1496518 but did not understand how to achieve ...has a WHEN slot to elicit part.
The documentation you linked say, "Users can combine your invocation name with an action, command or question. This sends the service for your skill an IntentRequest with the specific intent that corresponds to the user's request."
If a user invokes your skill in this way, the intent you find in the first request of that user's session will be CampaignIntent (the IntentRequest you've defined) instead of LaunchRequest. There isn't any "jumping" you need to do on your end. The behavior will be the same with or without slot values.

Messaging a user a bot does not know

I am using the Slack RTM node client and having a bit of an issue with DM's. Say a user joins the channel who has never DM'ed the bot before, the user types a command in the channel that the bot usually will respond to and by default the bot responds in a private message to the user. However, the bot cannot do this because the dataStore does not contain any DM data for this user. Code sample below...
rtm.on(RTM_EVENTS.MESSAGE, function (message) {
user = rtm.getUserById(message.user);
console.log(user); // It gets the user object fine
dm = rtm.getDMByName(user.name);
console.log(dm); // This is always undefined unless the user has DM'ed the bot previously
});
Is there a way around this? I can't seem to find anything in the docs or code to suggest there might be.
You can use the im.open method of the web API. Here's roughly how you'd do it with #slack/client (untested, apologies in advance!):
var webClient = new WebClient(token);
...
rtm.on(RTM_EVENTS.MESSAGE, function (message) {
var dm = rtm.getDMById(message.user);
if (dm) {
console.log(`Already open IM: ${dm}`);
// send a message or whatever you want to do here
} else {
webClient.im.open(message.user, function (err, result) {
var dm = result.channel.id;
console.log(`Newly opened IM: ${dm}`);
// send a message or whatever you want to do here
});
}
});

Resources