Mesaj oluşturma, okuma, güncelleme ve silme

Koleksiyonlar ile düzeninizi koruyun İçeriği tercihlerinize göre kaydedin ve kategorilere ayırın.

Google Chat API ile, ilgili yöntemleri çağırarak eşzamansız şekilde Google Chat'te mesaj oluşturabilir, okuyabilir, güncelleyebilir veya silebilirsiniz. Bu kılavuzda, aşağıdaki yöntemlerin nasıl çağrılacağı açıklanmaktadır:

Chat uygulamaları, eşzamansız olarak Chat API'yi çağırmadan Chat etkinliklerine (ör. mesajlar ve alana eklenme) yanıt verebilir. Chat etkinliklerine eşzamanlı olarak yanıt veren bir Chat uygulaması oluşturmak için Chat uygulaması oluşturma başlıklı makaleyi inceleyin. Bir Chat uygulaması, Chat API ile eşzamanlı ve eşzamansız olarak çalışabilir.

Chat uygulamasında Chat alanı olmadan eşzamansız olarak mesaj oluşturmak için bir webhook ayarlayın.

Ön koşullar

Bu kılavuzdaki örnekleri çalıştırmak için aşağıdaki ön koşulları sağlamanız gerekir:

Python

Mesaj oluşturun

Google Chat'te eşzamansız olarak mesaj oluşturmak için Message kaynağındaki create yöntemini çağırın. Metin veya kart mesajı oluşturabilirsiniz. Mesaj dizisini başlatmak veya yanıtlamak için threadKey ya da thread.name ifadesini girin.

Oluşturduğunuz bir mesajın name içeriğini not edin. Böylece, daha sonra okumanız, güncellemeniz veya silmeniz gerekirse mesaja başvurabilirsiniz. Alternatif olarak mesajları adlandırabilirsiniz.

Kısa mesaj oluşturma

Metin mesajını nasıl oluşturacağınız aşağıda açıklanmıştır:

Python

  1. Çalışma dizininizde chat_create_text_message.py adlı bir dosya oluşturun.
  2. chat_create_text_message.py uygulamasına aşağıdaki kodu ekleyin:

    from httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
        'service_account.json', SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
    
    # Create a Chat message.
    result = chat.spaces().messages().create(
    
        # The space to create the message in.
        #
        # Replace SPACE with a space name.
        # Obtain the space name from the spaces resource of Chat API,
        # or from a space's URL.
        parent='spaces/SPACE',
    
        # The message to create.
        body={'text': 'Hello, world!'}
    
    ).execute()
    
    print(result)
    
  3. Koddaki SPACE yerine Chat API'sindeki spaces.list() yöntemini veya bir alanın URL'sini kullanarak bir alan adı girin.

  4. Çalışma dizininizde örneği oluşturun ve çalıştırın:

    python3 chat_create_text_message.py
    

Kart mesajı oluşturma

Aşağıda gösterilen şekilde bir kart mesajı oluşturmak için şunları yapın:

Chat REST API ile oluşturulmuş bir kart mesajı.
Şekil 1: Chat API ile oluşturulan bir kart mesajı.

Python

  1. Çalışma dizininizde chat_create_card_message.py adlı bir dosya oluşturun.
  2. chat_create_card_message.py uygulamasına aşağıdaki kodu ekleyin:

    from httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
        'service_account.json', SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
    
    # Create a Chat message.
    result = chat.spaces().messages().create(
    
        # The space to create the message in.
        #
        # Replace SPACE with a space name.
        # Obtain the space name from the spaces resource of Chat API,
        # or from a space's URL.
        parent='spaces/SPACE',
    
        # The message to create.
        body=
        {
          'cardsV2': [{
            'cardId': 'createCardMessage',
            'card': {
              'header': {
                'title': 'A Card Message!',
                'subtitle': 'Created with Chat REST API',
                'imageUrl': 'https://developers.google.com/chat/images/chat-product-icon.png',
                'imageType': 'CIRCLE'
              },
              'sections': [
                {
                  'widgets': [
                    {
                      'buttonList': {
                        'buttons': [
                          {
                            'text': 'Read the docs!',
                            'onClick': {
                              'openLink': {
                                'url': 'https://developers.google.com/chat'
                              }
                            }
                          }
                        ]
                      }
                    }
                  ]
                }
              ]
            }
          }]
        }
    
    ).execute()
    
    print(result)
    
  3. Koddaki SPACE yerine Chat API'sindeki spaces.list() yöntemini veya bir alanın URL'sini kullanarak bir alan adı girin.

  4. Çalışma dizininizde örneği oluşturun ve çalıştırın:

    python3 chat_create_card_message.py
    

