사용자가 Google Meet에서 클래스룸을 사용 중인가요? Google Meet에서 학생의 참석 여부를 확인하는 방법 관련 Apps Script 빠른 시작을 확인하세요.

교사 및 학생 관리

학생과 교사는 사용자 프로필과 과정 간의 특정 매핑이며, 과정에서 사용자의 역할을 나타냅니다. 학생과 교사를 지정하는 것은 전역적이지 않습니다. 즉, 한 사용자를 한 교사의 교사로 지정하고 다른 과정에서는 학생을 지정할 수 있습니다. 'student' 또는 '교사'라는 지정은 특정 과정의 특정 사용자에 대한 권한 집합을 나타냅니다.

학생
학생 리소스는 특정 과정에서 학생으로 등록된 사용자를 나타냅니다. 학생은 이 과정의 세부정보 및 교사를 볼 수 있습니다.
교사
교사 리소스는 특정 과정을 가르치는 사용자를 나타냅니다. 교사는 과정 세부정보를 확인 및 변경하고, 교사와 학생을 확인하고, 추가 교사와 학생을 관리할 수 있습니다.

학생과 교사는 Google Admin SDK에서 반환한 사용자의 고유 ID나 이메일 주소로 식별됩니다. 현재 사용자는 "me" 약칭을 사용하여 자신의 ID를 참조할 수도 있습니다.

직접 추가

도메인 관리자는 초대 흐름을 우회하여 도메인 내의 사용자를 도메인 내 과정에 교사 또는 학생으로 직접 추가할 수 있습니다. 과정 소유자가 관리자의 도메인에 있는 경우 교육 과정 내에서 강의가 고려됩니다. 인증된 도메인 관리자 도메인 외부의 사용자 또는 과정의 경우 애플리케이션은 invitations.create() 메서드로 초대를 전송하여 사용자의 동의를 얻어야 합니다.

교사 추가 또는 삭제

도메인 관리자는 다음 샘플과 같이 도메인 내의 교사를 teachers.create()를 사용하여 과정에 직접 추가할 수 있습니다.

.NET

classroom/snippets/클래스룸스니펫/Addteacher.cs
using Google.Apis.Auth.OAuth2;
using Google.Apis.Classroom.v1;
using Google.Apis.Classroom.v1.Data;
using Google.Apis.Services;
using System;
using System.Net;
using Google;

namespace ClassroomSnippets
{
    // Class to demonstrate the use of Classroom Create Teacher API
    public class AddTeacher
    {
       /// <summary>
       /// Add teacher to the Course
       /// </summary>
       /// <param name="courseId"></param>
       /// <param name="teacherEmail"></param>
       /// <returns></returns>
        public static Teacher ClassroomAddTeacher( string courseId,
                 string teacherEmail)
         {
             try 
             {
                 /* Load pre-authorized user credentials from the environment.
                  TODO(developer) - See https://developers.google.com/identity for 
                  guides on implementing OAuth2 for your application. */
                 GoogleCredential credential = GoogleCredential.GetApplicationDefault()
                     .CreateScoped(ClassroomService.Scope.ClassroomRosters);

                 // Create Classroom API service.
                 var service = new ClassroomService(new BaseClientService.Initializer
                 {
                     HttpClientInitializer = credential,
                     ApplicationName = "Classroom API Snippet"
                 });

                 var teacher = new Teacher
                 {
                     UserId = teacherEmail
                 };
                 // Add the teacher to the course.
                 teacher = service.Courses.Teachers.Create(teacher, courseId).Execute();
                     Console.WriteLine(
                         "User '{0}' was added as a teacher to the course with ID '{1}'.\n",
                         teacher.Profile.Name.FullName, courseId);
                     return teacher;
             }
             catch (Exception e)
             {
                 // TODO(developer) - handle error appropriately
                 if (e is AggregateException)
                 {
                     Console.WriteLine("Credential Not found");
                 }
                 else if (e is GoogleApiException)
                 {
                     Console.WriteLine("Failed to Add the teacher. Error message: {0}", e.Message);
                 }
                 else
                 {
                     throw;
                 }
             }

             return null;
         }


    }

}

자바

classroom/snippets/src/main/java/Add교사.java
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.classroom.Classroom;
import com.google.api.services.classroom.ClassroomScopes;
import com.google.api.services.classroom.model.Teacher;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Collections;

