إدارة "المهام الدراسية"

يتيح تطبيق Classroom ثلاثة أنواع من عناصر البث: CourseWork وCourseWorkMaterials وAnnouncements. يوضّح هذا الدليل كيفية إدارة CourseWork، ولكن واجهات برمجة التطبيقات لجميع عناصر البث متشابهة. اطّلِع على مراجع واجهات برمجة التطبيقات لمعرفة مزيد من المعلومات عن أنواع عناصر البث واختلافاتها.

يمثّل المرجع CourseWork عنصر عمل تم إسناده إلى الطلاب في دورة تدريبية معيّنة، بما في ذلك أي مواد وتفصيل إضافية، مثل تاريخ الاستحقاق أو الحد الأقصى للنتيجة. هناك أربعة أنواع فرعية من CourseWork: المهام ومهام الاختبارات وأسئلة الإجابة القصيرة و أسئلة الخيارات المتعدّدة. تتيح Classroom API استخدام ثلاثة من هذه الأنواع الفرعية: المهام والأسئلة ذات الإجابات القصيرة والأسئلة بخيارات متعدّدة. يتم تمثيل هذه الأنواع من خلال الحقل CourseWork.workType.

بالإضافة إلى مورد CourseWork، يمكنك إدارة العمل المكتمل باستخدام مورد StudentSubmission.

إنشاء CourseWork

لا يمكن إنشاء CourseWork إلا نيابةً عن معلّم الدورة التدريبية. تؤدي محاولة إنشاء CourseWork نيابةً عن طالب أو مشرف نطاق ليس معلّمًا في الدورة التدريبية إلى خطأ PERMISSION_DENIED. اطّلِع على أنواع المستخدمين لمعرفة المزيد من المعلومات عن الدوار المختلفة في Classroom.

عند إنشاء CourseWork باستخدام الطريقة courses.courseWork.create، يمكنك إرفاق الروابط على أنّها materials، كما هو موضّح في الرمز البرمجي النموذجي أدناه:

Java

classroom/snippets/src/main/java/CreateCourseWork.java
CourseWork courseWork = null;
try {
  // Create a link to add as a material on course work.
  Link articleLink =
      new Link()
          .setTitle("SR-71 Blackbird")
          .setUrl("https://www.lockheedmartin.com/en-us/news/features/history/blackbird.html");

  // Create a list of Materials to add to course work.
  List<Material> materials = Arrays.asList(new Material().setLink(articleLink));

  /* Create new CourseWork object with the material attached.
  Set workType to `ASSIGNMENT`. Possible values of workType can be found here:
  https://developers.google.com/classroom/reference/rest/v1/CourseWorkType
  Set state to `PUBLISHED`. Possible values of state can be found here:
  https://developers.google.com/classroom/reference/rest/v1/courses.courseWork#courseworkstate */
  CourseWork content =
      new CourseWork()
          .setTitle("Supersonic aviation")
          .setDescription(
              "Read about how the SR-71 Blackbird, the world’s fastest and "
                  + "highest-flying manned aircraft, was built.")
          .setMaterials(materials)
          .setWorkType("ASSIGNMENT")
          .setState("PUBLISHED");

  courseWork = service.courses().courseWork().create(courseId, content).execute();

  /* Prints the created courseWork. */
  System.out.printf("CourseWork created: %s\n", courseWork.getTitle());
} catch (GoogleJsonResponseException e) {
  // TODO (developer) - handle error appropriately
  GoogleJsonError error = e.getDetails();
  if (error.getCode() == 404) {
    System.out.printf("The courseId does not exist: %s.\n", courseId);
  } else {
    throw e;
  }
  throw e;
} catch (Exception e) {
  throw e;
}
return courseWork;

Python

