Pub/Sub-এর সাহায্যে ফায়ারওয়ালের পিছনে Google Chat অ্যাপ তৈরি করা

এই পৃষ্ঠা থেকে জানা যায় যে কীভাবে এমন একটি Chat অ্যাপ তৈরি করতে হয় যা Pub/Sub ব্যবহার করে Chat থেকে ইভেন্ট গ্রহণ করে। আপনার সংস্থা যদি ফায়ারওয়াল ব্যবহার করে, যা আপনার Chat অ্যাপে মেসেজ পাঠানো থেকে Chat-কে আটকাতে পারে, তাহলে Chat অ্যাপের জন্য এই ধরনের আর্কিটেকচার কাজে লাগে। এছাড়াও, আপনি যদি Google Workspace Events API-এর মাধ্যমে কোনও Chat স্পেস বা ব্যবহারকারী সম্পর্কে ইভেন্ট পাঠাতে বা পেতে চান, তাহলেও এটি কাজে লাগে। তবে, এই আর্কিটেকচারের নিম্নলিখিত সীমাবদ্ধতা রয়েছে কারণ এইসব Chat অ্যাপ শুধুমাত্র অ্যাসিঙ্ক্রোনাস মেসেজ পাঠাতে ও পেতে পারে:

  • মেসেজে ডায়ালগ ব্যবহার করা যায় না। এর পরিবর্তে, একটি কার্ড মেসেজ ব্যবহার করুন।
  • সিঙ্ক্রোনাস উত্তরের মাধ্যমে আলাদা আলাদা কার্ড আপডেট করা যায় না। পরিবর্তে, patch মেথড কল করে সম্পূর্ণ মেসেজ আপডেট করুন।

নিচের ডায়াগ্রামে Pub/Sub-এর সাহায্যে তৈরি করা চ্যাট অ্যাপের আর্কিটেকচার দেখানো হয়েছে:

Pub/Sub-এর মাধ্যমে প্রয়োগ করা চ্যাট অ্যাপের আর্কিটেকচার।

পূর্ববর্তী ডায়াগ্রামে, কোনও ব্যবহারকারী Pub/Sub চ্যাট অ্যাপের সাথে ইন্টার‍্যাক্ট করলে, তথ্যের নিম্নলিখিত ফ্লো থাকে:

  1. কোনও ব্যবহারকারী Chat অ্যাপের সাথে ইন্টার‍্যাক্ট করেন, যেমন, সেটিতে মেসেজ পাঠান, কোনও কমান্ড দেন অথবা কোনও Chat স্পেস থেকে সেটি যোগ করেন বা সরিয়ে দেন অথবা Chat স্পেসে কোনও ইভেন্ট হয় যার জন্য Chat অ্যাপের অ্যাক্টিভ সাবস্ক্রিপশন আছে।

  2. Chat, Pub/Sub টপিকে মেসেজ পাঠায়।

  3. একটি অ্যাপ্লিকেশন সার্ভার, যা হল একটি ক্লাউড বা অন-প্রিমিজেস সিস্টেম যা চ্যাট অ্যাপের লজিক কন্টেন করে, ফায়ারওয়ালের মাধ্যমে মেসেজ পাওয়ার জন্য Pub/Sub টপিকে সাবস্ক্রাইব করে।

  4. বিকল্প হিসেবে, Chat অ্যাপ অ্যাসিঙ্ক্রোনাসভাবে মেসেজ পোস্ট করতে বা অন্যান্য অপারেশন পারফর্ম করতে Chat API-কে কল করতে পারে।

পূর্বশর্ত

Node.js

Python

Java

এনভায়রনমেন্ট সেট-আপ করা

Google API ব্যবহার করার আগে, আপনাকে Google Cloud প্রোজেক্টে সেগুলি চালু করতে হবে। আপনি একটি Google Cloud প্রোজেক্টে এক বা একাধিক API চালু করতে পারবেন।

Pub/Sub সেট-আপ করা

  1. একটি Pub/Sub বিষয় তৈরি করুন যেখানে Chat API মেসেজ পাঠাতে পারে। আমরা সাজেস্ট করি যে আপনি প্রতিটি Chat অ্যাপে একটি করে বিষয় ব্যবহার করুন।

  2. Pub/Sub এবং Chat-এর সাথে অনুমোদন করতে এবং আপনার ওয়ার্কিং ডিরেক্টরিতে ব্যক্তিগত কী ফাইল সেভ করতে Chat অ্যাপের জন্য পরিষেবা অ্যাকাউন্ট তৈরি করুন।

  3. বিষয়টির জন্য পুল সাবস্ক্রিপশন তৈরি করুন ।

  4. আপনি আগে তৈরি করেছেন এমন পরিষেবা অ্যাকাউন্টের জন্য সাবস্ক্রিপশনে Pub/Sub সাবস্ক্রাইবার ভূমিকা অ্যাসাইন করুন ।

স্ক্রিপ্ট লেখা

এই বিভাগে, আপনার Chat অ্যাপের জন্য অ্যাপ্লিকেশন লজিক নির্ধারণ করুন। আপনি এমন একটি স্ক্রিপ্ট লিখুন যা Google Cloud-এর সাথে যাচাই করে এবং Chat থেকে ইভেন্ট পেতে Pub/Sub টপিকে সাবস্ক্রাইব করে, যেমন কোনও ব্যবহারকারী আপনার Chat অ্যাপে মেসেজ পাঠালে।

স্ক্রিপ্ট কোনও মেসেজ পেলে, সেটি ইভেন্ট ডেটা প্রসেস করে এবং ব্যবহারকারী বা স্পেসে উত্তর পোস্ট করার জন্য Google Chat API ব্যবহার করে। এই সেট-আপ আপনার Chat অ্যাপকে ফায়ারওয়ালের পিছনে কাজ করতে দেয়, একই সাথে Chat ব্যবহারকারীদের সাথে ইন্টার‍্যাক্ট করতে দেয়।

