Add image to notification when using sendToTopic method - javascript

I want to use sendToTopic method to send notification to a topic, How can I add image to the notification?
There is no option such as notification.imageUrl

It can be done like this -
const message: TopicMessage = {
topic: reqData.topic,
data: {
abc: reqData.abc
},
notification: {
title: reqData.title,
body: reqData.body,
imageUrl: reqData.imageUrl
}
};
// messageRes is a message ID string.
const messageRes = await admin.messaging().send(message);

Related

discord.js Editting Slash Command Interaction Messages

So I'm using discord.js with this code here:
client.api.interactions(interaction.id, interaction.token).callback.post({
data: {
type: 4,
data: {
content: "Getting Data..."
}
}
})
I would like to be able to edit this message afterwards, but everything I have seen requireds a message id, and I seem to be unable to get the message id off of this code.
You can edit an interaction response with this patch request (See: Followup Messages):
PATCH /webhooks/<application_id>/<interaction_token>/messages/#original
Basic example using the axios library:
axios.patch(`https://discord.com/api/v8/webhooks/${appId}/${interaction.token}/messages/#original`, { content: 'New content' });
The answer to this request will also contain the message-id.
Here is an example function that will edit the original message either as plain text or an embed object and returns the discord message object for further usage (e.g. add reply emojis etc.):
const editInteraction = async (client, interaction, response) => {
// Set the data as embed if reponse is an embed object else as content
const data = typeof response === 'object' ? { embeds: [ response ] } : { content: response };
// Get the channel object by channel id:
const channel = await client.channels.resolve(interaction.channel_id);
// Edit the original interaction response:
return axios
.patch(`https://discord.com/api/v8/webhooks/${appId}/${interaction.token}/messages/#original`, data)
.then((answer) => {
// Return the message object:
return channel.messages.fetch(answer.data.id)
})
};
Also instead of sending an initial message like "getting data..." you also can send an empty response of type 5. This is the build-in method and displays a little loading animation too :) See here (One advantage is that this way no "edited" appears.)
client.api.interactions(interaction.id, interaction.token).callback.post({
data: {
type: 5,
},
})

How to post a button in postMessageToChannel to the slack channel and call a function on click of button?

