Pub/Sub ile güvenlik duvarı arkasında bir Google Chat uygulaması derleme

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:

Pub/Sub ile uygulanan Chat uygulaması mimarisi.

Yukarıdaki şemada, Pub/Sub Chat uygulamasıyla etkileşimde bulunan kullanıcılar aşağıdaki bilgi akışına sahiptir:

  1. 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.

  2. Chat, mesajı bir Pub/Sub konusuna gönderir.

  3. 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.

  4. İ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

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.

Pub/Sub'ı ayarlama

  1. Chat API'nin mesaj gönderebileceği bir Pub/Sub konusu oluşturun. Her Chat uygulaması için tek bir konu kullanmanızı öneririz.

  2. 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
    
  3. 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.

  4. Konu için bir pull aboneliği oluşturun.

  5. Daha önce oluşturduğunuz hizmet hesabı için abonelikte Pub/Sub Abone Rolü'nü atayın.

Komut dosyasını yazın

Java

  1. KSA'da hizmet hesabı kimlik bilgilerini sağlayın:

    export GOOGLE_APPLICATION_CREDENTIALS=SERVICE_ACCOUNT_FILE_PATH
    
  2. Çalışma dizininizde pom.xml adında bir dosya oluşturun.

  3. 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>
    
  4. Çalışma dizininizde src/main/java dizin yapısını oluşturun.

  5. src/main/java dizininde Main.java adında bir dosya oluşturun.

  6. 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

  1. Google Cloud konsolunda Menü > API'ler ve Hizmetler > Etkin API'ler ve Hizmetler > Google Chat API > Yapılandırma'ya gidin.

    Yapılandırma'ya git

  2. Pub/Sub için Chat uygulamasını yapılandırın:

    1. Uygulama adı alanına Quickstart App yazın.
    2. Avatar URL'sine https://developers.google.com/chat/images/quickstart-app-avatar.png girin.
    3. Açıklama alanına Quickstart app girin.
    4. İşlevler bölümünde Bire bir mesaj al ve Alanlara ve grup görüşmelerine katıl'ı seçin.
    5. 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.
    6. 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.
    7. Günlükler bölümünde Hataları Logging'e kaydet'i seçin.
  3. 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 uygulamaya doğrudan mesaj gönderin:

  1. Google Chat'i açın.
  2. Uygulamaya doğrudan mesaj göndermek için Sohbet başlat'ı tıklayın ve açılan pencerede Uygulama bul'u tıklayın.
  3. Uygulamaları bul iletişim kutusunda "Hızlı Başlangıç Uygulaması"nı arayın.
  4. Uygulamayla doğrudan bir mesaj açmak için Hızlı Başlangıç Uygulaması'nı bulun ve Ekle > Sohbet'i tıklayın.
  5. Doğrudan mesaja Hello yazıp enter tuşuna basın. Chat uygulaması, mesajı size yankılar.

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 sorun oluştu." veya "İsteğiniz işleme alınamıyor" mesajı gösterilir. 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 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 başlıklı makaleyi inceleyin.

Temizleme

Bu eğiticide kullanılan kaynaklar için Google Cloud hesabınızın ücretlendirilmesini istemiyorsanız Cloud projesini silmenizi öneririz.

  1. Google Cloud konsolunda Kaynakları yönetin sayfasına gidin. Menü > IAM ve Yönetici > Kaynakları Yönet'i tıklayın.

    Resource Manager'a git

  2. Proje listesinden silmek istediğiniz projeyi seçin ve Sil'i tıklayın.
  3. İletişim kutusuna proje kimliğini yazın, ardından projeyi silmek için Kapat'ı tıklayın.