الإشعارات الفورية (Dialogflow)

الاستكشاف في Dialogflow

انقر على متابعة لاستيراد نموذج الإشعارات في Dialogflow. بعد ذلك، اتّبِع الخطوات أدناه لنشر النموذج واختباره:

  1. أدخِل اسم وكيل وأنشِئ وكيل Dialogflow جديدًا للنموذج.
  2. بعد الانتهاء من استيراد الوكيل، انقر على الانتقال إلى الوكيل.
  3. من قائمة التنقّل الرئيسية، انتقِل إلى توصيل الطلبات.
  4. فعِّل المحرِّر المضمّن، ثم انقر على نشر. ويتضمّن المحرِّر نموذج الرمز.
  5. من قائمة التنقّل الرئيسية، انتقِل إلى عمليات الدمج، ثم انقر على مساعد Google.
  6. في النافذة المشروطة التي تظهر، فعِّل تغييرات المعاينة التلقائية وانقر على اختبار لفتح محاكي الإجراءات.
  7. في المحاكي، أدخِل Talk to my test app لاختبار العيّنة.
متابعة

يمكن أن يدفع الإجراء الخاص بك إشعارات إلى المستخدمين كلما كان ذلك مناسبًا، مثل إرسال تذكير عند اقتراب تاريخ إنجاز مهمة.

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

مساحات العرض المتوافقة

تتوفّر الإشعارات الفورية على أجهزة Android وiOS (يجب تثبيت تطبيق "مساعد Google" على أجهزة iOS لتلقّي الإشعارات الفورية). وهي غير متاحة حاليًا على مكبّرات الصوت التي يتم تفعيل الصوت فيها أو الشاشات الذكية أو مساحات العرض الأخرى.

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

يجب ضبط إجراء واحد على الأقل من الإجراءات في مشروع "المهام" ضمن مشروع الإجراءات الذي سيتم استدعاؤه عندما ينقر المستخدم على إشعار تم استلامه من "مساعد Google".

لا يمكن ضبط الإجراءات لتشغيل هدف الترحيب التلقائي من إشعار فوري.

إعداد وحدة التحكّم

لإتاحة الإشعارات الفورية إلى الإجراء الخاص بك:

  1. انتقِل إلى وحدة تحكّم الإجراءات وانتقِل إلى إنشاء > الإجراءات.

  2. انقر على الإجراء الذي يتطابق مع الغرض الإضافي المشغِّل الذي تريد تفعيل الإشعارات الفورية له.

    بالنسبة إلى عينة نصائح 'المهام مع مساعد Google'، يمكنك تحديد "tell_latest_tip".

  3. مرِّر للأسفل إلى قسم تفاعل المستخدمين وفعِّل الخيار هل تريد إرسال إشعارات فورية.

  4. أدخِل عنوان المحتوى.

    بالنسبة إلى نموذج نصائح 'المهام مع مساعد Google'، قد يكون العنوان "تمت إضافة نصيحة جديدة".

  5. انقر على حفظ.

عمليات الاستيراد

لأغراض الأقسام التالية، في رمز التنفيذ، عليك الإفصاح عن عمليات الاستيراد التالية:

Dialogflow
const {
  dialogflow,
  UpdatePermission,
  Suggestions,
} = require('actions-on-google');
حزمة تطوير البرامج (SDK) الخاصة بالإجراءات
const {
  actionssdk,
  UpdatePermission,
  Suggestions,
} = require('actions-on-google');

تفعيل المستخدمين

قبل أن تتمكّن من إرسال إشعارات فورية إلى المستخدمين، يجب أن تطلب منهم تفعيل هذه الميزة. ويمكنك إجراء ذلك من خلال عرض شريحة اقتراح لهم لطلب الإذن. وعند منحه الإذن، تتلقى رقم تعريف مستخدم تحديث لإرسال إشعارات فورية إلى هذا المستخدم.

عرض شرائح الاقتراحات لتفعيل الميزة

قبل أن يتلقّى المستخدمون إشعارات فورية من الإجراء الخاص بك، يجب عرض شريحة اقتراح لهم لدعوتهم إلى تفعيل الإشعارات الفورية.

