Create posts from Google Forms responses

Since the API changed, the code for Google Forms (Google App Script) changed too. Here is a sample with a single question in the form.

FORM_ID = "<get this from the form URL>"
ITEM_ID = <get this from the Developer tools, look for the id of the whole question element> // int value

URL = "<site URL with the trailing />"
CATEGORY = <from sites.json> // int value
API_KEY = "<admin API key>"
POSTER = "<assigned user name to the key>"

MAX_TITLE_SIZE = 50  // this is just to keep title size in control

function onFormSubmit() {
  var form = FormApp.openById(FORM_ID),
      item = form.getItemById(ITEM_ID), // repeat this for all items in the form or use alternative means of getting all items
      formResponses = form.getResponses(),
      newestResponse = formResponses[formResponses.length - 1],
      response = newestResponse.getResponseForItem(item).getResponse(); // this reads only the single item noted above

  console.log(response)

  if (response.length < 20) {
    response = "New topic posted: " + response   // just to make sure response captured is > 20 characters
  }

  var title = response.substring(0,Math.min(MAX_TITLE_SIZE,response.length)); // just to make sure the title is not too big

	const url = URL + "posts";
	
  const fetched = UrlFetchApp.fetch(url, {
		"method": "POST",
		"headers": {
			"Api-Key": API_KEY,
			"Api-Username": POSTER,
			"Content-Type": "multipart/form-data",
			"Accept": "application/json",
			"Content-Type": "application/json"
		},
		"muteHttpExceptions": true,
		"followRedirects": true,
		"validateHttpsCertificates": true,
		"contentType": "application/json",
		"payload": JSON.stringify({"title":title,"raw":response,"category":CATEGORY})
	});

	Logger.log("Response code is %s", fetched.getResponseCode());
	Logger.log(fetched.getContentText());
}

I hope this helps anyone looking for something similar for the original topic but with the new API.

לייק 1