Xuất bản và quản lý người trả lời trên biểu mẫu

Trang này mô tả cách thực hiện các thao tác liên quan đến biểu mẫu sau:

  • Xuất bản biểu mẫu để người trả lời có thể truy cập
  • Tìm người trả lời biểu mẫu
  • Chia sẻ biểu mẫu của bạn với nhiều người trả lời hơn
  • Xoá người trả lời khỏi biểu mẫu
  • Kiểm tra xem biểu mẫu có chấp nhận câu trả lời của "Bất kỳ ai có đường liên kết" hay không
  • Đóng biểu mẫu
  • Huỷ xuất bản biểu mẫu
  • Dừng chấp nhận câu trả lời cho một biểu mẫu
  • Kiểm tra xem một biểu mẫu có phải là biểu mẫu cũ hay không

Trước khi bắt đầu

Hãy làm các việc sau trước khi tiếp tục thực hiện các nhiệm vụ trên trang này:

Xuất bản biểu mẫu để người trả lời có thể truy cập

Bạn có thể xuất bản một biểu mẫu hiện có bằng phương thức forms.setPublishSettings.

REST

Nội dung yêu cầu mẫu

{
  "publishSettings": {
    "isPublished": true,
    "isAcceptingResponses": true
  }
}

Apps Script

/**
 * Publishes a Google Form using its URL.
 */
function publishMyForm() {
  // Replace with the URL of your Google Form
  const formUrl = 'https://docs.google.com/forms/d/YOUR_FORM_ID/edit';

  try {
    const form = FormApp.openByUrl(formUrl);

    // Publish the form. This also enables accepting responses.
    form.setPublished(true);
    Logger.log(`Form "${form.getTitle()}" published successfully.`);

    // Optional: Verify the state
    if (form.isPublished()) {
      Logger.log('Form is now published.');
    }
    if (form.isAcceptingResponses()) {
      Logger.log('Form is now accepting responses.')
    }

  } catch (error) {
    Logger.log(`Error publishing form: ${error}`);
  }
}

Python

forms/snippets/publish_form.py
import os.path

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


# If modifying these SCOPES, delete the file token.json.
SCOPES = ["https://www.googleapis.com/auth/forms.body"]
DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1"
CLIENT_SECRET_FILE = "client_secrets.json"
TOKEN_FILE = "token.json"

# TODO: Replace with your Form ID
YOUR_FORM_ID = "YOUR_FORM_ID"


def get_credentials():
  """Gets the credentials for the user."""
  creds = None
  if os.path.exists(TOKEN_FILE):
    creds = Credentials.from_authorized_user_file(TOKEN_FILE, SCOPES)
  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(
          CLIENT_SECRET_FILE, SCOPES
      )
      creds = flow.run_local_server(port=8080)
    with open(TOKEN_FILE, "w") as token:
      token.write(creds.to_json())
  return creds


def publish_form():
  """Publishes the form."""
  creds = get_credentials()
  form_service = build(
      "forms",
      "v1",
      credentials=creds,
      discoveryServiceUrl=DISCOVERY_DOC,
      static_discovery=False,
  )

  # Request body for updating publish settings
  set_publish_settings_request = {
      "publishSettings": {
          "publishState": {"isPublished": True, "isAcceptingResponses": True}
      },
  }

  try:
    response = (
        form_service.forms()
        .setPublishSettings(
            formId=YOUR_FORM_ID, body=set_publish_settings_request
        )
        .execute()
    )
    print(f"Form {YOUR_FORM_ID} publish settings updated: {response}")
  except Exception as e:
    print(f"An error occurred: {e}")


if __name__ == "__main__":
  publish_form()

Node.js

forms/snippets/publish_form.js
'use strict';

const path = require('path');
const {forms} = require('@googleapis/forms');
const {authenticate} = require('@google-cloud/local-auth');

// TODO: Replace with your Form ID
const YOUR_FORM_ID = 'YOUR_FORM_ID';

const CREDENTIALS_PATH = path.join(__dirname, 'credentials.json');
const SCOPES = 'https://www.googleapis.com/auth/forms.body';

/**
 * Publishes a Google Form.
 *
 * @param {string} formIdToPublish The ID of the form to publish.
 */
async function runSample(formIdToPublish) {
  const authClient = await authenticate({
    keyfilePath: CREDENTIALS_PATH,
    scopes: SCOPES,
  });

  const formsClient = forms({
    version: 'v1',
    auth: authClient,
  });

  const setPublishSettingsRequest = {
    publishSettings: {
      publishState: {
        isPublished: true,
        isAcceptingResponses: true,
      },
    }
  };

  try {
    const res = await formsClient.forms.setPublishSettings({
      formId: formIdToPublish,
      requestBody: setPublishSettingsRequest,
    });
    console.log('Form publish settings updated:', res.data);
  } catch (err) {
    console.error('Error setting publish settings:', err);
  }
}

if (module === require.main) {
  runSample(YOUR_FORM_ID).catch(console.error);
}
module.exports = runSample;

Tìm người trả lời biểu mẫu

Bạn có thể truy xuất danh sách tất cả người dùng có quyền truy cập vào người trả lời (vai trò PUBLISHED_READER) bằng cách sử dụng Form.getPublishedReaders(). Thao tác này sẽ trả về một mảng các đối tượng người dùng.