يرسل مقتطف الرمز التالي للمستخدم شريحة اقتراح "تنبيهي بنصائح جديدة" بجانب استجابة نصية.

Dialogflow Node.js
conv.ask('I can send you push notifications. Would you like that?');
conv.ask(new Suggestions('Send notifications'));
حزمة SDK الخاصة بالإجراءات Node.js
conv.ask(' I can send you push notifications. Would you like that?');
conv.ask(new Suggestions('Send notifications'));
JavaScript Dialogflow
responseBuilder
    .add("I can send you push notifications. Would you like that?")
    .addSuggestions(new String[] {
        "Send notifications"
    });
حزمة تطوير البرامج (SDK) لـ "الإجراءات" بلغة Java
responseBuilder
    .add("I can send you push notifications. Would you like that?")
    .addSuggestions(new String[] {
        "Send notifications"
    });
Dialogflow JSON

تجدر الإشارة إلى أنّ تنسيق JSON أدناه يصف الردّ التلقائي على الويب.

{
  "payload": {
    "google": {
      "expectUserResponse": true,
      "richResponse": {
        "items": [
          {
            "simpleResponse": {
              "textToSpeech": "Hi! Welcome to Push Notifications!"
            }
          },
          {
            "simpleResponse": {
              "textToSpeech": "I can send you push notifications. Would you like that?"
            }
          }
        ],
        "suggestions": [
          {
            "title": "Send notifications"
          }
        ]
      }
    }
  }
}
حزمة SDK الخاصة بالإجراءات بتنسيق JSON

تجدر الإشارة إلى أنّ تنسيق JSON أدناه يصف الردّ التلقائي على الويب.

{
  "expectUserResponse": true,
  "expectedInputs": [
    {
      "possibleIntents": [
        {
          "intent": "actions.intent.TEXT"
        }
      ],
      "inputPrompt": {
        "richInitialPrompt": {
          "items": [
            {
              "simpleResponse": {
                "textToSpeech": "Hi! Welcome to Push Notifications!"
              }
            },
            {
              "simpleResponse": {
                "textToSpeech": " I can send you push notifications. Would you like that?"
              }
            }
          ],
          "suggestions": [
            {
              "title": "Send notifications"
            }
          ]
        }
      }
    }
  ]
}

بعد النقر على الشريحة، عليك طلب إذن "UPDATE". يوضّح لك الرمز التالي كيفية إجراء ذلك باستخدام الدالة askForUpdatePermission في مكتبة عميل Node.js.

Dialogflow Node.js
  1. افتح وكيلك في وحدة تحكّم Dialogflow واختَر الغرض الذي تريد ضبطه للحصول على التحديثات.
  2. انتقِل للأسفل وصولاً إلى الاستجابة وافتح علامة التبويب مساعد Google.
  3. انقر على إضافة محتوى رسالة واختَر شرائح الاقتراحات.
  4. اضبط نص الشريحة على عنصر يدعو المستخدم إلى الموافقة. وفي نموذج نصائح "المهام مع مساعد Google"، تم ضبط الشريحة على تنبيهي بشأن نصائح جديدة.
  5. أضِف هدفًا آخر في Dialogflow، يُسمى على سبيل المثال setup_push، واضبط إجراءً مقابلاً، مثل setup.push. يجب أن يتطابق تعبير المستخدم عن هذا الغرض مع نص شريحة الموافقة، في المثال تنبيهي بنصائح جديدة.
يوضّح المقتطف التالي كيفية طلب الإذن باستخدام مكتبة عملاء "المهام مع مساعد Google" لنظام Node.js:
app.intent('Subscribe to Notifications', (conv) => {
  conv.ask(new UpdatePermission({
    intent: 'Notification',
  }));
});
Actions SDK Node.js

يجب إعداد حل NLU لتشغيل وظيفة تطلب الإذن إذا كان تعبير المستخدم مطابقًا لقيمة طلب تفعيل الإشعارات الفورية. في ما يلي مثال بسيط يستند إلى مطابقة السلسلة:

conv.ask(new UpdatePermission({
  intent: 'Notification',
}));
JavaScript Dialogflow
  1. افتح وكيلك في وحدة تحكّم Dialogflow واختَر الغرض الذي تريد ضبطه للحصول على التحديثات.
  2. انتقِل للأسفل وصولاً إلى الاستجابة وافتح علامة التبويب مساعد Google.
  3. انقر على إضافة محتوى رسالة واختَر شرائح الاقتراحات.
  4. اضبط نص الشريحة على عنصر يدعو المستخدم إلى الموافقة. وفي نموذج نصائح "المهام مع مساعد Google"، تم ضبط الشريحة على تنبيهي بشأن نصائح جديدة.
  5. أضِف هدفًا آخر في Dialogflow، يُسمى على سبيل المثال setup_push، واضبط إجراءً مقابلاً، مثل setup.push. يجب أن يتطابق تعبير المستخدم عن هذا الغرض مع نص شريحة الموافقة، في المثال تنبيهي بنصائح جديدة.
يوضّح المقتطف التالي كيفية طلب الإذن باستخدام مكتبة عملاء "المهام مع مساعد Google" أو Kotlin:
@ForIntent("Subscribe to Notifications")
public ActionResponse subscribeToNotifications(ActionRequest request) {
  ResponseBuilder responseBuilder = getResponseBuilder(request);
  responseBuilder.add(new UpdatePermission().setIntent("Notification"));
  return responseBuilder.build();
}
حزمة تطوير البرامج (SDK) لـ "المهام مع مساعد Google"

يجب إعداد حل NLU لتشغيل وظيفة تطلب الإذن إذا كان تعبير المستخدم مطابقًا لقيمة طلب تفعيل الإشعارات الفورية. في ما يلي مثال بسيط يستند إلى مطابقة السلسلة:

ResponseBuilder responseBuilder = getResponseBuilder(request);
responseBuilder.add(new UpdatePermission().setIntent("Notification"));
return responseBuilder.build();
تنسيق Dialogflow JSON

تجدر الإشارة إلى أنّ تنسيق JSON أدناه يصف الردّ التلقائي على الويب باستخدام Dialogflow.

{
  "payload": {
    "google": {
      "expectUserResponse": true,
      "systemIntent": {
        "intent": "actions.intent.PERMISSION",
        "data": {
          "@type": "type.googleapis.com/google.actions.v2.PermissionValueSpec",
          "permissions": [
            "UPDATE"
          ],
          "updatePermissionValueSpec": {
            "intent": "tell_latest_tip"
          }
        }
      }
    }
  }
}
حزمة SDK الخاصة بالإجراءات بتنسيق JSON

تجدر الإشارة إلى أنّ ملف JSON أدناه يصف الردّ التلقائي على الويب باستخدام حزمة تطوير البرامج (SDK) للإجراءات.

{
  "expectUserResponse": true,
  "expectedInputs": [
    {
      "possibleIntents": [
        {
          "intent": "actions.intent.PERMISSION",
          "inputValueData": {
            "@type": "type.googleapis.com/google.actions.v2.PermissionValueSpec",
            "permissions": [
              "UPDATE"
            ],
            "updatePermissionValueSpec": {
              "intent": "tell_latest_tip"
            }
          }
        }
      ]
    }
  ]
}

إنهاء الاشتراك

لإنهاء الاشتراك من الرد التلقائي على الويب في Node.js، عليك حفظ معرّف إشعارات المستخدم والغرض الذي اختاره. يتم تمرير كلاهما كوسيطات إذا منح المستخدم الإذن.

إذا تم إنشاء الإجراء الخاص بك باستخدام Dialogflow، عليك تنفيذ ما يلي:

  • أضِف غرضًا يتعامل مع actions_intent_PERMISSION.
  • حدِّد اسم الإجراء للهدف على شيء يمكن للردّ التلقائي على الويب فلترته لوقت لاحق.

يوضّح الرمز التالي كيفية التعامل مع هدف Dialogflow باسم finish_push_setup واسم الإجراء finish.push.setup:

