RubyでTwitchAPIをOAuth認証して叩くスクリプト
最近TwitchAPIがOAth認証してないと401を返すようになった
どうやら2020/5/12頃にアプデがあったようだ
https://discuss.dev.twitch.tv/t/requiring-oauth-for-helix-twitch-api-endpoints/23916
https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#oauth-client-credentials-flow
色々調べてRubyでクライエントIDとクライエントシークレット(ダッシュボードではクライアントの秘密という)でOAuth認証する「OAuth client credentials flow」に従って回収した。
もしはじめてAPIを叩く実装するなら、あらかじめhttps://dev.twitch.tv/でアプリケーション登録してクライエントIDとクライエントシークレットを取得してね
require 'net/http'
require 'json'
require 'uri'
// https://dev.twitch.tv/console/apps で取得する「クライアントID」と「クライアントの秘密」
client_id = "xxxxxxxxxxclient_idxxxxxxxxxxxxxxxx"
client_secret = "xxxxxxxxxclient_secretxxxxxxxxxxxxx"
// 配信を調べたいTwitchのユーザー名
twitch_id = "ink_kasekai"
// アクセストークンの取得
uri = URI.parse("https://id.twitch.tv/oauth2/token?client_id=#{client_id}&client_secret=#{client_secret}&grant_type=client_credentials")
response = Net::HTTP.post_form(uri ,{})
p response.code # status code
res_json = JSON.parse(response.body)// アクセストークンを取得できた
access_token = res_json['access_token']
// アクセストークンを使ってAPI叩いてTwitchユーザー名からTwitchユーザーIDを取得
url = "https://api.twitch.tv/helix/users?login=#{twitch_id}"
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = uri.scheme === "https"
headers = { "Content-Type" => "application/json", "Client-ID" => client_id, "Authorization" => "Bearer #{access_token}"}
response = http.get(uri, headers)
res_json = JSON.parse(response.body)//ユーザーID取得できた
user_id = res_json["data"][0]["id"]
// アクセストークンを使ってAPI叩いてTwitchユーザーIDから配信情報を取得
url = "https://api.twitch.tv/helix/streams?user_id=#{user_id}"
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = uri.scheme === "https"
headers = { "Content-Type" => "application/json", "Client-ID" => client_id, "Authorization" => "Bearer #{access_token}" }
response = http.get(uri, headers)
res_json = JSON.parse(response.body)// 配信所法取得できた
p res_json['data']
配信してたらデータに中身ある。中身が空なら配信してない
だいたいこんなかんじ
エミリコはかわいいわね