Search code examples
google-apps-script

Google App Script file handling not working


I have a google app script project rn that uses DriveApp to store a list of people to a .txt file, but when I added the code ui.prompt('foo', 'bar', ui.ButtonSet.foobar) it just gave the error message 'Exception: Argument cannot be null: prompt'.

I tried things like changing the syntax and making it a variable, but it didnt work. If anyone can figure this out id greatly appreciate it :) Code:

var ui = DocumentApp.getUi()
function onOpen() {
  ui.createMenu('Social')
    .addItem('Ping', 'ping')
    .addSubMenu(ui.createMenu('Friends')
      .addItem('Add friend', 'addFriend')
      .addItem('View friends', 'viewFriends'))
    .addToUi();
}

function ping() {
  var person = ui.prompt('Ping', 'Enter recipient email', ui.ButtonSet.OK_CANCEL)
  MailApp.sendEmail(person.getResponseText(), ui.prompt('Subject', 'Enter subject', ui.ButtonSet.OK).getResponseText(), ui.prompt('Message', 'Enter message', ui.ButtonSet.OK).getResponseText())
}
function addFriend() {
  if (!DriveApp.getFilesByName('Friends.txt').hasNext()) {
    DriveApp.createFile('Friends', '')
  }
  var friend = ui.prompt('Add friend', 'Please enter friend email address', ui.ButtonSet.OK_CANCEL).getResponseText()
  DriveApp.getFilesByName('Friends.txt')[1].setContent(friend)
}

function viewFriends() {
  ui.alert(DriveApp.getFilesByName('Friends.txt')[1])
}

As you can see it creates the file if nonexistent and then writes to it but it doesnt work


Solution

  • function viewFriends() {
     ui.alert(DriveApp.getFilesByName('Friends.txt')[1])
    }
    

    DriveApp.getFilesByName gets a FileIterator rather than an array. You cannot refer to the results with indices like [1] but have to use hasNext() and next().