Dialogflow Node.js
app.intent('Confirm Notifications Subscription', (conv) => {
  if (conv.arguments.get('PERMISSION')) {
    const updatesUserId = conv.arguments.get('UPDATES_USER_ID');
    // Store user ID in database for later use
    conv.close(`Ok, I'll start alerting you.`);
  } else {
    conv.close(`Ok, I won't alert you.`);
  }
});
حزمة SDK الخاصة بالإجراءات Node.js
app.intent('actions.intent.PERMISSION', (conv) => {
  if (conv.arguments.get('PERMISSION')) {
    const updatesUserId = conv.arguments.get('UPDATES_USER_ID');
    // Store user ID in database for later use
    conv.close(`Ok, I'll start alerting you.`);
  } else {
    conv.close(`Ok, I won't alert you.`);
  }
});
JavaScript Dialogflow
@ForIntent("Confirm Notifications Subscription")
public ActionResponse confirmNotificationsSubscription(ActionRequest request) {
  // Verify the user has subscribed for push notifications
  ResponseBuilder responseBuilder = getResponseBuilder(request);
  if (request.isPermissionGranted()) {
    Argument userId = request.getArgument(ConstantsKt.ARG_UPDATES_USER_ID);
    if (userId != null) {
      // Store the user's ID in the database
    }
    responseBuilder.add("Ok, I'll start alerting you.");
  } else {
    responseBuilder.add("Ok, I won't alert you.");
  }
  responseBuilder.endConversation();
  return responseBuilder.build();
}
حزمة تطوير البرامج (SDK) لـ "الإجراءات" بلغة Java
@ForIntent("actions.intent.PERMISSION")
public ActionResponse confirmNotificationsSubscription(ActionRequest request) {
  // Verify the user has subscribed for push notifications
  ResponseBuilder responseBuilder = getResponseBuilder(request);
  if (request.isPermissionGranted()) {
    Argument userId = request.getArgument(ConstantsKt.ARG_UPDATES_USER_ID);
    if (userId != null) {
      // Store the user's ID in the database
    }
    responseBuilder.add("Ok, I'll start alerting you.");
  } else {
    responseBuilder.add("Ok, I won't alert you.");
  }
  responseBuilder.endConversation();
  return responseBuilder.build();
}
Dialogflow JSON

تجدر الإشارة إلى أنّ تنسيق JSON أدناه يصف طلبًا للردّ التلقائي على الويب.

