Google Apps Script

Google Apps Script é uma plataforma de script baseada em nuvem que permite aos usuários automatizar e expandir a funcionalidade de aplicativos do Google Workspace (como Google Sheets, Google Docs, Google Drive, Gmail e mais). Ele usa JavaScript para criar scripts e fluxos de trabalho personalizados que automatizam tarefas repetitivas, integram-se com outros serviços do Google e podem criar interfaces de usuário personalizadas. O Google Apps Script pode ser usado para criar fluxos de trabalho complexos, como gerar relatórios automaticamente, enviar e-mails personalizados, atualizar dados em tempo real ou gerenciar arquivos no Google Drive. É especialmente útil para empresas e indivíduos que desejam aumentar a produtividade e simplificar tarefas sem precisar de conhecimentos extensivos de programação. A plataforma também permite a criação de complementos para personalizar ainda mais os aplicativos do Google Workspace.

Esta é uma coleção de trechos de código que podem ser executados dentro do Google Apps Script. Os trechos são altamente personalizáveis e podem ser muito úteis quando não há infraestrutura de servidor própria disponível.

Google Calendar

Para cada função, o período pode ser ajustado alterando a variável hours. O valor padrão é 96.

Enviar SMS

A função SevenCalendarSMS envia um SMS para cada evento que ocorre no período especificado.

function SevenCalendarSMS() {
    const apiKey = 'IHR_API_SCHLÜSSEL'
    const to = 'INSERT_YOUR_RECIPIENT_OF_CHOICE'
    const toPlaceholder = key => `:${key}:`
    const placeholder_id = toPlaceholder('ID')
    const placeholder_time = toPlaceholder('TIME')
    const placeholder_title = toPlaceholder('TITLE')
    const now = new Date()
    const statusTagKey = 'seven_status_sms'
    const statusTagValue = 'ok'
    const textTemplate = 'Google Calendar informs you about the upcoming event {placeholder_title} with ID {placeholder_id} starting at {placeholder_time}.'
    const calendarName = ''
    const delay = ''
    const flash = false
    const foreign_id = ''
    const from = 'GoogleApps'
    const hours = 96 // hours from now until end date
    const label = ''
    const performance_tracking = false
    const calendar = '' === calendarName ?
        CalendarApp.getDefaultCalendar() :
        CalendarApp.getCalendarsByName(calendarName)

    const events = calendar.getEvents(now, new Date(now.getTime() + (hours * 60 * 60 * 1000)))

    for (const event of events) {
        if (statusTagValue === event.getTag(statusTagKey)) continue

        let text = textVorlage
        Object.entries({
            [placeholder_id]: () => event.getId(),
            [placeholder_time]: () => event.getStartTime(),
            [placeholder_title]: () => event.getTitle()
        }).forEach(([k, v]) => text = text.replace(k, v()))

        const payload = {
            from: from,
            text,
            to
        }
        Object.entries({
            delay,
            flash,
            foreign_id,
            from: from,
            label,
            performance_tracking
        }).forEach(([k, v]) => {
            if (false !== v) {
                if (true === v) payload[k] = '1'
                else if ('' !== v) payload[k] = v
            }
        })

        const response = UrlFetchApp.fetch('https://gateway.seven.io/api/sms', {
            headers: {'X-Api-Key': apiKey},
            method: 'post',
            payload
        }).getContentText()

        if (100 !== Number.parseInt(response))
            throw new Error(`Unexpected status code "${response}".`)

        Logger.log(response)

        event.setTag(statusTagKey, statusTagValue)
    }
}

Chamada de voz

A função SevenCalendarVoice realiza uma chamada de texto para fala para cada evento no período especificado.

function SevenCalendarVoice() {
    const apiKey = 'IHR_API_SCHLÜSSEL'
    const to = 'INSERT_YOUR_RECIPIENT_OF_CHOICE'
    const toPlaceholder = key => `:${key}:`
    const placeholder_id = toPlaceholder('ID')
    const placeholder_time = toPlaceholder('TIME')
    const placeholder_title = toPlaceholder('TITLE')
    const now = new Date()
    const statusTagKey = 'seven_status_voice'
    const statusTagValue = 'ok'
    const textTemplate = 'Google Calendar informs you about the upcoming event {placeholder_title} with ID {placeholder_id} starting at {placeholder_time}.'
    const calendarName = ''
    const from = '+49179876543210'
    const hours = 96 // hours from now until end date
    const calendar = '' === calendarName ?
        CalendarApp.getDefaultCalendar() :
        CalendarApp.getCalendarsByName(calendarName)
    const events = calendar.getEvents(now, new Date(now.getTime() + (hours * 60 * 60 * 1000)))

    for (const event of events) {
        if (statusTagValue === event.getTag(statusTagKey)) continue

        let text = textTemplate
        Object.entries({
            [placeholder_id]: () => event.getId(),
            [placeholder_time]: () => event.getStartTime(),
            [placeholder_title]: () => event.getTitle()
        }).forEach(([k, v]) => text = text.replace(k, v()))

        const payload = {
            from: from,
            text,
            to
        }

        const response = UrlFetchApp.fetch('https://gateway.seven.io/api/voice', {
            headers: {'X-Api-Key': apiKey},
            method: 'post',
            payload
        }).getContentText()

        Logger.log(response)

        const code = response.split('')[0]
        if ('100' !== code) throw new Error(`Unexpected status code "${code}".`)

        event.setTag(statusTagKey, statusTagValue)
    }
}

Contatos do Google

Enviar SMS

A função SevenContactsSMS envia um SMS para todos os seus contatos.

function SevenContactsSMS() {
    const apiKey = 'IHR_API_SCHLÜSSEL'
    const toPlaceholder = key => `:${key}:`
    const placeholder_id = toPlaceholder('ID')
    const placeholder_name = toPlaceholder('FULL_NAME')
    const placeholder_notes = toPlaceholder('NOTES')
    const textTemplate = 'Dear {placeholder_name} our new phone number is +4901234567890. Kind regards Phil from seven!'
    const delay = ''
    const flash = false
    const foreign_id = ''
    const from = 'GoogleApps'
    const label = ''
    const performance_tracking = false

    for (const contact of ContactsApp.getContacts()) {
        const phones = contact.getPhones()
        if (!phones.length) continue

        let text = textTemplate
        Object.entries({
            [placeholder_id]: () => contact.getId(),
            [placeholder_name]: () => contact.getFullName(),
            [placeholder_notes]: () => contact.getNotes()
        }).forEach(([k, v]) => text = text.replace(k, v()))

        const payload = {
            from: from,
            text,
            to: (phones.find(p => p.isPrimary()) || phones.shift()).getPhoneNumber()
        }
        Object.entries({
            delay,
            flash,
            foreign_id,
            from: from,
            label,
            performance_tracking
        }).forEach(([k, v]) => {
            if (false !== v) {
                if (true === v) payload[k] = '1'
                else if ('' !== v) payload[k] = v
            }
        })

        const response = UrlFetchApp.fetch('https://gateway.seven.io/api/sms', {
            headers: {'X-Api-Key': apiKey},
            method: 'post',
            payload
        }).getContentText()

        if (100 !== Number.parseInt(response))
            throw new Error(`Unexpected status code "${response}".`)

        Logger.log(response)
    }
}

Chamada de voz

A função SevenContactsVoice realiza uma chamada de texto para fala para todos os seus contatos.

function SevenContactsVoice() {
    const apiKey = 'IHR_API_SCHLÜSSEL'
    const toPlaceholder = key => `:{key}:`
    const placeholder_id = toPlaceholder('ID')
    const placeholder_name = toPlaceholder('FULL_NAME')
    const placeholder_notes = toPlaceholder('NOTES')
    const textTemplate = `Dear {placeholder_name} our new phone number is +4901234567890. Kind regards Phil from seven!`
    const from = '+49179876543210'

    for (const contact of ContactsApp.getContacts()) {
        const phones = contact.getPhones()
        if (!phones.length) continue

        let text = textTemplate
        Object.entries({
            [placeholder_id]: () => contact.getId(),
            [placeholder_name]: () => contact.getFullName(),
            [placeholder_notes]: () => contact.getNotes()
        }).forEach(([k, v]) => text = text.replace(k, v()))

        const payload = {
            from,
            text,
            to: (phones.find(p => p.isPrimary()) || phones.shift()).getPhoneNumber()
        }

        const response = UrlFetchApp.fetch('https://gateway.seven.io/api/voice', {
            headers: {'X-Api-Key': apiKey},
            method: 'post',
            payload
        }).getContentText()

        Logger.log(response)

        const code = response.split('')[0]
        if ('100' !== code) throw new Error(`Unexpected status code "${code}".`)
    }
}