I have a trouble. I want to read crypto prices data.
I make to this function.
function getCryptoPrice(ticker) {
var ticker = ticker || "ETH";
ticker = encodeURI(ticker);
var url=("https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?symbol="+ticker);
var requestOptions = {
method: 'GET',
uri: 'https://pro-api.coinmarketcap.com/.../cry.../listings/latest',
qs: {
start: 1,
limit: 5000,
convert: 'USD'
},
headers: {
'X-CMC_PRO_API_KEY': 'api'
},
json: true,
gzip: true
};
var httpRequest= UrlFetchApp.fetch(url, requestOptions);
var getContext= httpRequest.getContentText();
var parseData=JSON.parse(getContext);
return parseFloat(parseData.data.quote.USD.price)
}
When i debug the function result in picture
enter image description here
when result is google sheet is second picture
enter image description here
Please, help me.
i donť now where have mistake.
I expect function without mistake.
Shouldn't it be?
parseData.data.ETH.quote.USD.price
Or
parseData.data[ticker].quote.USD.price
Related
I know that it is possible to implement dall-e as a function in google sheets but I need your help to get it right.
openai is not defined and I don't know how to do it correctly.
function dalle() {
var setsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
var apiKey = setsheet.getRange(8,2).getValue()
response = openai.Image.create(
prompt="a white siamese cat",
n=1,
size="1024x1024"
)
image_url = response['data'][0]['url']
}
You copied the documentation from the OpenAI documentation, but it's mentioned that's only working for node.js or python.
For Apps Script, you have to use UrlFetch.fetch with the correct endpoint.
Example:
function call() {
var url = 'https://api.openai.com/v1/images/generations';
var options = {
"method": 'POST',
"headers": {
'Content-Type': 'application/json',
'Authorization': `Bearer YOUR_API_KEY`
},
"payload": JSON.stringify({
"model": "image-alpha-001",
"prompt": "a white siamese cat",
"num_images": 1,
"size": "256x256",
"response_format": "url"
}),
muteHttpExceptions: true
}
var response = UrlFetchApp.fetch(url, options);
var responseJson = response.getContentText();
var responseData = JSON.parse(responseJson);
Logger.log(responseData);
}
Reference:
UrlFetch
OpenAI authentification (see CURL method)
I've been using Google Sheets to track the value of my various crypto currencies but ran into an issue I'm unable to resolve. The issue is that I have a new crypto currency called 00 (aka L00p) but when I use my regular code to grab the value from CoinMarketCap I get the following error:
"Syntax error: SyntaxError: missing ) after argument list line: 27
file: Code.gs"
I believe the issue is that the currency/token identifier is two digits and not letter-based.
My code looks like this:
function getCryptoPrice() {
var sh2=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");
var sh3=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet3");
var apiKey=sh2.getRange(1, 2).getValue();
var url="https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?symbol=00"
var requestOptions = {
method: 'GET',
uri: 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest',
qs: {
start: 1,
limit: 5000,
convert: 'USD'
},
headers: {
'X-CMC_PRO_API_KEY': apiKey
},
json: true,
gzip: true
};
var httpRequest= UrlFetchApp.fetch(url, requestOptions);
var getContext= httpRequest.getContentText();
var parseData=JSON.parse(getContext);
sh3.getRange(48, 2).setValue(parseData.data.00.quote.USD.price)
}
For comparisons sake, here's the script I used as a template, and which works without issue:
function getCryptoPrice() {
var sh2=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");
var sh3=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet3");
var apiKey=sh2.getRange(1, 2).getValue();
var url="https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?symbol=XCN"
var requestOptions = {
method: 'GET',
uri: 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest',
qs: {
start: 1,
limit: 5000,
convert: 'USD'
},
headers: {
'X-CMC_PRO_API_KEY': apiKey
},
json: true,
gzip: true
};
var httpRequest= UrlFetchApp.fetch(url, requestOptions);
var getContext= httpRequest.getContentText();
var parseData=JSON.parse(getContext);
sh3.getRange(47, 2).setValue(parseData.data.XCN.quote.USD.price)
}
It seems as though the 00 on row 27 in the 00-script appears to be "un-tethered" from the 00 on row 7. And there's no missing end parenthesis, as the error code claims.
Any ideas?
#TheWizEd, thank you!
After changing the code per TheWizEd's suggestion it now works. The thing that tricked me on my first attemt was that I though TheWizEd had forgot to enter a period in after "data", so I added one before testing. That was the wrong thing to do. I also thought that I had to make a similar change on row 7, but that was also not the case.
The complete - and functioning - code looks like this:
function getCryptoPrice() {
var sh2=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");
var sh3=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet3");
var apiKey=sh2.getRange(1, 2).getValue();
var url="https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?symbol=00"
var requestOptions = {
method: 'GET',
uri: 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest',
qs: {
start: 1,
limit: 5000,
convert: 'USD'
},
headers: {
'X-CMC_PRO_API_KEY': apiKey
},
json: true,
gzip: true
};
var httpRequest= UrlFetchApp.fetch(url, requestOptions);
var getContext= httpRequest.getContentText();
var parseData=JSON.parse(getContext);
sh3.getRange(48, 2).setValue(parseData.data["00"].quote.USD.price)
}
Again, huge thank you to TheWizEd!
Based on several examples, I wrote a function in Google apps script that takes a given input file and saves it at the specified location on Dropbox. It does this using a short lived access token obtained from the Dropbox apps console...
function driveToDropbox(inputFile, targetFilePath, writeMode='add') {
//inputFile = Drive file object, targetFilePath = string, writeMode = 'overwrite' or 'add'
inputFile = DriveApp.getFilesByName('temp.html').next(); //for testing
targetFilePath = '/temp.html' //for testing
var apiUrl = 'https://content.dropboxapi.com/2/files/upload';
var dropboxAccessToken = '<SL Token>';
var parameters = {
path: targetFilePath,
mode: writeMode,
autorename: true,
mute: false,
strict_conflict: false,
};
var headers = {
'Content-Type': 'application/octet-stream',
Authorization: 'Bearer ' + dropboxAccessToken,
'Dropbox-API-Arg': JSON.stringify(parameters),
};
var options = {
method: 'POST',
headers: headers,
payload: inputFile.getBlob().getBytes(),
};
var response = JSON.parse(UrlFetchApp.fetch(apiUrl, options).getContentText());
//Logger.log(response);
Logger.log('File uploaded successfully');
}
This will only work for 4 hours, so I obtained the refresh token for the app through the standard flow, and with this cURL command via terminal I am able to generate new working SL tokens.
curl https://api.dropbox.com/oauth2/token -d grant_type=refresh_token -d refresh_token=<R Token> -u <App key>:<App secret>
My problem is converting that CURL command into Google apps Javascript and pulling the returned SL token. This was my attempt...
var apiUrl = 'https://api.dropbox.com/oauth2/token';
var refreshToken = '<R Token>';
var appKey = '<App key>';
var appSecret = '<App secret>';
var appKeySecret = '<Combined app key+secret>'
var parameters = {
refresh_token: refreshToken,
client_id: appKey,
client_secret: appSecret,
};
var headers = {
'Content-Type': 'application/json',
Authorization: 'Basic ' + appKeySecret
'Dropbox-API-Arg': JSON.stringify(parameters),
};
var options = {
method: 'POST',
headers: headers,
grant_type: "refresh_token",
muteHttpExceptions: true,
};
var response = JSON.parse(UrlFetchApp.fetch(apiUrl, options).getContentText());
Logger.log(response);
My error response is "{error_description=missing required field "grant_type", error=unsupported_grant_type}" confirming that my issue is misunderstanding the formatting, but I'm not sure how to fix it.
After fixing that, I would parse out the SL token from the response and then use that with the working file upload code above. Is there something obvious that I am missing with the formatting?
EDIT: Here is the working function based on the selected answer. This should probably be broken into two functions.
function driveToDropbox(inputFile, targetFilePath, writeMode='add') {
//inputFile = Drive file object, targetFilePath = string, writeMode = 'overwrite' or 'add'
inputFile = DriveApp.getFilesByName('temp.html').next(); //for testing
targetFilePath = '/temp.html'; //for testing
////Obtain new 4 hour SL access token with Refresh token
var refreshToken = '<R Token>';
var appKey = '<App key>';
var appSecret = '<App secret>';
var apiUrl = 'https://api.dropbox.com/oauth2/token';
var options = {
method: 'POST',
headers: { "Authorization": "Basic " + Utilities.base64Encode(`${appKey}:${appSecret}`) },
payload: {
grant_type: "refresh_token",
refresh_token: refreshToken
},
muteHttpExceptions: true,
};
var response = UrlFetchApp.fetch(apiUrl, options);
var accessToken = JSON.parse(response.getContentText()).access_token;
////Transfer file with refreshed SL access token
apiUrl = 'https://content.dropboxapi.com/2/files/upload';
var parameters = {
path: targetFilePath,
mode: writeMode,
autorename: true,
mute: false,
strict_conflict: false,
};
options = {
method: 'POST',
headers: {
'Content-Type': 'application/octet-stream',
Authorization: 'Bearer ' + accessToken,
'Dropbox-API-Arg': JSON.stringify(parameters),
},
payload: inputFile.getBlob().getBytes(),
};
response = JSON.parse(UrlFetchApp.fetch(apiUrl, options).getContentText());
Logger.log('File uploaded successfully');
}
I believe your goal is as follows.
You want to convert the following curl command to Google Apps Script.
curl https://api.dropbox.com/oauth2/token -d grant_type=refresh_token -d refresh_token= -u :
In this case, how about the following modification?
Modified script:
Please set your values of refreshToken, appKey, appSecret.
var refreshToken = '<R Token>';
var appKey = '<App key>';
var appSecret = '<App secret>';
var apiUrl = 'https://api.dropbox.com/oauth2/token';
var options = {
method: 'POST',
headers: { "Authorization": "Basic " + Utilities.base64Encode(`${appKey}:${appSecret}`) },
payload: {
grant_type: "refresh_token",
refresh_token: refreshToken
},
muteHttpExceptions: true,
};
var response = UrlFetchApp.fetch(apiUrl, options);
var obj = JSON.parse(response.getContentText());
var accessToken = obj.access_token; // You can retrieve the access token.
console.log(accessToken);
When I saw your sample curl command, it seems that it is required to send grant_type and refresh_token as the form data. And, the basic authorization is used.
Note:
In this answer, it supposes that your sample curl command works. Please be careful about this.
Reference:
fetch(url, params)
I am trying to write code in Google Apps Script that will dump the data shown on the url https://coinmarketcap.com/ into a Google Sheet (say starting in A1). Not just data for one symbol, but all the symbols shown on this page. Specifically I am looking for the data for 'symbol' 'name' 'price' 'market_cap' .
The API documentation is here: https://coinmarketcap.com/api/documentation/v1/#operation/getV1CryptocurrencyListingsLatest
I used to use an API connector to do this, but would rather a couple of lines of code. I spent a couple of hours reading about different approaches from search results, but they were either appropriate for a single symbol, or involved too many requests.
My code is below. I am not getting error, but it isn't returning any data either. I believe I need to tweak 'setValue' but am not sure how to do it.
Would appreciate any help. Thank you!
function coin_price() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Coins')
var requestOptions = {
method: 'GET',
uri: 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?aux=cmc_rank',
qs: {
start: '1',
limit: '5000',
convert: 'USD',
},
headers: {
'X-CMC_PRO_API_KEY': 'MY API KEY'
},
json: true,
gzip: true,
};
var url = `https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?aux=cmc_rank`;
var result = UrlFetchApp.fetch(url, requestOptions);
var txt = result.getContentText()
var d = JSON.parse(txt);
sheet.getRange(100,1).setValue(d.data.market_cap)
}
Suggestion
Perhaps you can try this tweaked script below:
Script:
function coin_price() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Coins')
var requestOptions = {
method: 'GET',
uri: 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?aux=cmc_rank',
qs: {
start: '1',
limit: '5000',
convert: 'USD',
},
headers: {
'X-CMC_PRO_API_KEY': 'API_Key'
},
json: true,
gzip: true,
};
var url = `https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?aux=cmc_rank`;
var result = UrlFetchApp.fetch(url, requestOptions);
var txt = result.getContentText()
var d = JSON.parse(txt);
var dSymbol = [];
var name = [];
var price = [];
var marketCap = [];
for(i=0; i<d.data.length; i++){
marketCap.push([d.data[i].quote.USD.market_cap]);
dSymbol.push([d.data[i].symbol]);
name.push([d.data[i].name]);
price.push([d.data[i].quote.USD.price])
}
//getRange structure (starting row, start col, total number of rows,total number of cols)
sheet.getRange(1,1,dSymbol.length,1).setValues(dSymbol); //Symbol in Col A (start col #1)
sheet.getRange(1,2,name.length,1).setValues(name); //Name in Col B (start col #2)
sheet.getRange(1,3,price.length,1).setValues(price); //Price in Col C (start col #3)
sheet.getRange(1,4,marketCap.length,1).setValues(marketCap); //Market Cap in Col D (start col #4)
}
Sample Result:
Reference:
getRange(row, column, numRows, numColumns)
setValues(values)
I am trying to make a Pastebin.com paste using Google Apps Script from the spreadsheet script editor. Can anyone tell me what I'm doing wrong?
function postPastebinPost() {
var options, url, apiKey, payload, response;
apiKey = <api key goes here>;
payload = 'Hello World';
options = {
'method' : 'post',
'payload' : payload
};
url = 'https://pastebin.com/api/api_post.php'
+ '?api_dev_key=' + apiKey
+ '&api_option=paste'
+ '&api_paste_code=' + encodeURIComponent(payload);
response = UrlFetchApp.fetch(url, options);
Logger.log(response);
}
I run this and my log reads Bad API request, invalid api_option. I've searched for solutions but I have not found any.
Documentation:
• Pastebin.com API
• Google Apps Script's UrlFetchApp Class
The parameters should be passed in the payload of the POST request.
function postPastebinPost() {
var apiKey = 'YOUR KEY GOES HERE';
var text = 'Hello World';
var payload = {
api_dev_key: apiKey,
api_option: 'paste',
api_paste_code: text
};
var options = {
method : 'POST',
payload: payload
};
var url = 'https://pastebin.com/api/api_post.php';
var response = UrlFetchApp.fetch(url, options);
Logger.log(response.getContentText());
}
The following is in case the user wants to create a new paste as part of their own Pastebin account (and not «Paste as a guest»). It's just an adaptation of Amit Agarwal's answer.
function postPastebinPost() {
var title = 'abc';
var contents = 'Hello World \n next line of content \n more text';
var payload = {
api_dev_key: 'aa6f3ab...', // https://pastebin.com/api#1
api_option: 'paste',
api_paste_name: title,
api_paste_code: contents,
api_paste_private: '0', // public paste
api_user_name: 'diccionario...', // name of your Pastebin account
api_user_password: 'dk398d...', // password to your Pastebin account
api_user_key: '39dk3...', // https://pastebin.com/api/api_user_key.html
};
var options = {
method : 'POST',
payload: payload
};
var url = 'https://pastebin.com/api/api_post.php';
var response = UrlFetchApp.fetch(url, options);
Logger.log(response.getContentText());
}
The whole documentation is at https://pastebin.com/api.