Search code examples
rubygoogle-cloud-platformgoogle-apigoogle-hangoutsgoogle-chat

How to create and send a google chat message with Ruby


In my rails application, I am trying to create and send a google chat message using the api method spaces.messages.create as explained in this documentation. To do that, I will have to authenticate with a service account. I cant find examples on how to do this with ruby in reference to google chat. It seems like I will have to use the ruby cloud sdk but I cant find any reference to google chat here . Instead of using the google cloud sdk, is it possible to do this with a ruby http client?

I will like to know how to authenticate using a service account and sending a message to google chat using the api method spaces.messages.create


Solution

  • I think the steps are as follows:

    1. Create a service account in order to use the https://www.googleapis.com/auth/chat.bot scope.

    Only supports service accounts. You can't authenticate user credentials using this scope.

    1. Use the Service Account Auth Flow within googleauth.
    scope = 'https://www.googleapis.com/auth/androidpublisher'
    
    authorizer = Google::Auth::ServiceAccountCredentials.make_creds(
      json_key_io: File.open('/path/to/service_account_json_key.json'),
      scope: scope)
    
    authorizer.fetch_access_token!
    

    3- Use the google-apis-chat_v1 for performing the request.

    In any case, I strongly review the documentation for Google Chats API, for a full understanding on how the authorization flow works.

    Updated

    Sample ruby client send message
    require 'googleauth'
    require 'googleauth/stores/file_token_store'
    require 'google/apis/chat_v1'
    
    scope = 'https://www.googleapis.com/auth/chat.bot'
    
    authorizer = Google::Auth::ServiceAccountCredentials.make_creds(
      json_key_io: File.open('./credentials.json'),
      scope: scope)
    
    
    chat =  Google::Apis::ChatV1::HangoutsChatService.new
    msg = Google::Apis::ChatV1::Message.new(text: 'test')
    
    chat.authorization = Google::Auth::ServiceAccountCredentials.make_creds(
      json_key_io: File.open('./credentials.json'),
      scope: scope)
      
      
    chat.create_space_message('spaces/XXXXXXXX', msg)