Mesaj dizisi başlatma veya yanıtlama

Bir mesaj dizisi başlatmak için bir mesaj oluşturun ve thread.name alanını boş bırakın; Google Chat, mesaj dizisini oluştururken bu alanı dolduracaktır. İsteğe bağlı olarak, mesaj dizisinin adını özelleştirmek için mesaj dizisinin adı olarak thread.threadKey değerini belirtin.

Bir mesaj dizisine yanıt vermek için mesaj dizisinin adı olarak thread.threadKey veya thread.name değerini belirtin. Aynı thread.threadKey veya thread.name etiketine sahip olan sonraki mesajlar yanıtlarla aynı mesaj dizisinde yayınlanır.

Her thread.threadKey, Chat uygulamasına veya uygulamayı ayarlayan webhook'a özeldir. İki farklı uygulama veya webhook aynı thread.threadKey olarak ayarlandıysa iletiler ileti dizisi şeklinde gösterilmez. Bunun yerine iki farklı ileti dizisi başlar. İki farklı uygulama veya webhook, thread.name belirterek aynı ileti dizisinde yanıt yayınlayabilir.

thread.threadKey "nameOfThread" öğesine sahip bir ileti dizisini nasıl başlatacağınız veya yanıtlayacağınız aşağıda açıklanmıştır:

Python

  1. Çalışma dizininizde chat_create_message_thread.py adlı bir dosya oluşturun.
  2. chat_create_message_thread.py uygulamasına aşağıdaki kodu ekleyin:

    from httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
        'service_account.json', SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
    
    # Create a Chat message.
    result = chat.spaces().messages().create(
    
        # The space to create the message in.
        #
        # REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD replies to an existing thread
        # if one exists, otherwise it starts a new one.
        #
        # Replace SPACE with a space name.
        # Obtain the space name from the spaces resource of Chat API,
        # or from a space's URL.
        parent='spaces/SPACE',
    
        # Whether to start a thread or reply to an existing one.
        #
        # Required when threading is enabled in a space unless starting a
        # thread.  Ignored in other space types. Threading is enabled when
        # space.spaceThreadingState is THREADED_MESSAGES.
        messageReplyOption='REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD',
    
        # The message body.
        body={
    
            # The message to create.
            'text': 'Start or reply to another message in a thread!',
    
            # The thread to start or reply to.
            'thread': {
                'threadKey': 'nameOfThread'
            }
        }
    
    ).execute()
    
    print(result)
    
  3. Koddaki SPACE yerine Chat API'sindeki spaces.list() yöntemini veya bir alanın URL'sini kullanarak bir alan adı girin.

  4. Çalışma dizininizde örneği oluşturun ve çalıştırın:

    python3 chat_create_message_thread.py
    

Mesaj oluşturma ve adlandırma

Oluşturulan bir mesaj üzerinde daha sonra yapılacak işlemleri kolaylaştırmak için mesaja özel bir name atayın. Özel bir ad atanması, Chat uygulamasının mesajı oluştururken döndürülen yanıt gövdesinden name mesajı kaydedilmeden mesajı hızlı bir şekilde hatırlamasını sağlar.

Özel bir ad atandığında Chat uygulaması mesajı oluştururken döndürülen yanıt gövdesindeki name mesajını kaydetmeden mesajı hatırlayabilir.

Özel bir ad atanması, oluşturulan name alanının yerini almaz, mesajın kaynak adı. Bunun yerine, özel adı clientAssignedMessageId alanı olarak ayarlar. Bu alan daha sonra mesajı güncelleme veya silme gibi sonraki işlemler sırasında başvuruda bulunulabilir.

İleti oluştururken ikinci el bir özel ad belirtmek hata döndürür ancak update ve delete gibi diğer yöntemler beklendiği gibi çalışır.

Özel ad gereksinimleri:

  • client- ile başlayın. Örneğin, client-custom-name geçerli bir özel ad, ancak custom-name değil.
  • Yalnızca küçük harf, sayı ve kısa çizgi içerebilir.
  • 63 karakterden uzun olmamalıdır.

Mesaj oluşturma ve adlandırma:

Python

  1. Çalışma dizininizde chat_create_named_message.py adlı bir dosya oluşturun.
  2. chat_create_named_message.py uygulamasına aşağıdaki kodu ekleyin:

    from httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
        'service_account.json', SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
    
    # Create a Chat message with a custom name.
    result = chat.spaces().messages().create(
    
        # The space to create the message in.
        #
        # Replace SPACE with a space name.
        # Obtain the space name from the spaces resource of Chat API,
        # or from a space's URL.
        parent='spaces/SPACE',
    
        # Custom name for the message used to facilitate later operations.
        messageId='client-custom-name',
    
        # The message to create.
        body={'text': 'Hello, world!'}
    
    ).execute()
    
    print(result)
    
  3. Koddaki SPACE yerine Chat API'sindeki spaces.list() yöntemini veya bir alanın URL'sini kullanarak bir alan adı girin.

  4. Çalışma dizininizde örneği oluşturun ve çalıştırın:

    python3 chat_create_named_message.py
    

