Welcome message Bot Framework v4 nodejs - node.js

I'm developing a multichannel bot (focusing on web and telegram) that's based on Microsoft's Bot Framework (https://learn.microsoft.com/en-us/azure/bot-service/?view=azure-bot-service-4.0)
I'm stuck with the initial message the user is getting.
My bot is based on the complex bot published by Microsoft: https://github.com/Microsoft/BotFramework-Samples/tree/master/SDKV4-Samples/js/complexDialogBot
Issue I'm seeing is that in the emulator bot is working great, on the web user is not greeted with the welcome message. I've used iframe to integrate the bot.
I'm checking activity types and when members are added to the chat, but seems like it's not triggering on the web.
if (turnContext.activity.type === ActivityTypes.ConversationUpdate) {
if (turnContext.activity.membersAdded && turnContext.activity.membersAdded.length > 0) {
await this.sendWelcomeMessage(turnContext);
}
}
I saw similar questions asked but either for bot framework v3 or C# implementation (like this one Welcome message not visibile in Webchat,but work in Emulator and Welcome Message not working in Azure portal using Microsoft Bot Builder SDK(v4) for nodejs)

try using this
enter code here
this.onMembersAdded(async context => {
const membersAdded = context.activity.membersAdded;
for (let cnt = 0; cnt < membersAdded.length; cnt++) {
if (membersAdded[cnt].id == context.activity.recipient.id) {
const welcomeCard = CardFactory.adaptiveCard(WelcomeCard);
}
}
});

You can solve your problem in below code
in iframe to integrate the bot you can write member Adding code copy in inside !turnContext.responded
if (turnContext.activity.type === ActivityTypes.Message) {
if (!turnContext.responded) {
await this.sendWelcomeMessage(turnContext);
}
}

Related

Direct Messaging custom slack bot built on node.js

