tanaike - Google Apps Script, Gemini API, and Developer Tips

The Thinker

Copying and Overwriting GAS Project

Gists

Pattern 1

This is a sample script for copying GAS project to a container-bound script of Google Docs (Spreadsheet, Document and Form (and Slides)). The project is created as a new project.

In order to use this sample, please do the following installation flow.

If you use this sample script, at first, please test using a new project and new Google Docs. By this, please understand the work of this script.

Batching Requests for Google Apps Script

Gists

There is the bathing requests in the Google APIs. The bathing requests can use the several API calls as a single HTTP request. By using this, for example, users can modify filenames of a lot of files on Google Drive. But there are limitations for the number of API calls which can process in one batch request. For example, Drive API can be used the maximum of 100 calls in one batch request.

Zaif API for Google Apps Script

Gists

This sample script is for using Zaif API by Google Apps Script.

The following go script is a sample at Zaif API.

package main

import (
    "fmt"
    "time"
    "strconv"
    "crypto/hmac"
    "crypto/sha512"
    "io/ioutil"
    "net/http"
    "encoding/hex"
    "net/url"
    "strings"
)

var key = "<your_key>"
var secret = "<your_secret>"

func main() {

    uri := "https://api.zaif.jp/tapi"
    values := url.Values{}
    values.Add("method", "get_info")
    values.Add("nonce", strconv.FormatInt(time.Now().Unix(), 10))

    encodedParams := values.Encode()
    req, _ := http.NewRequest("POST", uri, strings.NewReader(encodedParams))

    hash := hmac.New(sha512.New, []byte(secret))
    hash.Write([]byte(encodedParams))
    signature := hex.EncodeToString(hash.Sum(nil))

    req.Header.Add("Key", key)
    req.Header.Add("Sign", signature)
    client := new(http.Client)
    resp, _ := client.Do(req)
    defer resp.Body.Close()

    byteArray, _ := ioutil.ReadAll(resp.Body)
    fmt.Println(string(byteArray))
}

When this is converted to GAS, the script is as follows.

Bittrex API for Google Apps Script

Gists

This sample script is for using Bittrex API by Google Apps Script.

The following PHP script is a sample at bittrex.com.

$apikey='xxx';
$apisecret='xxx';
$nonce=time();
$uri='https://bittrex.com/api/v1.1/market/getopenorders?apikey='.$apikey.'&nonce='.$nonce;
$sign=hash_hmac('sha512',$uri,$apisecret);
$ch = curl_init($uri);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('apisign:'.$sign));
$execResult = curl_exec($ch);
$obj = json_decode($execResult);

When this is converted to GAS, the script is as follows.

function main() {
  var apikey = '#####'; // Please input your key.
  var apisecret = '#####'; // Please input your secret.

  var nonce = Number(new Date().getTime() / 1000).toFixed(0);
  var uri = 'https://bittrex.com/api/v1.1/market/getopenorders?apikey=' + apikey + '&nonce=' + nonce;
  var sign = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512, uri, apisecret);
  sign = sign.map(function(e) {return ("0" + (e < 0 ? e + 256 : e).toString(16)).slice(-2);}).join("");
  var params = {
    method: "get",
    headers: {Apisign: sign}
  }
  var res = UrlFetchApp.fetch(uri, params);
  Logger.log(res.getContentText())
}

Binance API for Google Apps Script

Gists

This sample script is for using Binance API by Google Apps Script. This script encryptes “signature” like samples. In this script, “Example 1: As a query string” is used, and it retrieves “All orders (SIGNED)” by “GET”.

function main() {
    var key = '#####'; // Please input your key.
    var secret = '#####'; // Please input your secret.
    var api = "/api/v3/allOrders"; // Please input API Endpoint you want.
    var timestamp = Number(new Date().getTime()).toFixed(0);
    var string = "symbol=LTCBTC&timestamp=" + timestamp; // Please input query parameters for the inputterd API.

    var baseUrl = "https://api.binance.com";
    var signature = Utilities.computeHmacSha256Signature(string, secret);
    signature = signature.map(function(e) {
        var v = (e < 0 ? e + 256 : e).toString(16);
        return v.length == 1 ? "0" + v : v;
    }).join("");
    var query = "?" + string + "&signature=" + signature;
    var params = {
        'method': 'get',
        'headers': {'X-MBX-APIKEY': key},
        'muteHttpExceptions': true
    };
    var data = UrlFetchApp.fetch(baseUrl + api + query, params);
    Logger.log(data.getContentText())
}

CLI Tool - goodls

Overview

This is a CLI tool to download shared files from Google Drive.

Description

We have already known that the shared files on Google Drive can be downloaded without the authorization. But when the size of file becomes large (about 40MB), it requires a little ingenuity to download the file. It requires to access 2 times to Google Drive. At 1st access, it retrieves a cookie and a code for downloading. At 2nd access, the file is downloaded using the cookie and code. I created this process as a CLI tool. This tool has the following features.

Send mails from Gmail using Nodemailer

Gists

This is a sample script for sending e-mails from gmail using Nodemailer. In order to use this, please retrieve the folloing parameters before run this script.

  1. gmail address
  2. client ID
  3. client Secret
  4. Refresh token
    • Please include https://mail.google.com/ in the scope.
  5. Enable gmail API at API console.
  6. Install Nodemailer
const nodemailer = require('nodemailer');

var auth = {
    type: 'oauth2',
    user: '### your gmail address ###',
    clientId: '### client ID ###',
    clientSecret: '### client secret ###',
    refreshToken: '### refresh token ###',
};

var mailOptions = {
    from: '#####',
    to: '#####',
    subject: 'sample subject',
    text: 'sample text',
    html: '<b>sample html</b>',
};

var transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: auth,
});

transporter.sendMail(mailOptions, (err, res) => {
    if (err) {
        return console.log(err);
    } else {
        console.log(JSON.stringify(res));
    }
});

Reference :

Add-on - ShapeApp

ShapeApp for Google Slides was published as an add-on application

When you use Google Slides, have you ever thought about creating and updating shapes on Slides by inputting parameters, and arranging selected shapes? I have thought about them. Recently, since Class SlidesApp was added to GAS, it came to be able to easily to create various applications for Slides. So I created this. This application is add-on application which was made of GAS.

Which of Drive API v2 or v3 is used for DriveApp.searchFiles()

Gists

Experiment

It has investigated the differences between the documents of “Search for Files” for v2 and v3. The following table shows the comparison of v2 and v3 for “Valid fields for files.list”. The column of DriveApp.searchFiles() means whether the query can be used for DriveApp.searchFiles().

v2 v3 Difference DriveApp.searchFiles()
title name different v2: succeed, v3: fail
fullText fullText same
mimeType mimeType same
modifiedDate modifiedTime same
lastViewedByMeDate viewedByMeTime different v2: succeed, v3: fail
trashed trashed same
starred starred same
parents parents same
owners owners same
writers writers same
readers readers same
sharedWithMe sharedWithMe same
properties properties same
properties with visibility=‘PRIVATE’ appProperties different v2: succeed, v3: fail
visibility visibility same

Result

As the result, it is considered that DriveApp.searchFiles() is used as Drive API v2 yet.