Node.js

  1. CLI-তে, পরিষেবা অ্যাকাউন্টের ক্রেডেনশিয়াল দিন:

    export GOOGLE_APPLICATION_CREDENTIALS=SERVICE_ACCOUNT_FILE_PATH
    
  2. CLI-তে, Google Cloud প্রোজেক্ট আইডি দিন:

    export PROJECT_ID=PROJECT_ID
    
  3. CLI-তে, আপনার আগে তৈরি করা Pub/Sub সাবস্ক্রিপশনের সাবস্ক্রিপশন আইডি দিন:

    export SUBSCRIPTION_ID=SUBSCRIPTION_ID
    
  4. আপনার ওয়ার্কিং ডিরেক্টরিতে, package.json নামের একটি ফাইল তৈরি করুন।

  5. package.json ফাইলে, নিম্নলিখিত কোড পেস্ট করুন:

    {
      "name": "pub-sub-app",
      "version": "1.0.0",
      "description": "Google Chat App that listens for messages via Cloud Pub/Sub",
      "main": "index.js",
      "scripts": {
        "start": "node index.js",
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "dependencies": {
        "@google-apps/chat": "^0.4.0",
        "@google-cloud/pubsub": "^4.5.0"
      },
      "license": "Apache-2.0"
    }
    
  6. আপনার ওয়ার্কিং ডিরেক্টরিতে, index.js নামের একটি ফাইল তৈরি করুন।

  7. index.js-এ, নিম্নলিখিত কোড পেস্ট করুন:

    const {ChatServiceClient} = require('@google-apps/chat');
    const {MessageReplyOption} = require('@google-apps/chat').protos.google.chat.v1.CreateMessageRequest;
    const {PubSub} = require('@google-cloud/pubsub');
    const {SubscriberClient} = require('@google-cloud/pubsub/build/src/v1');
    
    // Receives messages from a pull subscription.
    function receiveMessages() {
      const chat = new ChatServiceClient({
        keyFile: process.env.GOOGLE_APPLICATION_CREDENTIALS,
        scopes: ['https://www.googleapis.com/auth/chat.bot'],
      });
    
      const subscriptionPath = new SubscriberClient()
        .subscriptionPath(process.env.PROJECT_ID, process.env.SUBSCRIPTION_ID)
      const subscription = new PubSub()
        .subscription(subscriptionPath);
    
      // Handle incoming message, then acknowledge the received message
      const messageHandler = message => {
        console.log(`Id : ${message.id}`);
        const event = JSON.parse(message.data);
        console.log(`Data : ${JSON.stringify(event)}`);
    
        // Post the response to Google Chat.
        const request = formatRequest(event);
        if (request != null) {
          chat.createMessage(request);
        }
    
        // Acknowledge the message.
        message.ack();
      }
    
      subscription.on('message', messageHandler);
      console.log(`Listening for messages on ${subscriptionPath}`);
    
      // Keep main thread from exiting while waiting for messages
      setTimeout(() => {
        subscription.removeListener('message', messageHandler);
        console.log(`Stopped listening for messages.`);
      }, 60 * 1000);
    }
    
    // Send message to Google Chat based on the type of event
    function formatRequest(event) {
      const chatEvent = event.chat || {};
    
      // If the app was removed, we don't respond.
      if (chatEvent.removedFromSpacePayload) {
        console.log(`App removed from space.`);
        return null;
      }
    
      const payload = chatEvent.messagePayload || chatEvent.addedToSpacePayload;
      const spaceName = payload?.space?.name;
    
      if (!spaceName) {
        console.log('No space name in event.');
        return null;
      }
    
      if (chatEvent.addedToSpacePayload) {
        // 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.
        return {
          parent: spaceName,
          message: { text: 'Thank you for adding me!' },
        };
      } else if (chatEvent.messagePayload) {
        // In case of message, post the response in the same thread.
        const message = chatEvent.messagePayload.message;
        return {
          parent: spaceName,
          messageReplyOption: MessageReplyOption.REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD,
          message: {
            text: 'You said: `' + message.text + '`',
            thread: { name: message.thread.name },
          },
        };
      }
    }
    
    if (!process.env.PROJECT_ID) {
      console.log('Missing PROJECT_ID env var.');
      process.exit(1);
    }
    if (!process.env.SUBSCRIPTION_ID) {
      console.log('Missing SUBSCRIPTION_ID env var.');
      process.exit(1);
    }
    if (!process.env.GOOGLE_APPLICATION_CREDENTIALS) {
      console.log('Missing GOOGLE_APPLICATION_CREDENTIALS env var.');
      process.exit(1);
    }
    
    receiveMessages();
    

Python

  1. CLI-তে, পরিষেবা অ্যাকাউন্টের ক্রেডেনশিয়াল দিন:

    export GOOGLE_APPLICATION_CREDENTIALS=SERVICE_ACCOUNT_FILE_PATH
    
  2. CLI-তে, Google Cloud প্রোজেক্ট আইডি দিন:

    export PROJECT_ID=PROJECT_ID
    
  3. CLI-তে, আপনার আগে তৈরি করা Pub/Sub সাবস্ক্রিপশনের সাবস্ক্রিপশন আইডি দিন:

    export SUBSCRIPTION_ID=SUBSCRIPTION_ID
    
  4. আপনার ওয়ার্কিং ডিরেক্টরিতে, requirements.txt নামের একটি ফাইল তৈরি করুন।

  5. requirements.txt ফাইলে, নিম্নলিখিত কোড পেস্ট করুন:

    google-cloud-pubsub>=2.23.0
    google-apps-chat==0.1.9
    
  6. আপনার ওয়ার্কিং ডিরেক্টরিতে, app.py নামের একটি ফাইল তৈরি করুন।

  7. app.py-এ, নিম্নলিখিত কোড পেস্ট করুন:

    import json
    import logging
    import os
    import sys
    import time
    from google.apps import chat_v1 as google_chat
    from google.cloud import pubsub_v1
    from google.oauth2.service_account import Credentials
    
    def receive_messages():
      """Receives messages from a pull subscription."""
    
      scopes = ['https://www.googleapis.com/auth/chat.bot']
      service_account_key_path = os.environ.get('GOOGLE_APPLICATION_CREDENTIALS')
      creds = Credentials.from_service_account_file(service_account_key_path)
      chat = google_chat.ChatServiceClient(
          credentials=creds, client_options={'scopes': scopes}
      )
    
      project_id = os.environ.get('PROJECT_ID')
      subscription_id = os.environ.get('SUBSCRIPTION_ID')
      subscriber = pubsub_v1.SubscriberClient()
      subscription_path = subscriber.subscription_path(project_id, subscription_id)
    
      # Handle incoming message, then acknowledge the received message
      def callback(message):
        event = json.loads(message.data)
        logging.info('Data : %s', event)
    
        # Post the response to Google Chat.
        request = format_request(event)
        if request is not None:
          chat.create_message(request)
    
        # Acknowledge the message.
        message.ack()
    
      subscriber.subscribe(subscription_path, callback = callback)
      logging.info('Listening for messages on %s', subscription_path)
    
      # Keep main thread from exiting while waiting for messages
      while True:
        time.sleep(60)
    
    def format_request(event):
      """Send message to Google Chat based on the type of event.
      Args:
        event: A dictionary with the event data.
      """
      chat_event = event.get('chat', {})
    
      # If the app was removed, we don't respond.
      if 'removedFromSpacePayload' in chat_event:
        logging.info('App removed from space.')
        return
    
      payload = chat_event.get('messagePayload') or chat_event.get(
          'addedToSpacePayload'
      )
      space_name = payload.get('space', {}).get('name') if payload else None
    
      if not space_name:
        logging.warning('No space name in event.')
        return
    
      if 'addedToSpacePayload' in chat_event:
        # 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.
        return google_chat.CreateMessageRequest(
            parent = space_name,
            message = {
              'text': 'Thank you for adding me!'
            }
        )
      elif 'messagePayload' in chat_event:
        # In case of message, post the response in the same thread.
        message = chat_event['messagePayload']['message']
        return google_chat.CreateMessageRequest(
            parent = space_name,
            message_reply_option = google_chat.CreateMessageRequest.MessageReplyOption.REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD,
            message = {
              'text': 'You said: `' + message['text'] + '`',
              'thread': {
                'name': message['thread']['name']
              }
            }
        )
    
    if __name__ == '__main__':
      if 'PROJECT_ID' not in os.environ:
        logging.error('Missing PROJECT_ID env var.')
        sys.exit(1)
    
      if 'SUBSCRIPTION_ID' not in os.environ:
        logging.error('Missing SUBSCRIPTION_ID env var.')
        sys.exit(1)
    
      if 'GOOGLE_APPLICATION_CREDENTIALS' not in os.environ:
        logging.error('Missing GOOGLE_APPLICATION_CREDENTIALS env var.')
        sys.exit(1)
    
      logging.basicConfig(
          level=logging.INFO,
          style='{',
          format='{levelname:.1}{asctime} {filename}:{lineno}] {message}')
      receive_messages()
    

Java

  1. CLI-তে, পরিষেবা অ্যাকাউন্টের ক্রেডেনশিয়াল দিন:

    export GOOGLE_APPLICATION_CREDENTIALS=SERVICE_ACCOUNT_FILE_PATH
    
  2. CLI-তে, Google Cloud প্রোজেক্ট আইডি দিন:

    export PROJECT_ID=PROJECT_ID
    
  3. CLI-তে, আপনার আগে তৈরি করা Pub/Sub সাবস্ক্রিপশনের সাবস্ক্রিপশন আইডি দিন:

    export SUBSCRIPTION_ID=SUBSCRIPTION_ID
    
  4. আপনার ওয়ার্কিং ডিরেক্টরিতে, pom.xml নামের একটি ফাইল তৈরি করুন।

  5. pom.xml ফাইলে, নিম্নলিখিত কোড পেস্ট করুন:

    <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.addon</groupId>
     <artifactId>pubsub-addon-chat-app</artifactId>
     <version>0.1.0</version>
    
     <name>pubsub-addon-chat-app-java</name>
    
     <properties>
       <maven.compiler.release>11</maven.compiler.release>
       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
     </properties>
    
     <dependencyManagement>
       <dependencies>
         <dependency>
           <groupId>com.google.cloud</groupId>
           <artifactId>libraries-bom</artifactId>
           <version>26.41.0</version> <!-- Use a recent BOM version -->
           <type>pom</type>
           <scope>import</scope>
         </dependency>
       </dependencies>
     </dependencyManagement>
    
     <dependencies>
       <!-- Google Chat GAPIC library -->
       <dependency>
         <groupId>com.google.cloud</groupId>
         <artifactId>google-cloud-chat</artifactId>
       </dependency>
       <!-- Google Cloud Pub/Sub library -->
       <dependency>
         <groupId>com.google.cloud</groupId>
         <artifactId>google-cloud-pubsub</artifactId>
       </dependency>
       <!-- Google Apps Add-ons Event Object -->
       <dependency>
         <groupId>com.google.apps.addons.v1</groupId>
         <artifactId>google-apps-addons-v1-java</artifactId>
         <version>0.2.0</version> <!-- Check for latest version -->
       </dependency>
       <!-- Protobuf JSON utility -->
       <dependency>
         <groupId>com.google.protobuf</groupId>
         <artifactId>protobuf-java-util</artifactId>
       </dependency>
       <!-- Google Auth Library -->
       <dependency>
         <groupId>com.google.auth</groupId>
         <artifactId>google-auth-library-oauth2-http</artifactId>
       </dependency>
       <dependency>
         <groupId>com.google.api</groupId>
         <artifactId>gax</artifactId>
       </dependency>
       <!-- JSON utilities for PubSub message (if needed, though protobuf-java-util is primary for EventObject) -->
       <dependency>
         <groupId>com.fasterxml.jackson.core</groupId>
         <artifactId>jackson-databind</artifactId>
         <version>2.14.2</version>
       </dependency>
       <dependency>
         <groupId>org.slf4j</groupId>
         <artifactId>slf4j-jdk14</artifactId>
         <version>1.7.36</version>
         <scope>runtime</scope>
       </dependency>
     </dependencies>
    
     <build>
       <plugins>
         <plugin>
           <groupId>org.apache.maven.plugins</groupId>
           <artifactId>maven-compiler-plugin</artifactId>
           <version>3.13.0</version>
           <configuration>
             <source>11</source>
             <target>11</target>
           </configuration>
         </plugin>
         <plugin>
           <groupId>org.codehaus.mojo</groupId>
           <artifactId>exec-maven-plugin</artifactId>
           <version>3.3.0</version>
           <configuration>
             <mainClass>Main</mainClass>
           </configuration>
         </plugin>
       </plugins>
     </build>
    </project>
    
  6. আপনার ওয়ার্কিং ডিরেক্টরিতে, ডিরেক্টরি স্ট্রাকচার src/main/java তৈরি করুন।

  7. src/main/java ডিরেক্টরিতে, Main.java নামের একটি ফাইল তৈরি করুন।

  8. Main.java-এ, নিম্নলিখিত কোড পেস্ট করুন:

    import com.fasterxml.jackson.databind.JsonNode;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.api.gax.core.FixedCredentialsProvider;
    import com.google.auth.oauth2.GoogleCredentials;
    import com.google.chat.v1.ChatServiceClient;
    import com.google.chat.v1.ChatServiceSettings;
    import com.google.chat.v1.CreateMessageRequest;
    import com.google.chat.v1.CreateMessageRequest.MessageReplyOption;
    import com.google.chat.v1.Message;
    import com.google.chat.v1.Thread;
    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.ProjectSubscriptionName;
    import com.google.pubsub.v1.PubsubMessage;
    import java.io.FileInputStream;
    import java.util.Collections;
    
    public class Main {
    
      public static final String PROJECT_ID_ENV_PROPERTY = "PROJECT_ID";
      public static final String SUBSCRIPTION_ID_ENV_PROPERTY = "SUBSCRIPTION_ID";
      public static final String CREDENTIALS_PATH_ENV_PROPERTY = "GOOGLE_APPLICATION_CREDENTIALS";
    
      public static void main(String[] args) throws Exception {
        ProjectSubscriptionName subscriptionName =
            ProjectSubscriptionName.of(
                System.getenv(Main.PROJECT_ID_ENV_PROPERTY),
                System.getenv(Main.SUBSCRIPTION_ID_ENV_PROPERTY));
    
        // 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("Subscriber is listening to events...");
        subscriber.startAsync();
    
        // Wait for termination
        subscriber.awaitTerminated();
      }
    }
    
    /**
     * A demo app which implements {@link MessageReceiver} to receive messages.
     * It echoes 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, 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";
    
      private static final String ADDED_RESPONSE = "Thank you for adding me!";
    
      ChatServiceClient chatServiceClient;
    
      EchoApp() throws Exception {
        GoogleCredentials credential =
            GoogleCredentials.fromStream(new FileInputStream(SERVICE_ACCOUNT_KEY_PATH))
                .createScoped(Collections.singleton(GOOGLE_CHAT_API_SCOPE));
    
        // Create the ChatServiceSettings with the app credentials
        ChatServiceSettings chatServiceSettings =
            ChatServiceSettings.newBuilder()
                .setCredentialsProvider(FixedCredentialsProvider.create(credential))
                .build();
    
        // Set the Chat service client
        chatServiceClient = ChatServiceClient.create(chatServiceSettings);
      }
    
      // 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 acknowledge 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);
          // Negative acknowledgement makes Pub/Sub redeliver the message.
          consumer.nack();
        }
      }
    
      // Send message to Google Chat based on the type of event.
      public void handle(JsonNode eventJson) throws Exception {
        // Google Chat events for add-ons are wrapped in a 'chat' object.
        if (!eventJson.has("chat")) {
          System.out.println("Ignored: Not a Chat event (missing 'chat' field).");
          return;
        }
    
        JsonNode chatNode = eventJson.get("chat");
        CreateMessageRequest createMessageRequest = null;
    
        if (chatNode.has("messagePayload")) {
          // HANDLE MESSAGE
          JsonNode messagePayload = chatNode.get("messagePayload");
          JsonNode message = messagePayload.get("message");
          JsonNode space = messagePayload.get("space");
    
          String spaceName = space.get("name").asText();
          String userText = message.has("text") ? message.get("text").asText() : "";
          String threadName = message.has("thread") ? message.get("thread").get("name").asText() : "";
    
          System.out.println("Received message in " + spaceName + ": " + userText);
    
          createMessageRequest =
              CreateMessageRequest.newBuilder()
                  .setParent(spaceName)
                  .setMessageReplyOption(MessageReplyOption.REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD)
                  .setMessage(
                      Message.newBuilder()
                          .setText("You said: `" + userText + "`")
                          .setThread(Thread.newBuilder().setName(threadName).build())
                          .build())
                  .build();
    
        } else if (chatNode.has("addedToSpacePayload")) {
          // HANDLE ADDED TO SPACE
          JsonNode addedPayload = chatNode.get("addedToSpacePayload");
          JsonNode space = addedPayload.get("space");
          String spaceName = space.get("name").asText();
    
          System.out.println("Added to space: " + spaceName);
    
          createMessageRequest =
              CreateMessageRequest.newBuilder()
                  .setParent(spaceName)
                  .setMessage(Message.newBuilder().setText(ADDED_RESPONSE).build())
                  .build();
    
        } else if (chatNode.has("removedFromSpacePayload")) {
          System.out.println("Removed from space.");
          return;
        } else {
          System.out.println("Ignored: Unhandled Chat event type.");
          return;
        }
    
        if (createMessageRequest != null) {
          // Post the response to Google Chat.
          chatServiceClient.createMessage(createMessageRequest);
          System.out.println("Sent reply.");
        }
      }
    }
    

Chat অ্যাপ কনফিগার করা

Google Cloud কনসোলে Chat অ্যাপ কনফিগার করে এর নাম ও অবতারের মতো বিবরণ দিন এবং Pub/Sub টপিকের সাথে কানেকশন সেট-আপ করুন।

Pub/Sub টপিকের সাথে কানেক্ট করার মাধ্যমে, আপনি Chat-কে আপনার অ্যাপে ইভেন্ট পাঠানোর অনুমতি দেন। আপনার স্ক্রিপ্ট, যা টপিক সাবস্ক্রাইব করে, সেটি তারপরে এইসব ইভেন্ট পেতে এবং ব্যবহারকারীদের উত্তর দিতে পারে।

  1. Google Cloud Console-এ, মেনু > API ও পরিষেবা > চালু করা API ও পরিষেবা > Google Chat API > কনফিগারেশন বিকল্পে যান।

    Chat API কনফিগারেশনে যান

  2. Pub/Sub-এর জন্য Chat অ্যাপ কনফিগার করা:

    1. অ্যাপের নাম বিকল্পে Quickstart App লিখুন।
    2. অবতার URL-এ https://developers.google.com/workspace/chat/images/quickstart-app-avatar.png লিখুন।
    3. বিবরণ বিভাগে, Quickstart app লিখুন।
    4. কার্যকারিতা বিকল্পের মধ্যে, স্পেস ও গ্রুপ কথোপকথনে যোগ দিন বিকল্প বেছে নিন।
    5. কানেকশন সেটিংস বিকল্পের মধ্যে, Cloud Pub/Sub বেছে নিন এবং আগে তৈরি করা Pub/Sub টপিকের নাম পেস্ট করুন।
    6. দৃশ্যমানতা বিকল্পের মধ্যে, আপনার ডোমেনে নির্দিষ্ট লোকজন ও গ্রুপের জন্য এই Google Chat অ্যাপ উপলভ্য করুন বিকল্প বেছে নিন এবং আপনার ইমেল আইডি লিখুন।
    7. লগ বিকল্পের মধ্যে, লগিংয়ে লগ সংক্রান্ত সমস্যা বিকল্প বেছে নিন।
  3. সেভ করুন বিকল্পে ক্লিক করুন।

আপনি Chat অ্যাপ কনফিগার করার পরে, আপনাকে অবশ্যই Pub/Sub কনফিগারেশন আপডেট করতে হবে।

  1. Chat API কনফিগারেশন পৃষ্ঠায়, কানেকশন সেটিংসের মধ্যে পরিষেবা অ্যাকাউন্টের ইমেল কপি করুন, এটি হল আপনার Google Cloud প্রোজেক্টের জন্য তৈরি করা অনন্য ইমেল।
  2. আপনি আগে কপি করেছেন এমন পরিষেবা অ্যাকাউন্টের ইমেলে Pub/Sub Publisher ভূমিকা অ্যাসাইন করে, বিষয়টিতেপ্রকাশ করার জন্য চ্যাট অনুমতি দিন ।

Chat-এ মেসেজ গ্রহণ ও উত্তর দেওয়ার জন্য অ্যাপ রেডি।

স্ক্রিপ্ট রান করানো

CLI-তে, আপনার ওয়ার্কিং ডিরেক্টরিতে পরিবর্তন করুন এবং স্ক্রিপ্ট রান করান:

Node.js

npm install
npm start

Python

python -m venv env
source env/bin/activate
pip install -r requirements.txt -U
python app.py

Java

mvn compile exec:java -Dexec.mainClass=Main

আপনি কোড রান করালে, Pub/Sub টপিকে প্রকাশিত মেসেজ অ্যাপ্লিকেশন শোনা শুরু করে।

আপনার Chat অ্যাপ পরীক্ষা করা

আপনার Chat অ্যাপ পরীক্ষা করতে, Chat অ্যাপের মাধ্যমে সরাসরি মেসেজ স্পেস খুলুন এবং একটি মেসেজ পাঠান:

  1. আপনি বিশ্বস্ত পরীক্ষক হিসেবে নিজেকে যোগ করার সময় যে Google Workspace অ্যাকাউন্ট প্রদান করেছিলেন সেটি ব্যবহার করে Google Chat খুলুন।

    Google Chat-এ যান

  2. নতুন চ্যাট বিকল্পে ক্লিক করুন।
  3. ১ বা একাধিক লোকজনকে যোগ করুন ফিল্ডে, আপনার Chat অ্যাপের নাম টাইপ করুন।
  4. ফলাফল থেকে আপনার Chat অ্যাপ বেছে নিন। সরাসরি মেসেজ খুলে যায়।

  5. অ্যাপের সাথে নতুন সরাসরি মেসেজে, Hello টাইপ করে enter প্রেস করুন।

বিশ্বস্ত পরীক্ষক যোগ করতে এবং ইন্ট্যার‍্যাক্টিভ ফিচার পরীক্ষা করা সম্পর্কে আরও জানতে, Google Chat অ্যাপের জন্য ইন্ট্যার‍্যাক্টিভ ফিচার পরীক্ষা করুন দেখুন।

সমস্যার সমাধান করুন

Google Chat অ্যাপ বা কার্ড কোনও সমস্যার মেসেজ দেখালে, Chat ইন্টারফেস "কিছু সমস্যা হয়েছে" লেখা মেসেজ দেখায়। অথবা "আপনার অনুরোধ প্রসেস করা যায়নি" কখনও কখনও Chat UI কোনও সমস্যার মেসেজ না দেখালেও, Chat অ্যাপ বা কার্ড অপ্রত্যাশিত ফলাফল দেয়; যেমন, কার্ড মেসেজ দেখানো নাও হতে পারে।

যদিও Chat UI-তে কোনও সমস্যার মেসেজ নাও দেখাতে পারে, Chat অ্যাপের জন্য সমস্যা লগ করার সুবিধা চালু করা থাকলে, সমস্যার বিবরণ সহ মেসেজ ও লগ ডেটা আপনাকে সমস্যা সমাধান করতে সাহায্য করার জন্য উপলভ্য থাকে। দেখতে, ডিবাগ করতে এবং সমস্যার সমাধান করতে সাহায্য পেতে, Google Chat সংক্রান্ত সমস্যার সমাধান ও তা ঠিক করা দেখুন।

অপ্রয়োজনীয়গুলি মুছুন

এই টিউটোরিয়ালে ব্যবহৃত রিসোর্সের জন্য আপনার Google Cloud অ্যাকাউন্টে চার্জ যাতে না লাগে, তার জন্য আমরা Cloud প্রোজেক্টটি মুছে দেওয়ার সাজেস্ট করি।

  1. Google Cloud Console-এ, রিসোর্স ম্যানেজ করুন পৃষ্ঠায় যান। মেনু > IAM ও অ্যাডমিন > রিসোর্স ম্যানেজ করুন বিকল্পে ক্লিক করুন।

    রিসোর্স ম্যানেজারে যান

  2. প্রোজেক্টের তালিকা থেকে, যে প্রোজেক্টটি মুছতে চান সেটি বেছে নিন এবং তারপরে মুছুন বিকল্পে ক্লিক করুন।
  3. ডায়ালগে, প্রোজেক্ট আইডি টাইপ করুন এবং তারপর প্রোজেক্ট মুছে দিতে বন্ধ করুন বিকল্পে ক্লিক করুন ।

অ্যাড-অন নয় এমন চ্যাট অ্যাপ: Pub/Sub-এর সাহায্যে Google Chat অ্যাপ তৈরি করা

Pub/Sub-এর সাহায্যে Google Workspace অ্যাড-অন নয় এমন Chat অ্যাপ তৈরি করতে, Pub/Sub প্রকাশনার অনুমতি দিতে, স্ক্রিপ্ট লিখতে এবং অ্যাড-অন নয় এমন Chat অ্যাপ কনফিগার করতে এইসব ধাপ অনুসরণ করুন।

বিষয়ে প্রকাশ করার জন্য Chat-কে অনুমতি দিন

প্রকাশ করার জন্য চ্যাট সংক্রান্ত অনুমতি দিন নিম্নলিখিত পরিষেবা অ্যাকাউন্টে Pub/Sub প্রকাশক ভূমিকা অ্যাসাইন করে Pub/Sub টপিকে:

chat-api-push@system.gserviceaccount.com

অ্যাড-অন নয় এমন Chat অ্যাপের জন্য স্ক্রিপ্ট লেখা

Node.js

  1. CLI-তে, পরিষেবা অ্যাকাউন্টের ক্রেডেনশিয়াল দিন:

    export GOOGLE_APPLICATION_CREDENTIALS=SERVICE_ACCOUNT_FILE_PATH
    
  2. CLI-তে, Google Cloud প্রোজেক্ট আইডি দিন:

    export PROJECT_ID=PROJECT_ID
    
  3. CLI-তে, আপনার আগে তৈরি করা Pub/Sub সাবস্ক্রিপশনের সাবস্ক্রিপশন আইডি দিন:

    export SUBSCRIPTION_ID=SUBSCRIPTION_ID
    
  4. আপনার ওয়ার্কিং ডিরেক্টরিতে, package.json নামের একটি ফাইল তৈরি করুন।

  5. package.json ফাইলে, নিম্নলিখিত কোড পেস্ট করুন:

    node/pub-sub-app/package.json
    {
      "name": "pub-sub-app",
      "version": "1.0.0",
      "description": "Google Chat App that listens for messages via Cloud Pub/Sub",
      "main": "index.js",
      "scripts": {
        "start": "node index.js",
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "dependencies": {
        "@google-apps/chat": "^0.4.0",
        "@google-cloud/pubsub": "^4.5.0"
      },
      "license": "Apache-2.0"
    }
  6. আপনার ওয়ার্কিং ডিরেক্টরিতে, index.js নামের একটি ফাইল তৈরি করুন।

  7. index.js-এ, নিম্নলিখিত কোড পেস্ট করুন:

    node/pub-sub-app/index.js
    const {ChatServiceClient} = require('@google-apps/chat');
    const {MessageReplyOption} = require('@google-apps/chat').protos.google.chat.v1.CreateMessageRequest;
    const {PubSub} = require('@google-cloud/pubsub');
    const {SubscriberClient} = require('@google-cloud/pubsub/build/src/v1');
    
    // Receives messages from a pull subscription.
    function receiveMessages() {
      const chat = new ChatServiceClient({
        keyFile: process.env.GOOGLE_APPLICATION_CREDENTIALS,
        scopes: ['https://www.googleapis.com/auth/chat.bot'],
      });
    
      const subscriptionPath = new SubscriberClient()
        .subscriptionPath(process.env.PROJECT_ID, process.env.SUBSCRIPTION_ID)
      const subscription = new PubSub()
        .subscription(subscriptionPath);
    
      // Handle incoming message, then ack/nack the received message
      const messageHandler = message => {
        console.log(`Id : ${message.id}`);
        const event = JSON.parse(message.data);
        console.log(`Data : ${JSON.stringify(event)}`);
    
        // Post the response to Google Chat.
        const request = formatRequest(event);
        if (request != null) {
          chat.createMessage(request);
        }
    
        // Ack the message.
        message.ack();
      }
    
      subscription.on('message', messageHandler);
      console.log(`Listening for messages on ${subscriptionPath}`);
    
      // Keep main thread from exiting while waiting for messages
      setTimeout(() => {
        subscription.removeListener('message', messageHandler);
        console.log(`Stopped listening for messages.`);
      }, 60 * 1000);
    }
    
    // Send message to Google Chat based on the type of event
    function formatRequest(event) {
      const spaceName = event.space.name;
      const eventType = event.type;
    
      // If the app was removed, we don't respond.
      if (event.type == 'REMOVED_FROM_SPACE') {
        console.log(`App removed rom space ${spaceName}`);
        return null;
      } else if (eventType == 'ADDED_TO_SPACE' && !eventType.message) {
        // 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.
        return {
          parent: spaceName,
          message: { text: 'Thank you for adding me!' }
        };
      } else if (eventType == 'ADDED_TO_SPACE' || eventType == 'MESSAGE') {
        // In case of message, post the response in the same thread.
        return {
          parent: spaceName,
          messageReplyOption: MessageReplyOption.REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD,
          message: {
            text: 'You said: `' + event.message.text + '`',
            thread: { name: event.message.thread.name }
          }
        };
      }
    }
    
    if (!process.env.PROJECT_ID) {
      console.log('Missing PROJECT_ID env var.');
      process.exit(1);
    }
    if (!process.env.SUBSCRIPTION_ID) {
      console.log('Missing SUBSCRIPTION_ID env var.');
      process.exit(1);
    }
    if (!process.env.GOOGLE_APPLICATION_CREDENTIALS) {
      console.log('Missing GOOGLE_APPLICATION_CREDENTIALS env var.');
      process.exit(1);
    }
    
    receiveMessages();

Python

  1. CLI-তে, পরিষেবা অ্যাকাউন্টের ক্রেডেনশিয়াল দিন:

    export GOOGLE_APPLICATION_CREDENTIALS=SERVICE_ACCOUNT_FILE_PATH
    
  2. CLI-তে, Google Cloud প্রোজেক্ট আইডি দিন:

    export PROJECT_ID=PROJECT_ID
    
  3. CLI-তে, আপনার আগে তৈরি করা Pub/Sub সাবস্ক্রিপশনের সাবস্ক্রিপশন আইডি দিন:

    export SUBSCRIPTION_ID=SUBSCRIPTION_ID
    
  4. আপনার ওয়ার্কিং ডিরেক্টরিতে, requirements.txt নামের একটি ফাইল তৈরি করুন।

  5. requirements.txt ফাইলে, নিম্নলিখিত কোড পেস্ট করুন:

    python/pub-sub-app/requirements.txt
    google-cloud-pubsub>=2.23.0
    google-apps-chat==0.1.9
  6. আপনার ওয়ার্কিং ডিরেক্টরিতে, app.py নামের একটি ফাইল তৈরি করুন।

  7. app.py-এ, নিম্নলিখিত কোড পেস্ট করুন:

    python/pub-sub-app/app.py
    import json
    import logging
    import os
    import sys
    import time
    from google.apps import chat_v1 as google_chat
    from google.cloud import pubsub_v1
    from google.oauth2.service_account import Credentials
    
    
    def receive_messages():
      """Receives messages from a pull subscription."""
    
      scopes = ['https://www.googleapis.com/auth/chat.bot']
      service_account_key_path = os.environ.get(
        'GOOGLE_APPLICATION_CREDENTIALS')
      creds = Credentials.from_service_account_file(
        service_account_key_path)
      chat = google_chat.ChatServiceClient(
        credentials = creds,
        client_options = {
          "scopes": scopes
        })
    
      project_id = os.environ.get('PROJECT_ID')
      subscription_id = os.environ.get('SUBSCRIPTION_ID')
      subscriber = pubsub_v1.SubscriberClient()
      subscription_path = subscriber.subscription_path(
          project_id, subscription_id)
    
      # Handle incoming message, then ack/nack the received message
      def callback(message):
        event = json.loads(message.data)
        logging.info('Data : %s', event)
        space_name = event['space']['name']
    
        # Post the response to Google Chat.
        request = format_request(event)
        if request is not None:
          chat.create_message(request)
    
        # Ack the message.
        message.ack()
    
      subscriber.subscribe(subscription_path, callback = callback)
      logging.info('Listening for messages on %s', subscription_path)
    
      # Keep main thread from exiting while waiting for messages
      while True:
        time.sleep(60)
    
    
    def format_request(event):
      """Send message to Google Chat based on the type of event.
      Args:
        event: A dictionary with the event data.
      """
      space_name = event['space']['name']
      event_type = event['type']
    
      # If the app was removed, we don't respond.
      if event['type'] == 'REMOVED_FROM_SPACE':
        logging.info('App removed rom space %s', space_name)
        return
      elif event_type == 'ADDED_TO_SPACE' and 'message' not in event:
        # 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.
        return google_chat.CreateMessageRequest(
            parent = space_name,
            message = {
              'text': 'Thank you for adding me!'
            }
        )
      elif event_type in ['ADDED_TO_SPACE', 'MESSAGE']:
        # In case of message, post the response in the same thread.
        return google_chat.CreateMessageRequest(
            parent = space_name,
            message_reply_option = google_chat.CreateMessageRequest.MessageReplyOption.REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD,
            message = {
              'text': 'You said: `' + event['message']['text'] + '`',
              'thread': {
                'name': event['message']['thread']['name']
              }
            }
        )
    
    
    if __name__ == '__main__':
      if 'PROJECT_ID' not in os.environ:
        logging.error('Missing PROJECT_ID env var.')
        sys.exit(1)
    
      if 'SUBSCRIPTION_ID' not in os.environ:
        logging.error('Missing SUBSCRIPTION_ID env var.')
        sys.exit(1)
    
      if 'GOOGLE_APPLICATION_CREDENTIALS' not in os.environ:
        logging.error('Missing GOOGLE_APPLICATION_CREDENTIALS env var.')
        sys.exit(1)
    
      logging.basicConfig(
          level=logging.INFO,
          style='{',
          format='{levelname:.1}{asctime} {filename}:{lineno}] {message}')
      receive_messages()

Java

  1. CLI-তে, পরিষেবা অ্যাকাউন্টের ক্রেডেনশিয়াল দিন:

    export GOOGLE_APPLICATION_CREDENTIALS=SERVICE_ACCOUNT_FILE_PATH
    
  2. CLI-তে, Google Cloud প্রোজেক্ট আইডি দিন:

    export PROJECT_ID=PROJECT_ID
    
  3. CLI-তে, আপনার আগে তৈরি করা Pub/Sub সাবস্ক্রিপশনের সাবস্ক্রিপশন আইডি দিন:

    export SUBSCRIPTION_ID=SUBSCRIPTION_ID
    
  4. আপনার ওয়ার্কিং ডিরেক্টরিতে, pom.xml নামের একটি ফাইল তৈরি করুন।

  5. pom.xml ফাইলে, নিম্নলিখিত কোড পেস্ট করুন:

    java/pub-sub-app/pom.xml
    <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</groupId>
      <artifactId>pub-sub-app</artifactId>
      <version>0.1.0</version>
    
      <name>pub-sub-app-java</name>
    
      <properties>
        <maven.compiler.release>21</maven.compiler.release>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
      </properties>
    
      <dependencies>
        <!-- Google Chat GAPIC library -->
        <dependency>
          <groupId>com.google.api.grpc</groupId>
          <artifactId>proto-google-cloud-chat-v1</artifactId>
          <version>0.8.0</version>
        </dependency>
        <dependency>
          <groupId>com.google.api</groupId>
          <artifactId>gax</artifactId>
          <version>2.48.1</version>
        </dependency>
        <dependency>
          <groupId>com.google.cloud</groupId>
          <artifactId>google-cloud-chat</artifactId>
          <version>0.1.0</version>
        </dependency>
        <!-- Google Cloud Pub/Sub library -->
        <dependency>
          <groupId>com.google.cloud</groupId>
          <artifactId>google-cloud-pubsub</artifactId>
        <version>1.125.8</version>
        </dependency>
        <!-- JSON utilities -->
        <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
          <version>2.14.2</version>
        </dependency>
      </dependencies>
    
    </project>
  6. আপনার ওয়ার্কিং ডিরেক্টরিতে, ডিরেক্টরি স্ট্রাকচার src/main/java তৈরি করুন।

  7. src/main/java ডিরেক্টরিতে, Main.java নামের একটি ফাইল তৈরি করুন।

  8. Main.java-এ, নিম্নলিখিত কোড পেস্ট করুন:

    java/pub-sub-app/src/main/java/Main.java
    import com.fasterxml.jackson.databind.JsonNode;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.api.gax.core.FixedCredentialsProvider;
    import com.google.auth.oauth2.GoogleCredentials;
    import com.google.chat.v1.ChatServiceClient;
    import com.google.chat.v1.ChatServiceSettings;
    import com.google.chat.v1.CreateMessageRequest;
    import com.google.chat.v1.CreateMessageRequest.MessageReplyOption;
    import com.google.chat.v1.Message;
    import com.google.chat.v1.Thread;
    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.ProjectSubscriptionName;
    import com.google.pubsub.v1.PubsubMessage;
    import java.io.FileInputStream;
    import java.util.Collections;
    
    public class Main {
    
      public static final String PROJECT_ID_ENV_PROPERTY = "PROJECT_ID";
      public static final String SUBSCRIPTION_ID_ENV_PROPERTY = "SUBSCRIPTION_ID";
      public static final String CREDENTIALS_PATH_ENV_PROPERTY = "GOOGLE_APPLICATION_CREDENTIALS";
    
      public static void main(String[] args) throws Exception {
        ProjectSubscriptionName subscriptionName = ProjectSubscriptionName.of(
          System.getenv(Main.PROJECT_ID_ENV_PROPERTY),
          System.getenv(Main.SUBSCRIPTION_ID_ENV_PROPERTY));
    
        // 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("Subscriber is listening to events...");
        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";
    
      private static final String ADDED_RESPONSE = "Thank you for adding me!";
    
      ChatServiceClient chatServiceClient;
    
      EchoApp() throws Exception {
        GoogleCredentials credential = GoogleCredentials
          .fromStream(new FileInputStream(SERVICE_ACCOUNT_KEY_PATH))
          .createScoped(Collections.singleton(GOOGLE_CHAT_API_SCOPE));
    
        // Create the ChatServiceSettings with the app credentials
        ChatServiceSettings chatServiceSettings = ChatServiceSettings.newBuilder()
          .setCredentialsProvider(FixedCredentialsProvider.create(credential)).build();
    
        // Set the Chat service client
        chatServiceClient = ChatServiceClient.create(chatServiceSettings);
      }
    
      // 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();
        }
      }
    
      // Send message to Google Chat based on the type of event.
      public void handle(JsonNode eventJson) throws Exception {
        CreateMessageRequest createMessageRequest;
        switch (eventJson.get("type").asText()) {
          case "ADDED_TO_SPACE":
            // 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")) {
              createMessageRequest = CreateMessageRequest.newBuilder()
                .setParent(eventJson.get("space").get("name").asText())
                .setMessage(Message.newBuilder().setText(ADDED_RESPONSE).build()).build();
              break;
            }
          case "MESSAGE":
            // In case of message, post the response in the same thread.
            createMessageRequest = CreateMessageRequest.newBuilder()
              .setParent(eventJson.get("space").get("name").asText())
              .setMessageReplyOption(MessageReplyOption.REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD)
              .setMessage(Message.newBuilder()
                .setText("You said: `" + eventJson.get("message").get("text").asText() + "`")
                .setThread(Thread.newBuilder()
                  .setName(eventJson.get("message").get("thread").get("name").asText())
                  .build()).build()).build();
            break;
          case "REMOVED_FROM_SPACE":
          default:
            // Do nothing
            return;
        }
    
        // Post the response to Google Chat.
        chatServiceClient.createMessage(createMessageRequest);
      }
    }

অ্যাড-অন নয় এমন Chat অ্যাপ কনফিগার করা

  1. Google Cloud Console-এ, মেনু > API ও পরিষেবা > চালু করা API ও পরিষেবা > Google Chat API > কনফিগারেশন বিকল্পে যান।

    কনফিগারেশনে যান

  2. Pub/Sub-এর অ্যাড-অন নয় এমন Chat অ্যাপ কনফিগার করুন:

    1. এই চ্যাট অ্যাপকে Google Workspace অ্যাড-অন হিসেবে তৈরি করো বিকল্পটি বাতিল করো। আপনাকে কনফার্ম করতে বলে একটি ডায়ালগ খুলবে। ডায়ালগে, বন্ধ করুন বিকল্পে ক্লিক করুন।
    2. অ্যাপের নাম বিকল্পে Quickstart App লিখুন।
    3. অবতার URL-এ https://developers.google.com/workspace/chat/images/quickstart-app-avatar.png লিখুন।
    4. বিবরণ বিভাগে, Quickstart app লিখুন।
    5. কার্যকারিতা বিকল্পের মধ্যে, স্পেস ও গ্রুপ কথোপকথনে যোগ দিন বিকল্প বেছে নিন।
    6. কানেকশন সেটিংস বিকল্পের মধ্যে, Cloud Pub/Sub বেছে নিন এবং আগে তৈরি করা Pub/Sub টপিকের নাম পেস্ট করুন।
    7. দৃশ্যমানতা বিকল্পের মধ্যে, আপনার ডোমেনে নির্দিষ্ট লোকজন ও গ্রুপের জন্য এই Google Chat অ্যাপ উপলভ্য করুন বিকল্প বেছে নিন এবং আপনার ইমেল আইডি লিখুন।
    8. লগ বিকল্পের মধ্যে, লগিংয়ে লগ সংক্রান্ত সমস্যা বিকল্প বেছে নিন।
  3. সেভ করুন বিকল্পে ক্লিক করুন।