REST

Thêm tham số truy vấn includePermissionsForView=published vào URL yêu cầu.

Apps Script

/**
 * Gets and logs the email addresses of all responders for a form.
 */
function listResponders() {
  // Replace with the URL of your Google Form
  const formUrl = 'https://docs.google.com/forms/d/YOUR_FORM_ID/edit';

  try {
    const form = FormApp.openByUrl(formUrl);

    // Get the array of User objects representing responders
    const responders = form.getPublishedReaders();

    // Log the responders
    Logger.log("Following can respond to the form");
    responders.forEach(responder => Logger.log(responder.getEmail()));

    return responders;

  } catch (error) {
    Logger.log(`Error getting responders: ${error}`);
  }
}

Python

forms/snippets/get_responders.py
import os.path

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


# If modifying these SCOPES, delete the file token.json.
SCOPES = ["https://www.googleapis.com/auth/drive.metadata.readonly"]
CLIENT_SECRET_FILE = "client_secrets.json"
TOKEN_FILE = "token.json"

# TODO: Replace with your Form ID
YOUR_FORM_ID = "YOUR_FORM_ID"


def get_credentials():
  """Gets the credentials for the user."""
  creds = None
  if os.path.exists(TOKEN_FILE):
    creds = Credentials.from_authorized_user_file(TOKEN_FILE, SCOPES)
  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(
          CLIENT_SECRET_FILE, SCOPES
      )
      creds = flow.run_local_server(port=8080)
    with open(TOKEN_FILE, "w") as token:
      token.write(creds.to_json())
  return creds


def get_responders():
  """Gets the responders for the form."""
  creds = get_credentials()
  drive_service = build("drive", "v3", credentials=creds)

  try:
    response = (
        drive_service.permissions()
        .list(
            fileId=YOUR_FORM_ID,
            fields="permissions(id,emailAddress,type,role,view)",
            includePermissionsForView="published",
        )
        .execute()
    )

    published_readers = []
    for permission in response.get("permissions", []):
      # 'view': 'published' indicates it's related to the published link.
      # 'role': 'reader' is standard for responders.
      # 'type': 'user' for specific users, 'anyone' for public.
      if (
          permission.get("view") == "published"
          and permission.get("role") == "reader"
      ):
        published_readers.append(permission)

    if published_readers:
      print("Responders for this form:")
      print(published_readers)
    else:
      print("No specific published readers found for this form.")

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


if __name__ == "__main__":
  get_responders()

Node.js

forms/snippets/get_responders.js
'use strict';

const path = require('path');
const {drive} = require('@googleapis/drive');
const {authenticate} = require('@google-cloud/local-auth');

// TODO: Replace with your form ID
const YOUR_FORM_ID = 'YOUR_FORM_ID';

const CREDENTIALS_PATH = path.join(__dirname, 'credentials.json');
const SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly'];

/**
 * Gets the responders to the form.
 *
 * @param {string} formId The ID of the form.
 */
async function runSample(formId, email) {
  const authClient = await authenticate({
    keyfilePath: CREDENTIALS_PATH,
    scopes: SCOPES,
  });

  const driveService = drive({version: 'v3', auth: authClient});

  try {
    const res = await driveService.permissions.list({
      fileId: formId,
      includePermissionsForView: 'published',
      fields: 'permissions(id,emailAddress,type,role,view)',
    });
    const permissions = res.data.permissions || [];
    if (permissions.length === 0) {
      console.log(`No permissions found for form ID: ${formId}`);
    } else {
      console.log('Responders for this form:');
      for (const permission of permissions) {
        if (permission.view === 'published' && permission.role === 'reader') {
          console.log(`Responder:`, permission);
        }
      }
    }
  } catch (err) {
    console.error('Error getting responders :', err);
  }
}

if (module === require.main) {
  runSample(YOUR_FORM_ID).catch(console.error);
}
module.exports = runSample;

Chia sẻ biểu mẫu của bạn với nhiều người trả lời hơn

Để thêm người trả lời vào biểu mẫu để họ có thể mở và trả lời biểu mẫu, bạn có thể sử dụng phương thức permissions.create của Drive.

  • Gọi phương thức permissions.create bằng mã biểu mẫu và chế độ cài đặt quyền truy cập.

REST

Nội dung yêu cầu mẫu

{
  "view": "published",
  "role": "reader",
  "type": "user",
  "emailAddress": "user@example.com"
}

Apps Script

/**
 * Adds a single responder to a form using their email address.
*/
function `addSingleResponderByEmail()` {
// Replace with the URL of your Google Form
  const formUrl = 'https://docs.google.com/forms/d/YOUR_FORM_ID/edit';
  // Replace with the responder's email address
  const responderEmail = 'responder@example.com';

  try {
    const form = FormApp.openByUrl(formUrl);

    // Add the user as a responder
    form.addPublishedReader(responderEmail);
    Logger.log(`Added ${responderEmail} as a responder to form "${
        form.getTitle()}".`);

  } catch (error) {
    Logger.log(`Error adding responder: ${error}`);
  }
}

Python

forms/snippets/add_responder.py
import os.path

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


# If modifying these SCOPES, delete the file token.json.
SCOPES = ["https://www.googleapis.com/auth/drive.file"]
CLIENT_SECRET_FILE = "client_secrets.json"
TOKEN_FILE = "token.json"

# TODO: Replace with your Form ID and responder's email
YOUR_FORM_ID = "YOUR_FORM_ID"
YOUR_RESPONDER_EMAIL = "user@example.com"


def get_credentials():
  """Gets the credentials for the user."""
  creds = None
  if os.path.exists(TOKEN_FILE):
    creds = Credentials.from_authorized_user_file(TOKEN_FILE, SCOPES)
  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(
          CLIENT_SECRET_FILE, SCOPES
      )
      creds = flow.run_local_server(port=8080)
    with open(TOKEN_FILE, "w") as token:
      token.write(creds.to_json())
  return creds


def add_responder():
  """Adds the responder to the form."""
  creds = get_credentials()
  drive_service = build("drive", "v3", credentials=creds)

  permission_body = {
      "view": "published",
      "role": "reader",
      "type": "user",
      "emailAddress": YOUR_RESPONDER_EMAIL,
  }

  try:
    response = (
        drive_service.permissions()
        .create(
            fileId=YOUR_FORM_ID,
            body=permission_body,
            sendNotificationEmail=False,  # Optional: to avoid sending an email
        )
        .execute()
    )
    print(
        f"Added responder {YOUR_RESPONDER_EMAIL}. Permission ID:"
        f" {response.get('id')}"
    )
    print(response)
  except Exception as e:
    print(f"An error occurred: {e}")


if __name__ == "__main__":
  add_responder()

Node.js

forms/snippets/add_responder.js
'use strict';

const path = require('path');
const {drive} = require('@googleapis/drive');
const {authenticate} = require('@google-cloud/local-auth');

// TODO: Replace with your form ID (fileId) and responder's email
const YOUR_FORM_ID = 'YOUR_FORM_ID';
const YOUR_RESPONDER_EMAIL = 'user@example.com';

const CREDENTIALS_PATH = path.join(__dirname, 'credentials.json');
const SCOPES = ['https://www.googleapis.com/auth/drive.file'];

/**
 * Adds a responder to the form.
 *
 * @param {string} formId The ID of the form.
 * @param {string} email The email of the responder.
 */
async function runSample(formId, email) {
  if (!formId || !email) {
    console.log('Form ID and responder email are required.');
    return;
  }
  const authClient = await authenticate({
    keyfilePath: CREDENTIALS_PATH,
    scopes: SCOPES,
  });

  const driveService = drive({version: 'v3', auth: authClient});

  const permissionBody = {
    role: 'reader',
    type: 'user',
    emailAddress: email,
    view: 'published',
  };

  try {
    const res = await driveService.permissions.create({
      fileId: formId,
      requestBody: permissionBody,
      fields: 'id,emailAddress,role,type,view',
      sendNotificationEmail: false,  // Optional
    });
    console.log('Responder added:', res.data);
  } catch (err) {
    console.error('Error adding responder:', err);
  }
}

if (module === require.main) {
  runSample(YOUR_FORM_ID, YOUR_RESPONDER_EMAIL).catch(console.error);
}
module.exports = runSample;

Xoá người trả lời khỏi biểu mẫu

Bạn có thể xoá từng người trả lời theo địa chỉ email của họ hoặc sử dụng đối tượng Người dùng. Việc xoá người trả lời sẽ thu hồi quyền xem và gửi biểu mẫu của họ, trừ phi họ có quyền truy cập thông qua các phương tiện khác như chia sẻ miền hoặc quyền truy cập vào ổ đĩa dùng chung.

Xoá một người trả lời theo địa chỉ email

REST

DELETE https://www.googleapis.com/drive/v3/files/{fileId}/permissions/PERMISSION

Bạn có thể tìm thấy permissionID bằng cách "liệt kê người trả lời" như mô tả trước đó

Apps Script

/**
 * Removes a single responder from a form using their email address.
*/
function `removeSingleResponderByEmail()` {
  // Replace with the URL of your Google Form
  const formUrl = 'https://docs.google.com/forms/d/YOUR_FORM_ID/edit';
  // Replace with the responder's email address to remove
  const responderEmailToRemove = 'responder-to-remove@example.com';

  try {
    const form = FormApp.openByUrl(formUrl);

    // Remove the user as a responder
    form.removePublishedReader(responderEmailToRemove);
    Logger.log(`Removed ${responderEmailToRemove} as a responder from form "${
        form.getTitle()}".`);

  } catch (error) {
    Logger.log(`Error removing responder: ${error}`);
  }
}

Python

forms/snippets/remove_responder.py
import os.path

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


# If modifying these SCOPES, delete the file token.json.
SCOPES = ["https://www.googleapis.com/auth/drive.file"]
CLIENT_SECRET_FILE = "client_secrets.json"
TOKEN_FILE = "token.json"

# TODO: Replace with your Form ID and responder's email
YOUR_FORM_ID = "YOUR_FORM_ID"
YOUR_RESPONDER_EMAIL = "user@example.com"


def get_credentials():
  """Gets the credentials for the user."""
  creds = None
  if os.path.exists(TOKEN_FILE):
    creds = Credentials.from_authorized_user_file(TOKEN_FILE, SCOPES)
  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(
          CLIENT_SECRET_FILE, SCOPES
      )
      creds = flow.run_local_server(port=8080)
    with open(TOKEN_FILE, "w") as token:
      token.write(creds.to_json())
  return creds


def remove_responder():
  """Removes the responder for the form."""
  creds = get_credentials()
  drive_service = build("drive", "v3", credentials=creds)

  try:
    # First, find the permission ID for the user
    permissions_result = (
        drive_service.permissions()
        .list(
            fileId=YOUR_FORM_ID,
            fields="permissions(id,emailAddress,role,view,type)",
            includePermissionsForView="published",
        )
        .execute()
    )

    permission_id_to_delete = None
    for p in permissions_result.get("permissions", []):
      if (
          p.get("emailAddress") == YOUR_RESPONDER_EMAIL
          and p.get("role") == "reader"
          and p.get("view") == "published"
          and p.get("type") == "user"
      ):
        permission_id_to_delete = p.get("id")
        break

    if permission_id_to_delete:
      drive_service.permissions().delete(
          fileId=YOUR_FORM_ID, permissionId=permission_id_to_delete
      ).execute()
      print(
          f"Successfully removed responder {YOUR_RESPONDER_EMAIL} (Permission"
          f" ID: {permission_id_to_delete}) from form {YOUR_FORM_ID}."
      )
    else:
      print(
          f"Responder {YOUR_RESPONDER_EMAIL} not found or not a published"
          f" reader for form {YOUR_FORM_ID}."
      )

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


if __name__ == "__main__":
  remove_responder()

Node.js

forms/snippets/remove_responders.js
'use strict';

const path = require('path');
const {drive} = require('@googleapis/drive');
const {authenticate} = require('@google-cloud/local-auth');

// TODO: Replace with your form ID (fileId) and responder's email
const YOUR_FORM_ID = 'YOUR_FORM_ID';
const YOUR_RESPONDER_EMAIL = 'responder-to-remove@example.com';

const CREDENTIALS_PATH = path.join(__dirname, 'credentials.json');
const SCOPES = ['https://www.googleapis.com/auth/drive.file'];

/**
 * Remove a responder to the form.
 *
 * @param {string} formId The ID of the form.
 * @param {string} email The email of the responder.
 */
async function runSample(formId, email) {
  const authClient = await authenticate({
    keyfilePath: CREDENTIALS_PATH,
    scopes: SCOPES,
  });

  const driveService = drive({version: 'v3', auth: authClient});

  try {
    const res = await driveService.permissions.list({
      fileId: formId,
      includePermissionsForView: 'published',
      fields: 'permissions(id,emailAddress,type,role,view)',
    });

    const permissions = res.data.permissions || [];
    const responderToRemove = permissions.find(
        (permission) => permission.view === 'published' &&
            permission.role === 'reader' && permission.emailAddress === email);

    if (responderToRemove) {
      const permissionId = responderToRemove.id;
      await driveService.permissions.delete({
        fileId: formId,
        permissionId: permissionId,
      });
      console.log(`Responder with permission ID '${
          permissionId}' removed successfully.`);

    } else {
      console.log('Responder not found for the specified form');
    }
  } catch (err) {
    console.error('Error removing responder:', err);
  }
}

if (module === require.main) {
  runSample(YOUR_FORM_ID, YOUR_RESPONDER_EMAIL).catch(console.error);
}
module.exports = runSample;

Để kiểm tra xem biểu mẫu có chấp nhận câu trả lời của bất kỳ ai có đường liên kết hay không, bạn cần bật Dịch vụ nâng cao của Drive.

  1. Bật Dịch vụ nâng cao của Drive:
    1. Mở dự án Apps Script.
    2. Nhấp vào Dịch vụ (biểu tượng dấu cộng bên cạnh Dịch vụ).
    3. Tìm Drive API rồi nhấp vào Thêm.
    4. Nhấp vào Thêm.

Apps Script

function `isAnyoneWithLinkResponder`(formId) {
  let permissions = Drive.Permissions.list(formId, { includePermissionsForView: 'published' }).permissions;
  if (permissions) {
    for (const permission of permissions) {
      if (permission.type === 'anyone' && permission.view === 'published' && permission.role === 'reader') {
        return true;
      }
    }
  }
  return false;
}

Python

forms/snippets/anyone_with_link_responder.py
def is_anyone_with_link_responder():
  """Checks if anyone with the link is a responder for the form."""
  creds = get_credentials()
  drive_service = build("drive", "v3", credentials=creds)
  anyone_with_link_responder = False

  try:
    permissions_result = (
        drive_service.permissions()
        .list(
            fileId=YOUR_FORM_ID,
            fields="permissions(id,type,role,view)",
            includePermissionsForView="published",
        )
        .execute()
    )

    permissions = permissions_result.get("permissions", [])
    if not permissions:
      print(f"No permissions found for form ID: {YOUR_FORM_ID}")
    else:
      for permission in permissions:
        if (
            permission.get("type") == "anyone"
            and permission.get("view") == "published"
            and permission.get("role") == "reader"
        ):
          anyone_with_link_responder = True
          break

    if anyone_with_link_responder:
      print(
          f"Form '{YOUR_FORM_ID}' IS configured for 'Anyone with the link' to"
          " respond."
      )
    else:
      print(
          f"Form '{YOUR_FORM_ID}' is NOT configured for 'Anyone with the link'"
          " to respond."
      )

  except Exception as e:
    print(f"An error occurred: {e}")
  return anyone_with_link_responder

Node.js

forms/snippets/anyone_with_link_responder.js
/**
 * Checks if anyone with the link is a responder for the form.
 *
 * @param {string} formId The ID of the Google Form.
 */
async function isAnyoneWithLinkResponder(formId) {
  const authClient = await authenticate({
    keyfilePath: CREDENTIALS_PATH,
    scopes: SCOPES,
  });

  const driveService = drive({version: 'v3', auth: authClient});
  let anyoneWithLinkResponder = false;

  try {
    const res = await driveService.permissions.list({
      fileId: formId,
      fields: 'permissions(id,type,role,view)',
      includePermissionsForView: 'published',
    });

    const permissions = res.data.permissions || [];
    if (permissions.length === 0) {
      console.log(`No permissions found for form ID: ${formId}`);
    } else {
      for (const permission of permissions) {
        if (permission.type === 'anyone' && permission.view === 'published' &&
            permission.role === 'reader') {
          anyoneWithLinkResponder = true;
          break;
        }
      }
    }

    if (anyoneWithLinkResponder) {
      console.log(`Form '${
          formId}' IS configured for 'Anyone with the link' to respond.`);
    } else {
      console.log(`Form '${
          formId}' is NOT configured for 'Anyone with the link' to respond.`);
    }
  } catch (err) {
    console.error(
        'Error checking "anyone with link" permission:', err.message || err);
  }
}

Cách đặt chế độ "Bất kỳ ai có đường liên kết" đều có thể trả lời biểu mẫu:

Apps Script

function `setAnyoneWithLinkResponder`(formId) {
  Drive.Permissions.create({
    type: 'anyone',
    view: 'published',
    role: 'reader',
  }, formId);
}

Python

forms/snippets/anyone_with_link_responder.py
def set_anyone_with_link_responder():
  """Sets anyone with the link to be a responder for the form."""
  creds = get_credentials()
  drive_service = build("drive", "v3", credentials=creds)

  permission_body = {
      "type": "anyone",
      "view": "published",  # Key for making it a responder setting
      "role": "reader",
  }

  try:
    response = (
        drive_service.permissions()
        .create(
            fileId=YOUR_FORM_ID,
            body=permission_body,
        )
        .execute()
    )
    print(
        "'Anyone with the link can respond' permission set for form"
        f" {YOUR_FORM_ID}: {response}"
    )
    return True
  except Exception as e:
    print(f"An error occurred: {e}")
  return False

Node.js

forms/snippets/anyone_with_link_responder.js
/**
 * Sets anyone with the link to be a responder for the form.
 *
 * @param {string} formId The ID of the Google Form.
 */
async function setAnyoneWithLinkResponder(formId) {
  const authClient = await authenticate({
    keyfilePath: CREDENTIALS_PATH,
    scopes: SCOPES,
  });

  const driveService = drive({version: 'v3', auth: authClient});

  const permissionBody = {
    type: 'anyone',
    view: 'published',  // Key for making it a responder setting
    role: 'reader',
  };

  try {
    const res = await driveService.permissions.create({
      fileId: formId,
      requestBody: permissionBody,
      fields: 'id',  // Request only needed fields
    });
    console.log(`'Anyone with the link can respond' permission set for form '${
        formId}'. Permission ID: ${res.data.id}`);
  } catch (err) {
    console.error(
        'Error setting "anyone with link" permission:', err.message || err);
  }
}

Cách xoá chế độ "Bất kỳ ai có đường liên kết" có thể trả lời biểu mẫu:

Apps Script

function `removeAnyoneWithLinkResponder`(formId) {
  let permissions = Drive.Permissions.list(formId, { includePermissionsForView: 'published' }).permissions;
  if (permissions) {
    for (const permission of permissions) {
      if (permission.type === 'anyone' && permission.role === 'reader') {
        Drive.Permissions.remove(formId, permission.id);
      }
    }
  }
}

Python

forms/snippets/anyone_with_link_responder.py
def remove_anyone_with_link_responder():
  """Removes anyone with the link as a responder for the form."""
  creds = get_credentials()
  drive_service = build("drive", "v3", credentials=creds)

  permission_id_to_delete = None

  try:
    permissions_result = (
        drive_service.permissions()
        .list(
            fileId=YOUR_FORM_ID,
            fields="permissions(id,type,role,view)",
            includePermissionsForView="published",
        )
        .execute()
    )

    permissions = permissions_result.get("permissions", [])
    for permission in permissions:
      if (
          permission.get("type") == "anyone"
          and permission.get("role") == "reader"
          and permission.get("view") == "published"
      ):
        permission_id_to_delete = permission.get("id")
        break

    if permission_id_to_delete:
      drive_service.permissions().delete(
          fileId=YOUR_FORM_ID, permissionId=permission_id_to_delete
      ).execute()
      print(
          "Successfully removed 'Anyone with the link' permission (ID:"
          f" {permission_id_to_delete}) from form {YOUR_FORM_ID}."
      )
      return True
    else:
      print(
          "'Anyone with the link can respond' permission not found for form"
          f" {YOUR_FORM_ID}."
      )

  except Exception as e:
    print(f"An error occurred: {e}")
  return False