{
  "responseId": "ee9e7ed5-fa1a-48c6-aac7-f9fbe94f1f58-712767ed",
  "queryResult": {
    "queryText": "actions_intent_PERMISSION",
    "action": "confirm.subscription",
    "parameters": {},
    "allRequiredParamsPresent": true,
    "fulfillmentMessages": [
      {
        "text": {
          "text": [
            ""
          ]
        }
      }
    ],
    "outputContexts": [
      {
        "name": "projects/PROJECT_ID/agent/sessions/ABwppHGIgmmU3zBcYMF_vWoHaM4JUo3wniYBHdbUF25l63G7EQWjRnlne8Ar7AOcRHWn1lrEKGy8qdP0UXLcWDBq93k/contexts/actions_capability_screen_output"
      },
      {
        "name": "projects/PROJECT_ID/agent/sessions/ABwppHGIgmmU3zBcYMF_vWoHaM4JUo3wniYBHdbUF25l63G7EQWjRnlne8Ar7AOcRHWn1lrEKGy8qdP0UXLcWDBq93k/contexts/actions_capability_account_linking"
      },
      {
        "name": "projects/PROJECT_ID/agent/sessions/ABwppHGIgmmU3zBcYMF_vWoHaM4JUo3wniYBHdbUF25l63G7EQWjRnlne8Ar7AOcRHWn1lrEKGy8qdP0UXLcWDBq93k/contexts/actions_capability_media_response_audio"
      },
      {
        "name": "projects/PROJECT_ID/agent/sessions/ABwppHGIgmmU3zBcYMF_vWoHaM4JUo3wniYBHdbUF25l63G7EQWjRnlne8Ar7AOcRHWn1lrEKGy8qdP0UXLcWDBq93k/contexts/actions_capability_audio_output"
      },
      {
        "name": "projects/PROJECT_ID/agent/sessions/ABwppHGIgmmU3zBcYMF_vWoHaM4JUo3wniYBHdbUF25l63G7EQWjRnlne8Ar7AOcRHWn1lrEKGy8qdP0UXLcWDBq93k/contexts/actions_capability_web_browser"
      },
      {
        "name": "projects/PROJECT_ID/agent/sessions/ABwppHGIgmmU3zBcYMF_vWoHaM4JUo3wniYBHdbUF25l63G7EQWjRnlne8Ar7AOcRHWn1lrEKGy8qdP0UXLcWDBq93k/contexts/google_assistant_input_type_keyboard"
      },
      {
        "name": "projects/PROJECT_ID/agent/sessions/ABwppHGIgmmU3zBcYMF_vWoHaM4JUo3wniYBHdbUF25l63G7EQWjRnlne8Ar7AOcRHWn1lrEKGy8qdP0UXLcWDBq93k/contexts/actions_intent_permission",
        "parameters": {
          "PERMISSION": true,
          "text": "yes",
          "UPDATES_USER_ID": "ABwppHHssyPbvEBF1mgN7Ddwb7mkhiVohW9PZ--I_svqy7zFElA4DHkf9pn04UBd5gwZo26_RfXCQ8otcztyIfe6MCQ"
        }
      }
    ],
    "intent": {
      "name": "projects/PROJECT_ID/agent/intents/c7f7b30b-5b88-4bb5-b0b8-1cd0862d1dd2",
      "displayName": "Confirm Notifications Subscription"
    },
    "intentDetectionConfidence": 1,
    "languageCode": "en"
  },
  "originalDetectIntentRequest": {
    "source": "google",
    "version": "2",
    "payload": {
      "user": {
        "permissions": [
          "UPDATE"
        ],
        "locale": "en-US",
        "userVerificationStatus": "VERIFIED"
      },
      "conversation": {
        "conversationId": "ABwppHGIgmmU3zBcYMF_vWoHaM4JUo3wniYBHdbUF25l63G7EQWjRnlne8Ar7AOcRHWn1lrEKGy8qdP0UXLcWDBq93k",
        "type": "ACTIVE",
        "conversationToken": "[]"
      },
      "inputs": [
        {
          "intent": "actions.intent.PERMISSION",
          "rawInputs": [
            {
              "inputType": "KEYBOARD",
              "query": "yes"
            }
          ],
          "arguments": [
            {
              "name": "PERMISSION",
              "boolValue": true,
              "textValue": "true"
            },
            {
              "name": "text",
              "rawText": "yes",
              "textValue": "yes"
            },
            {
              "name": "UPDATES_USER_ID",
              "textValue": "ABwppHHssyPbvEBF1mgN7Ddwb7mkhiVohW9PZ--I_svqy7zFElA4DHkf9pn04UBd5gwZo26_RfXCQ8otcztyIfe6MCQ"
            }
          ]
        }
      ],
      "surface": {
        "capabilities": [
          {
            "name": "actions.capability.SCREEN_OUTPUT"
          },
          {
            "name": "actions.capability.ACCOUNT_LINKING"
          },
          {
            "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
          },
          {
            "name": "actions.capability.AUDIO_OUTPUT"
          },
          {
            "name": "actions.capability.WEB_BROWSER"
          }
        ]
      },
      "availableSurfaces": [
        {
          "capabilities": [
            {
              "name": "actions.capability.AUDIO_OUTPUT"
            },
            {
              "name": "actions.capability.SCREEN_OUTPUT"
            },
            {
              "name": "actions.capability.WEB_BROWSER"
            }
          ]
        }
      ]
    }
  },
  "session": "projects/PROJECT_ID/agent/sessions/ABwppHGIgmmU3zBcYMF_vWoHaM4JUo3wniYBHdbUF25l63G7EQWjRnlne8Ar7AOcRHWn1lrEKGy8qdP0UXLcWDBq93k"
}
حزمة SDK الخاصة بالإجراءات بتنسيق JSON

تجدر الإشارة إلى أنّ تنسيق JSON أدناه يصف طلبًا للردّ التلقائي على الويب.