classroom/snippets/classroom_create_coursework.py
import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def classroom_create_coursework(course_id):
  """
  Creates the coursework the user has access to.
  Load pre-authorized user credentials from the environment.
  TODO(developer) - See https://developers.google.com/identity
  for guides on implementing OAuth2 for the application.
  """

  creds, _ = google.auth.default()
  # pylint: disable=maybe-no-member

  try:
    service = build("classroom", "v1", credentials=creds)
    coursework = {
        "title": "Ant colonies",
        "description": """Read the article about ant colonies
                              and complete the quiz.""",
        "materials": [
            {"link": {"url": "http://example.com/ant-colonies"}},
            {"link": {"url": "http://example.com/ant-quiz"}},
        ],
        "workType": "ASSIGNMENT",
        "state": "PUBLISHED",
    }
    coursework = (
        service.courses()
        .courseWork()
        .create(courseId=course_id, body=coursework)
        .execute()
    )
    print(f"Assignment created with ID {coursework.get('id')}")
    return coursework

  except HttpError as error:
    print(f"An error occurred: {error}")
    return error


if __name__ == "__main__":
  # Put the course_id of course whose coursework needs to be created,
  # the user has access to.
  classroom_create_coursework(453686957652)

حقلَا title وworkType مطلوبان. وجميع الحقول الأخرى اختيارية. إذا لم يتم تحديد state، يتم إنشاء CourseWork في حالة مسودة.

استخدِم مصدر رابط مع هدف محدّد url لتضمين مواد مرتبطة في CourseWork. تُسترجع واجهة برمجة تطبيقات Classroom تلقائيًا title وعنوان URL لصورة الصورة المصغّرة (thumbnailUrl). تتيح واجهة برمجة التطبيقات Classroom API أيضًا استخدام مواد Google Drive وYouTube بشكلٍ تلقائي، ويمكن تضمينها مع مرجعملف Drive أو مرجعفيديو YouTube بطريقة مشابهة.

لتحديد تاريخ استحقاق، اضبط الحقلَين dueDate وdueTime على التوقيت العالمي المنسق المقابل. يجب أن يكون تاريخ الاستحقاق في المستقبل.

يتضمّن استجابة CourseWork معرّفًا يحدّده الخادم ويمكن استخدامه للإشارة إلى عملية التخصيص في طلبات واجهة برمجة التطبيقات الأخرى.

استرداد CourseWork

يمكنك استرداد CourseWork نيابةً عن الطلاب والمعلّمين في الدورة التدريبية المعنية. يمكنك أيضًا استرداد CourseWork نيابةً عن مشرفي النطاق ، حتى إذا لم يكونوا معلّمين في الدورة التدريبية. لاسترداد CourseWork محدّد، استخدِم courses.courseWork.get. لاسترداد كل CourseWork (اختياريًا مطابقة بعض المعايير)، استخدِم courses.courseWork.list.

يعتمد النطاق المطلوب على الدور الذي يلعبه المستخدم المُقدّم للطلب في الدورة التدريبية. إذا كان المستخدم طالبًا، استخدِم أحد النطاقات التالية:

  • https://www.googleapis.com/auth/classroom.coursework.me.readonly
  • https://www.googleapis.com/auth/classroom.coursework.me

إذا كان المستخدم معلّمًا أو مشرف نطاق، استخدِم أحد النطاقات التالية:

  • https://www.googleapis.com/auth/classroom.coursework.students.readonly
  • https://www.googleapis.com/auth/classroom.coursework.students

إنّ الحصول على إذن باسترداد CourseWork لا يعني حصولك على أذونات للوصول إلى المواد أو البيانات الوصفية للمواد. يعني ذلك عمليًا أنّه قد لا يظهر لمشرف ما عنوان ملف مُرفَق في Drive إذا لم يكن عضوًا في الدورة التدريبية.

إدارة ردود الطلاب

يمثّل مرجع StudentSubmission العمل الذي أنجزه طالب في أحد CourseWork. يتضمّن المرجع بيانات وصفية مرتبطة بالعمل، مثل حالة العمل ودرجته. يتم تلقائيًا إنشاء StudentSubmission لكل طالب عند إنشاء CourseWork جديد.

