Send Form response from prefilled link in Apps Script - google-apps-script

I've tried to find some topic about it but without results
I would need only send Form from copied prefilled link in apps script but i am not able to find out where doing misstakes.
Here are two options what i've found but without good results.
Form doesn't send any response
I've replace in prefilled Link "viewform" for "formResponse" according to some instructions in web, but it does't work.
Do you can help me anyone?
function send() {
var config = {
muteHttpExceptions: true,
method: "get"
};
var url = "https://docs.google.com/forms/d/e/<form_id>/formResponse?usp=pp_url&entry.231322462=ANO&entry.133135319=1&entry.1743053173=2023-01-15";
var response = UrlFetchApp.fetch(url, config);
//Logger.log(response)
}
or:
function send() {
var url = "https://docs.google.com/forms/d/e/<form_id>/formResponse?usp=pp_url&entry.231322462=ANO&entry.133135319=1&entry.1743053173=2023-01-15";
var response = UrlFetchApp.fetch(url);
//Logger.log(response)
}

You have an existing Google Form and you want to write a script in order to edit existing Form Responses in in the Form.
At the time of writing, this isn't possible.
Refer:
Edit Form Responses as soon as it is submitted

Related

Google scripts function to fetch curl data to Google Sheets

I'm trying to fetch some data to a google sheet. The code goes like this:
function ls() {
var url = "https://api.loanscan.io/v1/interest-rates?tokenFilter=BTC";
var params = {
"contentType": "application/json",
"headers":{"x-api-key": "KEY",
},
};
var json = UrlFetchApp.fetch(url, params);
var jsondata=json.getContentText();
var page = JSON.parse(jsondata);
Logger.log page
return page;
}
The Logger.log gives the correct Data, as you can see in the next link.
Log
However when I run the function in the google sheet, it returns a blank cell.
Please help, thank you.
You should write the Logger.log(page); with parentheses, because sheets is probably hanging on your Logger statement.
I don't have an API key for that site, but I do get the forbidden error response from the API when using =ls() in a cell in sheets.

how to send data from telegram bot inline keyboard to specific column in google spreadsheet?

I am not really familiar with the Telegram API and need to use JSON.
I want to create an inline keyboard that have options [yes/no] only.
Then, send it to a spreadsheet.
I managed to create the inline keyboard but nothing happens when I press it.
Is it possible to send data to a spreadsheet from the Telegram bot?
Code:
{"inline_keyboard":[[{"text":"yes","callback_data":"yes"}]]}
Yes, this is possible :)
You'd first need to setup a webhook for your telegram bot -
var telegramToken = 'Your-Telegram-Bot-Token-Goes-Here';
function setup() {
var method = 'setWebhook';
var payload = {
url: ScriptApp.getService().getUrl()
}
var options = {
'method' : 'post',
'contentType': 'application/json',
'payload' : JSON.stringify(payload)
};
var response = UrlFetchApp.fetch('https://api.telegram.org/bot' + telegramToken + '/' + method, options);
Logger.log(response);
}
and then setup a simple doPost(e) to capture incoming data from said webhook. You can refer some of the code from a bot that's i'd built here but please feel free to share more details with what you require so I could assist accordingly.

Web scraping with Google Apps Script

I'm trying to pull data from the following sample web page using Google Apps Script:
url = http://www.premierleague.com/players/2064/Wayne-Rooney/stats?se=54
using, UrlFetchApp.Fetch(url)
The problem is when I use UrlFetchApp.Fetch(url) to do that, I don't get the page information defined by the 'se' parameter in the url. Instead, I get the information on the following URL because it looks like the 'se=54' page is asynchronously loaded:
http://www.premierleague.com/players/2064/Wayne-Rooney/stats
Is there any way to pass the parameter 'se' some other way? I was looking at the function and it allows the specification of 'options', as they are referred to, but the documentation on the topic is very limited.
Any help would be most appreciated. Many thanks
Tommy
Go to that website in your browser and open the developer tools (F12 or ctr-shift-i). Click on the network tab and reload the page with F5.
A list of requests will appear. At the bottom of the list you should see the asynchronous requests made to fetch the information. Those requests get the data in json form from footballapi.pulselive.com.
You can do the same thing in apps script. But you have to send a correct "origin" header line or your request gets rejected.
Here is an example.
function fetchData() {
var url = "http://footballapi.pulselive.com/football/stats/player/2064?comps=1";
var options = {
"headers": {
"Origin": "http://www.premierleague.com"
}
}
var json = JSON.parse(UrlFetchApp.fetch(url, options).getContentText());
for(var i = 0; i < json.stats.length; i++) {
if(json.stats[i].name === "goals") Logger.log(json.stats[i]);
}
}
Please try the following solution:
var options =
{
"method" : "GET",
"followRedirects" : true,
"muteHttpExceptions": true
};
var result = UrlFetchApp.fetch(url, options);

Google form url point to last updated answer

