How to detect when bot was added to conversation and other events? - node.js

I am testing a bot that I am building using the Bot Framework. The emulator for local testing that Microsoft created has several events that can be provided to the bot to solicit a response.
I looked at the GitHub samples provided for Node.js here, but I can not find any example that responds to the different events within the Bot Framework Emulator.
The states are:
Bot Added to Conversation
Bot Removed from Conversation
User Added to Conversation
User Removed from Conversation
End of Conversation
Ping
Delete User Data
The API also does not make it clear how to achieve any of these actions.
Does anyone have any insight on where I should be looking for a example, or the API entries that I should be using?
In response to one of the answers, I did try code -
.onDefault(function (session) { console.log(session.message.type); }
But it only ever display "message" if a message was sent by the user.

The incoming message.type field will have "BotAddedToConversation" etc.

For the Node SDK, the botConnectorBot is able to trigger custom listeners on events using the on() handler.
Example
var builder = require('botbuilder');
var bot = new builder.BotConnectorBot({ appId: 'APPID', appSecret: 'APPSECRET' });
bot.on('DeleteUserData', function(message) {
// Handle Deleting User Data
});
More information can be found here.
You are also able to configure some standard messages using the configure() method.
Example
bot.configure({
userWelcomeMessage: "Hello... Welcome to the group.",
goodbyeMessage: "Goodbye..."
});
More information on what can be configured through options is located here.
Concerns
This is not part of the question, as the question was to identify how to listen to these events. But as a general concern, the event listener does not return a session object. It is unclear how to act once you handle the event.

Related

How do I provide real time update in nodejs?

I am working on an e-commerce site. There are times where a product would no longer be available but the user would have added it to the cart or added to their saved items. How do I implement the feature such that if the product has been updated, the user would be notified as soon as possible?
I thought about doing a cron job that would check the status of the product if it still available or has been recently updated. But I do not know if that is feasible. I am open to better ideas
Thanks
Similar images are included below
What you are trying to achieve falls into real-time updates category and technically there would be more than one option to achieve this.
The chosen solution would depend on your application architecture and requirements. Meanwhile, I can suggest looking into Ably SDK for Node.js which can offer a good starter.
Here down a sample implementation where on the back-end you will be publishing messages upon item's stock reaching its limit:
// create client
var client = new Ably.Realtime('your-api-key');
// get appropriate channel
var channel = client.channels.get('product');
// publish a named (may be the product type in your case) message (you can set the quantity as the message payload
channel.publish('some-product-type', 0);
On the subscriber side, which would be your web client, you can subscribe to messages and update your UI accordingly:
// create client using same API key
var client = new Ably.Realtime('your-api-key');
// get product channel
var channel = client.channels.get('product');
// subscribe to messages and update your UI
channel.subscribe(function (message) {
const productName = message.name;
const updatedQuantity = message.data;
// update your UI or perform whatever action
});
Did a live betting app once and of course live updates are the most important part.
I suggest taking a look into websockets. The idea is pretty straight forward. On backend you emit an event let's say itemGotDisabled and on frontend you just connect to your websocket and listen to events.
You can create a custom component that will handle the logic related to webscoket events in order to have a cleaner and more organized code an you can do any type of logic you want to updated to component as easy as yourFEWebsocketInstance.onmessage = (event) => {}.
Of course it's not the only way and I am sure there are packages that implements this in an even more easy to understand and straight forward way.

Proactive messaging bot in Teams without mentioning the bot beforehand

I'm using the Microsoft bot-framework to create a bot and integrate it into teams.
Part of the bot's requirements include proactively messaging users once per day. From what I understand, I can only message users that has been added to the team/groupChat after the bot, or that have messaged the bot directly.
My question is - can I somehow bypass this limitation?
A friend of my referred me to a new feature of graphAPI, as part of the new beta version - https://learn.microsoft.com/en-us/graph/api/user-add-teamsappinstallation?view=graph-rest-beta&tabs=http.
To me it doesn't seem like it could be related to the solution since I'm not getting any data back in the response, so if I have no conversationReference object I still can't message the user.
At the moment my solution is to simply broadcast a message in the channel when it's added, asking users to "register" with it by messaging it. Anyone has any other suggestion?
The easiest way is to:
Install the bot for the team
Query the Team Roster -- The link in Step 3 has an alternative way to do this towards the bottom
Create a conversation with the user and send a proactive message
There's a lot of code in those links and it's better to just visit them than to copy/paste it here.
The end of Step 3 also mentions trustServiceUrl, which you may find handy if you run into permissions/auth issues when trying to send a proactive message.
Edit for Node:
Install Necessary Packages
npm i -S npm install botbuilder-teams#4.0.0-beta1 botframework-connector
Note: The #<version> is important!
Prepare the Adapter
In index.js
const teams = require('botbuilder-teams');
adapter.use(new teams.TeamsMiddleware());
Get the Roster
// Get Team Roster
const credentials = new MicrosoftAppCredentials(process.env.MicrosoftAppId, process.env.MicrosoftAppPassword);
const connector = new ConnectorClient(credentials, { baseUri: context.activity.serviceUrl });
const roster = await connector.conversations.getConversationMembers(context.activity.conversation.id);
Send the Proactive Message
const { TeamsContext } = require('botbuilder-teams');
// Send Proactive Message
const teamsCtx = TeamsContext.from(context);
const parameters = {
members: [
roster[0] // Replace with appropriate user
],
channelData: {
tenant: {
id: teamsCtx.tenant.id
}
}
};
const conversationResource = await connector.conversations.createConversation(parameters);
const message = MessageFactory.text('This is a proactive message');
await connector.conversations.sendToConversation(conversationResource.id, message);
Trust the ServiceUrl, as Necessary
Read about it. You'd want this before the message is sent.
MicrosoftAppCredentials.trustServiceUrl(context.activity.serviceUrl);
EDIT: The Graph API you've referenced is only necessary if you wish to proactively message a user who is not in a channel/groupChat where the bot is installed. If you need to proactively message only people who are in context where the bot is installed already, the answer from mdrichardson is the easiest possible method.
We've identified a couple of issues with the Graph API beta endpoint you referenced that should be fixed in the near term. In the meantime workarounds are as follows:
Calling:
POST https://graph.microsoft.com/beta/me/teamwork/installedApps/
{"teamsapp#odata.bind":"https://graph.microsoft.com/beta/appcatalogs/teamsapps/APP-GUID"}
Will install an app in the personal scope of a user.
Known issue: Currently, if the app contains a bot, then installation will not lead to creation of thread between the bot and the user. However to ensure that any missing chat threads, get created, call:
GET https://graph.microsoft.com/beta/me/chats?$filter=installedApps/any(x:x/teamsApp/id eq 'APP-GUID')
Calling:
GET https://graph.microsoft.com/beta/me/chats?$filter=installedApps/any(x:x/teamsApp/id eq 'APP-GUID')
Gets the chat between a user and an app containing a bot.
Known issue: Calling this API will lead to sending a conversation update event to the bot even though there were no updates to the conversation. Your bot will essentially get two install events and you'll need to make sure you don't send the welcome message twice.
We'll also be adding more detailed documentation for the proactive messaging flow using these Graph APIs

In a chatbot conversation using dialogflow, Is there a way to make the bot speak first?

Is it possible to format a conversation so that the bot initiates conversation using dialogflow in a web demo integration?
The objective is to say something like “Hi, I’m a bot, I can do x” to establish that it’s a chatbot rather than a human.
Can anyone suggest any idea for this?
You can set a welcome intent, then send a /query request containing an event parameter. Set the event parameter to WELCOME and your chatbot will respond with whatever conversation opening you set.
More info here: https://dialogflow.com/docs/events
If you are using something other than the API for interacting with your Dialogflow agent (Slack, Facebook Messenger, etc.) you will need to add an appropriate event under "intents" in your console (such as the "Facebook Welcome" event).
For interacting with your Dialogflow agent via the API, see below.
In the API interaction quickstart documentation, Dialogflow gives you the SessionClient's detectIntent method for sharing messages with your bot.
Each language has a different solution. But on an abstract level, you want to change the request object that you send to Dialogflow to include a "Welcome" event (no input message required), as Omegastick described.
For example, in Node.js, your request object would look like this:
// The text query request.
const request = {
session: sessionPath,
queryInput: {
event: {
name: "Welcome",
languageCode: languageCode
}
},
};
This assumes you have an appropriate intent set up in your Dialogflow console to handle Welcome events. One is provided by default that you can observe.
You can also add contexts, so that your agent gives a different greeting message based on some condition.

Microsoft / Botbuilder for NodeJS: Bind URL Parameters to bot session

SDK
Homepage: https://github.com/Microsoft/BotBuilder
SDK Platform: Node.js
SDK Version: 3.14.0
Issue Description
Hi, I searched for this for a long time now but I haven't found an answer.
I was wondering if there is a way to bind some URL parameters to the User's Bot Session.
For example, if for a specific chat dialog, I set my Endpoint URL to:
http://localhost:3978/api/messages?pronuntiation=british
is there a way to get that url parameter named "pronuntiation" down in the session object like...
bot.dialog("/", function(session){
var desiredPronuntiation = session.someUrlParameters.pronuntiation;
if( desiredPronuntiation == "british"){
///blah
}
});
I think it is possible in C# SDK but I was trying to do this in NodeJS...
I already debugged the proces from the server.post('/api/messages', connector.listen()) down to the ChatConnector.verifyBotFramework() where at the end I found it calls _this.dispatch(req.body, res, next); (ChatbotConnector.js on line 149) passing only the post body but not the request object itself...
So at a first glance I think this is not possible, I just wanted to be sure that I didn't miss anything...
Thanks,
Luis
As far as I know, this isn't supported by the Bot Framework, however I don't see why you need to do it this way. This is something you want to store in the state, for example the userData. You can read more here about managing state in the Bot Framework.
If you want to pass user data to the bot, it depends on the channel. For example Facebook and Webchat allow you to pass data direct to the bot, without user input.

Botframework LUIS Slack bot only reply when name is mentioned

I'm creating a bot in slack using Microsoft's botframework and LUIS and in Node.js. Currently my bot will reply every time someone says something in the channel, however I want my bot to only reply when its name is mentioned in my slack channel. i.e. #my-bot do this
How would I approach this? Would I have to add slack api in order to do this?
One way I'm thinking is to create an entity to check for if #my-bot is mentioned, and if it is then reply and if not then don't. However, I feel there are better ways in doing this.
Thanks.
Edit:
dialog.onDefault(function (session) {
var msg = new builder.Message(session).entities();
console.log(msg);
console.log(session);
session.endDialog('Default Dialog');
});
I've looked through both msg and session and the Entities of both are empty.
I was able to use session.message.entities to use mentioned to know whenever the bot was mentioned.

Resources