Sending the file from bot to user(1:1) - node.js

I am new to development in teams and botkit. There is a bot that is up and running on Teams.
I want to share a file generated by the bot to the user(send a file from bot to the user) on teams. I have read the Microsoft-teams document. According to which first step is to send a Message requesting permission to upload which I am able to complete successfully. Below is the code, I have used to show the card to the user to ask for permission.
controller.hears('download', ['message_received', 'direct_message', 'direct_mention'], function (bot, message) {
var reply = { text:"" ,attachments: [] }
var ticketObj = {
"contentType": "application/vnd.microsoft.teams.card.file.consent",
"name": "result.txt",
"content": {
"description": "Text recognized from image",
"sizeInBytes": 4348,
"acceptContext": {
"resultId": "1a1e318d-8496-471b-9612-720ee4b1b592"
},
"declineContext": {
"resultId": "1a1e318d-8496-471b-9612-720ee4b1b592"
}
}
}
reply.attachments.push(ticketObj)
bot.reply(message, reply)
})
According to the Microsoft-teams document, when the user will click on accept button, the bot will receive an Invoke activity with a location URL.
But, when I click on the accept, nothing goes to my bot. It shows the error message: "This card action is not supported".
How to provide support for this card action?

Adding answer from comment section for more visibility:
Issue is resolved now. The issue was of uploading the manifest.json.
To send and receive files in the bot, set the supportsFiles property
in the manifest to true. This property is described in the bots
section of the Manifest reference.
The definition looks like this, "supportsFiles": true. If the bot does
not enable supportsFiles, the features listed in this section do not
work.
https://learn.microsoft.com/en-us/microsoftteams/platform/bots/how-to/bots-filesv4#configure-the-bot-to-support-files
Sample Link:
https://github.com/microsoft/BotBuilder-Samples/tree/main/samples/javascript_nodejs/56.teams-file-upload

Related

Why do I not have access to my firebase storage images?

I have two image files uploaded to firebase storage:
capsule house.jpg was uploaded through the UI (clicking the Upload file button).
upload_64e8fd... was uploading from my backend server (node.js) using this:
const bucket = fbAdmin.storage().bucket('gs://assertivesolutions2.appspot.com');
const result = await bucket.upload(files.image.path);
capsule house.jps is recognized as a jpeg and a link to it is supplied in the right hand margin. If I click on it, I see my image in a new tab. You can see for yourself:
https://firebasestorage.googleapis.com/v0/b/assertivesolutions2.appspot.com/o/capsule%20house.jpg?alt=media&token=f5e0ccc4-7916-4245-b813-dbdf1838556f
upload_64e8fd... is not recognized as any kind of image file and no link it provided.
The result returned on the backend is a huge json object with the following fields:
"selfLink": "https://www.googleapis.com/storage/v1/b/assertivesolutions2.appspot.com/o/upload_64e8fd09f787acfe2728ae73158e20ab"
"mediaLink": "https://storage.googleapis.com/download/storage/v1/b/assertivesolutions2.appspot.com/o/upload_64e8fd09f787acfe2728ae73158e20ab?generation=1590547279565389&alt=media"
The first one sends me to a page that says this:
{
"error": {
"code": 401,
"message": "Anonymous caller does not have storage.objects.get access to the Google Cloud Storage object.",
"errors": [
{
"message": "Anonymous caller does not have storage.objects.get access to the Google Cloud Storage object.",
"domain": "global",
"reason": "required",
"locationType": "header",
"location": "Authorization"
}
]
}
}
The second one gives me something similar:
Anonymous caller does not have storage.objects.get access to the Google Cloud Storage object.
The rules for my storage bucket are as follows:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if true;
}
}
}
I'm allowing all reads and writes.
So why does it say I don't have access to see my image when it's uploaded through my backend server?
I'd also like to know why it doesn't recognize it as a jpeg when it's uploaded through my backend server, but it does when uploaded through the UI, but I'd like to focus on the access issue for this question.
Thanks.
By default, the files are uploaded as private, unless you change your bucket settings, as mentioned here. The below code is an example of how to change the visibility of your documents.
/**
* {#inheritdoc}
*/
public function setVisibility($path, $visibility)
{
$object = $this->getObject($path);
if ($visibility === AdapterInterface::VISIBILITY_PRIVATE) {
$object->acl()->delete('allUsers');
} elseif ($visibility === AdapterInterface::VISIBILITY_PUBLIC) {
$object->acl()->add('allUsers', Acl::ROLE_READER);
}
$normalised = $this->normaliseObject($object);
$normalised['visibility'] = $visibility;
return $normalised;
}
You can check how to set that via console, following the tutorial in the official documentation: Making data public
Besides that, as indicated in the comment by #FrankvanPuffelen, you won't have a generated URL for the file to be accessed. You can find more information about it here.
Let me know if the information helped you!
The other answer helped me! I have no idea why the Console had me make those security rules if they won't apply...
Based on nodejs docs (and probably other languages) there is a simple way to make the file public during upload:
const result = await bucket.upload(files.image.path, {public: true});
This same option works for bucket.file().save() and similar APIs.