{
  "user": {
    "permissions": [
      "UPDATE"
    ],
    "locale": "en-US",
    "userVerificationStatus": "VERIFIED"
  },
  "conversation": {
    "conversationId": "ABwppHEP6OAFZHkSGEiZ5HYM9qrlk8YtIH1DQmJ52cxXELSPvM-kSc_tMJ_5O6ITbgVJlY9i2FIsKWjE_HXLke48",
    "type": "NEW"
  },
  "inputs": [
    {
      "intent": "actions.intent.PERMISSION",
      "rawInputs": [
        {
          "inputType": "KEYBOARD",
          "query": "yes"
        }
      ],
      "arguments": [
        {
          "name": "PERMISSION",
          "boolValue": true,
          "textValue": "true"
        },
        {
          "name": "text",
          "rawText": "yes",
          "textValue": "yes"
        },
        {
          "name": "UPDATES_USER_ID",
          "textValue": "ABwppHFvBKC-tMYUsUjJkm3YECgZvd6A3sOc7KuQvO4ZdQX3bGLmyoQ41dh4Zmtlzv_kaOKBt1Sf6eRpNbayynrl"
        }
      ]
    }
  ],
  "surface": {
    "capabilities": [
      {
        "name": "actions.capability.AUDIO_OUTPUT"
      },
      {
        "name": "actions.capability.WEB_BROWSER"
      },
      {
        "name": "actions.capability.SCREEN_OUTPUT"
      },
      {
        "name": "actions.capability.ACCOUNT_LINKING"
      },
      {
        "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
      }
    ]
  },
  "availableSurfaces": [
    {
      "capabilities": [
        {
          "name": "actions.capability.AUDIO_OUTPUT"
        },
        {
          "name": "actions.capability.SCREEN_OUTPUT"
        },
        {
          "name": "actions.capability.WEB_BROWSER"
        }
      ]
    }
  ]
}

إرسال الإشعارات

يمكنك إرسال إشعارات فورية إلى المستخدمين باستخدام Actions API. لاستخدام واجهة برمجة التطبيقات هذه، عليك تفعيل واجهة برمجة التطبيقات في مشروعك على Google Cloud وإعداد مفتاح حساب خدمة JSON وتنزيله. اطّلِع على الخطوة رقم 8 في التعليمات الواردة في نموذج الرمز هنا.

يمكنك بعد ذلك استخدام مكتبة عملاء Google OAuth2 لاستبدال مفتاح حساب الخدمة برمز الدخول واستخدام الرمز المميّز لمصادقة طلباتك من Actions API.

الحصول على مفتاح حساب خدمة

  1. انتقل إلى عنوان URL هذا، مع استبدال "example-project-1" في النهاية برقم تعريف مشروعك في وحدة تحكم الإجراءات: https://console.developers.google.com/apis/api/actions.googleapis.com/overview?project=example-project-1
  2. في حال ظهور الزر تفعيل، انقر عليه. وبخلاف ذلك، انتقِل إلى الخطوة 3.
  3. انتقل إلى عنوان URL هذا، مع استبدال "example-project-1" في النهاية برقم تعريف مشروعك في وحدة تحكم الإجراءات: https://console.developers.google.com/apis/credentials?project=example-project-1
  4. انقر على إنشاء بيانات اعتماد > مفتاح حساب الخدمة.
  5. انقر على المربع Select (اختيار) ضمن Service Account (حساب الخدمة)، ثم انقر على New Service Account (حساب خدمة جديد).
  6. امنح حساب الخدمة اسمًا مثل "الإشعارات" ودور مالك المشروع.
  7. اختَر نوع مفتاح JSON وانقر على إنشاء. يتم تنزيل مفتاح حساب خدمة JSON على جهازك المحلي.

استبدال المفتاح برمز وصول وإرسال إشعار

لإرسال إشعار من خلال Actions API، عليك استبدال مفتاح حساب الخدمة برمز دخول. ننصحك باستخدام مكتبة عميل واجهة Google API لإجراء ذلك. في سلسلة مقتطفات الرمز التالية، نستخدم مكتبة عملاء Node.js لواجهة برمجة تطبيقات Google.

  1. ثبِّت مكتبة عملاء Google API واطلب تنفيذ ما يلي: npm install googleapis request --save
  2. استخدِم الرمز التالي للحصول على رمز دخول من مفتاح حساب الخدمة وإرسال إشعار فوري:
