إرسال محتوى منظّم

مستوى الترميز: مبتدئ
المدة: 20 دقيقة
نوع المشروع: التشغيل الآلي باستخدام عامل تشغيل مستند إلى الأحداث

الأهداف

  • فهم دور الحلّ
  • فهم ما تفعله خدمات Apps Script ضمن الحلّ
  • إعداد النص البرمجي
  • شغِّل النص البرمجي.

لمحة عن هذا الحل

إذا كانت لديك أنواع مختلفة من المحتوى تريد تقديمها لجمهورك، يمكنك السماح للمستخدمين باختيار المحتوى الذي يتلقّونه منك باستخدام "نماذج Google". يتيح هذا الحل للمستخدمين اختيار المواضيع التي تهمّهم، ثم يتم تلقائيًا إرسال المحتوى الذي اختاروه إليهم عبر البريد الإلكتروني.

عرض توضيحي لإرسال المحتوى باستخدام "نماذج Google" وGmail

آلية العمل

يُثبِّت النص البرمجي عامل تشغيل مستندًا إلى الأحداث يتم تشغيله في كل مرة يُرسِل فيها أحد المستخدِمين نموذجًا. مع كل عملية إرسال نموذج، ينشئ النص البرمجي رسالة إلكترونية ويرسلها من نموذج في "مستندات Google". تتضمّن الرسالة الإلكترونية اسم المستخدم والمحتوى الذي اختاره. يمكن أن يكون المحتوى الذي تقدّمه من أي نوع طالما أنّه تتم الإشارة إليه باستخدام عنوان URL.

خدمات "برمجة تطبيقات Google"

يستخدم هذا الحلّ الخدمات التالية:

  • خدمة النصوص البرمجية: تُثبِّت عامل التفعيل المستنِد إلى الأحداث والذي يتم تشغيله كلما أرسل أحد المستخدِمين النموذج.
  • خدمة المستندات: لفتح نموذج "مستندات Google" الذي يستخدمه النص البرمجي لإنشاء الرسالة الإلكترونية.
  • خدمة البريد: لإنشاء الرسالة الإلكترونية وإرسالها مع اسم المستخدم واختيار المحتوى.
  • خدمة جدول البيانات: تُضيف رسالة تأكيد إلى ورقة بيانات ردود النموذج بعد أن يُرسِل النص البرمجي الرسالة الإلكترونية.

المتطلبات الأساسية

لاستخدام هذا العيّنة، يجب استيفاء المتطلبات الأساسية التالية:

  • حساب Google (قد تحتاج حسابات Google Workspace إلى موافقة المشرف).
  • متصفح ويب يمكنه الوصول إلى الإنترنت

إعداد النص البرمجي

  1. انقر على الزر التالي لإنشاء نسخة من جدول بيانات إرسال محتوى منظَّم. تم إرفاق مشروع "برمجة التطبيقات" لهذا الحلّ بجدول البيانات.
    إنشاء نسخة

  2. في جدول البيانات المنسوخ، انقر على الإضافات > Apps Script.

  3. في القائمة المنسدلة للوظائف، اختَر installTrigger.

  4. انقر على تشغيل.

  5. امنح الإذن للنصّ البرمجي عند مطالبتك بذلك. إذا ظهرت الرسالة التحذيرية لم يتم التحقّق من هذا التطبيق على شاشة موافقة OAuth، يمكن المتابعة من خلال النقر على الإعدادات المتقدّمة > الانتقال إلى {Project Name} (غير آمن).

ملاحظة مهمة: في حال تنفيذ installTrigger أكثر من مرّة، ينشئ النص البرمجي عوامل تشغيل متعددة تُرسِل كلٌّ منها رسالة إلكترونية عندما يُرسِل أحد المستخدِمين النموذج. لحذف عوامل التشغيل الإضافية وتجنُّب الرسائل الإلكترونية المكرّرة، انقر على العوامل المشغّلة . انقر بزر الماوس الأيمن على كل عامل تشغيل إضافي ثم انقر على حذف عامل التشغيل.

تشغيل النص البرمجي

  1. ارجع إلى جدول البيانات وانقر على الأدوات > إدارة النموذج > الانتقال إلى النموذج المنشور.
  2. املأ النموذج وانقر على إرسال.
  3. تحقَّق من بريدك الإلكتروني بحثًا عن رسالة إلكترونية تتضمّن روابط تؤدي إلى المحتوى الذي اخترته.

مراجعة الرمز

لمراجعة رمز Apps Script لهذا الحل، انقر على عرض رمز المصدر أدناه:

عرض رمز المصدر

Code.gs

solutions/automations/content-signup/Code.js
// To learn how to use this script, refer to the documentation:
// https://developers.google.com/apps-script/samples/automations/content-signup

