summaryrefslogtreecommitdiff
path: root/src/twitcr/rest.cr
diff options
context:
space:
mode:
Diffstat (limited to 'src/twitcr/rest.cr')
-rw-r--r--src/twitcr/rest.cr22
1 files changed, 21 insertions, 1 deletions
diff --git a/src/twitcr/rest.cr b/src/twitcr/rest.cr
index 1de8d6f..cb2c1a0 100644
--- a/src/twitcr/rest.cr
+++ b/src/twitcr/rest.cr
@@ -11,7 +11,9 @@ module Twitcr::REST
# Executes an HTTP request against the API_BASE url
def request(method : String, route : String, version = "5", headers = HTTP::Headers.new, body : String? = nil)
- headers["Authorization"] = @token
+ get_token unless @token
+
+ headers["Authorization"] = @token || "test"
headers["Client-ID"] = @client_id
response = HTTP::Client.exec(
@@ -21,6 +23,12 @@ module Twitcr::REST
tls: SSL_CONTEXT
)
+ if response.status_code == 401
+ get_token
+ puts "Had to get new token"
+ return request(method, route, version, headers, body)
+ end
+
response.body
end
@@ -47,4 +55,16 @@ module Twitcr::REST
list.data.first
end
+
+ def get_token
+ response = HTTP::Client.exec(
+ "POST",
+ "https://id.twitch.tv/oauth2/token?client_id=#{@client_id}&client_secret=#{@client_secret}&grant_type=client_credentials",
+ tls: SSL_CONTEXT
+ )
+
+ access_token = Token.from_json(response.body).access_token
+
+ @token = "Bearer #{access_token}"
+ end
end