I have built a slack bot using the slack/bots apis in node.js: https://slack.dev/bolt-js/tutorial/getting-started
Currently, it is working fine when I type <bot> help in a channel I have set up for using webhooks. I am trying to run those same commands in a DM with the bot using the app.event('app_mention',...) method but it is not working. its like the message doesn't register in a DM with the bot for some reason but it works in a public channel. code snippet below:
app.event('app_mention', async ({ event, client}) => {
console.log(event);
const text = event.text;
const parentMessageId = event.ts;
const eventChannel = event.channel;
if (text.includes("help")) {
console.log(event);
try {
await client.chat.postMessage({
channel: eventChannel,
text: helpMessage,
thread_ts: parentMessageId
});
} catch (err) {
console.error(err);
}
I should have permissions set up correctly as well. I basically have all the permissions that I can add for the bot
The documentation of the app_mention api specifically mentions that this event does not work with DMs.
Messages sent to your app in direct message conversations are not
dispatched via app_mention, whether the app is explicitly mentioned or
otherwise. Subscribe to message.im events to receive messages directed
to your bot user in direct message conversations.
Check here : https://api.slack.com/events/app_mention

Microsoft Bot Framework mixing conversation and dialogs between users who send request to bot at same time

I have implemented a bot using Microsoft Bot Framework SDK 4. The Bot is working fine, however I have experienced its not working when two users sends the request to the bot at same time.
I have printed the turnContext values for the users on each turn and its printing correct user and conversation data, however when the beginDialog calls, then sometimes its encountered with Error or sometimes it's mixing dialog response to users (Bot send response to other user).
I have implemented multiple dialogs steps using Waterfall Dialog: Find below code snippet : Where Message 'Hi there :) Welcome User : Name of the user ' is working fine with multiple users, but beginDialog is not working and mixing response to users.
In bot.ts
adapter.onMessage = async turnContext => {
const results = await adapter.continueDialog()
const recognitionResult = await Luis.recognize(turnContext)
const { topScoringIntent } = recognitionResult
if (topScoringIntent === 'welcome') {
await turnContext.sendActivity(`Hi there :) Welcome User ${turnContext.activity.form.name}` )
await adapter.beginDialog(DialogsTimebot.GreetingDialog, {
recognitionResult
})
}
}
In adapter.ts
async beginDialog(dialog: Dialog, options: object | undefined) {
if (!dialogMap.has(dialog)) {
const id = `dialog-${randomId()}`
const dialogClass = new (class extends ComponentDialog {
constructor() {
super(id)
this.addDialog(
new WaterfallDialog(
`waterfall-${id}`,
dialog.steps.map(step => modStep(step, dialogMap))
)
)
}
})()
dialogMap.set(dialog, { id, dialogClass })
_dialogSet.add(dialogClass)
}
const dialogId = dialogMap.get(dialog)!.id
await _dialogContext.beginDialog(dialogId, options)
},
Can anyone please help how to solve this issue? I have got stuck and not able to find the root cause. Thank you.

How to create Quick Replies using MS Bot Framework on Facebook Messenger?

I have been using Node.js and the MS Bot Framework(3.0) for my bot development needs for quite some time now.
One of my needs is to request a user to share its e-mail address with the bot.
Facebook offers a Quick Replies API exactly for that.
I am having a hard time understanding how should i utilize the framework to create a custom message with the quick reply option.
One of my first attempts was to pass native metadata to a channel using custom channel data
I have succeeded implementing various templates which are supported by Messenger platform, but quick replies are sort of other beast compared to buttons, lists and other templates. currently i struggle to create a quick reply message using the framework provided tools.
Please point me in the right direction.
You can send Facebook quick replies either through the source data in V3 of the BotFramework or through the channel data in V4 of the framework. See the two examples below:
Node
V4
await turnContext.sendActivity({
text: 'What is your email?',
channelData: {
"quick_replies":[
{
"content_type": "user_email"
}
]
}
});
V3
var message = new botbuilder.Message(session)
.text('What is your email?')
.sourceEvent({
facebook: {
"quick_replies":[
{
"content_type": "user_email"
}
]
}
});
session.send(message);
CSharp
V4
Activity reply = turnContext.Activity.CreateReply();
reply.Text = "What is your location?";
reply.ChannelData = JObject.FromObject( new {
quick_replies = new object[]
{
new
{
content_type = "location",
},
},
});
await turnContext.SendActivityAsync(reply, cancellationToken);
Hope this helps!
On v3 you can just add the JSON of the quick_reply template defined by facebook to the channeldata as JSON object (JObject)
reply.channelData = new JOBject("[JSON HERE]");

getting user list from slack API using NodeJS

I am creating a slack bot and am trying to get the list of members in a slack workspace. Below is my code.
getUserList() {
axios.get(`https://slack.com/api/users.list?token=`+process.env.SLACK_BOT_TOKEN).then((res) => {
var jsonParsed = JSON.parse(res);
for (i = 0; i < jsonParsed; i++) {
workspace_users.push(jsonParsed[i].name);
}
});
},
I am getting below response.
{"ok":true,"no_op":true,"already_open":true,"channel":{"id":"*****"},"scopes":["identify","bot:basic"],"acceptedScopes":["im:write","post"]}
I went to https://api.slack.com/methods/users.list and I am not getting the kind of result mention in the URL.
I have already given the scope permission to my bot.
Any help would be appreciated.

How to add Get Started button in the typing bar using bot builder sdk for node.js

I am using bot builder sdk for node.js to create a chatbot. Also connected it to facebook channel. I am using the following code to greet the user:
var bot = new builder.UniversalBot(connector, [
(session, result, next) => {
let text = '';
switch(session.message.address.channelId) {
case 'facebook':
text = 'Hi ' + session.message.user.name + ' !';
break;
default:
text = 'Hi !';
}
session.sendTyping();
session.say(text);
next();
},
(session, say) => {
}
]);
The above code works fine, but I want to add "Get Started" button in the typing bar to invoke the above code. Note that this button appears only once. Please find image of the typing bar below:
Is there a way to achieve this using bot builder sdk for node.js ?
Thanks
Although one can certainly add a button to start any activity with the bot, but that will limit the bots potential to only one customizable channel, i.e. WebChat.
I think there are better 2 alternative ways to get the desired functionality which will work across many channels.
First
I would suggest to add a conversation update event. Code goes in the botbuilder's middleware. Here is a sample code from the docs.
bot.on('conversationUpdate', function (message) {
if (message.membersAdded && message.membersAdded.length > 0) {
// Say hello
var txt = "Send me a Hi";
var reply = new builder.Message()
.address(message.address)
.text(txt);
bot.send(reply);
});
What this will do is make the bot send a message Send me a Hi to the user, if it determines this is a first time visitor. This will give the visitor enough cue to send the bot Hi by typing it. Although he can enter whatever he wants, but this will result in the invocation of the 1st dialog configured which in this case is the will be the dialog which you have posted in question.
Second
You can mark some dialog to be invoked automatically if your bot has never encountered this visitor. Here is the sample code...
var bot = new builder.UniversalBot(connector);
bot.dialog('firstRun', function (session) {
session.userData.firstRun = true;
session.send("Hello...").endDialog();
}).triggerAction({
onFindAction: function (context, callback) {
// Only trigger if we've never seen user before
if (!context.userData.firstRun) {
// Return a score of 1.1 to ensure the first run dialog wins
callback(null, 1.1);
} else {
callback(null, 0.0);
}
}
});
Here we have split the bot creation and dialog registration in 2 steps. And while registering the firstRun dialog, we have provided it the triggerAction that if the visitor is new, then trigger this dialog.
Both of these approaches do not use adding some extra buttons and it is up to the bot either to educate him on sending some message which in turn will start the 1st dialog or directly start some dialog.
For more info on conversationEvent you can refer to this page
I tried the above options, but they didn't seem to be working for facebook messenger. But I found a solution to add the Get Started button into the typing bar of the messenger. For that we need to use the Facebook Graph API and not the bot builder sdk.
https://graph.facebook.com/v2.6/me/messenger_profile?access_token=<PAGE_ACCESS_TOKEN>
{
"get_started":{
"payload":"Get Started"
}
}
The above API call will add the button for you to get the conversation started.
Thanks all for the help!!

Resources