Dialogflow Node.js
const {google} = require('googleapis');
const request = require('request');

const jwtClient = new google.auth.JWT(
  serviceAccount.client_email, null, serviceAccount.private_key,
  ['https://www.googleapis.com/auth/actions.fulfillment.conversation'],
  null
);

jwtClient.authorize((err, tokens) => {
  if (!err) {
    request.post('https://actions.googleapis.com/v2/conversations:send', {
      auth: {
        bearer: tokens.access_token,
      },
      json: true,
      body: {
        customPushMessage: {
          userNotification: {
            title: 'Push Notification Title',
          },
          target: {
            userId: '<UPDATES_USER_ID>',
            intent: 'Notification Intent',
          },
        },
        isInSandbox: true,
      },
    }, (err, httpResponse, body) => {
      console.log(`${httpResponse.statusCode}: ${httpResponse.statusMessage}`);
    });
  }
});
حزمة SDK الخاصة بالإجراءات Node.js
const {google} = require('googleapis');
const request = require('request');

const jwtClient = new google.auth.JWT(
  serviceAccount.client_email, null, serviceAccount.private_key,
  ['https://www.googleapis.com/auth/actions.fulfillment.conversation'],
  null
);

jwtClient.authorize((err, tokens) => {
  if (!err) {
    request.post('https://actions.googleapis.com/v2/conversations:send', {
      auth: {
        bearer: tokens.access_token,
      },
      json: true,
      body: {
        customPushMessage: {
          userNotification: {
            title: 'Push Notification Title',
          },
          target: {
            userId: '<UPDATES_ORDER_ID>',
            intent: 'Notification Intent',
          },
        },
        isInSandbox: true,
      },
    }, (err, httpResponse, body) => {
      console.log(`${httpResponse.statusCode}: ${httpResponse.statusMessage}`);
    });
  }
});
JavaScript Dialogflow
final class Notification {

  private final String title;

  Notification(String title) {
    this.title = title;
  }

  String getTitle() {
    return title;
  }
}

final class Target {

  private final String userId;
  private final String intent;
  private final String locale;

  Target(String userId, String intent, String locale) {
    this.userId = userId;
    this.intent = intent;
    this.locale = locale;
  }

  String getUserId() {
    return userId;
  }

  String getIntent() {
    return intent;
  }

  String getLocale() {
    return locale;
  }
}

final class PushMessage {

  private final Notification userNotification;
  private final Target target;

  PushMessage(Notification userNotification, Target target) {
    this.userNotification = userNotification;
    this.target = target;
  }

  Notification getUserNotification() {
    return userNotification;
  }

  Target getTarget() {
    return target;
  }
}

final class PushNotification {

  private final PushMessage customPushMessage;
  private boolean isInSandbox;

  PushNotification(PushMessage customPushMessage, boolean isInSandbox) {
    this.customPushMessage = customPushMessage;
    this.isInSandbox = isInSandbox;
  }

  PushMessage getCustomPushMessage() {
    return customPushMessage;
  }

  boolean getIsInSandbox() {
    return isInSandbox;
  }
}

private PushNotification createNotification(String title, String userId, String intent, String locale) {
  Notification notification = new Notification(title);
  Target target = new Target(userId, intent, locale);
  PushMessage message = new PushMessage(notification, target);
  boolean isInSandbox = true;
  return new PushNotification(message, isInSandbox);
}

private ServiceAccountCredentials loadCredentials() throws IOException {
  String actionsApiServiceAccountFile =
      this.getClass().getClassLoader().getResource("service-account.json").getFile();
  InputStream actionsApiServiceAccount = new FileInputStream(actionsApiServiceAccountFile);
  ServiceAccountCredentials serviceAccountCredentials =
      ServiceAccountCredentials.fromStream(actionsApiServiceAccount);
  return (ServiceAccountCredentials)
      serviceAccountCredentials.createScoped(
          Collections.singleton(
              "https://www.googleapis.com/auth/actions.fulfillment.conversation"));
}

