اعلان‌های لحظه‌ای (Dialogflow)

کاوش در Dialogflow

روی ادامه کلیک کنید تا نمونه «اعلان‌های» ما را در Dialogflow وارد کنید. سپس، مراحل زیر را برای استقرار و آزمایش نمونه دنبال کنید:

  1. نام عاملی را وارد کنید و عامل Dialogflow جدیدی برای نمونه ایجاد کنید.
  2. پس‌از اینکه وارد کردن عامل تمام شد، روی رفتن به عامل کلیک کنید.
  3. از منو پیمایش اصلی، به تکمیل بروید.
  4. ویرایشگر درون‌خطی را فعال کنید، سپس روی استقرار کلیک کنید. ویرایشگر حاوی کد نمونه است.
  5. از منو پیمایش اصلی، به ادغام‌ها بروید، سپس روی دستیار Google کلیک کنید.
  6. در پنجره مقیدی که ظاهر می‌شود، پیش‌نمایش خودکار تغییرات را فعال کنید و روی آزمایش کلیک کنید تا شبیه‌ساز «کنش‌ها» باز شود.
  7. در شبیه‌ساز، Talk to my test app را برای آزمایش نمونه وارد کنید!
ادامه

«کنش» شما می‌تواند هر زمان که لازم باشد اعلان لحظه‌ای برای کاربران ارسال کند، مثلاً ارسال یادآوری وقتی سررسید تکلیفی نزدیک است.

در این راهنما، از نمونه نکته‌های Actions on Google به‌عنوان مرجع استفاده می‌کنیم تا به شما نشان دهیم چگونه اعلان‌های لحظه‌ای را برای «کنش» خود راه‌اندازی کنید. وقتی کاربران این «کنش» را فراخوانی می‌کنند، از آن‌ها می‌پرسد که آیا می‌خواهند نکته‌ای درباره توسعه «کنش» خودشان بشنوند یا نه. کاربران می‌توانند دسته‌ای خاص یا تصادفی را برای نکته انتخاب کنند، یا می‌توانند انتخاب کنند که جدیدترین نکته را بشنوند.

سطوح پشتیبانی‌شده

اعلان‌های لحظه‌ای در دستگاه‌های Android و iOS دردسترس است (دستگاه‌های iOS برای دریافت اعلان‌های لحظه‌ای باید برنامه «دستیار» را نصب کرده باشند). درحال‌حاضر، این ویژگی‌ها در بلندگوهای فعال‌شده با صدا، نمایشگرهای هوشمند، یا سطوح دیگر پشتیبانی نمی‌شوند.

پیش‌نیازها

حداقل یکی از «کنش‌ها» در پروژه «کنش‌های» شما باید به‌عنوان قصد راه‌انداز پیکربندی شود که وقتی کاربر روی اعلان دریافتی از «دستیار» تک‌ضرب می‌زند، فراخوانده شود.

«کنش‌های» شما نمی‌تواند برای راه‌اندازی «قصد خوشامدگویی پیش‌فرض» از اعلان لحظه‌ای پیکربندی شود.

راه‌اندازی کنسول

برای افزودن پشتیبانی از اعلان‌های لحظه‌ای به «کنش»:

  1. به کنسول Actions بروید و به ساختن > Actions بروید.

  2. روی «کنش» منطبق با قصد راه‌انداز اضافی که می‌خواهید اعلان لحظه‌ای را برای آن فعال کنید کلیک کنید.

    برای نمونه نکته‌های Actions on Google، باید «tell_latest_tip» را انتخاب کنید.

  3. به بخش تعامل کاربر پیمایش کنید و آیا می‌خواهید اعلان لحظه‌ای ارسال کنید را روشن کنید.

  4. عنوان محتوا را وارد کنید.

    برای نمونه نکته‌های Actions on Google، عنوان می‌تواند «نکته جدید اضافه شد» باشد.

  5. روی ذخیره کلیک کنید.

واردات

برای اهداف بخش‌های بعدی، در کد تحقق، باید واردات زیر را اعلام کنید:

Dialogflow
const {
  dialogflow,
  UpdatePermission,
  Suggestions,
} = require('actions-on-google');
کیت توسعه نرم‌افزار Actions
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'));
Actions SDK Node.js
conv.ask(' I can send you push notifications. Would you like that?');
conv.ask(new Suggestions('Send notifications'));
Dialogflow Java
responseBuilder
    .add("I can send you push notifications. Would you like that?")
    .addSuggestions(new String[] {
        "Send notifications"
    });
کیت توسعه نرم‌افزار Actions 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"
          }
        ]
      }
    }
  }
}
Actions 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. نوشتار تراشه را روی چیزی تنظیم کنید که کاربر را به موافقت کردن دعوت کند. در نمونه نکته‌های Actions on Google، تراشه را روی نکته‌های جدید را به من هشدار بده تنظیم کردیم.
  5. هدف Dialogflow دیگری اضافه کنید، مثلاً setup_push، و کنش متناظری تنظیم کنید، مثلاً setup.push. عبارت کاربر برای این قصد باید با نوشتار تراشه موافقت مطابقت داشته باشد، در مثال ما نکات جدید را به من هشدار بده.
قطعه کد زیر نشان می‌دهد که چگونه بااستفاده از کتابخانه مشتری Actions on Google برای Node.js، اجازه را درخواست کنید:
app.intent('Subscribe to Notifications', (conv) => {
  conv.ask(new UpdatePermission({
    intent: 'Notification',
  }));
});
Actions SDK Node.js

باید راهکار «درک زبان طبیعی» خود را به‌گونه‌ای پیکربندی کنید که اگر عبارت کاربر با مقدار درخواست موافقت با اعلان لحظه‌ای مطابقت داشت، تابعی را راه‌اندازی کند که اجازه را درخواست می‌کند. در اینجا نمونه‌ای بسیار ساده براساس مطابقت رشته ارائه شده است:

conv.ask(new UpdatePermission({
  intent: 'Notification',
}));
Dialogflow Java
  1. عاملتان را در کنسول Dialogflow باز کنید و قصدی را که برای به‌روزرسانی‌ها پیکربندی می‌کنید انتخاب کنید.
  2. به پایین پیمایش کنید تا به پاسخ برسید و برگه دستیار Google را باز کنید.
  3. روی افزودن محتوای پیام کلیک کنید و تراشه‌های پیشنهادی را انتخاب کنید.
  4. نوشتار تراشه را روی چیزی تنظیم کنید که کاربر را به موافقت کردن دعوت کند. در نمونه نکته‌های Actions on Google، تراشه را روی نکته‌های جدید را به من هشدار بده تنظیم کردیم.
  5. هدف Dialogflow دیگری اضافه کنید، مثلاً setup_push، و کنش متناظری تنظیم کنید، مثلاً setup.push. عبارت کاربر برای این قصد باید با نوشتار تراشه موافقت مطابقت داشته باشد، در مثال ما نکات جدید را به من هشدار بده.
قطعه کد زیر نحوه درخواست اجازه بااستفاده از کتابخانه کارخواه Actions on Google Java/Kotlin را نشان می‌دهد:
@ForIntent("Subscribe to Notifications")
public ActionResponse subscribeToNotifications(ActionRequest request) {
  ResponseBuilder responseBuilder = getResponseBuilder(request);
  responseBuilder.add(new UpdatePermission().setIntent("Notification"));
  return responseBuilder.build();
}
کیت توسعه نرم‌افزار Actions Java

باید راهکار «درک زبان طبیعی» خود را به‌گونه‌ای پیکربندی کنید که اگر عبارت کاربر با مقدار درخواست موافقت با اعلان لحظه‌ای مطابقت داشت، تابعی را راه‌اندازی کند که اجازه را درخواست می‌کند. در اینجا نمونه‌ای بسیار ساده براساس مطابقت رشته ارائه شده است:

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"
          }
        }
      }
    }
  }
}
قالب JSON کیت توسعه نرم‌افزار Actions

توجه داشته باشید که JSON زیر پاسخ وب‌قلاب را بااستفاده از Actions 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.`);
  }
});
Actions 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.`);
  }
});
Dialogflow Java
@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();
}
کیت توسعه نرم‌افزار Actions 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"
}
Actions 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، اعلان لحظه‌ای برای کاربران ارسال کنید. برای استفاده از این API، باید API را در پروژه Google Cloud خود فعال کنید و یک کلید حساب سرویس JSON را راه‌اندازی و بارگیری کنید. مرحله ۸ را در دستورالعمل‌های نمونه کد در اینجا ببینید.

سپس می‌توانید از کتابخانه کارخواه Google OAuth2 برای مبادله کلید حساب سرویس با کد دسترسی استفاده کنید و از این کد برای اصالت‌سنجی درخواست‌هایتان به Actions API استفاده کنید.

دریافت کلید حساب سرویس

  1. به این نشانی وب بروید و «example-project-1» را در انتها با شناسه پروژه خود در کنسول Actions جایگزین کنید: https://console.developers.google.com/apis/api/actions.googleapis.com/overview?project=example-project-1
  2. اگر دکمه فعال کردن را می‌بینید، روی آن کلیک کنید. درغیراین‌صورت، به مرحله ۳ بروید.
  3. به این نشانی وب بروید و «example-project-1» را در انتها با شناسه پروژه خود در کنسول Actions جایگزین کنید: https://console.developers.google.com/apis/credentials?project=example-project-1
  4. روی ایجاد اطلاعات کاربری > کلید حساب خدمات کلیک کنید.
  5. روی چارگوش انتخاب در زیر حساب سرویس کلیک کنید و روی حساب سرویس جدید کلیک کنید.
  6. نامی مثل «اعلان‌ها» و نقش مالک پروژه را به «حساب سرویس» بدهید.
  7. نوع کلید JSON را انتخاب کنید و روی ایجاد کلیک کنید. کلید حساب سرویس JSON در دستگاه محلی شما بارگیری می‌شود.

مبادله کلید با کد دسترسی و ارسال اعلان

برای ارسال اعلان ازطریق Actions API، باید کلید حساب سرویس را با کد دسترسی مبادله کنید. توصیه می‌کنیم برای این کار از کتابخانه کارخواه Google API استفاده کنید. در سری تکه‌کدهای زیر، از کتابخانه مشتری Google API Node.js استفاده می‌کنیم.

  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}`);
    });
  }
});
Actions 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}`);
    });
  }
});
Dialogflow 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;
  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);
}
کیت توسعه نرم‌افزار Actions 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);
}