Mesaj okudunuz

Google Chat'te bir mesajı eşzamansız olarak okumak için Message kaynağında get yöntemini çağırın ve okunacak mesajın name değerini iletin.

İletileri nasıl okuyacağınız aşağıda açıklanmıştır:

Python

  1. Çalışma dizininizde chat_read_message.py adlı bir dosya oluşturun.
  2. chat_read_message.py uygulamasına aşağıdaki kodu ekleyin:

    from httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
        'service_account.json', SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
    
    # Get a Chat message.
    result = chat.spaces().messages().get(
    
        # The message to read.
        #
        # Replace SPACE with a space name.
        # Obtain the space name from the spaces resource of Chat API,
        # or from a space's URL.
        #
        # Replace MESSAGE with a message name.
        # Obtain the message name from the response body returned
        # after creating a message asynchronously with Chat REST API.
        name='spaces/SPACE/messages/MESSAGE'
    
      ).execute()
    
    # Print Chat API's response in your command line interface.
    print(result)
    
  3. Koddaki SPACE yerine Chat API'sindeki spaces.list() yöntemini veya bir alanın URL'sini kullanarak bir alan adı girin.

  4. Koddaki MESSAGE yerine, Chat API'yi kullanarak eşzamansız olarak mesaj oluşturduktan sonra döndürülen yanıt gövdesinden veya mesaj oluşturulurken atanan özel addan aldığınız mesaj adını yazın.

  5. Çalışma dizininizde örneği oluşturun ve çalıştırın:

    python3 chat_read_message.py
    

Mesaj güncelleme

Google Chat'te mevcut bir mesajı eşzamansız olarak güncellemek için Message kaynağında update yöntemini çağırın ve güncellenecek mesajın name değerini, ayrıca güncellenen mesajı belirten bir updateMask ve body değeri iletin.

Kısa mesajı güncelleme veya kart mesajının başına kısa mesaj ekleme

Bir kısa mesaj mesajını güncellemek için mesajı iletin:

  • Güncellenecek mesajın name.
  • updateMask='text'
  • Güncellenmiş mesajı belirten body.

Güncellenen mesaj bir kart mesajıysa kısa mesajın başında kart mesajı (gösterilmeye devam eder) bulunur.

Kısa mesajın mesajını kısa mesajla güncellemek veya kısa mesajın başına kart eklemek için:

Python

  1. Çalışma dizininizde chat_update_text_message.py adlı bir dosya oluşturun.
  2. chat_update_text_message.py uygulamasına aşağıdaki kodu ekleyin:

    from httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
      'service_account.json', SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
    
    # Update a Chat message.
    result = chat.spaces().messages().update(
    
      # The message to update, and the updated message.
      #
      # Replace SPACE with a space name.
      # Obtain the space name from the spaces resource of Chat API,
      # or from a space's URL.
      #
      # Replace MESSAGE with a message name.
      # Obtain the message name from the response body returned
      # after creating a message asynchronously with Chat REST API.
      name='spaces/SPACE/messages/MESSAGE',
      updateMask='text',
      body={'text': 'Updated message!'}
    
    ).execute()
    
    # Print Chat API's response in your command line interface.
    print(result)
    
  3. Koddaki SPACE yerine Chat API'sindeki spaces.list() yöntemini veya bir alanın URL'sini kullanarak bir alan adı girin.

  4. Koddaki MESSAGE yerine, Chat API'yi kullanarak eşzamansız olarak mesaj oluşturduktan sonra döndürülen yanıt gövdesinden veya mesaj oluşturulurken atanan özel addan aldığınız mesaj adını yazın.

  5. Çalışma dizininizde örneği oluşturun ve çalıştırın:

    python3 chat_update_text_message.py
    

Kart mesajını güncelleme veya kısa mesaja kart mesajı ekleme

Bir kart mesajını güncellemek için aşağıdakileri iletin:

  • Güncellenecek mesajın name
  • updateMask='cardsV2'
  • Güncellenmiş mesajı belirten body.

Güncellenen mesaj bir kısa mesaj ise kısa mesaja bir kart eklenir (gösterilmeye devam eder). Güncellenen mesajın kendisi bir kart ise gösterilen kart güncellenir.