I want to send a button in bot.postMessageToChannel() and want to call a function(handleMessage) on Click of that button.
//start handler
bot.on('start', () => {
const params = {
icon_emoji: ':information_source:'
}
//here i want to post a button to a channel.
bot.postMessageToChannel(
'ABC', //channel name
'*Welcome to AB*...',
params
)
})
function i want to call,
handleMessage = (message) => {
console.log("hello")
}
I have tried the slack API.
Message Buttons with Node.js but it is from the slash commands.
interactive message button it is just giving me similar JSON data.
I wanted to confirm what you were looking for before I answered. I did something similar recently - where I would return a button off of a command, mainly so that when the user clicked on the button I would have a trigger_id that I could use to send a modal form for them to provide more info. An example of how I handled this:
First go to the Event Subscriptions section of your app settings page, and enable it. Provide the url that will listen for said events, then you need to select the events that your bot will be listening for. I subscribed to app_mention ( which will fire when your bot is #), and message.channels, which will fire on every message sent to the channel your bot is in.
Once you have done that you can subscribe to events... (by using the slack SDK https://slack.dev/node-slack-sdk/)
slackEvents.on('message', (event, body) => {
// do something here
console.log(`Received a message event: user ${event.user} in channel ${event.channel} says ${event.text}`);
});
In my case, once I received that message (I parse through the text to handle multiple commands) I would then use blocks to create a message with a button and send it back...
Payload:
channel: context.channelId,
text: "",
blocks: JSON.stringify([
{
type: "section",
text: {
type: "mrkdwn",
text: "So, you say you want to create a new task?\n*Great!*\nI just need your permission first, in order to initiate this action.\nPlease click the button below to launch this process, or cancel if you have changed your mind"
}
},
{
type: "actions",
block_id: "processAddTask",
elements: [
{
type: "button",
text: {
type: "plain_text",
emoji: true,
text: "Process"
},
style: "primary",
value: "1"
},
{
type: "button",
text: {
type: "plain_text",
emoji: true,
text: "Cancel"
},
style: "danger",
value: "0"
}
]
}
])
Then send that payload back to channel...
const response = await web.chat.postMessage(responseMessage);
Once all this was done the user would be presented with a couple of buttons, and when they clicked on the "go" button it will fire another event that you can catch:
slackInteractions.action({ callbackId: 'addTaskRequest' }, (payload, respond) => {
console.log('payload', payload);
let triggerId = payload.trigger_id;
let view = payloads.addTaskModal({ triggerId });
(async () => {
try {
let result = await slackClient.callAPIMethod("views.open", view);
respond("");
} catch (error) {
if (error.code === ErrorCode.PlatformError) {
respond(error.data);
} else {
respond('Well, that was unexpected.');
}
}
})();
});

How do I add an analytics label to data messages with the Javascript (or typescript) Firebase Admin SDK?

I want set a label in the message.And I read the official document here and similar question here.
But I can't figure out how to write it in javascript.
my code here:
const message = {
notification: {
title: "myTitle",
body: "myBody"
},
condition: "!('TopicA' in topics)",
AnalyticsLabel : "mylabel" <=== something like this?
};
const response = await admin.messaging().send(message);
Here is the trick...
const message = {
notification: {
title: "myTitle",
body: "myBody"
},
condition: "!('TopicA' in topics)",
fcmOptions: {
analyticsLabel : "MyLabel"
}
};

YouTube Api V3 - Videos.update - Forbidden error

I'm trying to update video's description using Youtube API, but I'm just getting Forbidden Error.
Videos.insert call is actually working, the authentication is being done on the same way for both (as I show on code). But for Videos.update it just doesn't work.
I'm not trying to do these two operations at once, it's just to explain better the situation and make the code shorter to read.
const Youtube = require('youtube-api');
const request = require('request');
// test variables below
const accessToken = 'ASPODKODASP';
const title = 'test';
const description ='test';
const url = 'https://testvideo.url/sadokdas.mp4';
const youtubeId = 'm_23k21423';
Youtube.authenticate({
type: 'oauth',
access_token: accessToken
});
Youtube.videos.insert({
resource: {
snippet: {
title: title,
description: description
},
status: {
privacyStatus: 'public'
}
},
part: 'snippet, status',
media: {
body: request(url)
}
}); // <- THIS WORKS
Youtube.videos.update({
id: youtubeId,
snippet: {
title: title,
description: description,
categoryId: '22'
},
part: 'snippet'
}, (err, data) => {
if (err) {
console.log('error on updating youtube description');
console.log(err);
return;
}
});
I expected the video description to get updated but instead I'm getting
code: 403,
errors:
[ { domain: 'youtube.video',
reason: 'forbidden',
message: 'Forbidden' } ]
You want to update a video of YouTube using "youtube-api" of Node.js.
You have already been able to insert new video using your script.
In your environment, you have already been able to use YouTube Data API.
In your script, an error occurs at Youtube.videos.update().
If my understanding is correct, how about this modification? In this modification, the request body of Youtube.videos.update() was modified.
Modified script:
From:
Youtube.videos.update({
id: youtubeId,
snippet: {
title: title,
description: description,
categoryId: '22'
},
part: 'snippet'
}, (err, data) => {
To:
Youtube.videos.update({
resource: { // Added
id: youtubeId,
snippet: {
title: title,
description: description,
categoryId: '22'
}
},
part: 'snippet'
}, (err, data) => {
References:
Videos: update
youtube-api
If I misunderstood your question, I apologize.

Getting values from my web chat call in my website using backchannel

I'm trying to integrate the backchannel and getting the values.
https://github.com/Microsoft/BotFramework-WebChat/tree/master/samples/15.d.backchannel-send-welcome-event
I also tried this. Get URL Referer and Origin header from Microsoft Bot Framework
I also tried deserializing the values still not able to get the data.
how can i get the language values?
here's my sample code:
var userinfo = {
id: 'user-id',
name: 'user name',
locale: 'es'
};
var botConnection = new BotChat.DirectLine({
token: 'mytoken',
user: userinfo,
locale: 'es'
});
BotChat.App({
botConnection : botConnection,
user: userinfo,
bot: { id: 'bot-id', name: 'bot name' },
}, document.getElementById('botDiv'));
botConnection
.postActivity({
from: userinfo,
name: 'ConversationUpdate',
type: 'event',
value: '',
})
.subscribe(function (id) {
console.log('"trigger ConversationUpdate" sent');
});
The purpose of this I want to pass the locale to my bot from my website.
just like in the emulator.
Thanks!
I would recommend adding the locale to the back channel event's channel data. That way on the bot side you can simply access the locale in the incoming activity without having to deserialize any JSON objects when you receive the event. Note, you can also use text or value in place of channelData. See the code snippets below.
BotChat Back Channel Event
// Send back channel event
botConnection.postActivity({
from: userinfo,
name: 'setLocale',
type: 'event',
channelData: "es"
}).subscribe(id => console.log(id));
Bot - C#
public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
{
if (turnContext.Activity.Type == ActivityTypes.Message)
{
...
} else if (turnContext.Activity.Type == "event") {
// Check for `setLocale` events
if (turnContext.Activity.Name == "setLocale") {
await turnContext.SendActivityAsync($"Your locale is set to {turnContext.Activity.ChannelData}");
}
}
else
{
await turnContext.SendActivityAsync($"{turnContext.Activity.Type} event detected");
}
}
Hope this helps!

Categories