DEV Community

Cover image for Tasting Groogle
Jorge
Jorge

Posted on

Tasting Groogle

As we saw in previous post, Groogle is an DSL oriented to interact with Google services. You can include it as a dependency lib and/or writing Groovy Scripts

In this post we'll taste how the DSL looks with an example. In this example we'll read a GoogleSheet cell and send and email to a friend using this value

Requirements

As specified in previous post you need to have a Java JDK installed (>11) as Groovy 4.x (you can use sdkman to install both of them)

Also you need to have downloaded a credentials file (client_secret.json in this example) and enable Sheet and Gmail APIs from Google Cloud console

Sheet

Create a Google Sheet and write some value in cell A1

The ID of this Sheet is in the URL : https://docs.google.com/spreadsheets/d/[THE_ID_OF_THE_SHEET]

You can change also the name of the tab, for example "Todo"

Script

Create a text file:

import com.google.api.services.gmail.GmailScopes
import com.google.api.services.sheets.v4.SheetsScopes
import es.edn.groogle.*

@Grab("es.edn:groogle:4.0.0-rc6") 
@GrabConfig(systemClassLoader=true)

groogle = GroogleBuilder.build {
    withOAuthCredentials {
        applicationName 'test-gmail-sheet'
        scopes GmailScopes.MAIL_GOOGLE_COM, SheetsScopes.SPREADSHEETS
        usingCredentials "client_secret.json"
        storeCredentials true
    }
}

groogle.with{

  service(SheetService).with {
        // REPLACE WITH THE ID OF THE SHEET
        withSpreadSheet "THE-ID-OF-THE-SHEET", {

            // REPLACE WITH THE NAME OF THE TAB
            withSheet "Todo", {

                def message = """Hi
                this is the status of the task 
                $A1
                """.strip()

                service(GmailService).with {
                    sendEmail {
                        from "me"
                        to "myfriend@email.com"
                        subject "Testing Groogle"
                        body message
                    }
                }
            }
        }
   }
}
Enter fullscreen mode Exit fullscreen mode

Run the script with groovy myscript.groovy and if all goes well you'll send an email to your friend using the value of the cell A1

Explanation

In the first part of the script we're configuring Groogle setting the scopes we'll need, specifying the credentials and so on

In the second part we're using 2 of the services provided by Groogle: SheetService and GmailService

SheetService allows to us to open a Sheet and read/write cells. Did you see how we use "$A1" in the multiline String?

GmailService allows to us send an email to someone using our account. Only need to use the sendMail closure, specifying the details of the email and the service will send it.

Top comments (0)