I can't log in successfully from Google Apps Script despite looking for solutions hours long, including many entries in SoF.
The login process sends a POST request to this url: https://finbox.com/_/api/v5/tokens
Input of the credentials happens here: https://finbox.com/login/email
Response code is 400.
Any help will be really appreciated :)
So far I ended up with this:
function testFinBoxWithCredentials(stock = "AAPL") {
var options = {
method: 'post',
contentType: 'application/json',
payload: {
email: 'xxxxxxxxx',
password: 'xxxxxxxxx'
},
muteHttpExceptions: true,
followRedirects: false
};
const response = UrlFetchApp.fetch("https://finbox.com/_/api/v5/tokens", options);
Logger.log(response.getResponseCode());
if ( response.getResponseCode() == 200 ) {
Logger.log("Couldn't login.");
}
else if ( response.getResponseCode() == 302 ) {
Logger.log("Logged in successfully");
var cookie = response.getAllHeaders()['Set-Cookie'];
Logger.log(cookie);
//Access then a link like https://finbox.com/NASDAQGS:AAPL
/* var cookies = response.getAllHeaders()['Set-Cookie'];
for (var i = 0; i < cookies.length; i++) {
cookies[i] = cookies[i].split( ';' )[0];
};
url2 = "https://finbox.com/NASDAQGS:AAPL";
options2 = {
"method": "get",
"headers": {
"Cookie": cookies.join(';')
}
}
var response2 = UrlFetchApp.fetch(url2, options2);
var content = response2.getContentText();
Logger.log(content)*/
} ```
Related
I have developed the following code based on other code I found on the internet, but it does not work.
Can someone help me to understand my issue?
I get an error saying I don't have the right.
What is the problem?
Thank you very much for your support, that will be well appreciated.
var tokenService_ = function(){return ScriptApp.getOAuthToken()};
function exe() {
var listObj = reportTeamDrivePermissions('id of the folder');
console.log(listObj.toString());
}
function reportTeamDrivePermissions(driveId) {
// Reading the Drive permissions
var options = {"supportsAllDrives": true, "fields": 'permissions,nextPageToken', "pageSize":100};
var paramString = Object.keys(options).map(function(key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(options[key]);
}).join('&');
var url = "files/"+driveId+"/permissions";
url = url + (url.indexOf('?') >= 0 ? '&' : '?') + paramString;
url = "https://www.googleapis.com/drive/v3/" + url;
var fetchOptions = {method:"GET",muteHttpExceptions:true, contentType:"application/json", headers:{Authorization:"Bearer "+tokenService_()}};
var response = UrlFetchApp.fetch(url, fetchOptions);
if(response.getResponseCode() != 200){
throw new Error(response.getContentText());
} else {
var PermissionListResource = JSON.parse(response.getContentText());
}
var myPermisionList = PermissionListResource.permissions;
var nextPageToken = PermissionListResource.nextPageToken;
while (nextPageToken != null) {
// Reading the Drive permissions
options = {"supportsAllDrives": true, "fields": 'permissions,nextPageToken', "pageSize":100, 'pageToken': nextPageToken};
paramString = Object.keys(options).map(function(key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(options[key]);
}).join('&');
url = "files/"+driveId+"/permissions";
url = url + (url.indexOf('?') >= 0 ? '&' : '?') + paramString;
url = "https://www.googleapis.com/drive/v3/" + url;
fetchOptions = {method:"GET",muteHttpExceptions:true, contentType:"application/json", headers: {Authorization:"Bearer "+tokenService_()}}
response = UrlFetchApp.fetch(url, fetchOptions)
if(response.getResponseCode() != 200){
throw new Error(response.getContentText());
} else {
var PermissionListResource2 = JSON.parse(response.getContentText());
}
myPermisionList = myPermisionList.concat(PermissionListResource2.permissions);
nextPageToken = myPermisionObject2.nextPageToken;
}
return myPermisionList;
}
I want to set some command on my t-bot, but i cant understand how to do that
var token = "123456....";
var url = "https://api.telegram.org/bot" + token;
function setMyCommands(chat_id, message_id){
var data = {
method: "post",
payload:{
method: "setMyCommands",
chat_id: String(chat_id),
message_id: message_id,
parse_mode: "HTML"
}
};
UrlFetchApp.fetch(url + '/', data);
}
Now, I am doing like
if message is "/command" to do so. through following:
function sendMessage(id, text, keyBoard){
var data = {
method: "post",
payload: {
method: "sendMessage",
chat_id: String(id),
text: text,
parse_mode: "HTML",
reply_markup: JSON.stringify(keyBoard)
}
};
UrlFetchApp.fetch(url + "/", data);
}
function doPost(e) {
var contents = JSON.parse(e.postData.contents);
var id = contents.message.from.id;
var text = contents.message.text;
if (text == "/command") {
sendMessage(id,"someTEXT...")
}
}
could u pls, also explain what should var data look like and where can I take a form(or structure) of this to apply other methods from telegram bot API
Pyhton case:
create variables:
BOT_TOKEN = '12324'
BOT_COMMANDS= [{"command":"a", "description":"aaa"},{"command":"b","description":"bbb"}]
create the function:
def setMyCommands():
send_text = 'https://api.telegram.org/bot' + BOT_TOKEN + '/setMyCommands?commands=' + str(json.dumps(BOT_COMMANDS) )
response = requests.get(send_text)
and finnaly execute:
if __name__ == '__main__':
#getMyCommands()
setMyCommands()
I am attempting to authenticate with a service account to work on behalf of a user account on the domain. I have delegated admin access and added to the GSuite console. I can get an access token with the below but the making batch requests to copy drive files returns "code: 404, message: 'File not found:". The below code is writted in Google Apps Script. Am I missing something form the process to creating and authenticating the service account?
var CREDENTIALS = {
private_key: "-----BEGIN PRIVATE KEY----- XXXXXXX \n-----END PRIVATE KEY-----\n",
client_email: "XXXXXX#fXXXXXX.iam.gserviceaccount.com",
client_id: "1XXXXXXXXXXXXXXXX",
user_email: "XXXXX#XXXX.XXX.XXX",
scopes: ["https://www.googleapis.com/auth/drive","https://www.googleapis.com/auth/spreadsheets","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/script.external_request"]
};
function oAuthToken(){
var url = "https://www.googleapis.com/oauth2/v3/token";
var header = {
alg: "RS256",
typ: "JWT",
};
var now = Math.floor(Date.now() / 1000);
var claim = {
iss: CREDENTIALS.client_id,
sub: CREDENTIALS.user_email,
scope: CREDENTIALS.scopes.join(" "),
aud: url,
exp: (now + 3600).toString(),
iat: now.toString(),
};
var signature = Utilities.base64Encode(JSON.stringify(header)) + "." + Utilities.base64Encode(JSON.stringify(claim));
var jwt = signature + "." + Utilities.base64Encode(Utilities.computeRsaSha256Signature(signature, CREDENTIALS.private_key));
var params = {
method: "post",
payload: {
assertion: jwt,
grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
},
};
var res = UrlFetchApp.fetch(url, params).getContentText();
return JSON.parse(res)
}
The batch process is a bit rough but this is the gist of it.
var request={
batchPath:
requests:[]
}
var backoff =0
function batch(request) {
var oAuth=oAuthToken().access_token
var url ='https://www.googleapis.com/'+request.batchPath
var body =request.requests
if(body.length<1){
return []
}
var boundary = 'xxxxxxxxxx';
var contentId = 0;
var data = '--' + boundary + '\r\n';
for (var i in body) {
if(typeof body[i]=='object'){
data += 'Content-Type: application/http\r\n';
data += 'Content-ID: ' + ++contentId + '\r\n\r\n';
data += body[i].method + ' ' + body[i].endpoint + '\r\n';
data += body[i].requestBody ? 'Content-Type: application/json; charset=utf-8\r\n\r\n' : '\r\n';
data += body[i].requestBody ? JSON.stringify(body[i].requestBody) + '\r\n' : '';
data += "--" + boundary + '\r\n';
}
}
var parseBatchRes = function(res) {
var splittedRes = res.split('--batch');
return splittedRes.slice(1, splittedRes.length - 1).map(function(e) {
return {
contentId: Number(e.match(/Content-ID: response-(\d+)/)[1]),
status: Number(e.match(/HTTP\/\d+.\d+ (\d+)/)[1]),
object: JSON.parse(e.match(/{[\S\s]+}/)[0]),
};
});
};
var payload = Utilities.newBlob(data).getBytes();
var head = {Authorization: 'Bearer ' + oAuth}
var options = {
method: 'POST',
contentType: 'multipart/mixed; boundary=' + boundary,
payload: payload,
headers: head,
muteHttpExceptions: false
};
var complete=false;
var finalResponse=[];
for (var n=0; n<=backoff; n++) {
if(complete){
break;
}
var complete = true
console.log('backoff',n);
var response =UrlFetchApp.fetch(url, options).getContentText();
for(var j=0;j<response.length;j++){
if(response[r].status!=200){
var complete = false
}
}
}
}
Add the supportsAllDrives = true query parameter to the request.
The parameters indicates whether the requesting application supports both My Drives and shared drives and the default value for this is false.
Reference
Drive API Parameters
I'm getting the error:
Invalid JSON payload received. Unable to parse number. INVALID_ARGUMENT
I got the key and everything and I'm still having the same error return. A few suggestions are resizing the image first to less fit the 4MB image limit.
I also tried emulating the same JSON request coming from their docs. But still have the same issue.
https://cloud.google.com/vision/docs/drag-and-drop
Here's the code I'm using: (I got the sample from Akshay Kadam)
me.detection_types = {
LABEL_DETECTION: 'label',
DOCUMENT_TEXT_DETECTION: 'text',
LOGO_DETECTION: 'logo',
LANDMARK_DETECTION: 'landmark'
};
var api_key = '';
$scope.takePicture = function(){
var options = {
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.CAMERA,
targetWidth: 150,
targetHeight: 150,
correctOrientation: true,
cameraDirection: 0,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
quality: 25
};
$cordovaCamera.getPicture(options).then(function(imagedata){
me.current_image = "data:image/jpeg;base64," + imagedata;
me.image_description = '';
me.locale = '';
var vision_api_json = {
"requests":[
{
"image":{
"content": imagedata
},
"imageContext": {
"cropHintsParams": {
"aspectRatios": [
0.8,
1,
1.2
]
}
},
"features":[
{
"type": me.detection_type,
"maxResults": 1
}
]
}
]
}
var file_contents = JSON.stringify(vision_api_json);
$cordovaFile.writeFile(
cordova.file.applicationStorageDirectory,
'file.json',
file_contents,
true
).then(function(result){
var headers = {
'Content-Type': 'application/json'
};
options.headers = headers;
var server = 'https://vision.googleapis.com/v1/images:annotate?key=' + api_key;
var filePath = cordova.file.applicationStorageDirectory + 'file.json';
$cordovaFileTransfer.upload(server, filePath, options, true)
.then(function(result){
alert(JSON.stringify(result))
var res = JSON.parse(result.response);
var key = me.detection_types[me.detection_type] + 'Annotations';
me.image_description = res.responses[0][key][0].description;
}
Need help. Thank you!
UPDATE:
I tried adding Content-Length and was still having the same problem.
i want a telegram bot that set a specific photo as a group image. Here you can see the bot api about that method(https://core.telegram.org/bots/api#setchatphoto).
I'm using this function but it doesn't work.
function myFunction(){
var chatId = SUPERGOUP_CHAT_ID
var photo = {
file_id: FILE_ID,
file_size: 425707,
file_path: 'documents/file_2.png'
}
var data = {
method: "post",
payload: {
method: "setChatPhoto",
chat_id: String(zone),
photo: JSON.stringify(photo)
}
}
UrlFetchApp.fetch('https://api.telegram.org/bot' + token + '/', data);
}
Telegram answer to the function up here:
{"ok":false,"error_code":400,"description":"Bad Request: photo should be uploaded as an InputFile"}
Searching online i found this solution but it also doesn't work.
function uploadFile() {
var group = SUPERGOUP_CHAT_ID
var boundary = "labnol";
var blob = DriveApp.getFileById('FILE_ID').getBlob();
var attributes = "{\"name\":\"asd.jpg\", \"parent\":{\"id\":\"FOLDER_ID\"}}";
var requestBody = Utilities.newBlob(
"--"+boundary+"\r\n"
+ "Content-Disposition: form-data; name=\"attributes\"\r\n\r\n"
+ attributes+"\r\n"+"--"+boundary+"\r\n"
+ "Content-Disposition: form-data; name=\"file\"; filename=\""+blob.getName()+"\"\r\n"
+ "Content-Type: " + blob.getContentType()+"\r\n\r\n").getBytes()
.concat(blob.getBytes())
.concat(Utilities.newBlob("\r\n--"+boundary+"--\r\n").getBytes());
var options = {
method: "post",
contentType: "multipart/form-data; boundary="+boundary,
payload: {
method: "setChatPhoto",
chat_id: String(group),
photo: requestBody
}
};
var request = UrlFetchApp.fetch('https://api.telegram.org/bot' + token , options);
Logger.log(request.getContentText());
}
Telegram answer to the function up here:
Timeout: https://api.telegram.org/bot_TOKEN
Can you maybe find a solution?
Thanks in advance.