/* Class to demonstrate the use of Classroom Add Teacher API */
public class AddTeacher {
    /**
     * Add teacher to a specific course.
     *
     * @param courseId - Id of the course.
     * @param teacherEmail - Email address of the teacher.
     * @return newly created teacher
     * @throws IOException - if credentials file not found.
     */
    public static Teacher addTeacher(String courseId, String teacherEmail)
            throws IOException {
        /* Load pre-authorized user credentials from the environment.
           TODO(developer) - See https://developers.google.com/identity for
            guides on implementing OAuth2 for your application. */
        GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
                .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_ROSTERS));
        HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
                credentials);

        // Create the classroom API client
        Classroom service = new Classroom.Builder(new NetHttpTransport(),
                GsonFactory.getDefaultInstance(),
                requestInitializer)
                .setApplicationName("Classroom samples")
                .build();

        Teacher teacher = new Teacher().setUserId(teacherEmail);
        try {
            // Add a teacher to a specified course
            teacher = service.courses().teachers().create(courseId, teacher).execute();
            // Prints the course id with the teacher name
            System.out.printf("User '%s' was added as a teacher to the course with ID '%s'.\n",
                    teacher.getProfile().getName().getFullName(), courseId);
        } catch (GoogleJsonResponseException e) {
            // TODO(developer) - handle error appropriately
            GoogleJsonError error = e.getDetails();
            if (error.getCode() == 409) {
                System.out.printf("User '%s' is already a member of this course.\n", teacherEmail);
            } else if (error.getCode() == 403) {
                System.out.println("The caller does not have permission.\n");
            } else {
                throw e;
            }
        }
        return teacher;
    }
}

PHP

classroom/snippets/src/classroomAdd교사.php
use Google\Client;
use Google\Service\Classroom;
use Google\Service\Classroom\Teacher;
use Google\service\Exception;

function addTeacher($courseId, $teacherEmail)
{
    /* Load pre-authorized user credentials from the environment.
    TODO (developer) - See https://developers.google.com/identity for
     guides on implementing OAuth2 for your application. */
    $client = new Client();
    $client->useApplicationDefaultCredentials();
    $client->addScope("https://www.googleapis.com/auth/classroom.profile.photos");
    $service = new Classroom($client);
    $teacher = new Teacher([
        'userId' => $teacherEmail
    ]);
    try {
        //  calling create teacher
        $teacher = $service->courses_teachers->create($courseId, $teacher);
        printf("User '%s' was added as a teacher to the course with ID '%s'.\n",
            $teacher->profile->name->fullName, $courseId);
    } catch (Exception $e) {
        if ($e->getCode() == 409) {
            printf("User '%s' is already a member of this course.\n", $teacherEmail);
        } else {
            throw $e;
        }
    }
    return $teacher;
}

Python

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