توضّح الأقسام التالية الإجراءات الشائعة التي تُدير ردود الطلاب.

استرداد ردود الطلاب

يمكن للطلاب استرداد المحتوى الذي أرسلوه، ويمكن للمعلّمين استرداد المحتوى الذي أرسله جميع الطلاب في الدورات التدريبية التي يدرّسونها، ويمكن لمشرفي النطاق استرداد كل المحتوى الذي أرسله جميع الطلاب في نطاقهم. يتم تحديد معرّف لكل StudentSubmission. إذا كنت تعرف المعرّف، استخدِم courses.courseWork.studentSubmissions.get لاسترداد العينة التي تم إرسالها.

استخدِم طريقة courses.courseWork.studentSubmissions.list للحصول على كل موارد StudentSubmission التي تتطابق مع بعض المعايير، كما هو موضّح في المثال التالي:

Java

classroom/snippets/src/main/java/ListSubmissions.java
List<StudentSubmission> studentSubmissions = new ArrayList<>();
String pageToken = null;

try {
  do {
    ListStudentSubmissionsResponse response =
        service
            .courses()
            .courseWork()
            .studentSubmissions()
            .list(courseId, courseWorkId)
            .setPageToken(pageToken)
            .execute();

    /* Ensure that the response is not null before retrieving data from it to avoid errors. */
    if (response.getStudentSubmissions() != null) {
      studentSubmissions.addAll(response.getStudentSubmissions());
      pageToken = response.getNextPageToken();
    }
  } while (pageToken != null);

  if (studentSubmissions.isEmpty()) {
    System.out.println("No student submission found.");
  } else {
    for (StudentSubmission submission : studentSubmissions) {
      System.out.printf(
          "Student id (%s), student submission id (%s)\n",
          submission.getUserId(), submission.getId());
    }
  }
} catch (GoogleJsonResponseException e) {
  // TODO (developer) - handle error appropriately
  GoogleJsonError error = e.getDetails();
  if (error.getCode() == 404) {
    System.out.printf(
        "The courseId (%s) or courseWorkId (%s) does not exist.\n", courseId, courseWorkId);
  } else {
    throw e;
  }
} catch (Exception e) {
  throw e;
}
return studentSubmissions;

Python

classroom/snippets/classroom_list_submissions.py
import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def classroom_list_submissions(course_id, coursework_id):
  """
  Creates the courses the user has access to.
  Load pre-authorized user credentials from the environment.
  TODO(developer) - See https://developers.google.com/identity
  for guides on implementing OAuth2 for the application.
  """

  creds, _ = google.auth.default()
  # pylint: disable=maybe-no-member
  submissions = []
  page_token = None

  try:
    service = build("classroom", "v1", credentials=creds)
    while True:
      coursework = service.courses().courseWork()
      response = (
          coursework.studentSubmissions()
          .list(
              pageToken=page_token,
              courseId=course_id,
              courseWorkId=coursework_id,
              pageSize=10,
          )
          .execute()
      )
      submissions.extend(response.get("studentSubmissions", []))
      page_token = response.get("nextPageToken", None)
      if not page_token:
        break

    if not submissions:
      print("No student submissions found.")

    print("Student Submissions:")
    for submission in submissions:
      print(
          "Submitted at:"
          f"{(submission.get('id'), submission.get('creationTime'))}"
      )

  except HttpError as error:
    print(f"An error occurred: {error}")
    submissions = None
  return submissions


if __name__ == "__main__":
  # Put the course_id and coursework_id of course whose list needs to be
  # submitted.
  classroom_list_submissions(453686957652, 466086979658)

يمكنك استرداد StudentSubmission موردًا ينتمي إلى طالب معيّن من خلال تحديد المَعلمة userId، كما هو موضّح في المثال التالي:

Java

classroom/snippets/src/main/java/ListStudentSubmissions.java
List<StudentSubmission> studentSubmissions = new ArrayList<>();
String pageToken = null;

