Hi I have been experimenting with webhooks and I'm wondering how do you send a normal message(not embeded) through a webhook with a custom avatar and name
const user = message.mentions.users.first() || client.users.cache.get(args[0]);
let announcement = args.slice(1).join(" ");
if(!announcement) return message.channel.send(`lol say something`)
const wc = new WebhookClient('id', 'token')
const embed = new MessageEmbed()
.setTitle("").setColor('GREEN').setTimestamp().setDescription(announcement)
wc.send({
username : user.username,
avatarURL : user.displayAvatarURL({ dynamic : true }),
embeds : [embed]
})
}
```
If you wish to send Discord webhooks you need to make a POST API request to the webhook url.
For that you can basically use any module you want however in this example I'll use node-fetch. Simply install it in your console
npm install node-fetch
and then require it where you need to use it
const fetch = require('node-fetch');
Now that we have what we need to make it work lets create the API request.
For that we start with the params variable. Here you set all the things that make the webhook look like you want it to look. Note: I also included how to send embeds just in case. If you want to see all options check here.
var params = {
username: "Your name",
avatar_url: "",
content: "Some message you want to send",
embeds: [
{
"title": "Some title",
"color": 15258703,
"thumbnail": {
"url": "",
},
"fields": [
{
"name": "Your fields here",
"value": "Whatever you wish to send",
"inline": true
}
]
}
]
}
Now that we have the params we can create the actual POST request. For that you simply call the fetch function and provide the webhook url.
First you specify the method you want to use. By default the method is GET. Next make sure to set the headers to 'Content-type': 'application/json', otherwise you'll get an error. Lastly include the params from earlier in the body. We use JSON.stringify() here to make it work.
fetch('URL', {
method: "POST",
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify(params)
}).then(res => {
console.log(res);
})
At the end you have the option to catch any errors you might receive.
Related
I am attempting to add dynamic links to push notifications so users tap them and open to a specific app page. I have been following the documentation and the links do not open to the page they should when I tap the push notifications but when tested in the browser the links do open to the correct page. From what I have read, there are 2 possible solutions depending on the version of firebase the project is using. The older "way" is to add a click_action property to the apns payload object, the newer way is to create a webpush object with the fcm_options property set to the value of the link. Neither of these options seems to work regardless of where the objects are placed in the request. Is my request formatted incorrectly or am I possibly missing something? Below is the current request:
const [title, body, deepLink] = titleAndBody;
let accessToken = await getAccessToken();
accessToken = "Bearer " + accessToken;
const options = {
method: "POST",
url: URL,
headers: {
Authorization: accessToken,
"Content-Type": "application/json",
},
body: JSON.stringify({
message: {
token: fcmToken,
notification: {
body: body,
title: title,
},
webpush: {
fcm_options: {
link: deepLink,
}
},
apns: {
headers: {
priority: "10",
},
payload: {
//click_action: deepLink,
aps: {
badge: 0,
mutable_content: 1,
},
},
}
},
}),
};```
Using fastify and fluent-json-schema
I'm trying to figure out how to make a POST route body required in the openapi schema output
const postSomethingSchema = S.object()
.prop("fieldA", S.string())
export const postSchema = {
operationId: "createSomething",
body: postSomethingSchema,
response: { 200: somethingSchema },
};
Today, this generates the following, (without the required key I'm looking for of course)
"post": {
"operationId": "createSomething",
"requestBody": {
"required": true, // I can't figure out how to get this!
"content": {...}
Im trying to update a distribution list by sending a put request, when I run this code and test it in postman by giving it a JSON body I get this error in my node.js terminal stating SyntaxError: Unexpected end of JSON input ... any idea what I should change?
My PUT API request
app.put("/api/Dls/Add/:groupId" , (req, res) => {
const response = {
success: false
};
if (Authorized.myToken) {
response.success = true;
response.data = {};
var options = {
method: 'PUT',
url: 'https://SomeAPI.com/' + req.params.groupId,
headers:
{
Accept: 'application/json',
Authorization: 'Bearer' + ' ' + Authorized.myToken
},
body: JSON.stringify(req.body)
};
request(options, function (error, response, body){
if (error) {
console.log(error);
return;
}
const data = response.body;
const dls = JSON.parse(data)
return res.json(dls);
});
}
});
JSON body I'm passing through postman to test the API call
{
"groupId": "123456789",
"SomeField1": null,
"SomeField2": "xxxxxxxxx",
"SomeField3": true,
"SomeField4": "xxxxxxxxx",
"SomeField5": "xxxxxxxxx",
"SomeField6": [
"xxxxxxxxx"
],
"SomeField7": "xxxxxxxxx",
"SomeField8": "xxxxxxxxx",
"SomeField9": "xxxxxxxxx",
"SomeField10": "xxxxxxxxx",
"SomeField11": [],
"SomeField12": "xxxxxxxxx",
"SomeField13": null,
"SomeField14": false,
"SomeField15": ["xxxxxxxxx"]
}
Any feedback is appreciated!
If the JSON that you posted here is the real one that you pass via postman then, it is not the valid JSON as you have the same name properties. When I say valid it means you get something like this after posting to the endpoint.
{
"groupId": "123456789",
"SomeField": [
"xxxxxxxxx"
]
}
Request npm package is also deprecated so it is better to not use it and replace it with something like Axios. TBH I did not see any error in the code that causes the error that you mentioned, do you have access to the API to check the logs? Maybe something went wrong on the https://SomeAPI.com/ endpoint.
I figured out what the issue was, I needed to add the .end to the return statement
ex. return res.status(200).end()
Currently checking out https://www.npmjs.com/package/swagger-client. The docs are a bit confusing to me.
I intend to hit a URL like www.mysite.com/topic/:topicName
I tried a few things like this:
const authHeaders = {
'X-Api-Key': 'mykey',
Authorization: `Bearer mytoken`,
};
const topic = await client.apis.Topic.getTopic({
headers: authHeaders,
parameters: {
topicName: 'myName'
}
});
I can't seem to figure the right way to send headers and fill in the variable from the swagger docs to form the URL. I'd seen examples where the headers are the first argument so I also had tried
const topic = await client.apis.Topic.getTopic(authHeaders, {
parameters: {
topicName: 'myName'
}
});
When I look at the docs for the word headers, they just talk about setting up the initial client. I figure making it send the auth headers every time is another good solution so I'm kind of looking for both ways (since either can make sense depending on the header).
Using the swagger-client is a little different that a regular http client because it follow exactly your swagger file, you will have to provide the parameters that your swagger spec describes.
for swagger client v3, this format works for me:
Swagger({
url: "www.example.org/swagger.json",
authorization: {
// This must be described in your swagger file, if not, will be ignored.
// See https://swagger.io/docs/specification/authentication/bearer-authentication/
bearerAuth: {type: 'apiKey', 'in': 'header', name: 'Authorization'}
}
}).then(client => {
client.apis.Topic.getTopic({
// The parameters need to be described in the swagger file, or will be ignored.
// Also make sure that the getTopic operation describes that uses the bearerAuth
// Or swagger-client will not send the Auth credentials.
topicName: "myName"
}).then(response => {
// Do magic.
})
});
The swagger portion for your getTopic operation should be similar to this:
{
"/rest/3/topic/{topicName}": {
"tags": ["topic"]
"operationId": "getTopic"
"get": {
"parameters": [
{
"name": "topicName", "in": "path", "required": true, "type": "string"
}
],
"security": { "basicAuth": "global" }
}
}
}
Using Angular and SendGrid, I am trying to send an email. I installed the NPM package correctly but am having issues with implementing the code. I generated an API key and stored it in the directory with
echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > sendgrid.env
echo "sendgrid.env" >> .gitignore
source ./sendgrid.env
The Typescript is:
sgemail(){
const sgMail = require('#sendgrid/mail'); //ERROR: Cannot find name 'require'.
sgMail.setApiKey(process.env.SENDGRID_API_KEY); //ERROR: Cannot find name 'process'.
const msg = {
to: 'test#example.com',
from: 'test#example.com',
subject: 'Sending with SendGrid is Fun',
text: 'and easy to do anywhere, even with Node.js',
html: '<strong>and easy to do anywhere, even with Node.js</strong>',
};
console.log(msg);
sgMail.send(msg);
}
I am firing this on a button click.
Sendgrid has no information on their site about importing packages like how you have to use import { Vibration } from '#ionic-native/vibration'; to use Ionic's vibration package.
You could try sending a POST request manually using fetch to their Send Mail API. And don't forget the Authorization Headers. Below is a same untested JavaScript code snippet to try. Fill in YOUR_API_KEY and update the to email to one of your emails.
var payload = {
"personalizations": [
{
"to": [
{
"email": "john#example.com"
}
],
"subject": "Hello, World!"
}
],
"from": {
"email": "from_address#example.com"
},
"content": [
{
"type": "text/plain",
"value": "Hello, World!"
}
]
};
var myHeaders = new Headers({
"Content-Type": "application/json",
"Authorization": "Bearer YOUR_API_KEY",
});
var data = new FormData();
data.append( "json", JSON.stringify( payload ) );
fetch("https://api.sendgrid.com/v3/mail/send",
{
method: "POST",
headers: myHeaders,
body: data
})
.then(function(res){ return res.json(); })
.then(function(data){ console.log( JSON.stringify( data ) ) })