Node.js

forms/snippets/anyone_with_link_responder.js
/**
 * Removes anyone with the link as a responder for the form.
 *
 * @param {string} formId The ID of the Google Form.
 */
async function removeAnyoneWithLinkResponder(formId) {
  const authClient = await authenticate({
    keyfilePath: CREDENTIALS_PATH,
    scopes: SCOPES,
  });

  const driveService = drive({version: 'v3', auth: authClient});
  let permissionIdToDelete = null;

  try {
    const res = await driveService.permissions.list({
      fileId: formId,
      fields: 'permissions(id,type,role,view)',
      includePermissionsForView: 'published',
    });

    const permissions = res.data.permissions || [];
    for (const permission of permissions) {
      if (permission.type === 'anyone' && permission.role === 'reader' &&
          permission.view === 'published') {
        permissionIdToDelete = permission.id;
        break;
      }
    }

    if (permissionIdToDelete) {
      await driveService.permissions.delete({
        fileId: formId,
        permissionId: permissionIdToDelete,
      });
      console.log(
          `Successfully removed 'Anyone with the link' permission (ID: ${
              permissionIdToDelete}) from form '${formId}'.`);
    } else {
      console.log(
          `'Anyone with the link can respond' permission not found for form '${
              formId}'. Nothing to remove.`);
    }
  } catch (err) {
    console.error(
        'Error removing "anyone with link" permission:', err.message || err);
  }
}

Đóng biểu mẫu