def classroom_add_teacher(course_id):
    """
    Adds a teacher to a 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
    service = build('classroom', 'v1', credentials=creds)

    teacher_email = 'gduser1@workspacesamples.dev'
    teacher = {
        'userId': teacher_email
    }

    try:
        teachers = service.courses().teachers()
        teacher = teachers.create(courseId=course_id,
                                  body=teacher).execute()
        print('User %s was added as a teacher to the course with ID %s'
              % (teacher.get('profile').get('name').get('fullName'),
                 course_id))
    except HttpError as error:
        print('User "{%s}" is already a member of this course.'
              % teacher_email)
        return error
    return teachers


if __name__ == '__main__':
    # Put the course_id of course for which Teacher needs to be added.
    classroom_add_teacher(453686957652)

인증된 교사를 대신하여 교사를 추가하는 경우 invitations.create() 메서드를 사용해야 합니다.

teachers.delete() 메서드를 사용하여 추가 교사를 수업에서 삭제할 수 있습니다. 이렇게 하면 지정된 교사만 수업에서 삭제되며 다른 과정 또는 사용자 프로필에 대한 할당에는 영향을 미치지 않습니다.

학생 등록 또는 삭제

도메인 관리자는 다음 샘플과 같이 students.create() 메서드를 사용하여 도메인 내에서 학생을 직접 추가할 수 있습니다.

.NET

classroom/snippets/클래스룸스니펫/AddStudent.cs
using Google.Apis.Auth.OAuth2;
using Google.Apis.Classroom.v1;
using Google.Apis.Classroom.v1.Data;
using Google.Apis.Services;
using System;
using System.Net;
using Google;

namespace ClassroomSnippets
{
    // Class to demonstrate the use of Classroom Create Student API
    public class AddStudent
    {
        public static Student ClassroomAddStudent(string courseId, string enrollmentCode)
        {
            try
            {
                /* Load pre-authorized user credentials from the environment.
                 TODO(developer) - See https://developers.google.com/identity for 
                 guides on implementing OAuth2 for your application. */
                GoogleCredential credential = GoogleCredential.GetApplicationDefault()
                    .CreateScoped(ClassroomService.Scope.ClassroomRosters);
                var service = new ClassroomService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Classroom API .NET Quickstart"
                });

                var student = new Student
                {
                    UserId = "me"
                };

                var request = service.Courses.Students.Create(student, courseId);
                request.EnrollmentCode = enrollmentCode;
                student = request.Execute();
                Console.WriteLine(
                    "User '{0}' was enrolled  as a student in the course with ID '{1}'.\n",
                    student.Profile.Name.FullName, courseId);
            }
            catch (Exception e)
            {
                // TODO(developer) - handle error appropriately
                if (e is AggregateException)
                {
                    Console.WriteLine("Credential Not found");
                }
                else if (e is GoogleApiException)
                {
                    Console.WriteLine("Failed to Add the Student. Error message: {0}", e.Message);
                }
                else
                {
                    throw;
                }
            }

            return null;
        }
    }

}

자바

classroom/snippets/src/main/java/AddStudent.java
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.classroom.Classroom;
import com.google.api.services.classroom.ClassroomScopes;
import com.google.api.services.classroom.model.Student;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Collections;

/* Class to demonstrate the use of Classroom Add Student API */
public class AddStudent {
    /**
     * Add a student in a specified course.
     *
     * @param courseId - Id of the course.
     * @param enrollmentCode - Code of the course to enroll.
     * @return newly added student
     * @throws IOException - if credentials file not found.
     */
    public static Student addStudent(String courseId, String enrollmentCode)
            throws IOException {
        /* Load pre-authorized user credentials from the environment.
           TODO(developer) - See https://developers.google.com/identity for
            guides on implementing OAuth2 for your application. */
        GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
                .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_ROSTERS));
        HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
                credentials);

        // Create the classroom API client
        Classroom service = new Classroom.Builder(new NetHttpTransport(),
                GsonFactory.getDefaultInstance(),
                requestInitializer)
                .setApplicationName("Classroom samples")
                .build();

        Student student = new Student().setUserId("me");
        try {
            // Enrolling a student to a specified course
            student = service.courses().students().create(courseId, student)
                    .setEnrollmentCode(enrollmentCode)
                    .execute();
            // Prints the course id with the Student name
            System.out.printf("User '%s' was enrolled as a student in the course with ID '%s'.\n",
                    student.getProfile().getName().getFullName(), courseId);
        } catch (GoogleJsonResponseException e) {
            // TODO(developer) - handle error appropriately
            GoogleJsonError error = e.getDetails();
            if (error.getCode() == 409) {
                System.out.println("You are already a member of this course.");
            } else if (error.getCode() == 403) {
                System.out.println("The caller does not have permission.\n");
            } else {
                throw e;
            }
        }
        return student;
    }
}

PHP

classroom/snippets/src/클래스룸AddStudent.php
use Google\Client;
use Google\Service\Classroom;
use Google\Service\Classroom\Student;
use Google\Service\Exception;

function enrollAsStudent($courseId,$enrollmentCode)
{
    /* Load pre-authorized user credentials from the environment.
    TODO (developer) - See https://developers.google.com/identity for
     guides on implementing OAuth2 for your application. */
    $client = new Client();
    $client->useApplicationDefaultCredentials();
    $client->addScope("https://www.googleapis.com/auth/classroom.profile.emails");
    $service = new Classroom($client);
    $student = new Student([
        'userId' => 'me'
    ]);
    $params = [
        'enrollmentCode' => $enrollmentCode
    ];
    try {
        $student = $service->courses_students->create($courseId, $student, $params);
        printf("User '%s' was enrolled  as a student in the course with ID '%s'.\n",
            $student->profile->name->fullName, $courseId);
    } catch (Exception $e) {
        if ($e->getCode() == 409) {
            print "You are already a member of this course.\n";
        } else {
            throw $e;
        }
    }
    return $student;
}

Python

classroom/snippets/classroom_add_student.py
from __future__ import print_function

import os

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

SCOPES = ['https://www.googleapis.com/auth/classroom.coursework.students']


def classroom_add_student_new(course_id):
    """
    Adds a student to a course, the teacher has access to.
    The file token.json stores the user's access and refresh tokens, and is
    created automatically when the authorization flow completes for the first
    time.
    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 = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w', encoding="utf8") as token:
            token.write(creds.to_json())

    enrollment_code = 'abc-def'
    student = {
            'userId': 'gduser1@workspacesamples.dev'
        }
    try:
        service = build('classroom', 'v1', credentials=creds)
        student = service.courses().students().create(
                courseId=course_id,
                enrollmentCode=enrollment_code,
                body=student).execute()
        print(
                '''User {%s} was enrolled as a student in
                   the course with ID "{%s}"'''
                % (student.get('profile').get('name').get('fullName'),
                   course_id))
        return student
    except HttpError as error:
        print(error)
        return error


if __name__ == '__main__':
    # Put the course_id of course for which student needs to be added.
    classroom_add_student_new(478800920837)

인증된 교사를 대신하여 학생을 추가하려면 invitations.create() 메서드를 사용해야 합니다.

students.delete() 메서드를 사용하여 수업에서 학생을 삭제할 수 있습니다. 이렇게 하면 지정된 학생만 수업에서 삭제되며 다른 과정 또는 사용자 프로필의 등록에는 영향을 미치지 않습니다.

사용자 과정 검색

학생 또는 교사를 위한 과정 목록을 가져오려면 courses.list()을 사용하여 해당 사용자의 studentId 또는 teacherId을 제공합니다.

사용자 프로필 검색

사용자의 ID와 이름을 포함한 요약된 프로필을 검색하려면 사용자의 ID, 이메일 또는 요청하는 사용자에 대해 userProfiles.get()를 호출합니다.

emailAddress 필드를 검색하려면 classroom.profile.emails 범위를 포함해야 합니다.

반환된 ID는 일치하는 studentId 또는 teacherId를 포함하는 Directory API 사용자 리소스에 해당합니다.