javascriptgoogle-apps-scriptgoogle-apigoogle-developers-consolegoogle-classroom

Create assignment with file drive using google apps script


I'm a new developer, I want to add an assignment in Google Classroom using a script. Here is the code that was created:

function assignmentWithDriveFile(){
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getSheetByName('ASSIGNMENT (Drive File)');
  const courseId = sheet.getRange('B1').getValue();
  const topicId = sheet.getRange('B2').getValue.toString();

  var assignment = {
    topicId: topicId,
    title: sheet.getRange('B3').getValue().toString(),
    description: sheet.getRange('B4').getValue().toString(),
    materials :[{
      driveFile: {
        driveFile: {
          id: sheet.getRange('B5').getValue.toString(),
          title: sheet.getRange('B6').getValue.toString()
        },
        shareMode: "STUDENT_COPY"
      }
    }],
    maxPoints : sheet.getRange('B7').getValue().toString(),
    state: "PUBLISHED",
    workType: "ASSIGNMENT"
  };

  const newCourseAssignment = Classroom.Courses.CourseWork.create(assignment, courseId);
  const assId = newCourseAssignment.id;
  sheet.getRange('D1').setValue(assId);
}

after running I get a notification in my spreadsheet that is "GoogleJsonResponseException: API call to classroom.courses.courseWork.create failed with error: @AttachmentNotVisible The item referenced by an attachment was not found or not visible to the user." well what should i do? I really wait for your answer and I appreciate it```

Do I have to change the drive ID?


Solution

  • Modification points:

    When these points are reflected in your script, how about the following modification?

    Modified script:

    function assignmentWithDriveFile() {
      const ss = SpreadsheetApp.getActiveSpreadsheet();
      const sheet = ss.getSheetByName('ASSIGNMENT (Drive File)');
      const [[courseId], [topicId], [title], [description], [driveFileId], [driveFileTitle], [maxPoints]] = sheet.getRange("B1:B7").getDisplayValues();
      var assignment = {
        topicId,
        title,
        description,
        materials: [{
          driveFile: {
            driveFile: {
              id: driveFileId, title: driveFileTitle
            },
            shareMode: "STUDENT_COPY"
          }
        }],
        maxPoints: maxPoints,
        state: "PUBLISHED",
        workType: "ASSIGNMENT"
      };
      const newCourseAssignment = Classroom.Courses.CourseWork.create(assignment, courseId);
      const assId = newCourseAssignment.id;
      sheet.getRange('D1').setValue(assId);
    }