I have created a Google form with a Google spreadsheet associated to it that can be accessed (using the form URL) by each recipient I am sending it to. Right now the URL isn't unique to each recipient. The recipient can access the form then submit it. Upon submit, I am generating an edit URL via the GetEditResponse() function available in the Google FormResponse Class. The recipient can then edit their response using the edit url I provide them once they submit the form.
Here is my Google App Script code:
function myFunction() {
assignEditUrls();
}
function assignEditUrls() {
var form = FormApp.openById('formId');
//enter form ID here
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Form Responses');
//Change the sheet name as appropriate
var data = sheet.getDataRange().getValues();
var urlCol = 5; // column number where URL's should be populated; A = 1, B = 2 etc
var responses = form.getResponses();
var timestamps = [], urls = [], resultUrls = [];
for (var i = 0; i < responses.length; i++) {
timestamps.push(responses[i].getTimestamp().setMilliseconds(0));
urls.push(shortenUrl(responses[i].getEditResponseUrl()));
}
for (var j = 1; j < data.length; j++) {
resultUrls.push([data[j][0]?urls[timestamps.indexOf(data[j][0].setMilliseconds(0))]:'']);
}
sheet.getRange(2, urlCol, resultUrls.length).setValues(resultUrls);
}
function shortenUrl(longUrl) {
// google url shortener api key
var key = "apiKey";
var serviceUrl="https://www.googleapis.com/urlshortener/v1/url?key="+key;
var options={
muteHttpExceptions:true,
method:"post",
contentType: "application/json",
payload : JSON.stringify({'longUrl': longUrl })
};
var response=UrlFetchApp.fetch(serviceUrl, options);
if(response.getResponseCode() == 200) {
var content = JSON.parse(response.getContentText());
if ( (content != null) && (content["id"] != null) )
return content["id"];
}
return longUrl;
}
You can also view the Spreadsheet associated with the form.
The problem with this model is that the recipients need to get back an edited URL in order to edit their response at a later time. Instead I want them to keep the same URL I originally provided them with and each time they come back to that URL I should identify which recipient it is and redirect them with the last updated URL.
For that scenario to happen I would need to:
1. Create a unique URL (identifier) for each recipient.
2. The same URL should point to the last updated URL (Form) so that they can always use the same URL originally provided (backend process).
Is this possible to achieve using Google's available tools? If it is, how can I create a unique url to identify which recipient responded to the form?
Staying within the confines of Google Apps Script, you cannot provide a redirection to a Google Form.
Here are two ideas off the top of my head...
If you're willing to use another service to handle the redirection, you could have it do the redirection for you. (I'm not recommending any, just saying it's an option.)
You could write a Google Apps Script web service that would present a mock-up of your real form. Users would have a unique URL to pass their unique identifier as a HTTP query parameter; heck, you could use goo.gl to produce a short URL for each of them as you do now. Based on the identifier, pre-fill the fake form with their last results. Upon commit, your web service can submit the form programmatically.
Create a unique URL (identifier) for each recipient.
Creating a separate Google Form for each person will give you this.
The same URL should point to the last updated URL
Assuming your go with creating a separate Form for each user, try placing the edit URL back into each Form's description or 1st page some where after submission of the 1st response. You'd have to make it clear that they have to click on that link going forward. There isn't a setting to automatically re-direct original Google Form URLs to their corresponding Edit Response ones AFAIK, if that's what you are asking for.

UrlFetch from Google Sheet exportLink['application/pdf'] not returning PDF data

I create and send a periodic email as an update from a Google Sheet. For various client reasons this is done 3 ways, as a link to the Sheet, and as attachments (PDF and XLSX).
This was working 'til recently. The XSLX attachment still works, but the PDF is no longer sent as a response to a UrlFetch to the file.exportLinks('application/pdf') url. No matter what the request headers it always returns as Content-Type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Did something else undocumented change that I am missing here?
function exportAsPDF(spreadsheetId) {
spreadsheetId = spreadsheetId || 'SECRET_ID';
var file = Drive.Files.get(spreadsheetId),
url = file.exportLinks['application/pdf'];
url += '&format=pdf&size=7&fzr=true&portrait=true&fitw=true&gid=0&gridlines=false&printtitle=false&sheetnames=false&pagenum=UNDEFINED&attachment=true'
var token = ScriptApp.getOAuthToken(),
response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var headers = response.getAllHeaders(); // revealing content-type returned isn't pdf
var pdfBlob = response.getBlob().getAs('application/pdf');
var pdfString = pdfBlob.getDataAsString(); // this naturally throws an error
return response.getBlob(); // this returns to the send mail script
}
I'm able to get PDFs using the utility from Convert all sheets to PDF with Google Apps Script.
That working script modifies the spreadsheet's edit URL into an export URL, which looks like:
https://docs.google.com/spreadsheets/d/<%SS-ID%>/export?exportFormat=pdf...
The advanced Drive service gives an export URL formatted like:
https://docs.google.com/spreadsheets/export?id=<%SS-ID%>&exportFormat=pdf...
I'd expect the URL provided by exportLinks to be more reliable than the hack in the working script. Apparently, it's not.
This has been raised as Issue 5114. Star it to receive updates.