Bu sayfada, Pub/Sub kullanarak nasıl Chat uygulaması oluşturacağınız açıklanmaktadır. Bir Chat uygulaması için bu mimari tür, kuruluşunuzun Chat uygulamanıza mesaj göndermesini engelleyen bir güvenlik duvarına sahipse veya Chat uygulaması Google Workspace Etkinlikleri API'sini kullanıyorsa kullanışlıdır. Ancak, bu Chat uygulamalarının yalnızca eşzamansız mesajlar gönderip alabilmesi nedeniyle bu mimaride aşağıdaki sınırlamalar mevcuttur:
- Mesajlarda iletişim kutuları kullanılamaz. Bunun yerine bir kart mesajı kullanın.
- Eşzamanlı yanıt içeren tek tek kartlar güncellenemez. Bunun yerine,
patch
yöntemini çağırarak mesajın tamamını güncelleyin.
Aşağıdaki şemada, Pub/Sub ile oluşturulan Chat uygulamasının mimarisi gösterilmektedir:
Yukarıdaki şemada, Pub/Sub Chat uygulamasıyla etkileşimde bulunan kullanıcılar aşağıdaki bilgi akışına sahiptir:
Kullanıcı, Chat'te doğrudan mesaj aracılığıyla veya bir Chat alanında bir Chat uygulamasına mesaj gönderir ya da Chat uygulamasının etkin bir aboneliği bulunan Chat alanında etkinlik gerçekleştirilir.
Chat, mesajı bir Pub/Sub konusuna gönderir.
Chat uygulaması mantığını içeren bulut veya şirket içi sistem olan uygulama sunucuları, mesajı güvenlik duvarı üzerinden almak için Pub/Sub konusuna abone olur.
İsteğe bağlı olarak, Chat uygulaması eşzamansız olarak mesaj yayınlamak veya diğer işlemleri gerçekleştirmek için Chat API'yi çağırabilir.
Ön koşullar
Java
- Google Chat'e erişimi olan bir Google Workspace hesabı.
- Bir Google Cloud projesi.
- Cloud projeniz için faturalandırmayı etkinleştirdiğinizden emin olun. Projelerinizin faturalandırma durumunu nasıl doğrulayacağınızı öğrenin.
- Java 11 veya üzeri.
- Apache Maven
Ortamı ayarlama
Google API'lerini kullanmadan önce bunları bir Google Cloud projesinde etkinleştirmeniz gerekir. Tek bir Google Cloud projesinde bir veya daha fazla API etkinleştirebilirsiniz.Google Cloud konsolunda Google Chat API ve Pub/Sub API'yi etkinleştirin.
Pub/Sub'ı ayarlama
Chat API'nin mesaj gönderebileceği bir Pub/Sub konusu oluşturun. Her Chat uygulaması için tek bir konu kullanmanızı öneririz.
Aşağıdaki hizmet hesabına Pub/Sub Yayıncısı rolünü atayarak Chat'e yayınlama izni verin:
chat-api-push@system.gserviceaccount.com
Chat uygulaması için Pub/Sub ve Chat ile yetkilendirmek üzere bir hizmet hesabı oluşturun ve özel anahtar dosyasını çalışma dizininize kaydedin.
Konu için bir pull aboneliği oluşturun.
Daha önce oluşturduğunuz hizmet hesabı için abonelikte Pub/Sub Abone Rolü'nü atayın.
Komut dosyasını yazın
Java
KSA'da hizmet hesabı kimlik bilgilerini sağlayın:
export GOOGLE_APPLICATION_CREDENTIALS=SERVICE_ACCOUNT_FILE_PATH
Çalışma dizininizde
pom.xml
adında bir dosya oluşturun.pom.xml
dosyasına aşağıdaki kodu yapıştırın:<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.google.chat.pubsub</groupId> <artifactId>java-pubsub-app</artifactId> <version>0.1.0</version> <name>java-pubsub-app</name> <properties> <maven.compiler.target>11</maven.compiler.target> <maven.compiler.source>11</maven.compiler.source> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>com.google.cloud</groupId> <artifactId>libraries-bom</artifactId> <version>26.26.0</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.9.1</version> </dependency> <dependency> <groupId>com.google.api-client</groupId> <artifactId>google-api-client</artifactId> <version>1.32.1</version> </dependency> <dependency> <groupId>com.google.cloud</groupId> <artifactId>google-cloud-pubsub</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.14.2</version> </dependency> </dependencies> <build> <pluginManagement> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> </plugins> </pluginManagement> </build> </project>
Çalışma dizininizde
src/main/java
dizin yapısını oluşturun.src/main/java
dizinindeMain.java
adında bir dosya oluşturun.Main.java
alanına aşağıdaki kodu yapıştırın: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 = PROJECT_ID; // Cloud Pub/Sub Subscription ID public static final String SUBSCRIPTION_ID = 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 <var>SUBSCRIPTION_ID</var> 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(); } }
Aşağıdakini değiştirin:
PROJECT_ID
: Google Cloud proje kimliği.SUBSCRIPTION_ID
: Daha önce oluşturduğunuz Pub/Sub aboneliğinin abonelik kimliği.
Uygulamayı Chat'te yayınlama
Google Cloud konsolunda Menü > API'ler ve Hizmetler > Etkin API'ler ve Hizmetler > Google Chat API > Yapılandırma'ya gidin.
Pub/Sub için Chat uygulamasını yapılandırın:
- Uygulama adı alanına
Quickstart App
yazın. - Avatar URL'sine
https://developers.google.com/chat/images/quickstart-app-avatar.png
girin. - Açıklama alanına
Quickstart app
girin. - İşlevler bölümünde Bire bir mesaj al ve Alanlara ve grup görüşmelerine katıl'ı seçin.
- Bağlantı ayarları bölümünde Cloud Pub/Sub'ı seçin ve daha önce oluşturduğunuz Pub/Sub konusunun adını yapıştırın.
- Görünürlük bölümünde, Bu Google Chat uygulamasını alanınızdaki belirli kullanıcılar ve gruplar için kullanılabilir yap'ı seçip e-posta adresinizi girin.
- Günlükler bölümünde Hataları Logging'e kaydet'i seçin.
- Uygulama adı alanına
Kaydet'i tıklayın.
Uygulama, Chat'te mesaj almaya ve mesajları yanıtlamaya hazır.
Komut dosyasını çalıştırma
CLI'da, çalışma dizininize geçin ve komut dosyasını çalıştırın:
Java
mvn compile exec:java -Dexec.mainClass=Main
Kodu çalıştırdığınızda uygulama, Pub/Sub konusunda yayınlanan mesajları dinlemeye başlar.
Chat uygulamanızı test etme
Chat uygulamanızı test etmek için Chat uygulamasıyla bir doğrudan mesaj alanı açın ve bir mesaj gönderin:
Kendinizi güvenilir test kullanıcısı olarak eklerken sağladığınız Google Workspace hesabını kullanarak Google Chat'i açın.
- Yeni sohbet'i tıklayın.
- 1 veya daha fazla kişi ekle alanına Chat uygulamanızın adını yazın.
Sonuçlardan Chat uygulamanızı seçin. Bir doğrudan mesaj açılır.
- Uygulamayla olan yeni doğrudan mesajda
Hello
yazıpenter
tuşuna basın.
Güvenilir test kullanıcıları eklemek ve etkileşimli özellikleri test etme hakkında daha fazla bilgi edinmek için Google Chat uygulamaları için etkileşimli özellikleri test etme başlıklı makaleyi inceleyin.
Sorun giderme
Bir Google Chat uygulaması veya kartı hata döndürdüğünde Chat arayüzünde "Bir hata oluştu" mesajı gösterilir. veya "İsteğiniz işlenemiyor". Bazen Chat kullanıcı arayüzünde hata mesajı gösterilmez ancak Chat uygulaması veya kartı beklenmedik bir sonuç üretir. Örneğin, kart mesajı görünmeyebilir.
Chat kullanıcı arayüzünde bir hata mesajı gösterilmese de, Chat uygulamaları için hata günlük kaydı etkinken hataları düzeltmenize yardımcı olacak açıklayıcı hata mesajları ve günlük verileri mevcuttur. Hataları görüntüleme, hata ayıklama ve düzeltme konusunda yardım için Google Chat hatalarını giderme ve düzeltme bölümünü inceleyin.
Temizleme
Bu eğiticide kullanılan kaynaklar için Google Cloud hesabınızın ücretlendirilmesini istemiyorsanız Cloud projesini silmenizi öneririz.
- Google Cloud konsolunda Kaynakları yönetin sayfasına gidin. Menü > IAM ve Yönetici > Kaynakları Yönet'i tıklayın.
- Proje listesinden silmek istediğiniz projeyi seçin ve Sil'i tıklayın.
- İletişim kutusuna proje kimliğini yazın, ardından projeyi silmek için Kapat'ı tıklayın.
İlgili konular
Chat uygulamanıza daha fazla özellik eklemek için aşağıdakileri inceleyin: