كيفية تمكين الإشعارات الفورية لتغييرات الملفات في Google Drive باستخدام Apps Script

هل تبحث عن طريقة لتلقي الإشعارات في الوقت الفعلي عندما يتم تعديل جدول بيانات مهم في Google Drive أو يتم حذفه عن طريق الخطأ في بعض الأحيان؟ حسنًا، يقدم Google Drive واجهة برمجة تطبيقات لمساعدتك في إعداد مراقبة لأي ملف في Google Drive سواء كان مستندًا أو عرضًا تقديميًا أو حتى ملف PDF. وهذا يعني أنه يمكنك تلقي إشعارات فورية كلما تغير محتوى هذا الملف أو حتى أذوناته.
يشرح هذا البرنامج التعليمي كيفية إعداد إشعارات المشاهدة على أي ملف في Google Drive بمساعدة Google Apps Script.
قم بإعداد مراقبة الملفات في Google Drive
للبدء، اكتب script.new
في المتصفح لفتح محرر Apps Script وإضافة الكود أدناه لإنشاء ساعة. ستحتاج إلى المعرف الفريد لملف Google Drive وعنوان URL للخطاف على الويب حيث سيتم إرسال الإشعارات عند تعديل الملف.
const API_BASE_URL = 'https://www.googleapis.com/drive/v3';
const SUBSCRIPTION_DURATION_MS = 24 * 60 * 60 * 1000; // 24 hours in milliseconds
/**
* Starts a subscription for receiving notifications about changes to a Google Drive file.
*
* @param {string} fileId - The ID of the file to watch for changes.
* @param {string} webhookUrl - The URL where notifications will be sent.
* @returns {void}
*/
const startSubscription = (fileId, webhookUrl) => {
try {
// Prepare the payload for the channel subscription
const channelPayload = {
id: Utilities.getUuid(), // Generate a unique ID for the channel
address: webhookUrl,
expiration: Date.now() + SUBSCRIPTION_DURATION_MS,
type: 'web_hook',
token: `fileId=${fileId}&source=labnol.org`,
};
// Construct the API endpoint URL for starting the subscription
const endPoint = Utilities.formatString(`${API_BASE_URL}/files/%s/watch?supportsAllDrives=true`, fileId);
// Call the Drive API to start the subscription
const response = UrlFetchApp.fetch(endPoint, {
method: 'POST',
contentType: 'application/json',
headers: {
Authorization: `Bearer ${ScriptApp.getOAuthToken()}`,
},
payload: JSON.stringify(channelPayload), // Convert payload to JSON string
});
// Parse the response to extract subscription information
const { id, resourceId } = JSON.parse(response);
// Store subscription information in script properties
const subscriptions = { id, resourceId, fileId, webhookUrl };
PropertiesService.getScriptProperties().setProperty('subscriptions', JSON.stringify(subscriptions));
} catch (error) {
// Handle errors that might occur during subscription setup
console.error(`Error starting subscription: ${error.message}`);
}
};
تهيئة مشغل مراقبة القيادة
بشكل افتراضي، تنتهي صلاحية مراقبة الملف خلال ساعة. لتمديد هذه المدة إلى 24 ساعة، سنستخدم المتغير SUBSCRIPTION_DURATION_MS. يرجى ملاحظة أنه لا توجد طريقة لإعداد ساعة غير محددة. وبالتالي، سنقوم بإعداد مشغل يعتمد على الوقت في Apps Script لتجديد الساعة تلقائيًا كل 24 ساعة.
const initializeWatchApp = () => {
const fileId = '<<Drive File Id>>';
const webhookUrl = 'https://<<Webhook URL>>';
startSubscription(fileId, webhookUrl);
ScriptApp.getProjectTriggers().forEach((trigger) => {
ScriptApp.deleteTrigger(trigger);
});
ScriptApp.newTrigger('triggerRenewSubscription').timeBased().everyHours(24).create();
// Used to add the necessary Drive Scope
const file = DriveApp.getFileById(fileId);
console.log(`Push notifications activated for ${file.getName()}`);
};
تجديد مشاهدة الملفات تلقائيا
تدير وظائف التشغيل عملية إنشاء وتجديد اشتراكات القناة لتلقي إشعارات حول التغييرات التي تطرأ على ملفات معينة في Google Drive. إنه يستفيد من طريقة UrlFetchApp.fetch بدلاً من Drive.Files.watch
الخدمة نظرًا لأن الأخير يستخدم الإصدار الأقدم v2 من Google Drive API.
نظرًا لأننا لا نريد إشعارات متعددة لنفس الملف، فإننا نقوم يدويًا بإيقاف أي اشتراكات موجودة لملف ما قبل إضافة ساعة جديدة.
const triggerRenewSubscription = () => {
try {
// Retrieve subscription information from script properties
const data = PropertiesService.getScriptProperties().getProperty('subscriptions');
const subscriptions = JSON.parse(data);
const { resourceId, id, fileId, webhookUrl } = subscriptions;
// Stop the current subscription
UrlFetchApp.fetch(`${API_BASE_URL}/channels/stop`, {
method: 'POST',
contentType: 'application/json',
headers: {
Authorization: `Bearer ${ScriptApp.getOAuthToken()}`,
},
payload: JSON.stringify({ id, resourceId }),
});
// Start a new subscription with the same details
startSubscription(fileId, webhookUrl);
console.log('Channel subscription renewed successfully!');
} catch (error) {
console.error(`Error renewing subscription: ${error.message}`);
}
};
إخطارات مراقبة الخط اليدوي
يمكنك استخدام خدمة ويب مثل webhook.site
أو requestbin.com
لاختبار إشعارات webhook لتغييرات الملف.
من الممكن أيضًا نشر Google Script كتطبيق ويب للتعامل مع إشعارات POST من Drive API ولكن هناك قيود – لا يمكن لـ Apps Script قراءة رأس طلب ويب وارد وتتضمن إشعارات Drive البيانات الموجودة في X-Goog-Channel-ID
, X-Goog-Channel-Token
و X-Goog-Resource-State
رؤوس الطلب.