How would I send a discord embed with JS? - javascript

Currently, I know how to send a normal message with JS, as the code shows below. But how could I turn it into an embed? (front-end)
const url = '*********************************************************************************'
const msg = {
"content": `this is a discord webhook message`
}
fetch(url, {
"method": "POST",
"headers": { "content-type": "application/json" },
"body": JSON.stringify(msg)
})
I tried searching, but found nothing in match to my inquiry.

You should read the documentation!
I assume, because of your content, that you are executing a webhook. So let's look at the documentation as to what may be provided for executing a webhook (creating a normal message is the same in this scenario): https://discord.com/developers/docs/resources/webhook#execute-webhook
The table has content in it just like you have as well as what you're after: embeds. It says it's an array of up to 10 embed objects. All you do now is visit the hyperlink to find out what you're able to use in an embed object and pass it as an array.
For example, { description: "test" } is a valid embed object. Put that in an array and place it alongside your content (or omit it) with the key embeds.

Related

Github API not assigning users or labels while creating issue

Update: Fixed by adding helper user as collaborator with write privileges
I realized that the helper user that is creating the issue cannot add assignees or labels unless it is a collaborator with write access to the specified repo
I am writing a google apps script that will run upon completion of a google form, and use the form data to create a github issue. I am using this API request to create the issue, but the tags and assignees are never added to the new issue. I am fairly certain my permissions are correct, since the docs say my access token just needs push access. I have given the token full repo control:
image of access token permissions
The executions tab in the apps script editor shows no errors.
The full code for the request is below:
const payload = {
owner: config.github.OWNER,
repo: config.github.REPO,
title: `Onboard ${data["Employee Full Name"]}`,
body: `## Issue created by: ${data["Email Address"]}\n${issueBody}`,
};
const options = {
method: "POST",
contentType: "application/json",
headers: {
Authorization: `token ${config.github.TOKEN}`,
"Content-Type": "application/json",
},
payload: JSON.stringify(payload),
assignees: ['user1', 'user2'],
labels: ['Onboarding'],
};
const response = UrlFetchApp.fetch(
`https://api.github.com/repos/${config.github.OWNER}/${config.github.REPO}/issues`,
options
);
const json = JSON.parse(response.getContentText());
Logger.log(json);

Cloudfare Api zone api key is failing to auth

I have a website that adds dns records to itself automatically using the cloudfare api.
So here is the fetch request that I do:
fetch("https://api.cloudflare.com/client/v4/zones/***{ACCOUNT_ID}***/dns_records", {
body: '{"type":"A","name":"example.com","content":"127.0.0.1","ttl":3600,"priority":10,"proxied":true}',
headers: {
"Content-Type": "application/json",
"X-Auth-Email": "********#gmail.com",
"X-Auth-Key": "************"
},
method: "POST"
}).then(res=>{res.json().then(r=>console.log(r))})
So the api key I am using is generated on the api zone keys, with perms to edit the zone that I am looking to. However, it gives me this:
{
success: false,
errors: [ { code: 10000, message: 'Authentication error' } ]
}
I have tried using X-Auth-User-Service-Key instead of X-Auth-Key and excluding the email, I have tried using my global api key as X-Auth-User-Service-Key and X-Auth-Key, I have tried using my local key, but nothing I do seems to work. I just get the same error. I have tried replacing the account id in the url by the seemingly random combination of letters and numbers provided in the cloudfare api docs, but still, nothing seems to work. Can someone tell me what I am doing wrong?

Intercepting requests in Puppeteer - updated postData not being sent

