Google Form文件上传集成至Slack Incoming Webhooks技术问询
Got it, let's tackle that file upload problem for your Google Form to Slack workflow! The original script works great for text fields, but since Google Form file uploads store files directly in Google Drive, we need to modify the script to pull those Drive files, set proper sharing permissions, and push clickable, accessible links to Slack. Here's a step-by-step solution:
Step 1: Update Script Permissions
First, your script needs explicit access to Google Drive to fetch uploaded files. Here's how to set that up:
- Open your Google Apps Script editor (from the Google Form, go to
Extensions > Apps Script). - Enable the Apps Script API: Navigate to
Extensions > Apps Script APIand toggle it on. - Open the manifest file (
appsscript.json) by clickingView > Show manifest file. - Add these OAuth scopes to the
oauthScopesarray (replace existing scopes if needed):
"oauthScopes": [ "https://www.googleapis.com/auth/forms.currentonly", "https://www.googleapis.com/auth/drive.readonly", "https://www.googleapis.com/auth/script.external_request" ]
This grants the script permission to read form responses, access Drive files, and send external requests to Slack.
Step 2: Modify the Response Handling Logic
Update the part of your script that processes form responses to detect and handle file upload fields. Here's the modified code snippet (replace your existing response-processing loop):
function onFormSubmit(e) { const form = FormApp.getActiveForm(); const items = form.getItems(); let slackMessageText = "*New Support Ticket Received:*\n"; // Loop through each form item and its corresponding response for (let i = 0; i < items.length; i++) { const item = items[i]; const response = e.response.getItemResponses()[i]; if (item.getType() === FormApp.ItemType.FILE_UPLOAD) { // File upload fields return an array of Google Drive file IDs const fileIds = response.getResponse(); if (fileIds && fileIds.length > 0) { let fileLinks = []; for (const fileId of fileIds) { const file = DriveApp.getFileById(fileId); // Set file to be viewable by anyone with the link (adjust for your security needs) file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW); // Format link for Slack (clickable display text) fileLinks.push(`<${file.getUrl()}|${file.getName()}>`); } slackMessageText += `\n*${item.getTitle()}*: ${fileLinks.join(', ')}`; } } else { // Handle regular text/choice fields (your original logic) const responseText = response.getResponse() || "No response provided"; slackMessageText += `\n*${item.getTitle()}*: ${responseText}`; } } // Send formatted message to Slack Webhook const slackWebhookUrl = "YOUR_SLACK_WEBHOOK_URL"; // Replace with your actual webhook URL const payload = { text: slackMessageText, mrkdwn: true, username: "Support Ticket Bot", icon_emoji: ":ticket:" }; const options = { method: "post", contentType: "application/json", payload: JSON.stringify(payload) }; UrlFetchApp.fetch(slackWebhookUrl, options); }
Key Changes Explained:
- File Upload Detection: Checks if the form item is a
FILE_UPLOADtype to handle it differently from text fields. - Drive File Access: Fetches each uploaded file by its unique ID from Google Drive.
- Sharing Permissions: Sets the file to be viewable by anyone with the link (adjust to
DriveApp.Access.DOMAINif you only want your Slack workspace members to access it). - Slack Link Format: Uses Slack's markdown
<url|display text>syntax to create clean, clickable file names in the message.
Step 3: (Optional) Use Slack Attachments for Better Formatting
For a more polished, structured look, you can use Slack's attachment system to display files as cards instead of plain links. Here's how to modify the payload section:
// Replace the payload section with this code const attachments = []; slackMessageText = "*New Support Ticket Received:*"; // Inside the FILE_UPLOAD loop, replace fileLinks with this: for (const fileId of fileIds) { const file = DriveApp.getFileById(fileId); file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW); attachments.push({ title: file.getName(), title_link: file.getUrl(), text: `Size: ${(file.getSize() / 1024 / 1024).toFixed(2)} MB`, color: "#36a64f" // Green accent color for visibility }); } const payload = { text: slackMessageText, mrkdwn: true, username: "Support Ticket Bot", icon_emoji: ":ticket:", attachments: attachments };
Step 4: Test the Workflow
Submit a test response to your Google Form with a file attached. Check your Slack channel—you should see a message with clickable links to the uploaded files, and the links should open directly in Google Drive for anyone with access.
Important Notes:
- Ensure the script's owner has access to the Google Drive folder where form uploads are stored (by default, this is a folder in the owner's Drive named "Form Responses [Form Name]").
- If you're using a shared/team Drive, adjust the
DriveAppcalls to target the correct folder and verify permissions for the script. - Avoid uploading sensitive files if you're using
ANYONE_WITH_LINKsharing—restrict access to your domain if needed.
内容的提问来源于stack exchange,提问作者shawnweber