/*
Copyright 2022 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// To use your own template doc, update the below variable with the URL of your own Google Doc template.
// Make sure you update the sharing settings so that 'anyone'  or 'anyone in your organization' can view.
const EMAIL_TEMPLATE_DOC_URL = 'https://docs.google.com/document/d/1enes74gWsMG3dkK3SFO08apXkr0rcYBd3JHKOb2Nksk/edit?usp=sharing';
// Update this variable to customize the email subject.
const EMAIL_SUBJECT = 'Hello, here is the content you requested';

// Update this variable to the content titles and URLs you want to offer. Make sure you update the form so that the content titles listed here match the content titles you list in the form.
const topicUrls = {
  'Google Calendar how-to videos': 'https://www.youtube.com/playlist?list=PLU8ezI8GYqs7IPb_UdmUNKyUCqjzGO9PJ',
  'Google Drive how-to videos': 'https://www.youtube.com/playlist?list=PLU8ezI8GYqs7Y5d1cgZm2Obq7leVtLkT4',
  'Google Docs how-to videos': 'https://www.youtube.com/playlist?list=PLU8ezI8GYqs4JKwZ-fpBP-zSoWPL8Sit7',
  'Google Sheets how-to videos': 'https://www.youtube.com/playlist?list=PLU8ezI8GYqs61ciKpXf_KkV7ZRbRHVG38',
};

/**
 * Installs a trigger on the spreadsheet for when someone submits a form.
 */
function installTrigger() {
  ScriptApp.newTrigger('onFormSubmit')
      .forSpreadsheet(SpreadsheetApp.getActive())
      .onFormSubmit()
      .create();
}

/**
 * Sends a customized email for every form response.
 * 
 * @param {Object} event - Form submit event
 */
function onFormSubmit(e) {
  let responses = e.namedValues;

  // If the question title is a label, it can be accessed as an object field.
  // If it has spaces or other characters, it can be accessed as a dictionary.
  let timestamp = responses.Timestamp[0];
  let email = responses['Email address'][0].trim();
  let name = responses.Name[0].trim();
  let topicsString = responses.Topics[0].toLowerCase();

  // Parse topics of interest into a list (since there are multiple items
  // that are saved in the row as blob of text).
  let topics = Object.keys(topicUrls).filter(function(topic) {
    // indexOf searches for the topic in topicsString and returns a non-negative
    // index if the topic is found, or it will return -1 if it's not found.
    return topicsString.indexOf(topic.toLowerCase()) != -1;
  });

  // If there is at least one topic selected, send an email to the recipient.
  let status = '';
  if (topics.length > 0) {
    MailApp.sendEmail({
      to: email,
      subject: EMAIL_SUBJECT,
      htmlBody: createEmailBody(name, topics),
    });
    status = 'Sent';
  }
  else {
    status = 'No topics selected';
  }

  // Append the status on the spreadsheet to the responses' row.
  let sheet = SpreadsheetApp.getActiveSheet();
  let row = sheet.getActiveRange().getRow();
  let column = e.values.length + 1;
  sheet.getRange(row, column).setValue(status);

  console.log("status=" + status + "; responses=" + JSON.stringify(responses));
}

/**
 * Creates email body and includes the links based on topic.
 *
 * @param {string} recipient - The recipient's email address.
 * @param {string[]} topics - List of topics to include in the email body.
 * @return {string} - The email body as an HTML string.
 */
function createEmailBody(name, topics) {
  let topicsHtml = topics.map(function(topic) {
  let url = topicUrls[topic];
    return '<li><a href="' + url + '">' + topic + '</a></li>';
  }).join('');
  topicsHtml = '<ul>' + topicsHtml + '</ul>';

  // Make sure to update the emailTemplateDocId at the top.
  let docId = DocumentApp.openByUrl(EMAIL_TEMPLATE_DOC_URL).getId();
  let emailBody = docToHtml(docId);
  emailBody = emailBody.replace(/{{NAME}}/g, name);
  emailBody = emailBody.replace(/{{TOPICS}}/g, topicsHtml);
  return emailBody;
}

/**
 * Downloads a Google Doc as an HTML string.
 * 
 * @param {string} docId - The ID of a Google Doc to fetch content from.
 * @return {string} The Google Doc rendered as an HTML string.
 */
function docToHtml(docId) {

  // Downloads a Google Doc as an HTML string.
  let url = "https://docs.google.com/feeds/download/documents/export/Export?id=" +
            docId + "&exportFormat=html";
  let param = {
    method: "get",
    headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
    muteHttpExceptions: true,
  };
  return UrlFetchApp.fetch(url, param).getContentText();
}

المساهمون

تُعدّ Google هذه العينة بمساعدة خبراء Google Developers.

الخطوات التالية