So after solving yesterday's problem (linked below) another one has popped up.
Setting a FormData key/value on click with Puppeteer/NodeJS
The issue I'm having today is that I'm trying to modify an existing key in the FormData that's being sent to the server. The request gets intercepted correctly, I parse the FormData using the "qs" query string parsing package, then try to modify an existing key and use "NEW VALUE" in it's place. When I log it everything looks fine. However when I run chrome with headless=false and inspect the traffic I can see that the request is being sent without "NEW VALUE". It's as if I'm just calling continue() without passing any parameters in. I've attached the code below.
await this.page.setRequestInterception(true);
this.page.on("request", interceptedRequest => {
const formDataObj = qs.parse(interceptedRequest.postData());
if (interceptedRequest.url() === "https://www.someurl.com" && formDataObj.email) {
formDataObj.existingKey= "NEW VALUE";
const options = {
'method': 'POST',
'postData': qs.stringify(formDataObj),
'headers': {
...interceptedRequest.headers(),
'Content-Type': 'application/x-www-form-urlencoded'
},
};
console.log("Sending with new data");
console.log(qs.stringify(formDataObj));
interceptedRequest.continue(options);
} else {
interceptedRequest.continue();
}
Not sure where to go from here. I've done a lot of reading and tried some things like different versions of Puppeteer, passing ONLY the FormData (as a string) in to the continue() call and using some flags like "--enable-feature=NetworkService" (suggested on github) when launching chrome but nothing is working. Any help would be greatly appreciated!

Send message to discord via google apps script

I'd like to send a bot message in a discord channel via google apps script when a certain event is triggered, but I don't know where to start. Is this even possible? If not, is there a way to do it via github?
EDIT: I have figured out how to get the OAuth tokens, now how do I make the bot send a message?
I know that there's pretty much no chance that the OP still needs this answer, but I'm putting it up here so that others who google this question will be able to find the answer
var webhooks = {
test: "Obtain a webhook for the channel you'd like and put it here."
};
function sendMessage(message, channel)
{
if(webhooks.hasOwnProperty(channel))
var url = webhooks[channel];
else {
Logger.log("Error Sending Message to Channel " + channel);
return "NoStoredWebhookException";
}
var payload = JSON.stringify({content: message});
var params = {
headers: {"Content-Type": "application/x-www-form-urlencoded"},
method: "POST",
payload: payload,
muteHttpExceptions: true
};
var res = UrlFetchApp.fetch(url, params);
Logger.log(res.getContentText());
}
// to call and send a message
sendMessage("Hi!", "test");
This is what I typically use for sending messages. Unfortunately, there's no way to receive triggers from the webhooks to my knowledge.
Note: The above answer references discord.js, which is not compatible with Google Apps Script
To start with, here is a documentation from discord.js.
To let your apps script communicate with discord, you can check the External APIs
Google Apps Script can interact with APIs from all over the web. This
guide shows how to work with different types of APIs in your scripts.
Examples are available in the provided documentations.
See these useful links for further details.
Website (source)
Documentation
Discord.js server
Discord API server
GitHub
NPM
Related libraries (see also discord-rpc)
Super easy. Just go to your Discord channel, choose "Edit Channel" > "Webhooks". You name the bot and set its profile picture. It will give you a webhook URL that already contains the authorization token.
Then you just POST to that public URL. TADA, a message will appear in the given channel, sent by the bot.
function postMessageToDiscord(message) {
message = message || "Hello World!";
var discordUrl = 'https://discordapp.com/api/webhooks/labnol/123';
var payload = JSON.stringify({content: message});
var params = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: "POST",
payload: payload,
muteHttpExceptions: true
};
var response = UrlFetchApp.fetch(discordUrl, params);
Logger.log(response.getContentText());
}
Source: https://ctrlq.org/code/20563-post-message-to-discord-webhooks
For anyone still looking and not having luck with previous answers, like me:
After making my message_string, this snippet successfully sent to my desired channel's webhook:
// Send the message to the Discord channel webhook.
let options = {
"method": "post",
"headers": {
"Content-Type": "application/json",
},
"payload": JSON.stringify({
"content": message_string
})
};
Logger.log(options, null, 2);
UrlFetchApp.fetch("your_webhook_url_here", options);
I can't make a comment yet, but if you are having issues with one of the above answers - try changing the content type from:'Content-Type':"application/x-www-form-urlencoded" to 'Content-Type':"application/json".

Javascript + MailChimp API subscribe

When making this request:
// Subscribe a new account holder to a MailChimp list
function subscribeSomeoneToMailChimpList()
{
var options =
{
"apikey": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"id": "xxxxxx",
"email":
{
"email": "me#example.com"
},
"send_welcome": false
};
var mcSubscribeRequest = UrlFetchApp.fetch("https://us4.api.mailchimp.com/2.0/lists/subscribe.json", options);
var mcListObject = Utilities.jsonParse(mcSubscribeRequest.getContentText());
}
This response is returned:
Request failed for https://us4.api.mailchimp.com/2.0/lists/subscribe.json returned code 500. Truncated server response: {"status":"error","code":-100,"name":"ValidationError","error":"You must specify a apikey value"} (use muteHttpExceptions option to examine full response) (line 120, file "v2")
Line 120 is the line on which UrlFetchApp.fetch is called.
The API key is valid (I have tested with simpler API calls that don't include associative arrays). When I append the API key directly to the base URL and remove it from the options, I get an error saying that the list ID is invalid. When I then append the list ID directly to the base URL and remove it from options, I get an error saying that the email address must be in associative array form.
My question is: Using the above format, how does one send requests that contain associative arrays?
The relevant API documentation can be found here.
After further research & tinkering, I was able to solve this:
https://<dc>.api.mailchimp.com/2.0/lists/subscribe.json?apikey=<my_api_key>&id=<my_list_id>&email[email]=test#test.com&merge_vars[FNAME]=John&merge_vars[LNAME]=Doe&double_optin=false&send_welcome=false
Where <dc> should be replaced with the portion after the dash in your API Key. e.g. "us1", "us2", "uk1", etc.
Doing this in javascript exposes your API key to the world. If someone has your key, he/she can make changes to or gain access to your account.
I think I figured out what is going on after reading through the UrlFetchApp.fetch Docs.
https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app?csw=1#fetch(String)
It looks like you should be using some of the extra params to do the request such as payload and method. Your options variable should look like this.
var payload = {
"apikey": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"id": "xxxxxx",
"email": {
"email": "me#example.com"
},
"send_welcome": false
};
payload = Utilities.jsonStringify(payload); // the payload needs to be sent as a string, so we need this
var options = {
method: "post",
contentType: "application/json", // contentType property was mistyped as ContentType - case matters
payload: payload
};
var result = UrlFetchApp.fetch("https://<dc>.api.mailchimp.com/2.0/lists/subscribe.json", options);
Where <dc> should be replaced with the portion after the dash in your API Key. e.g. "us1", "us2", "uk1", etc.
The issue is that your options variable is suppose to be used as JSON and not as a GET url parameter. Also mailchimp specifies that it is better to use POST instead of GET. So over all you should make sure to set you method to "post" and make sure your payload is valid JSON.

Categories