Để huỷ xuất bản biểu mẫu, bạn sử dụng phương thức Forms.setPublished(false). {/apps-script/reference/forms/form#setpublishedenabled} Việc huỷ xuất bản biểu mẫu sẽ khiến biểu mẫu đó không hoạt động và tự động ngừng chấp nhận câu trả lời.

REST

Nội dung yêu cầu mẫu

POST https://forms.googleapis.com/v1/forms/{formId}:setPublishSettings

{
  "publishSettings": {
    "publishState": {
      "isPublished": false
    }
  }
}

Apps Script

/**
* Unpublishes a Google Form using its URL.
*/
function unpublishMyForm() {
  // Replace with the URL of your Google Form
  const formUrl = 'https://docs.google.com/forms/d/YOUR_FORM_ID/edit';

  try {
    const form = FormApp.openByUrl(formUrl);

    // Unpublish the form. This also disables accepting responses.
    form.setPublished(false);
    Logger.log(`Form "${form.getTitle()}" unpublished successfully.`);

    // Optional: Verify the state
    if (!form.isPublished()) {
      Logger.log('Form is now unpublished.');
    }
    if (!form.isAcceptingResponses()) {
      Logger.log('Form is no longer accepting responses.');
    }

  } catch (error) {
    Logger.log(`Error unpublishing form: ${error}`);
  }
}

Python

forms/snippets/unpublish_form.py
import os.path

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


# If modifying these SCOPES, delete the file token.json.
SCOPES = ["https://www.googleapis.com/auth/forms.body"]
DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1"
CLIENT_SECRET_FILE = "client_secrets.json"
TOKEN_FILE = "token.json"

# TODO: Replace with your Form ID
YOUR_FORM_ID = "YOUR_FORM_ID"


def get_credentials():
  """Gets the credentials for the user."""
  creds = None
  if os.path.exists(TOKEN_FILE):
    creds = Credentials.from_authorized_user_file(TOKEN_FILE, SCOPES)
  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(
          CLIENT_SECRET_FILE, SCOPES
      )
      creds = flow.run_local_server(port=8080)
    with open(TOKEN_FILE, "w") as token:
      token.write(creds.to_json())
  return creds


def unpublish_form():
  """Unpublishes the form."""
  creds = get_credentials()
  form_service = build(
      "forms",
      "v1",
      credentials=creds,
      discoveryServiceUrl=DISCOVERY_DOC,
      static_discovery=False,
  )

  # Request body for updating publish settings
  set_publish_settings_request = {
      "publishSettings": {"publishState": {"isPublished": False}},
  }

  try:
    response = (
        form_service.forms()
        .setPublishSettings(
            formId=YOUR_FORM_ID, body=set_publish_settings_request
        )
        .execute()
    )
    print(
        f"Form {YOUR_FORM_ID} publish settings updated to unpublished:"
        f" {response}"
    )
    return True
  except Exception as e:
    print(f"An error occurred: {e}")
  return False


if __name__ == "__main__":
  unpublish_form()

Node.js

forms/snippets/unpublish_form.js
'use strict';

const path = require('path');
const {forms} = require('@googleapis/forms');
const {authenticate} = require('@google-cloud/local-auth');

// TODO: Replace with your Form ID
const YOUR_FORM_ID = 'YOUR_FORM_ID';

const CREDENTIALS_PATH = path.join(__dirname, 'credentials.json');
const SCOPES = 'https://www.googleapis.com/auth/forms.body';

/**
 * Unpublishes a Google Form.
 *
 * @param {string} formIdToUnpublish The ID of the form to unpublish.
 */
async function runSample(formIdToUnpublish) {
  const authClient = await authenticate({
    keyfilePath: CREDENTIALS_PATH,
    scopes: SCOPES,
  });

  const formsClient = forms({
    version: 'v1',
    auth: authClient,
  });

  const setPublishSettingsRequest = {
    publishSettings: {
      publishState: {
        isPublished: false,
      },
    }
  };

  try {
    const res = await formsClient.forms.setPublishSettings({
      formId: formIdToUnpublish,
      requestBody: setPublishSettingsRequest,
    });
    console.log('Form un-published.', res.data);
  } catch (err) {
    console.error('Error setting publish settings:', err);
  }
}

if (module === require.main) {
  runSample(YOUR_FORM_ID).catch(console.error);
}
module.exports = runSample;

Để ngừng chấp nhận câu trả lời cho một biểu mẫu mà không cần huỷ xuất bản biểu mẫu đó, bạn có thể sử dụng phương thức Form.setAcceptingResponses(false). Người trả lời biểu mẫu của bạn sẽ thấy trang biểu mẫu đã đóng và thông báo.

REST

Nội dung yêu cầu mẫu

POST https://forms.googleapis.com/v1/forms/{formId}:setPublishSettings

{
  "publishSettings": {
    "publishState": {
      "isPublished": true,
      "isAcceptingResponses": false
    }
  }
}

Apps Script

/**
 * Stop a Google Form from accepting responses using its URL.
*/
function closeMyFormForAcceptingResponses() {
  // Replace with the URL of your Google Form
  const formUrl = 'https://docs.google.com/forms/d/YOUR_FORM_ID/edit';

  try {
    const form = FormApp.openByUrl(formUrl);

    // This disables the form for accepting responses.
    form.setAcceptingResponses(false);
    Logger.log(`Form "${form.getTitle()}" closed for accepting responses successfully.`);

    // Optional: Verify the state
    if (form.isPublished()) {
      Logger.log('Form is still published.');
    }
    if (!form.isAcceptingResponses()) {
      Logger.log('Form is no longer accepting responses.');
    }

  } catch (error) {
    Logger.log(`Error unpublishing form: ${error}`);
  }
}

Python

forms/snippets/stop_accepting_responses.py
import os.path

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


# If modifying these SCOPES, delete the file token.json.
SCOPES = ["https://www.googleapis.com/auth/forms.body"]
DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1"
CLIENT_SECRET_FILE = "client_secrets.json"
TOKEN_FILE = "token.json"

# TODO: Replace with your Form ID
YOUR_FORM_ID = "YOUR_FORM_ID"


def get_credentials():
  """Gets the credentials for the user."""
  creds = None
  if os.path.exists(TOKEN_FILE):
    creds = Credentials.from_authorized_user_file(TOKEN_FILE, SCOPES)
  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(
          CLIENT_SECRET_FILE, SCOPES
      )
      creds = flow.run_local_server(port=8080)
    with open(TOKEN_FILE, "w") as token:
      token.write(creds.to_json())
  return creds


def close_form():
  """Closes the form for responses."""
  creds = get_credentials()
  form_service = build(
      "forms",
      "v1",
      credentials=creds,
      discoveryServiceUrl=DISCOVERY_DOC,
      static_discovery=False,
  )

  stop_accepting_request_body = {
      "publishSettings": {
          "publishState": {
              "isPublished": True,  # Keep it published
              "isAcceptingResponses": False,  # But stop accepting responses
          }
      }
  }

  try:
    response = (
        form_service.forms()
        .setPublishSettings(  # Corrected: form_service
            formId=YOUR_FORM_ID, body=stop_accepting_request_body
        )
        .execute()
    )
    print(f"Form {YOUR_FORM_ID} stopped accepting responses: {response}")
    return True
  except Exception as e:
    print(f"An error occurred: {e}")
  return False


if __name__ == "__main__":
  close_form()

Node.js

forms/snippets/stop_accepting_responses.js
'use strict';

const {authenticate} = require('@google-cloud/local-auth');
const {forms} = require('@googleapis/forms');
const path = require('path');

// TODO: Replace with your form ID
const YOUR_FORM_ID = 'YOUR_FORM_ID';

const CREDENTIALS_PATH = path.join(__dirname, 'credentials.json');
const SCOPES = 'https://www.googleapis.com/auth/forms.body';

/**
 * Stops accepting responses to the form.
 *
 * @param {string} formId The ID of the form.
 */
async function runSample(formId) {
  const authClient = await authenticate({
    keyfilePath: CREDENTIALS_PATH,
    scopes: SCOPES,
  });

  const formsClient = forms({
    version: 'v1',
    auth: authClient,
  });

  const setPublishSettingsRequest = {
    publishSettings: {
      publishState: {
        isPublished: true,  // Keep it published (or ensure it is if it wasn't)
        isAcceptingResponses: false,  // Stop accepting responses
      },
    }
  };

  try {
    const res = await formsClient.forms.setPublishSettings({
      formId: formId,
      requestBody: setPublishSettingsRequest,
    });
    console.log('Form is no longer accepting responses.', res.data);
  } catch (err) {
    console.error('Error setting publish settings:', err);
  }
}

if (module === require.main) {
  runSample(YOUR_FORM_ID).catch(console.error);
}
module.exports = runSample;

Kiểm tra xem một biểu mẫu có phải là biểu mẫu cũ hay không

Biểu mẫu cũ là những biểu mẫu không có trường publishSettings, trong khi tất cả biểu mẫu mới tạo đều hỗ trợ chế độ cài đặt phát hành.

Kiểm tra xem một biểu mẫu có phải là biểu mẫu cũ hay không bằng cách xác định xem biểu mẫu đó có hỗ trợ tính năng phát hành hay không. Phương thức này dùng để xác định xem các phương thức setPublished(enabled)isPublished() cũng như quyền của trình phản hồi có được bật hay không.

Apps Script

/**
 * Checks if a form supports advanced responder permissions (i.e., is not a legacy form).
*/
function `checkIfFormSupportsPublishing()` {
  // TODO(developer): Replace the URL with your own.
  const formUrl = 'https://docs.google.com/forms/d/YOUR_FORM_ID/edit';

  try {
    const form = FormApp.openByUrl(formUrl);

    // Checks whether the form supports publishing or not and logs it to the console.
    const supportsPublishing = form.supportsAdvancedResponderPermissions();

    if (supportsPublishing) {
      Logger.log(`Form "${form.getTitle()}" supports publishing (not a legacy
          form).`);
    } else {
      Logger.log(`Form "${form.getTitle()}" is a legacy form (does not support
          publishing).`);
    }
    return supportsPublishing;
  } catch (error) {
    Logger.log(`Error unpublishing form: ${error}`);
  }
}

Python

forms/snippets/supports_publishing.py
import os.path

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


# If modifying these SCOPES, delete the file token.json.
SCOPES = ["https://www.googleapis.com/auth/forms.body"]
DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1"
CLIENT_SECRET_FILE = "client_secrets.json"
TOKEN_FILE = "token.json"

# TODO: Replace with your Form ID
YOUR_FORM_ID = "YOUR_FORM_ID"


def get_credentials():
  """Gets the credentials for the user."""
  creds = None
  if os.path.exists(TOKEN_FILE):
    creds = Credentials.from_authorized_user_file(TOKEN_FILE, SCOPES)
  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(
          CLIENT_SECRET_FILE, SCOPES
      )
      creds = flow.run_local_server(port=8080)
    with open(TOKEN_FILE, "w") as token:
      token.write(creds.to_json())
  return creds


def supports_publishing():
  """Checks if the form supports publishing."""
  creds = get_credentials()
  form_service = build(
      "forms",
      "v1",
      credentials=creds,
      discoveryServiceUrl=DISCOVERY_DOC,
      static_discovery=False,
  )

  is_legacy = True  # Assume legacy until proven otherwise
  try:
    form_metadata = form_service.forms().get(formId=YOUR_FORM_ID).execute()
    # If 'publishSettings' field exists, it's not a legacy form regarding this feature.
    if "publishSettings" in form_metadata:
      print(
          f"Form '{YOUR_FORM_ID}' (Title:"
          f" {form_metadata.get('info', {}).get('title')}) is NOT a legacy form"
          " (supports publishSettings)."
      )
      is_legacy = False
    else:
      print(
          f"Form '{YOUR_FORM_ID}' (Title:"
          f" {form_metadata.get('info', {}).get('title')}) IS a legacy form"
          " (does not have publishSettings field)."
      )
    return not is_legacy  # Returns true if it supports publishing

  except Exception as e:
    print(f"An error occurred while checking form {YOUR_FORM_ID}: {e}")
    # Depending on the error, it might indicate non-existence or access issues,
    # not necessarily legacy status.
    return None


if __name__ == "__main__":
  supports_publishing()

Node.js

forms/snippets/supports_publishing.js
'use strict';

const path = require('path');
const {forms} = require('@googleapis/forms');
const {authenticate} = require('@google-cloud/local-auth');

// TODO: Replace with your form ID (fileId)
const YOUR_FORM_ID = 'YOUR_FORM_ID';

const CREDENTIALS_PATH = path.join(__dirname, 'credentials.json');
const SCOPES = 'https://www.googleapis.com/auth/forms.body';

/**
 * Checks if the form supports publishing.
 *
 * @param {string} formIdToCheck The ID of the form to check.
 */
async function runSample(formIdToCheck) {
  const authClient = await authenticate({
    keyfilePath: CREDENTIALS_PATH,
    scopes: SCOPES,
  });

  const formsClient = forms({
    version: 'v1',
    auth: authClient,
  });

  try {
    const res = await formsClient.forms.get({
      formId: formIdToCheck,
    });

    const formTitle = res.data.info.title;

    // If 'publishSettings' field exists (even if empty), it supports the new
    // publishing model.
    if (res.data && res.data.publishSettings !== undefined) {
      console.log(`Form '${formIdToCheck}' (Title: ${
          formTitle}) is NOT a legacy form (supports publishSettings).`);
    } else {
      console.log(`Form '${formIdToCheck}' (Title: ${
          formTitle}) IS a legacy form (does not have publishSettings field).`);
    }
  } catch (err) {
    console.error(`Error getting form metadata for '${formIdToCheck}':`, err);
  }
}

if (module === require.main) {
  runSample(YOUR_FORM_ID).catch(console.error);
}
module.exports = runSample;