Github API not assigning users or labels while creating issue - javascript

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

Related

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?

Clash Royale Node Fetch with Key

Im trying to make a discord bot where if you type -cr into the chat, it takes the Arguments of the user (Being the Clash Royale Player's player tag) and would then use the package node-fetch to receive data with my specified endpoint. I am constantly running into the error of { reason: 'accessDenied', message: 'Invalid authorization' }. Im rather new to this stuff, especially API's, but im hoping to access certain data which I can decide later on (Which I know how to do). My code is :
const fetch = require('node-fetch')
module.exports = {
name: 'clash',
aliases: ['cr', 'clashroyale'],
category: 'This',
utilisation: '{prefix}clash',
async execute(client, message) {
var msgArgs = message.content.slice(this.name.length + 1)
var endpoint = `/players/${msgArgs}`
var url = `https://api.clashroyale.com/v1`
var token = `hidingmytoken`
fetch(url + endpoint, {
method: 'POST',
headers: {
"Authorization": token
}
}).then(data => data.json()).then(json => {
console.log(json)
})
},
};
The message parts with msgArgs and discord sides all work but fetching that clash Royale API is a big hurdle for me. The API for Clash Royale can be found here https://developer.clashroyale.com/#/documentation and Im just generally stuck on this whole concept. Im using version 2.6.6 of node-fetch so I can use the require() method which should work if that does matter. In general, how can I pass my token properly to receive that API data?
Since the Clash Royale API uses bearer authentication, you need to specify that it will be a bearer token.
headers: {
'Authorization': `Bearer ${token}`
}
I've implemented the following functionality. The code is written in GO but you can copy the logic and translate into your language.
The library have the following functionality:
Login
Token generation
Token list
Token delete
https://github.com/alessiosavi/GoClashRoyale/blob/master/api/auth.go

Why do I get a 400 error trying to get data from an html page using fetch API?

Hi I'm doing a coding challenge and I'm trying to fetch data from an html page but I keep getting the 400 error. I don't see where my syntax would be wrong. The Promise returns an empty string as PromiseResult. Why do I not get the data from https://adventofcode.com/2021/day/2/input?
fetch('https://adventofcode.com/2021/day/2/input', {
method: 'GET',
mode: 'no-cors',
credentials: 'omit',
headers: {
'Content-Type': 'text/plain'
}
})
.then((response) => {
response.text();
})
.then((html) => {
var parser = new DOMParser();
var doc = parser.parseFromString(html, 'text/html');
})
.catch((err) => { console.log(err) })
After visting https://adventofcode.com/2021/day/2/input I get information that
Puzzle inputs differ by user. Please log in to get your puzzle input.
Please check if you are providing your login data correctly.
mode: 'no-cors',
This says that you are not going to do anything that requires permission to be granted using CORS. Anything that does require CORS will be quietly ignored.
You need CORS permission to read data across origins. Since you have said you aren't going to use CORS, you don't have permission, so you don't get any data.
This is why you get an empty string.
credentials: 'omit',
The input endpoint requires your credentials so that it can give you your input, which is unique to each user. Since told the browser not to send any, the end point doesn't understand the request.
As an aside:
headers: {
'Content-Type': 'text/plain'
}
This is just nonsense.
It claims that the request includes a body consisting of plain text.
You are making a GET request. There is no body on the request at all.
Advent of code expects you to manually download your input data. It doesn't expect your solution to fetch it from the AoC website.
JS solutions are generally run in Node.js (rather than a web browser) where they can use the fs module to read the local copy of the input file. (Tip: I find it handy to copy/paste the sample data into a sample file to test my results against the worked example on each day).

Building Chainlink External Adapter for Binance Withdrawals

I have already made an attempt to build the external adapter but unfortunately, I keep running into the error: "You are not authorized to execute this request"
If you want to know how to exactly build one there are the following resources (basically the same material but different format):
https://blog.chain.link/build-and-use-external-adapters/ (blogpost)
https://youtu.be/65NhO5xxSZc (video)
In the resources above a template is used in NodeJS:
https://github.com/PatrickAlphaC/CL-EA-NodeJS-Template
And this is the repo to my own attempt (with error). I just modified the index.js file:
https://github.com/gvandriel/CL-EA-NodeJS-Template
Then start the server with
yarn (install dependencies)
yarn start
Open up another terminal and paste the following to post a withdrawal request:
curl -X POST -H "content-type:application/json" "http://localhost:8080/" --data '{ "id": 0, "data": { "asset": "USDT", "address": "0xe66273cC443F774653E885496f76b486F956B47F", "amount": 10 } }'
Please note that since you are doing a withdrawal from Binance you need to enable that in your account API settings and set the restricted IP address. Moreover, I believe you can only withdraw funds from an address that you previously have withdrawn to. Also don't forget to update the .env_sample file with your own keys
What does work in the code?
We know that the totalstring at line 58 is working since we tested it outside the external adapter. Moreover we also know that the header with X-MBX-APIKEY is working. Thus we believe that the error consists in the following:
Requester.request(config, customError)
.then((response) => {
// It's common practice to store the desired value at the top-level
// result key. This allows different adapters to be compatible with
// one another.
response.data.result = Requester.validateResultNumber(response.data, [
"msg",
]);
callback(response.status, Requester.success(jobRunID, response));
})
.catch((error) => {
callback(500, Requester.errored(jobRunID, error));
});
The bug might also be somewhere else in the code so make sure to check the modified index.js file here:
https://github.com/gvandriel/CL-EA-NodeJS-Template
In your index.js file, you are setting the params and config objects:
const params = {
asset,
address,
amount,
recvWindow,
timestamp,
signature,
};
const config = {
method: "post",
url,
headers: {
"X-MBX-APIKEY": process.env.API_key,
},
};
However, params is never included into config. Also, it seems you want to send these params as POST data. Consider renaming the params object to data (Axios docs), and append data in your config:
const config = {
method: "post",
url,
headers: {
"X-MBX-APIKEY": process.env.API_key,
},
data
}

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".

Categories