private String getAccessToken() throws IOException {
  AccessToken token = loadCredentials().refreshAccessToken();
  return token.getTokenValue();
}

public void sendNotification(String title, String userId, String intent, String locale) throws IOException {
  Preconditions.checkNotNull(title, "title cannot be null.");
  Preconditions.checkNotNull(userId, "userId cannot be null.");
  Preconditions.checkNotNull(intent, "intent cannot be null.");
  Preconditions.checkNotNull(locale, "locale cannot be null");
  PushNotification notification = createNotification(title, userId, intent, locale);

  HttpPost request = new HttpPost("https://actions.googleapis.com/v2/conversations:send");

  String token = getAccessToken();

  request.setHeader("Content-type", "application/json");
  request.setHeader("Authorization", "Bearer " + token);

  StringEntity entity = new StringEntity(new Gson().toJson(notification));
  entity.setContentType(ContentType.APPLICATION_JSON.getMimeType());
  request.setEntity(entity);
  HttpClient httpClient = HttpClientBuilder.create().build();
  httpClient.execute(request);
}
حزمة تطوير البرامج (SDK) لـ "الإجراءات" بلغة Java
final class Notification {

  private final String title;

  Notification(String title) {
    this.title = title;
  }

  String getTitle() {
    return title;
  }
}

final class Target {

  private final String userId;
  private final String intent;

  Target(String userId, String intent) {
    this.userId = userId;
    this.intent = intent;
  }

  String getUserId() {
    return userId;
  }

  String getIntent() {
    return intent;
  }
}

final class PushMessage {

  private final Notification userNotification;
  private final Target target;

  PushMessage(Notification userNotification, Target target) {
    this.userNotification = userNotification;
    this.target = target;
  }

  Notification getUserNotification() {
    return userNotification;
  }

  Target getTarget() {
    return target;
  }
}

final class PushNotification {

  private final PushMessage customPushMessage;
  private boolean isInSandbox;

  PushNotification(PushMessage customPushMessage, boolean isInSandbox) {
    this.customPushMessage = customPushMessage;
    this.isInSandbox = isInSandbox;
  }

  PushMessage getCustomPushMessage() {
    return customPushMessage;
  }

  boolean getIsInSandbox() {
    return isInSandbox;
  }
}

private PushNotification createNotification(String title, String userId, String intent) {
  Notification notification = new Notification(title);
  Target target = new Target(userId, intent);
  PushMessage message = new PushMessage(notification, target);
  boolean isInSandbox = true;
  return new PushNotification(message, isInSandbox);
}

private ServiceAccountCredentials loadCredentials() throws IOException {
  String actionsApiServiceAccountFile =
      this.getClass().getClassLoader().getResource("service-account.json").getFile();
  InputStream actionsApiServiceAccount = new FileInputStream(actionsApiServiceAccountFile);
  ServiceAccountCredentials serviceAccountCredentials =
      ServiceAccountCredentials.fromStream(actionsApiServiceAccount);
  return (ServiceAccountCredentials)
      serviceAccountCredentials.createScoped(
          Collections.singleton(
              "https://www.googleapis.com/auth/actions.fulfillment.conversation"));
}

private String getAccessToken() throws IOException {
  AccessToken token = loadCredentials().refreshAccessToken();
  return token.getTokenValue();
}

public void sendNotification(String title, String userId, String intent) throws IOException {
  Preconditions.checkNotNull(title, "title cannot be null.");
  Preconditions.checkNotNull(userId, "userId cannot be null.");
  Preconditions.checkNotNull(intent, "intent cannot be null.");
  PushNotification notification = createNotification(title, userId, intent);

  HttpPost request = new HttpPost("https://actions.googleapis.com/v2/conversations:send");

  String token = getAccessToken();

  request.setHeader("Content-type", "application/json");
  request.setHeader("Authorization", "Bearer " + token);

  StringEntity entity = new StringEntity(new Gson().toJson(notification));
  entity.setContentType(ContentType.APPLICATION_JSON.getMimeType());
  request.setEntity(entity);
  HttpClient httpClient = HttpClientBuilder.create().build();
  httpClient.execute(request);
}