Add server params on PWA push notification - javascript

Is it possible to add custom title, body, etc. from server params on showNotification method ?
var title = 'My title';
event.waitUntil(
self.registration.showNotification(title, {
body: 'My body',
icon: 'images/icon.png',
tag: 'my-tag'
}));
I use an classic Firebase for stock my user token. For example, on new article, send the article title.

Yes. You can show custom push notifications using data from server, which applies to your use case as well. These notifications can be shown even with your app is not actively used by the user. Like how you receive deals notifications from Amazon app, you can show your new article title and body by getting data from the server using an push event listener like below and use that data to phrase and use it on different parts of your notification.
self.addEventListener('push', function(e) {
var body;
if (e.data) {
body = e.data.text();
} else {
body = 'Push message no payload';
}
var options = {
body: body,
icon: 'images/notification-flat.png',
vibrate: [100, 50, 100],
data: {
dateOfArrival: Date.now(),
primaryKey: 1
},
actions: [
{action: 'explore', title: 'Explore this new world',
icon: 'images/checkmark.png'},
{action: 'close', title: 'I don't want any of this',
icon: 'images/xmark.png'},
]
};
e.waitUntil(
self.registration.showNotification('Push Notification', options)
);
});
For more description, look at Receiving Data in the Service Worker section of this article.

Related

Slack API : how to update a user message from a button in ephemeral message

I exposed to you my problem with ephemeral message and update of user message
A simplified user case can :
when you write "hi" in a channel, that triggers an ephemeral message with a button "click", and when you click that button, it updates your first "hi" message, to "goodbye" for instance.
This is the code I tried. Unfortunatly, I think I have the wrong message_ts for the update. It seems to be the message_ts of the ephemeral message. Not the one of the original message. What do you think about it?
Have you an idea about how to achieve my goal?
const { WebClient } = require("#slack/web-api");
const slack_bot_token = process.env.SLACK_BOT_TOKEN;
const signing_secret = process.env.SLACK_SIGNING_SECRET;
const webClient = new WebClient(process.env.SLACK_BOT_TOKEN);
const { App } = require("#slack/bolt");
const app = new App({
token: slack_bot_token,
signingSecret: signing_secret,
});
app.message("hi", async ({ message, channel, say }) => {
// Respond to action with an ephemeral message
let channelID = message.channel;
let userID = message.user;
let ts = message.timestamp;
await webClient.chat.postEphemeral({
channel: channelID,
user: userID,
text: `👋 Hi <#${message.user}>`,
blocks: [
{
type: "section",
text: {
type: "mrkdwn",
text: `👋 Hey <#${message.user}>`,
},
accessory: {
type: "button",
text: {
type: "plain_text",
text: "Click me",
emoji: true,
},
action_id: "click",
},
},
],
});
});
// when the button with action_id "click" is clicked, the ephemeral message is discarded, and the user message is updated
app.action("click", async ({ ack, body, client, respond }) => {
// Acknowledge action request before anything else
await ack();
let channelID = body.channel.id;
let userID = body.user.id;
let message_ts = body.container.message_ts;
// erase original ephemeral message
respond({
response_type: "ephemeral",
text: "",
replace_original: true,
delete_original: true,
});
// update the original "hi" message
console.log (body.container);
webClient.chat.update({
token: slack_bot_token,
channel: body.container.channel_id,
ts: body.container.message_ts,
text: "goodbye",
replace_original: true,
delete_original: true,
});
});
(async () => {
// Start your app
await app.start(process.env.PORT || 3000);
console.log("⚡️ Bolt app is running!!");
})();
Thanks for your help
You're right that the message_ts you're trying to use right now is not the correct one. You'll need to save the message_ts of the original "hi" message instead.
You can do that in a number of ways, one would be to use a database, store the message_ts value and retrieve it when you need it again. However, if you want to avoid doing that, a neat thing you can do is set the value of the button you're generating in the ephemeral message as the message_ts of the original message.
// Keep in mind I've removed the code that isn't relevant
app.message("hi", async ({ message, channel, say }) => {
...
let ts = message.timestamp;
await webClient.chat.postEphemeral({
...
type: "button",
text: {
type: "plain_text",
text: "Click me",
emoji: true,
},
action_id: "click",
value: `${ts}` // <- store the message_ts here
},
},
],
});
});
So then in the response to the users button click, you'll receive a payload which will, among other things, contain the value that you set earlier when you generated the button. You can then use this value to update the original message, as you are doing right now.
An example of action response payload: https://api.slack.com/reference/interaction-payloads/block-actions#examples

Discord.js converting Javascript with console into embeds for discord

So I'm working on a bot right now and when looking at the api I get this as the example of how it'll work.
(async () => {
console.log(await bookwebsite.getHomepage(1))
})()
{
results: [ { bookId: 'web id',
thumbnail: 'thumbnail link',
title: 'book title' },
{ bookId: 'web id',
thumbnail: 'thumbnail link',
title: 'book title' },
{ bookId: 'web id',
thumbnail: 'thumbnail link',
title: 'book title' },
...
],
}
Can anyone lead me in the right direction on how to translate this from a console log script to running it within discord embeds? API WARNING NSFW
I'm not extremely sure what you're meaning as of translating console into embeds but I'm guessing you're trying to format the data returned in the api in to a embed in Discord.
const bookwebsite = require('nhentai-js');
(async () => {
var data = await bookwebsite.getHomepage(1);
data = data.results.slice(0, 25);
if(!data) return message.channel.send('Failed to retrieve data from api. ')
// slices to avoid discord embeds going beyond 25 fields
var embed = new Discord.MessageEmbed()
.setTitle('Results found');
// For each the data that's received(after its trimmed)
data.forEach(d=>{
// For every object inside of data, it takes the name and sets it as a field title and sets the description of the field as the id and thumbnail link.
embed.addField(`Name: ${d.title}`, `ID: ${d.bookId}\nThumbnail: ${d.thumbnail}`)
})
// Embeds done, now need to send into the channel
message.channel.send(embed)
})()
If you need any help further on, please comment below.

Can I give a link in standard message box in SAP UI5?

Is it possible to give a link instead of a message in standard message box in sap ui5? I want to navigate to another view on the click of that link. Is it possible to achieve without creating a new fragment and adding something in the standard message box?
The sap.m.MessageBox does not allow links, but the use of custom actions. Just take a look at the sample Error with custom action. Maybe this will help you.
I had the same problem and found the following solution:
if (!this.oSuccessMessageDialog) {
this.oSuccessMessageDialog = new sap.m.Dialog({
type: sap.m.DialogType.Message,
title: "Success",
state: sap.ui.core.ValueState.Success,
content: [
new sap.m.Text({ text: "Click on\u00a0" }),
new sap.m.Link({
text: "this",
emphasized: true,
press: <your_handler>
}),
new sap.m.Text({ text: "\u00a0Link." })
],
beginButton: new sap.m.Button({
type: sap.m.ButtonType.Emphasized,
text: "OK",
press: function () {
this.oSuccessMessageDialog.close();
}.bind(this)
})
});
}
this.oSuccessMessageDialog.open();

How do I share an image with text on Whatsapp in reactjs?

I have tried sharethis-reactjs https://libraries.io/npm/sharethis-reactjs
and also react share https://www.npmjs.com/package/react-share.
All I am able to do is send the url or some text across , I want to send an Image with some text (only image is also fine).
The answers on the internet is only to react-native , I am looking for a solution in reactjs.
I am creating a PWA so it will be working in mobiles.
<InlineShareButtons
config={{
alignment: 'center', // alignment of buttons (left, center, right)
color: 'social', // set the color of buttons (social, white)
enabled: true, // show/hide buttons (true, false)
font_size: 16, // font size for the buttons
labels: 'cta', // button labels (cta, counts, null)
language: 'en', // which language to use (see LANGUAGES)
networks: [ // which networks to include (see SHARING NETWORKS)
'whatsapp',
'linkedin',
'messenger',
'facebook',
'twitter'
],
padding: 12, // padding within buttons (INTEGER)
radius: 4, // the corner radius on each button (INTEGER)
show_total: true,
size: 40, // the size of each button (INTEGER)
// OPTIONAL PARAMETERS
url: '', // (defaults to current url)
image: '', // (defaults to og:image or twitter:image)
description: 'custom text', // (defaults to og:description or twitter:description)
title: 'custom title', // (defaults to og:title or twitter:title)
message: 'custom email text', // (only for email sharing)
subject: 'custom email subject', // (only for email sharing)
username: 'custom twitter handle' // (only for twitter sharing)
}}
/>
Can someone please tell me what I can enter in the image=" " to share an image or any other way to share an image in react js
You can use Web Share API in your React.js web application to share text, URLs, and files.
With the Web Share API, web apps are able to share text, URLs, and files to other apps installed on the device in the same way as native apps.
Web Share API has some limitations:
It can only be used on a site that supports HTTPS.
It must be invoked in response to a user action such as a click.
Invoking it through the onload handler is impossible.
As of mid-2020, it is only available on Safari and on Android in
Chromium forks.
https://web.dev/web-share/
Following code can be used to share text and URL along with an image:
const handleOnSubmit= async()=> {
const response = await fetch(image);
// here image is url/location of image
const blob = await response.blob();
const file = new File([blob], 'share.jpg', {type: blob.type});
console.log(file);
if(navigator.share) {
await navigator.share({
title: "title",
text: "your text",
url: "url to share",
files: [file]
})
.then(() => console.log('Successful share'))
.catch((error) => console.log('Error in sharing', error));
}else {
console.log(`system does not support sharing files.`);
}
}
useEffect(()=> {
if (navigator.share === undefined) {
if (window.location.protocol === 'http:') {
window.location.replace(window.location.href.replace(/^http:/, 'https:'));
}
}
}, []);

AMAZON SNS Push notification payload to android mobile using Node js

Implementation of Amazon SNS push notification to android device using aws-sdk package in NodeJS. I have few implementations mentioned below. Mobile device is displaying push notifications. I want to send data and notification object in payload.
let payload2 = JSON.stringify({
default: 'Naresh',
GCM: JSON.stringify({
notification : {
body : 'great match!',
title : 'Portugal vs. Denmark'
},
data:{
testdata: 'Check out these awesome deals!',
url: 'www.amazon.com'
}
})
});
It's not sending push notifications.
let payload1 = {
"GCM": "{
\"notification\": {
\"title\": \"this one last test in app\",
\"body\": \"mm hello tests\"
},
\"data\": {
\"turnclass\": \"efwfwe\",
\"flight\": \"truejet\"}
}"
};
It's sending push notifications.
sns.publish({ TargetArn: targetArn,
Message: payload1,
MessageStructure: 'json'
}, (error, data) => (error) ? reject(error) : resolve(data));
What is right format to send push notifications?
According to documentation:
When sending platform-specific payloads in messages using the Amazon
SNS console, the data must be key-value pair strings and formatted as
JSON with quotation marks escaped.
Example:
{
"GCM":"{
"data":{
"message":"Check out these awesome deals!",
"url":"www.amazon.com"
}
}"
}
What you are doing in the first payload produces the following output:
{"default":"Naresh","GCM":"{\"notification\":{\"body\":\"great match!\",\"title\":\"Portugal vs. Denmark\"},\"data\":{\"testdata\":\"Check out these awesome deals!\",\"url\":\"www.amazon.com\"}}"}
And that is not a valid format. That happens because you're double JSON.stringify a part of your object. So if you do:
let payload2 = JSON.stringify({
default: 'Naresh',
GCM: {
notification: {
body: 'great match!',
title: 'Portugal vs. Denmark'
},
data: {
testdata: 'Check out these awesome deals!',
url: 'www.amazon.com'
}
}
});
It will produce:
{"default":"Naresh","GCM":{"notification":{"body":"great match!","title":"Portugal vs. Denmark"},"data":{"testdata":"Check out these awesome deals!","url":"www.amazon.com"}}}
Which should work as expected.

Categories

Resources