Created
December 13, 2019 18:31
-
-
Save clairegraham/03370414189d9785821126dbcb678a07 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'google/apis/script_v1' | |
require 'googleauth' | |
require 'googleauth/stores/file_token_store' | |
require 'fileutils' | |
OOB_URI = 'urn:ietf:wg:oauth:2.0:oob' | |
APPLICATION_NAME = 'Append Row to Spreadsheet' | |
CLIENT_SECRETS_PATH = File.join(Dir.home, '.google-oauth.json') | |
CREDENTIALS_PATH = File.join(Dir.home, '.google-oauth.yml') | |
SCRIPT_ID = 'SCRIPT_ID_GOES_HERE' | |
SCOPE = 'https://www.googleapis.com/auth/spreadsheets' | |
server = ARGV[0] | |
domain = ARGV[1] | |
user = ARGV[2] | |
owner = ARGV[3] | |
suspended_at = ARGV[4] | |
if server.nil? or domain.nil? or user.nil? or owner.nil? or suspended_at.nil? | |
puts "You must fill in all fields.\n\nUsage: ./add_to_spreadsheet.rb [server] [domain] [user] [owner] [suspended_at]" | |
exit 1 | |
end | |
def authorize | |
client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH) | |
token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH) | |
authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store) | |
user_id = '[email protected]' | |
credentials = authorizer.get_credentials(user_id) | |
if credentials.nil? | |
url = authorizer.get_authorization_url( | |
base_url: OOB_URI) | |
puts "Open the following URL in the browser and enter the " + | |
"resulting code after authorization" | |
puts url | |
code = gets | |
credentials = authorizer.get_and_store_credentials_from_code( | |
user_id: user_id, code: code, base_url: OOB_URI) | |
end | |
credentials | |
end | |
service = Google::Apis::ScriptV1::ScriptService.new | |
service.client_options.application_name = APPLICATION_NAME | |
service.authorization = authorize | |
request = Google::Apis::ScriptV1::ExecutionRequest.new( | |
function: 'addEntryToSpreadsheet', | |
parameters: [[server, domain, user, owner, suspended_at]] | |
) | |
begin | |
resp = service.run_script(SCRIPT_ID, request) | |
if resp.error | |
puts "error! #{resp.error.inspect}" | |
else | |
puts "success!" | |
end | |
rescue Google::Apis::ClientError => e | |
puts "Error calling API! => #{e}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment