Skip to content

Instantly share code, notes, and snippets.

@cschell
Last active February 11, 2019 19:19
Show Gist options
  • Save cschell/fc7d7c5f160e141cc8a355e11057a91c to your computer and use it in GitHub Desktop.
Save cschell/fc7d7c5f160e141cc8a355e11057a91c to your computer and use it in GitHub Desktop.
This script queries the RIOT-API for the last game of a summoner
# Usage: ruby last_game.rb <summoner_name> <na/euw/...>
require "net/http"
require "json"
require "date"
# TODO: Insert your own key here!
API_KEY = "<YOUR-RIOT-API-KEY-HERE>"
@summoner_name = ARGV[0]
@region = ARGV[1] || "euw"
class Summoner < Struct.new(:name, :region)
def summoner_id
standardized_summoner_name = name.downcase.gsub(" ", "")
@summoner_id ||= get_from_api("/api/lol/#{region}/v1.4/summoner/by-name/#{standardized_summoner_name}")
.fetch(standardized_summoner_name)
.fetch("id")
end
def recent_game
@recent_game ||= get_from_api("/api/lol/#{region}/v1.3/game/by-summoner/#{summoner_id}/recent")["games"].first
end
def print_recent_game_info
infos = {
date: Time.at(recent_game["createDate"] / 1000)
.strftime("%Y-%m-%d (%H:%M)"),
summoner: name,
outcome: recent_game["stats"]["win"] ? "won" : "lost",
game_type: recent_game["subType"],
game_mode: recent_game["gameMode"]
}
p "On %{date} %{summoner} %{outcome} his last game, " \
"which was a %{game_type} (%{game_mode})" % infos
end
private
def get_from_api(path)
uri = URI(URI.join("https://#{region}.api.pvp.net", path) + "?api_key=#{API_KEY}")
http = Net::HTTP.new(uri.hostname, uri.port)
http.use_ssl = true
response = http.request(Net::HTTP::Get.new(uri, _header = {'Content-Type' =>'application/json'}))
case response
when Net::HTTPSuccess
return JSON.parse(response.body)
when Net::HTTPNotFound
raise "Couldn't find the record, maybe you misspelled something?"
else
raise "An error occurred while processing #{path}
Response #{response.code} #{response.message}:
#{response.body}"
end
end
end
summoner = Summoner.new(@summoner_name, @region)
summoner.print_recent_game_info
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment