Saat membuat aplikasi untuk organisasi, organisasi Anda mungkin menggunakan firewall, yang dapat mencegah Google Chat mengirim pesan ke aplikasi Anda. Untuk membantu hal ini, Google Chat dilengkapi dengan integrasi dengan Cloud Pub/Sub. Integrasi ini memungkinkan aplikasi Anda terhubung ke Cloud Pub/Sub dan menerima pesan.
Menyiapkan Cloud Pub/Sub
Bagian ini menjelaskan cara menyiapkan topik Cloud Pub/Sub dan membuat aplikasi Anda berlangganan topik tersebut.
Membuat project Google Cloud yang mendukung Pub/Sub
Untuk menggunakan Cloud Pub/Sub dengan aplikasi, Anda perlu membuat project Google Cloud Platform dengan Pub/Sub API yang diaktifkan.
- Buat project baru di Konsol Google Cloud.
- Di panel kiri konsol, pilih Pub/Sub, lalu pilih Enable API.
Membuat topik Pub/Sub
Selanjutnya, buat topik yang akan dikirimi pesan oleh Chat API. Lihat panduan memulai Konsol Pub/Sub untuk melihat cara membuat topik.
Mengaktifkan Google Chat API
Pastikan untuk mengaktifkan Google Chat API dan menetapkannya ke topik yang dibuat di langkah sebelumnya.
- Di panel kiri konsol, pilih APIs & Services, lalu aktifkan Google Chat API.
- Saat mengonfigurasi API, pastikan Setelan Koneksi ditetapkan ke Cloud Pub/Sub dan memberikan topik yang sama dari langkah sebelumnya.
- Isi kolom lain seperti yang dijelaskan dalam Panduan aplikasi contoh.
Memberikan hak publikasi atas topik Anda
Agar Google Chat dapat memublikasikan pesan ke topik Anda, aplikasi harus memiliki hak publikasi ke topik tersebut. Untuk memberikan izin ini kepada Google Chat, tetapkan peran Pub/Sub Publisher ke akun layanan berikut:
chat-api-push@system.gserviceaccount.com
Tindakan ini akan mengizinkan Google Chat untuk memublikasikan topik Anda.
Membuat akun layanan
Agar kode aplikasi Anda dapat melakukan otorisasi dengan Cloud Pub/Sub dan Google Chat, kode aplikasi perlu menggunakan akun layanan. Untuk menyiapkan akun layanan, lihat Memberikan otorisasi dan mengautentikasi dengan Chat API menggunakan akun layanan.
Membuat langganan
Ikuti Panduan Pelanggan Cloud Pub/Sub untuk menyiapkan langganan topik yang Anda buat. Konfigurasikan jenis langganan menjadi pull webhook. Tambahkan izin pada langganan untuk akun layanan yang Anda buat di langkah terakhir dan berikan Peran 'Pub/Sub Subscriber'.
Memublikasikan aplikasi Cloud Pub/Sub
Lihat panduan Memublikasikan aplikasi untuk mengetahui detail cara memublikasikan aplikasi Anda. Untuk aplikasi Cloud Pub/Sub, pilih opsi untuk Cloud Pub/Sub dan masukkan nama topik yang dibuat sepenuhnya memenuhi syarat. Nama topik harus dalam format berikut:
projects/PROJECT_ID/topics/TOPIC_ID
Misalnya, projects/pubsub-demo-2/topics/test-topic
Setelah Anda memublikasikan aplikasi dengan cara ini, pengguna akan dapat menggunakannya dan aplikasi akan menerima pesan tentang topik Pub/Sub yang telah dikonfigurasi.
Contoh di bagian berikutnya menunjukkan cara membuat dan menjalankan aplikasi sederhana yang mengimplementasikan objek-objek ini.
Contoh penerapan aplikasi
Kode contoh di bawah ini menunjukkan aplikasi sederhana yang menggunakan Cloud Pub/Sub untuk menerima pesan masuk. Untuk mencoba aplikasi ini, Anda harus:
- Mengedit nilai project ID dan ID langganan di class Utama
Berikan kredensial akun layanan seperti yang dijelaskan dalam panduan Mulai Menggunakan Autentikasi.
Export GOOGLE_APPLICATIONCREDENTIALS=<path_to_service_account_file>
Untuk menjalankan kode ini, Anda memerlukan dependensi berikut pada classpath Anda:
package com.google.chat;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.ByteArrayContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpContent;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpTransport;
import com.google.cloud.pubsub.v1.AckReplyConsumer;
import com.google.cloud.pubsub.v1.MessageReceiver;
import com.google.cloud.pubsub.v1.Subscriber;
import com.google.pubsub.v1.PubsubMessage;
import com.google.pubsub.v1.ProjectSubscriptionName;
import java.io.FileInputStream;
import java.util.Collections;
public class Main {
public static final String CREDENTIALS_PATH_ENV_PROPERTY = "GOOGLE_APPLICATION_CREDENTIALS";
// Google Cloud Project ID
public static final String PROJECT_ID = "my-project-id";
// Cloud Pub/Sub Subscription ID
public static final String SUBSCRIPTION_ID = "my-subscription-id";
public static void main(String[] args) throws Exception {
ProjectSubscriptionName subscriptionName =
ProjectSubscriptionName.of(PROJECT_ID, SUBSCRIPTION_ID);
// Instantiate app, which implements an asynchronous message receiver.
EchoApp echoApp = new EchoApp();
// Create a subscriber for "my-subscription-id" bound to the message receiver
final Subscriber subscriber =
Subscriber.newBuilder(subscriptionName, echoApp).build();
System.out.println("Starting subscriber...");
subscriber.startAsync();
// Wait for termination
subscriber.awaitTerminated();
}
}
/**
* A demo app which implements {@link MessageReceiver} to receive messages. It simply echoes the
* incoming messages.
*/
class EchoApp implements MessageReceiver {
// Path to the private key JSON file of the service account to be used for posting response
// messages to Google Chat.
// In this demo, we are using the same service account for authorizing with Cloud Pub/Sub to
// receive messages and authorizing with Google Chat to post messages. If you are using
// different service accounts, please set the path to the private key JSON file of the service
// account used to post messages to Google Chat here.
private static final String SERVICE_ACCOUNT_KEY_PATH =
System.getenv(Main.CREDENTIALS_PATH_ENV_PROPERTY);
// Developer code for Google Chat api scope.
private static final String GOOGLE_CHAT_API_SCOPE = "https://www.googleapis.com/auth/chat.bot";
// Response URL Template with placeholders for space id.
private static final String RESPONSE_URL_TEMPLATE =
"https://chat.googleapis.com/v1/__SPACE_ID__/messages";
// Response echo message template.
private static final String RESPONSE_TEMPLATE = "You said: `__MESSAGE__`";
private static final String ADDED_RESPONSE = "Thank you for adding me!";
GoogleCredential credential;
HttpTransport httpTransport;
HttpRequestFactory requestFactory;
EchoApp() throws Exception {
credential =
GoogleCredential.fromStream(new FileInputStream(SERVICE_ACCOUNT_KEY_PATH))
.createScoped(Collections.singleton(GOOGLE_CHAT_API_SCOPE));
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
requestFactory = httpTransport.createRequestFactory(credential);
}
// Called when a message is received by the subscriber.
@Override
public void receiveMessage(PubsubMessage pubsubMessage, AckReplyConsumer consumer) {
System.out.println("Id : " + pubsubMessage.getMessageId());
// handle incoming message, then ack/nack the received message
try {
ObjectMapper mapper = new ObjectMapper();
JsonNode dataJson = mapper.readTree(pubsubMessage.getData().toStringUtf8());
System.out.println("Data : " + dataJson.toString());
handle(dataJson);
consumer.ack();
} catch (Exception e) {
System.out.println(e);
consumer.nack();
}
}
public void handle(JsonNode eventJson) throws Exception {
JsonNodeFactory jsonNodeFactory = new JsonNodeFactory(false);
ObjectNode responseNode = jsonNodeFactory.objectNode();
// Construct the response depending on the event received.
String eventType = eventJson.get("type").asText();
switch (eventType) {
case "ADDED_TO_SPACE":
responseNode.put("text", ADDED_RESPONSE);
// An app can also be added to a space by @mentioning it in a message. In that case, we fall
// through to the MESSAGE case and let the app respond. If the app was added using the
// invite flow, we just post a thank you message in the space.
if(!eventJson.has("message")) {
break;
}
case "MESSAGE":
responseNode.put("text",
RESPONSE_TEMPLATE.replaceFirst(
"__MESSAGE__", eventJson.get("message").get("text").asText()));
// In case of message, post the response in the same thread.
ObjectNode threadNode = jsonNodeFactory.objectNode();
threadNode.put("name", eventJson.get("message").get("thread").get("name").asText());
responseNode.put("thread", threadNode);
break;
case "REMOVED_FROM_SPACE":
default:
// Do nothing
return;
}
// Post the response to Google Chat.
String URI =
RESPONSE_URL_TEMPLATE.replaceFirst(
"__SPACE_ID__", eventJson.get("space").get("name").asText());
GenericUrl url = new GenericUrl(URI);
HttpContent content =
new ByteArrayContent("application/json", responseNode.toString().getBytes("UTF-8"));
HttpRequest request = requestFactory.buildPostRequest(url, content);
com.google.api.client.http.HttpResponse response = request.execute();
}
}
Batasan dan pertimbangan
Perhatikan batas dan pertimbangan Pub/Sub berikut:
- Membuka, mengirimkan, atau membatalkan dialog memerlukan
respons sinkron dari aplikasi Chat dengan
DialogEventType
. Oleh karena itu, dialog tidak didukung oleh aplikasi Chat yang dibangun dengan arsitektur asinkron, seperti Cloud Pub/Sub. Sebagai solusinya, pertimbangkan untuk menggunakan pesan kartu, bukan dialog. - Aplikasi chat yang di-build dengan Cloud Pub/Sub tidak dapat memperbarui setiap kartu dengan respons sinkron. Untuk mengupdate kartu, perbarui seluruh pesan dengan memanggil metode Patch Message API.
Memecahkan masalah
Saat aplikasi atau kartu Google Chat menampilkan error, antarmuka Chat akan menampilkan pesan yang menyatakan "Terjadi masalah". atau "Tidak dapat memproses permintaan Anda". Terkadang UI Chat tidak menampilkan pesan error apa pun, tetapi aplikasi atau kartu Chat memberikan hasil yang tidak diharapkan; misalnya, pesan kartu mungkin tidak muncul.
Meskipun pesan error mungkin tidak ditampilkan di UI Chat, pesan error deskriptif dan data log tersedia untuk membantu Anda memperbaiki error saat logging error untuk aplikasi Chat diaktifkan. Untuk mendapatkan bantuan terkait melihat, men-debug, dan memperbaiki error, lihat Memecahkan masalah dan memperbaiki error Google Chat.