LoginSignup
8

More than 5 years have passed since last update.

仮想通貨取引所のAPIを叩いてGoogle Spread Sheetに反映する

Last updated at Posted at 2018-01-08

みなさんこんにちは、ゆりなです╰(´︶`)╯♡

Cryptopiaという取引所のAPIを叩いて仮想通貨の一覧を取得して、Google Spread Sheetに反映する方法を書きますよー!

認証情報の取得

まずはこちらを参考に設定を行ってください!

client_secret.jsonをDLして、google-api-clientをインストール出来たら オッケー です٩( 'ω' )و

スプレッドシート作成

通貨一覧を反映するためのスプレッドシートを作成してください! 
作成後URLのspreadsheet_idを控えてください╰(´︶`)╯♡
https://docs.google.com/spreadsheets/d/ 1MNX3EHGmf3SPDA-GixWcrTPY1yO3nDnk-SqBq488VHA /edit

コードを書こう!

先ほどDLした client_secret.json は同じ階層に持ってきてくださいね!
まだエラーハンドリングなどはしっかり出来ていないのでご了承ください:;(∩´﹏`∩);:

index.rb
require 'google/apis/sheets_v4'
require 'googleauth'
require 'googleauth/stores/file_token_store'
require 'fileutils'
require 'faraday'
require 'json'
require './parse.rb'
require './api.rb'
require './authorization.rb'
require './http_client.rb'
include API
include Parse
include Authorization
include Client

APPLICATION_NAME = 'CryptoCurrency Hack Sheet'
OBJECT_COUNT = 500

service = Google::Apis::SheetsV4::SheetsService.new
service.client_options.application_name = APPLICATION_NAME
service.authorization = Authorization.new
# Prints the names and majors of students in a sample spreadsheet:
# https://docs.google.com/spreadsheets/d/1MNX3EHGmf3SPDA-GixWcrTPY1yO3nDnk-SqBq488VHA/edit
spreadsheet_id = '1MNX3EHGmf3SPDA-GixWcrTPY1yO3nDnk-SqBq488VHA' #先ほどのspreadsheet_idに置き換えてくださいね!

cryptopia_client = Client.new(API::CRYPTOPIA::BASE)
cryptopia_res = cryptopia_client.get API::CRYPTOPIA::GET_ALL_CURRENCIES
results = JSON.parse(cryptopia_res.body)
rows = Parse.cryptopia_get_currencies(results)

requests = []
rows.each_slice(OBJECT_COUNT) do |row|
  requests.push({
    update_cells: {
      start: {sheet_id: 0, row_index: 2, column_index: 0},
      rows: row[0],
      fields: 'userEnteredValue'
    }
  })
  batch_update_request = {requests: requests}
  service.batch_update_spreadsheet(spreadsheet_id, batch_update_request, {})
end
authorization.rb
module Authorization
  OOB_URI = 'urn:ietf:wg:oauth:2.0:oob'
  CLIENT_SECRETS_PATH = 'client_secret.json'
  CREDENTIALS_PATH = File.join(Dir.home, '.credentials', "cryptocurrency_hack_sheet.yaml")
  SCOPE = Google::Apis::SheetsV4::AUTH_SPREADSHEETS

  def new
    FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))

    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 = 'default'
    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
  module_function :new
end
api.rb
module API
  module CRYPTOPIA
    BASE = 'https://www.cryptopia.co.nz/api'
    GET_ALL_CURRENCIES = BASE + '/GetCurrencies'
  end
end
http_client.rb
module Client
  def new(url)
    client = HTTPClient.new
    client.debug_dev = $stderr
    Faraday.new(:url => url) do |faraday|
      faraday.request  :url_encoded
      faraday.response :logger
      faraday.adapter  Faraday.default_adapter
    end
  end
  module_function :new
end
parse.rb
module Parse
  def cryptopia_get_currencies(results)
    values = []
    rows   = []
    results["Data"].each do |item|
      values.push(
        {
          values: [
            {
              user_entered_value: {number_value: item["Id"]}
            },
            {
              user_entered_value: {string_value: item["Name"]}
            },
            {
              user_entered_value: {string_value: item["Symbol"]}
            },
            {
              user_entered_value: {string_value: item["Algorithm"]}
            },
            {
              user_entered_value: {number_value: item["WithdrawFee"]}
            },
            {
              user_entered_value: {number_value: item["MinWithdraw"]}
            },
            {
              user_entered_value: {number_value: item["MaxWithdraw"]}
            },
            {
              user_entered_value: {number_value: item["MinBaseTrade"]}
            },
            {
              user_entered_value: {number_value: item["DepositConfirmations"]}
            },
            {
              user_entered_value: {string_value: item["ListingStatus"]}
            },
            {
              user_entered_value: {string_value: item["Status"]}
            },
            {
              user_entered_value: {string_value: item["StatusMessage"]}
            }
          ]
        }
      )
    end
    rows.push(values)
  end
  module_function :cryptopia_get_currencies
end

これらを書きましたら、実行してみましょう!٩( 'ω' )و

ruby index.rb

すると、URL開いてね!とURLが出てくるなので、開いて表示されたコードをコンソール上に貼り付けてください!
これで認証が完了し、スプレッドシート上に取得したデータが反映されます╰(´︶`)╯♡

実際のコードはGithubに載せていますので、参考にしてくださいね!
https://github.com/cryptyurina/cryptocurrency_hack_sheet

こちらは随時アップデートしていくので、上記のコードは変更になっている可能性があります!
もし上記時点のコードをみたければこちらのコミットを参考にしてください╰(´︶`)╯♡

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8