Slack bot fails to send message to restricted general channel via chat.postMessage

This is my first time trying to create a slack bot and I am following this template code to the word, I have not made any changes, and just remixed on glitch, copy-pasted the auth tokens correctly, things worked just fine.
That is until I made the #general channel restricted for Full Member users.
This is the error I see in the logs at glitch.
PostMessage Error: restricted_action
Is there an additional scope that I need to set, other than bot ?
Here is the workspace user permissions, I am the owner for this workspace.
Here is the code:
const postAnnouncementToChannel = (user, announcement) => {
const { title, details, channel } = announcement;
let announcementData = {
token: process.env.SLACK_ACCESS_TOKEN,
channel: channel,
text: `:loudspeaker: Announcement from: <#${user}>`,
attachments: JSON.stringify([
{
title: title,
text: details,
footer: 'DM me to make announcements.'
}
])
};
send(announcementData, user);
}
const send = async(data) => {
data.as_user = true; // send DM as a bot, not Slackbot
const result = await axios.post(`${apiUrl}/chat.postMessage`, qs.stringify(data))
try {
if(result.data.error) console.log(`PostMessage Error: ${result.data.error}`);
} catch(err) {
console.log(err);
}
}
Testing it via
https://api.slack.com/methods/chat.postMessage/test
using bot-token says
{
"ok": false,
"error": "restricted_action"
}
Testing this using xoxp-token gives this:-
{
"ok": false,
"error": "missing_scope",
"needed": "chat:write:user",
"provided": "identify,bot"
}
No. You are not missing any scopes. Its just that the user you used to auth your app can not post into the general channel. Apparently admins have restricted who can post messages in that channel, e.g. to admins only.
Either use a user that has posting rights for that channel to auth your app or switch to a different channel for your testing.
Bots are not full members so I had to use user token
xoxp-token
to post to chat.postmessage, with
as_user:false
and had to add a missing_scope that is
chat:write:user
And then I was able to make this work correctly.
Credit goes to #girliemac for helping out on this one.
https://github.com/slackapi/template-announcement-approvals/issues/6
Thanks

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]");

How do I get notifications when a bot sends a message in Teams?

I developed a bot for Microsoft Teams using the Microsoft Bot Framework v4 Nodejs SDK (botbuilder-sdk for nodejs). We have implemented the bot in such a way that, when we receive data using a REST API call from one of our CRMs, the data is posted to the channels on Microsoft Teams. However, when I do that, we do not receive a notification on the devices. Has anyone faced such an issue?
I am saving the context state initially. Everytime we receive data from a CRM, I am incrementing the activity id of the message (to send it as a new message and not a reply) and sending it to Microsoft Teams using context.sendActivity().
When we receive that adaptive card, we do not receive a notification in the activity feed or on any of the devices.
I have gone through all the steps as you described above. I've also gone through the troubleshooting steps. However, it still doesn't give me a notification for the card. However, when I initiate a conversation with the bot, I get a notification when the bot responds.
https://i.stack.imgur.com/Bi4fc.png
https://i.stack.imgur.com/ab6uP.png
In this image, I get a notification when I get the TMS Bot started! message. However, I don't get a notification for the next two messages.
Edit: OP and I have exchanged a few emails to get this answered. This answer, as a whole, is good information for accomplishing Teams Proactive messaging, in general, but the main answer is in the last section, Simplified Code.
This is a long answer that covers many areas, simply because I'm not 100% sure I know what kind of notification you aren't receiving.
Troubleshooting
Troubleshooting Guide
Pay special attention to the many areas where notifications need to be enabled
In particular, the user may need to "Follow" and/or "Favorite" the channel to receive notifications from it
If a user has the desktop app open, they will receive the notification there and will not receive one on their phone unless they have been inactive on the desktop app for 3+ minutes. Otherwise, it's likely a bug in Teams.
Chat Notifications
If you've followed the Troubleshooting Guide linked above, your users should receive chat notifications. If not, you can try updating your MS Teams desktop or mobile client. As #KyleDelaney mentioned, it may be helpful to # mention users and/or channels
Activity Feed Notifications
You can also create Activity Feed Notifications. The gist of it is that you need to:
Include text and summary in the message
Include channelData that sets notifications.alert to true
This code will accomplish that:
const msg = MessageFactory.text('my message');
msg.summary = 'my summary';
msg.channelData = {
notification: {
alert: true,
},
};
return await dc.context.sendActivity(msg);
Result:
Note: If your bot only creates notifications and doesn't have conversations, you may benefit from creating a notifications-only bot.
Full Implementation Code
import * as adaptiveCard from '../src/adaptiveCard.json';
...
const card = CardFactory.adaptiveCard(adaptiveCard);
const activity = {
attachments: [card],
text: 'Test Card',
summary: 'my summary',
channelData: {
notification: {
alert: true,
},
},
};
await turnContext.sendActivity(activity);
Result:
Using the Teams Extension
There's a Teams Extension for BobBuilder V4 that's currently in Beta, but seems to accomplish what you need. I believe the reason you weren't getting notifications while using the above is because your bot is creating a new reply chain in the channel and not replying directly to a user. I believe you can do all of this without the extension (by manually editing activity/context properties), but the extension should make it easier.
Here's the code I used to get working notifications within a channel:
In index.js (or app.js):
import * as teams from 'botbuilder-teams';
[...]
// Change existing to use "new teams.TeamsAdapter..."
const adapter = new teams.TeamsAdapter({
appId: endpointConfig.appId || process.env.microsoftAppID,
appPassword: endpointConfig.appPassword || process.env.microsoftAppPassword,
});
Wherever you're sending the message:
import * as teams from 'botbuilder-teams';
import * as adaptiveCard from '../src/adaptiveCard.json';
...
const card = CardFactory.adaptiveCard(adaptiveCard);
const activity = {
attachments: [card],
text: 'Test Card',
summary: 'my summary',
channelData: {
notification: {
alert: true,
},
},
};
const adapter = context.adapter as teams.TeamsAdapter;
await adapter.createReplyChain(context, [activity]);
Simplified Code
OP and I have emailed back and forth a bit and the key issue is that he needed to add the trustServiceUrl code from below. Normally, this manifests itself with a 500 error, but in this case, it appears to not create notifications.. After significant testing, here's all you really have to do to send different notifications to different channels. It basically amounts to setting a couple of properties of turncontext.activity and trusting the serviceUrl. No touching activity ID or using the Teams Extension at all. My code below is how I sent messages from Emulator that could then send cards to different Teams channels:
public onTurn = async (turnContext: TurnContext) => {
const dc = await this.dialogs.createContext(turnContext);
const dialogResult = await dc.continueDialog();
// Route message from Emulator to Teams Channel - I can send "1", "2", or "3" in emulator and bot will create message for Channel
let teamsChannel;
switch (turnContext.activity.text) {
// You can get teamsChannel IDs from turnContext.activity.channelData.channel.id
case '1':
teamsChannel = '19:8d60061c3d104exxxxxxxxxxxxxxxxxx#thread.skype';
break;
case '2':
teamsChannel = '19:0e477430ebad4exxxxxxxxxxxxxxxxxx#thread.skype';
break;
case '3':
teamsChannel = '19:55c1c5fb0d304exxxxxxxxxxxxxxxxx0#thread.skype';
break;
default:
break;
}
if (teamsChannel) {
const card = CardFactory.adaptiveCard(adaptiveCard);
const activity = {
attachments: [card],
summary: 'my summary',
text: 'Test Card',
};
const serviceUrl = 'https://smba.trafficmanager.net/amer/';
turnContext.activity.conversation.id = teamsChannel;
turnContext.activity.serviceUrl = serviceUrl;
// This ensures that your bot can send to Teams
MicrosoftAppCredentials.trustServiceUrl(serviceUrl);
await turnContext.sendActivity(activity);
} else {
[...Normal onTurn Code...]
await this.conversationState.saveChanges(turnContext);
}
Note: To receive notifications, you and your users must follow the channel.
I have gone through all the steps as you described above. I've also gone through the troubleshooting steps. However, it still doesn't give me a notification for the card. However, when I initiate a conversation with the bot, I get a notification when the bot responds.
https://i.stack.imgur.com/Bi4fc.png
https://i.stack.imgur.com/ab6uP.png
In this image, I get a notification when I get the TMS Bot started! message. However, I don't get a notification for the next two messages.

Send RAW Azure Push Message

I'm trying to send a raw push notification message from Azure to my mobile device through an Web API. Previously I made use of a toast message and I got that working just fine, but not so much with the raw message type. This is what I've tried so far in my web API, without any success:
var jObject = new JObject
{
{
"Body", pushMessage.Body
},
{
"From", pushMessage.From
},
{
"Date", DateTime.Now.ToString(CultureInfo.InvariantCulture)
},
{
"Title", pushMessage.Title
},
{
"TargetType", pushMessage.TargetType.ToString()
}
};
Notification notification = new WindowsNotification(jObject.ToString());
notification.Headers.Add("X-WNS-Type", "wns/raw");
notification.ContentType = "application/json";
var task = Notifications.Instance.Hub.SendNotificationAsync(notification, "some tag value");
The above code never pushes the actual message. Could someone please provide me with some information regarding this. I've tried various methods described on the web, without any success.
Many thanks!
Turns out the above code works just fine - there was an issue with one of the settings in Azure ... pretty stupid mistake in the end o_O

Resources