I am unable to find any documentation available where I can mention a user for every message sent in a teams channel. I have to use an incoming webhook to send messages to the channel.
The messages will be sent from an azure function. This is the code I have tried so far.
axios
.post(
'https://name.webhook.office.com/webhookb2/xxx#xyz/IncomingWebhook/xxx/xxxb',
{
'#type': 'MessageCard',
'#context': 'http://schema.org/extensions',
themeColor: '0072C6', // light blue
summary: 'Summary description',
sections: [
{
activityTitle: title,
text: message
}
]
}
)
.then(
(resolvedValue) => {
resolve(`Sent message to teams ${resolvedValue}`);
},
(error) => {
reject(error);
}
);
I want to mention a user so that they get alerted when the message arrives.
Please go through User mention in Incoming Webhook with Adaptive Cards which talks about adding #mentions within an Adaptive Card body for incoming webhooks.
Please check Format cards with Markdown to add formatting in cards.
Related
I have a bot and I use smooch to run the bot on whatsapp.
I use 'smooch-core' npm for that.
When I send a lot of messages one after the other sometimes the messages are displayed in reverse order in whatsapp.
Here is the code for sending messages:
for (const dataMessage of data) {
await sendMessage(dataMessage);
}
function sendMessage(dataMessage) {
return new Promise((resolve, reject) => {
smoochClient.appUsers.sendMessage({
appId: xxxx,
userId: userId,
message: dataMessage
}).then((response) => {
console.log('response: ' + JSON.stringify(response), 'green');
resolve();
}).catch(err => {
console.log('error: ' + JSON.stringify(err), 'red');
reject(err);
});
});
All dataMessage looks like this:
{
role: "appMaker",
type: "text",
text: txt
}
I tried to see how I could arrange it, and I saw that there was an option to get the message status from the webhook, and then wait for each message to arrive for the appropriate status. And only then send the following message.
But I would like to know is there something simpler? Is there a parameter that can add to the message itself to say what its order is? Or is there something in the npm that gives information about the message and its status?
In the doc below, Whatsapp mentions that they do not guarantee message ordering.
https://developers.facebook.com/docs/whatsapp/faq#faq_173242556636267
The same limitation applies to any async messaging platform (and most of them are), so backend processing times and other random factors can impact individual message processing/delivery times and thus ordering on the user device (e.g. backend congestion, attachments, message size, etc.).
You can try to add a small [type-dependent] delay between sending each message to reduce the frequency of mis-ordered messages (longer delay for messages with attachments, etc.).
The fool-proof way (with much more complexity) is to queue messages by appUser on your end, only sending the next message after receiving the message:delivery:user webhook event for the previous message.
I am trying to send a postBack text message to my bot but I don't know the right syntax.
Here is my code:
if (postback.payload == "WHAT_IS_MENTAL_HEALTH") {
await turnContext.sendActivity("TO-DO: Forward on 'What Is Mental Health?' to Bot Handler");
ActionTypes.postBack("What Is Mental Health?");
}
I'm trying to forward on the text "What Is Mental Health?" to my bot so it will pull back the QnA Maker response for that question.
The steps for this are as follows:
User clicks a button on a Facebook Messenger Generic Template Card (e.g. “What Is Mental Health?” Button)
The button sends a postBack payload to the bot (e.g. “WHAT_IS_MENTAL_HEALTH”)
I am detecting the postBack payload from Facebook Messenger (e.g if (postBack.payload == “WHAT_IS_MENTAL_HEALTH”))
Once that particular postBack payload is detected I then want to send an additional postBack to my bot as text (e.g. “What Is Mental Health?”) so it can be interpreted by my QnA and respond with the correct answer which has been programmed into my QnA Knowledge Base.
Facebook Events and the Bot Framework
When Facebook sends an event to your bot, it sends an Activity with an Event ActivityType. For some events, the event data is in the Activity.Value property. For other events, like a PostBack from a Quick Reply, the activity will be a Message and the data will be in Activity.ChannelData. For example, your bot might receive a postBack event as an activity like this:
{
channelId: 'facebook',
[...]
type: 'message',
channelData: {
recipient: {...},
sender: {...},
message: {
[...],
quick_reply: {
[...],
payload: '<your payload>'
}
}
}
}
Handling Facebook Events
This answer is going to pull heavily from the Facebook Events Sample. I highly recommend looking at that for additional help.
Capture Messages and Events
First, you want to capture the facebook messages and events with onMessage() and onEvent():
this.onMessage(async (turnContext) => {
console.log('Processing a Message Activity.');
// Show choices if the Facebook Payload from ChannelData is not handled
if (!await this.processFacebookPayload(turnContext, turnContext.activity.channelData)) {
if (turnContext.activity.channelId !== 'facebook') {
await turnContext.sendActivity('This sample is intended to be used with a Facebook bot.');
}
await this.showChoices(turnContext);
}
});
this.onEvent(async (turnContext) => {
console.log('Processing an Event Activity.');
// Analyze Facebook payload from EventActivity.Value
await this.processFacebookPayload(turnContext, turnContext.activity.value);
});
Process the Messages/Events
Facebook can send many types of events. You may want to use an if or switch statement to handle each type:
async processFacebookPayload(turnContext, data) {
// At this point we know we are on Facebook channel, and can consume the Facebook custom payload present in channelData.
const facebookPayload = data;
if (facebookPayload) {
if (facebookPayload.postback) {
// Postback
await this.onFacebookPostback(turnContext, facebookPayload.postback);
return true;
} else if (facebookPayload.optin) {
// Optin
await this.onFacebookOptin(turnContext, facebookPayload.optin);
return true;
[...]
}
return false;
}
Specifically, Handle a PostBack
The sample just does:
async onFacebookPostback(turnContext, postback) {
console.log('Postback message received.');
// TODO: Your postBack handling logic here...
// Answer the postback and show choices
await turnContext.sendActivity('Are you sure?');
await this.showChoices(turnContext);
}
As you want to route the question to QnA Maker, you might (using the QnA Maker Sample as guidance):
async onFacebookPostback(turnContext, postback) {
// qnaMaker.getAnswers doesn't accept string input, so we need to adjust our turnContext
// to match what it expects, which is a string in Activity.Text
turnContext.activity.text = postback.payload;
const qnaResults = await this.qnaMaker.getAnswers(turnContext);
// If an answer was received from QnA Maker, send the answer back to the user.
if (qnaResults[0]) {
await turnContext.sendActivity(qnaResults[0].answer);
// If no answers were returned from QnA Maker, reply with help.
} else {
await turnContext.sendActivity('No QnA Maker answers were found.');
}
}
I want to open widgets.getsitecontrol.com/ javascript page that I have implemented on my website. Whenever I type 'Help' inside my bot, the widget should open. Is it possible to open it? Thanks. I am using node js version. If it is possible, please provide me an approach to solve this issue.
I'm not sure exactly how your widget functions, but when the user sends a 'help' message to the bot, you can send a back channel event to WebChat to trigger opening the widget. Take a look at the code snippets below.
Bot Code - NodeJs
When the bot receives a 'help' message from the user, the bot can send an event by sending an activity with the type set to 'event'. We can also give the outgoing activity a name attribute so we can send mutltiple types of events to WebChat. In this case, we are going to name the out going activity 'helpEvent'.
async onTurn(turnContext) {
if(turnContext.activity.type === ActivityTypes.Message) {
if (turnContext.activity.text.toLowerCase() === 'help') {
// Send Back Channel Help Event
await turnContext.sendActivity({ type: 'event', name: 'helpEvent'});
}
...
}
}
WebChat Custom Middleware
In WebChat, we are going to create a custom middleware to check incoming activities. When we encounter an activity that has a name and type that we recognize, trigger your event on the webpage. In the example below, I just alerted the use that they asked for help, but here is where you launch your widget.
const store = window.WebChat.createStore(
{},
({ dispatch }) => next => action => {
if (action.type === 'DIRECT_LINE/INCOMING_ACTIVITY') {
const { name, type } = action.payload.activity;
if (type === 'event' && name === 'helpEvent') {
// Activate Widget
alert("You asked for help.");
}
}
return next(action);
}
);
window.WebChat.renderWebChat({
directLine: window.WebChat.createDirectLine({ token }),
store,
}, document.getElementById('webchat'));
For more details on back channel events and creating a custom middleware in WebChat, checkout this sample in the WebChat Repo.
Hope this helps!
I am developing a chatbot for Facebook Messenger using Microsoft Bot Framework. The bot sends the user proactive messages (reminders). Unfortunately, for some reason the messages never show up in a chat head (the Android widget for conversations), nor pop up a chat head if it wasn't present on the screen before. It does happen for other chatbots (Jarvis, for example).
This is the code that sends the reminders:
Reminder.find({ next_reminder: { $lte: new Date() } }, (err, res) => {
if (err !== null) {
return console.error(err);
}
res.forEach(reminder => {
// Build a notification message and address it to user who created the reminder
const msg = new builder.Message().text('...');
bot.beginDialog(reminder.user_address, '*:/sendReminder', {message: msg, nudnik: nudnik});
});
});
};
};
I have also tried bot.send(msg, () => ....) and session.beginDialog('sendReminder', msg). However, there is still no indication from Messenger when the message is received. What could go wrong here?
OK, I figured it out! Apparently, the default notification setting for a Facebook message is not to show a notification. To change it, in NodeJS you should add channel-specific data to the message with the following code:
msg = msg.sourceEvent({
facebook:
{notification_type: 'REGULAR'}
});
You can discover more in official documentation by Microsoft (here and here) and also in this Github discussion.
Hi I am using nodejs and developing a bot on facebook messenger platform. I have my webhook subscribed only to messages and messaging_postbacks events. However, when I test the bot, it seems to send callback three times. This is my webhook code
server.post('/', (req, res, next) => {
let postback = req.body.entry[0].messaging[0].postback;
if (postback.payload === 'Greet User'){
console.log(postback);
}
}
When I test my bot, the postback object gets printed thrice as below.
{ payload: 'Greet User', title: 'Get Started' }
{ payload: 'Greet User', title: 'Get Started' }
{ payload: 'Greet User', title: 'Get Started' }
Any help how to avoid it? I read in some of the posts here that I should deselect message_reads and message_deliveries subscriptions. But I do not have those selected anyways. Not sure what else I am missing? Please help me.
I have found the problem after some more searching on the net and debugging it myself. In case, if others reading this might be interested to know, the issue was I was not sending back 200 status back to facebook. I found the hint regarding the need to do that in this stack overflow post.
Facebook webhook making multiple calls for the same message?
After sending the 200 response, I m not getting this issue. So relieved :)