try {
  do {
    // Set the userId as a query parameter on the request.
    ListStudentSubmissionsResponse response =
        service
            .courses()
            .courseWork()
            .studentSubmissions()
            .list(courseId, courseWorkId)
            .setPageToken(pageToken)
            .set("userId", userId)
            .execute();

    /* Ensure that the response is not null before retrieving data from it to avoid errors. */
    if (response.getStudentSubmissions() != null) {
      studentSubmissions.addAll(response.getStudentSubmissions());
      pageToken = response.getNextPageToken();
    }
  } while (pageToken != null);

  if (studentSubmissions.isEmpty()) {
    System.out.println("No student submission found.");
  } else {
    for (StudentSubmission submission : studentSubmissions) {
      System.out.printf("Student submission: %s.\n", submission.getId());
    }
  }

Python

classroom/snippets/classroom_list_student_submissions.py
import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def classroom_list_student_submissions(course_id, coursework_id, user_id):
  """
  Creates the courses the user has access to.
  Load pre-authorized user credentials from the environment.
  TODO(developer) - See https://developers.google.com/identity
  for guides on implementing OAuth2 for the application.
  """

  creds, _ = google.auth.default()
  # pylint: disable=maybe-no-member
  submissions = []
  page_token = None

  try:
    service = build("classroom", "v1", credentials=creds)
    while True:
      coursework = service.courses().courseWork()
      response = (
          coursework.studentSubmissions()
          .list(
              pageToken=page_token,
              courseId=course_id,
              courseWorkId=coursework_id,
              userId=user_id,
          )
          .execute()
      )
      submissions.extend(response.get("studentSubmissions", []))
      page_token = response.get("nextPageToken", None)
      if not page_token:
        break

    if not submissions:
      print("No student submissions found.")

    print("Student Submissions:")
    for submission in submissions:
      print(
          "Submitted at:"
          f"{(submission.get('id'), submission.get('creationTime'))}"
      )

  except HttpError as error:
    print(f"An error occurred: {error}")
  return submissions


if __name__ == "__main__":
  # Put the course_id, coursework_id and user_id of course whose list needs
  # to be submitted.
  classroom_list_student_submissions(453686957652, 466086979658, "me")

يتم تحديد الطلاب من خلال المعرّف الفريد أو عنوان البريد الإلكتروني، كما هو موضّح في مورد Student. يمكن للمستخدم الحالي أيضًا الإشارة إلى معرّفه باستخدام الاختصار "me".

من الممكن أيضًا استرداد المهام التي أرسلها الطلاب لجميع المهام الدراسية ضمن أحد الدورات الدراسية. لإجراء ذلك، استخدِم القيمة الثابتة "-" كقيمة courseWorkId، كما هو موضَّح في المثال التالي:

Java

service.courses().courseWork().studentSubmissions()
    .list(courseId, "-")
    .set("userId", userId)
    .execute();

Python

service.courses().courseWork().studentSubmissions().list(
    courseId=<course ID or alias>,
    courseWorkId='-',
    userId=<user ID>).execute()

يعتمد النطاق المطلوب على الدور الذي يلعبه المستخدم الذي يطلب إذن الوصول في الدورة التدريبية. إذا كان المستخدم معلّمًا أو مشرف نطاق، استخدِم النطاق التالي:

  • https://www.googleapis.com/auth/classroom.coursework.students.readonly
  • https://www.googleapis.com/auth/classroom.coursework.students

إذا كان المستخدم طالبًا، استخدِم النطاق التالي:

  • https://www.googleapis.com/auth/classroom.coursework.me.readonly
  • https://www.googleapis.com/auth/classroom.coursework.me

إنّ الحصول على إذن لاسترداد StudentSubmission لا يعني أنّ لديك أذونات للوصول إلى المرفقات أو البيانات الوصفية للمرفقات. يعني ذلك عمليًا أنّه قد لا يظهر لأحد المشرفين عنوان ملف Drive مرفق إذا لم يكن عضوًا في الدورة التدريبية.

إضافة مرفقات إلى ردّ أحد الطلاب

يمكنك إرفاق روابط بأحد العناصر التي أرسلها الطالب من خلال إرفاق مرجع Link أو DriveFile أو YouTubeVideo. يتم ذلك باستخدام الرمز courses.courseWork.studentSubmissions.modifyAttachments، كما هو موضّح في المثال التالي:

Java

classroom/snippets/src/main/java/ModifyAttachmentsStudentSubmission.java
StudentSubmission studentSubmission = null;
try {
  // Create ModifyAttachmentRequest object that includes a new attachment with a link.
  Link link = new Link().setUrl("https://en.wikipedia.org/wiki/Irrational_number");
  Attachment attachment = new Attachment().setLink(link);
  ModifyAttachmentsRequest modifyAttachmentsRequest =
      new ModifyAttachmentsRequest().setAddAttachments(Arrays.asList(attachment));

  // The modified studentSubmission object is returned with the new attachment added to it.
  studentSubmission =
      service
          .courses()
          .courseWork()
          .studentSubmissions()
          .modifyAttachments(courseId, courseWorkId, id, modifyAttachmentsRequest)
          .execute();

  /* Prints the modified student submission. */
  System.out.printf(
      "Modified student submission attachments: '%s'.\n",
      studentSubmission.getAssignmentSubmission().getAttachments());
} catch (GoogleJsonResponseException e) {
  // TODO (developer) - handle error appropriately
  GoogleJsonError error = e.getDetails();
  if (error.getCode() == 404) {
    System.out.printf(
        "The courseId (%s), courseWorkId (%s), or studentSubmissionId (%s) does "
            + "not exist.\n",
        courseId, courseWorkId, id);
  } else {
    throw e;
  }
} catch (Exception e) {
  throw e;
}
return studentSubmission;

Python

classroom/snippets/classroom_add_attachment.py
def classroom_add_attachment(course_id, coursework_id, submission_id):
  """
  Adds attachment to existing course with specific course_id.
  Load pre-authorized user credentials from the environment.
  TODO(developer) - See https://developers.google.com/identity
  for guides on implementing OAuth2 for the application.
  """
  creds, _ = google.auth.default()
  # pylint: disable=maybe-no-member
  request = {
      "addAttachments": [
          {"link": {"url": "http://example.com/quiz-results"}},
          {"link": {"url": "http://example.com/quiz-reading"}},
      ]
  }

  try:
    service = build("classroom", "v1", credentials=creds)
    while True:
      coursework = service.courses().courseWork()
      coursework.studentSubmissions().modifyAttachments(
          courseId=course_id,
          courseWorkId=coursework_id,
          id=submission_id,
          body=request,
      ).execute()

  except HttpError as error:
    print(f"An error occurred: {error}")


if __name__ == "__main__":
  # Put the course_id, coursework_id and submission_id of course in which
  # attachment needs to be added.
  classroom_add_attachment("course_id", "coursework_id", "me")

يتم تحديد مرفق Link من خلال العنصر المستهدَف url، ويعمل Classroom على retrievingtitle وصورة المصغّرة (thumbnailUrl) تلقائيًا. اطّلِع على Material للتعرّف على المواد التي يمكن إرفاقها بStudentSubmissions.

لا يمكن تعديل StudentSubmission إلا من قِبل معلّم الدورة التدريبية أو الطالب الذي يملكها. لا يمكنك إرفاق Materials إلا إذا كان CourseWorkType StudentSubmission هو ASSIGNMENT.

يعتمد النطاق المطلوب على الدور الذي يلعبه المستخدم المُقدّم للطلب في الدورة التدريبية. إذا كان المستخدم معلّمًا، استخدِم النطاق التالي:

  • https://www.googleapis.com/auth/classroom.coursework.students

إذا كان المستخدم طالبًا، استخدِم النطاق التالي:

  • https://www.googleapis.com/auth/classroom.coursework.me