Bir mesajı, card mesajı olarak güncellemek için:

Python

  1. Çalışma dizininizde chat_update_card_message.py adlı bir dosya oluşturun.
  2. chat_update_card_message.py uygulamasına aşağıdaki kodu ekleyin:

    from httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
      'service_account.json', SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
    
    # Update a Chat message.
    result = chat.spaces().messages().update(
    
      # The message to update, and the updated message.
      #
      # Replace SPACE with a space name.
      # Obtain the space name from the spaces resource of Chat API,
      # or from a space's URL.
      #
      # Replace MESSAGE with a message name.
      # Obtain the message name from the response body returned
      # after creating a message asynchronously with Chat REST API.
      name='spaces/SPACE/messages/MESSAGE',
      updateMask='cardsV2',
      body=
      {
        'cardsV2': [{
          'cardId': 'updateCardMessage',
          'card': {
            'header': {
              'title': 'An Updated Card Message!',
              'subtitle': 'Updated with Chat REST API',
              'imageUrl': 'https://developers.google.com/chat/images/chat-product-icon.png',
              'imageType': 'CIRCLE'
            },
            'sections': [
              {
                'widgets': [
                  {
                    'buttonList': {
                      'buttons': [
                        {
                          'text': 'Read the docs!',
                          'onClick': {
                            'openLink': {
                              'url': 'https://developers.google.com/chat'
                            }
                          }
                        }
                      ]
                    }
                  }
                ]
              }
            ]
          }
        }]
      }
    
    ).execute()
    
    # Print Chat API's response in your command line interface.
    print(result)
    
  3. Koddaki SPACE yerine Chat API'sindeki spaces.list() yöntemini veya bir alanın URL'sini kullanarak bir alan adı girin.

  4. Koddaki MESSAGE yerine, Chat API'yi kullanarak eşzamansız olarak mesaj oluşturduktan sonra döndürülen yanıt gövdesinden veya mesaj oluşturulurken atanan özel addan aldığınız mesaj adını yazın.

  5. Çalışma dizininizde örneği oluşturun ve çalıştırın:

    python3 chat_update_card_message.py
    

Mesajı silme

Google Chat'te mevcut bir mesajı eşzamansız olarak silmek için Message kaynağında delete yöntemini çağırın ve silinecek mesajın name değerini iletin.

Mesajları şu şekilde silebilirsiniz:

Python

  1. Çalışma dizininizde chat_delete_message.py adlı bir dosya oluşturun.
  2. chat_delete_message.py uygulamasına aşağıdaki kodu ekleyin:

    from httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
      'service_account.json', SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
    
    # Delete a Chat message.
    result = chat.spaces().messages().delete(
    
      # The message to delete.
      #
      # Replace SPACE with a space name.
      # Obtain the space name from the spaces resource of Chat API,
      # or from a space's URL.
      #
      # Replace MESSAGE with a message name.
      # Obtain the message name from the response body returned
      # after creating a message asynchronously with Chat REST API.
      name='spaces/SPACE/messages/MESSAGE'
    
    ).execute()
    
    # Print Chat API's response in your command line interface.
    # When deleting a message, the response body is empty.
    print(result)
    
  3. Koddaki SPACE yerine Chat API'sindeki spaces.list() yöntemini veya bir alanın URL'sini kullanarak bir alan adı girin.

  4. Koddaki MESSAGE yerine, Chat API'yi kullanarak eşzamansız olarak mesaj oluşturduktan sonra döndürülen yanıt gövdesinden veya mesaj oluşturulurken atanan özel addan aldığınız mesaj adını yazın.

  5. Çalışma dizininizde örneği oluşturun ve çalıştırın:

    python3 chat_delete_message.py
    

Sınırlar ve dikkat edilmesi gereken noktalar

  • Google Chat'te bir mesajın name değerini almanın tek yolu, mesajı oluştururken verilen yanıt gövdesidir. Oluşturduğunuz bir mesajı daha sonra okumanız, güncellemeniz veya silmeniz gerekiyorsa bu mesaja referans verebilmek için name notlarını not etmeyi unutmayın. Alternatif olarak mesajları adlandırabilirsiniz.
  • Bir hizmet hesabıyla uygulama olarak kimlik doğrulama yapılırken Chat uygulamaları yalnızca kendi mesajlarını okuyabilir, güncelleyebilir ve silebilir.
  • Geliştirici Önizlemesi: Bir uygulama kullanıcı kimlik doğrulaması ile işlem gerçekleştirdiğinde, Google Chat kullanıcılara yetkilendirilen kullanıcı adına işlemi gerçekleştiren uygulamanın adını bildiren bir ilişkilendirme mesajı görüntüleyebilir.