Skip to content

Commit 2f88f54

Browse files
committed
update Twitch API example
Now uses settings.toml by default, minor Twitch API change to GET follower count. Updated for 8.2.7, untested on 9.0.alpha
1 parent 7f2a608 commit 2f88f54

File tree

1 file changed

+38
-53
lines changed

1 file changed

+38
-53
lines changed

examples/requests_api_twitch.py

Lines changed: 38 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,57 +1,49 @@
1-
# SPDX-FileCopyrightText: 2022 DJDevon3 for Adafruit Industries
1+
# SPDX-FileCopyrightText: 2023 DJDevon3
22
# SPDX-License-Identifier: MIT
3-
# Coded for Circuit Python 8.0
4-
"""DJDevon3 Adafruit Feather ESP32-S2 Twitch_API_Example"""
5-
import gc
3+
# Coded for Circuit Python 8.2.x
4+
# Twitch_API_Example
5+
6+
import os
67
import time
78
import ssl
89
import wifi
910
import socketpool
1011
import adafruit_requests
1112

12-
# Twitch Developer Account & 0Auth App Required:
13+
# Initialize WiFi Pool (There can be only 1 pool & top of script)
14+
pool = socketpool.SocketPool(wifi.radio)
15+
16+
# Twitch Developer Account & oauth App Required:
1317
# Visit https://dev.twitch.tv/console to create an app
14-
# Ensure Twitch_ClientID & Twitch_Client_Secret are in secrets.py or .env
1518

19+
# Ensure these are in secrets.py or settings.toml
1620
# "Twitch_ClientID": "Your Developer APP ID Here",
1721
# "Twitch_Client_Secret": "APP ID secret here",
22+
# "Twitch_UserID": "Your Twitch UserID here",
1823

24+
# Use settings.toml for credentials
25+
ssid = os.getenv("CIRCUITPY_WIFI_SSID")
26+
appw = os.getenv("CIRCUITPY_WIFI_PASSWORD")
27+
twitch_client_id = os.getenv("Twitch_ClientID")
28+
twitch_client_secret = os.getenv("Twitch_Client_Secret")
1929
# For finding your Twitch User ID
2030
# https://www.streamweasels.com/tools/convert-twitch-username-to-user-id/
21-
Twitch_UserID = "0000000" # Set User ID you want endpoints from
22-
23-
# Initialize WiFi Pool (There can be only 1 pool & top of script)
24-
pool = socketpool.SocketPool(wifi.radio)
31+
twitch_user_id = os.getenv("Twitch_UserID") # User ID you want endpoints from
2532

2633
# Time between API refreshes
2734
# 900 = 15 mins, 1800 = 30 mins, 3600 = 1 hour
2835
sleep_time = 900
2936

30-
try:
31-
from secrets import secrets
32-
except ImportError:
33-
print("Secrets File Import Error")
34-
raise
3537

36-
37-
# Converts seconds in minutes/hours/days
38+
# Converts seconds to minutes/hours/days
3839
def time_calc(input_time):
3940
if input_time < 60:
40-
sleep_int = input_time
41-
time_output = f"{sleep_int:.0f} seconds"
42-
elif 60 <= input_time < 3600:
43-
sleep_int = input_time / 60
44-
time_output = f"{sleep_int:.0f} minutes"
45-
elif 3600 <= input_time < 86400:
46-
sleep_int = input_time / 60 / 60
47-
time_output = f"{sleep_int:.0f} hours"
48-
elif 86400 <= input_time < 432000:
49-
sleep_int = input_time / 60 / 60 / 24
50-
time_output = f"{sleep_int:.1f} days"
51-
else: # if > 5 days convert float to int & display whole days
52-
sleep_int = input_time / 60 / 60 / 24
53-
time_output = f"{sleep_int:.0f} days"
54-
return time_output
41+
return f"{input_time:.0f} seconds"
42+
if input_time < 3600:
43+
return f"{input_time / 60:.0f} minutes"
44+
if input_time < 86400:
45+
return f"{input_time / 60 / 60:.0f} hours"
46+
return f"{input_time / 60 / 60 / 24:.1f} days"
5547

5648

5749
# First we use Client ID & Client Secret to create a token with POST
@@ -63,21 +55,20 @@ def time_calc(input_time):
6355
print("\n===============================")
6456
print("Connecting to WiFi...")
6557
requests = adafruit_requests.Session(pool, ssl.create_default_context())
66-
while not wifi.radio.ipv4_address:
58+
while not wifi.radio.connected:
6759
try:
68-
wifi.radio.connect(secrets["ssid"], secrets["password"])
60+
wifi.radio.connect(ssid, appw)
6961
except ConnectionError as e:
7062
print("Connection Error:", e)
7163
print("Retrying in 10 seconds")
7264
time.sleep(10)
73-
gc.collect()
7465
print("Connected!\n")
7566

7667
while True:
7768
try:
7869
# ----------------------------- POST FOR BEARER TOKEN -----------------------
7970
print(
80-
"\nAttempting to GENERATE Twitch Bearer Token!"
71+
"Attempting Bearer Token Request!"
8172
) # ---------------------------------------
8273
# Print Request to Serial
8374
debug_bearer_request = (
@@ -88,9 +79,9 @@ def time_calc(input_time):
8879
print("===============================")
8980
twitch_0auth_data = (
9081
"&client_id="
91-
+ secrets["Twitch_ClientID"]
82+
+ twitch_client_id
9283
+ "&client_secret="
93-
+ secrets["Twitch_Client_Secret"]
84+
+ twitch_client_secret
9485
+ "&grant_type=client_credentials"
9586
)
9687

@@ -113,12 +104,12 @@ def time_calc(input_time):
113104
print("JSON Dump: ", twitch_0auth_json)
114105
print("Header: ", twitch_0auth_header)
115106
print("Access Token: ", twitch_access_token)
107+
twitch_token_type = twitch_0auth_json["token_type"]
108+
print("Token Type: ", twitch_token_type)
116109

110+
print("Board Uptime: ", time_calc(time.monotonic()))
117111
twitch_token_expiration = twitch_0auth_json["expires_in"]
118112
print("Token Expires in: ", time_calc(twitch_token_expiration))
119-
twitch_token_type = twitch_0auth_json["token_type"]
120-
print("Token Type: ", twitch_token_type)
121-
print("Monotonic: ", time.monotonic())
122113

123114
# ----------------------------- GET DATA -------------------------------------
124115
# Bearer token is refreshed every time script runs :)
@@ -128,14 +119,13 @@ def time_calc(input_time):
128119
# ----------------------------------------------------------------------------
129120
twitch_header = {
130121
"Authorization": "Bearer " + twitch_access_token + "",
131-
"Client-Id": "" + secrets["Twitch_ClientID"] + "",
122+
"Client-Id": "" + twitch_client_id + "",
132123
}
133124
TWITCH_FOLLOWERS_SOURCE = (
134-
"https://api.twitch.tv/helix/users"
135-
+ "/follows?"
136-
+ "to_id="
137-
+ Twitch_UserID
138-
+ "&first=1"
125+
"https://api.twitch.tv/helix/channels"
126+
+ "/followers?"
127+
+ "broadcaster_id="
128+
+ twitch_user_id
139129
)
140130
print(
141131
"\nAttempting to GET TWITCH Stats!"
@@ -159,16 +149,11 @@ def time_calc(input_time):
159149
print("Header: ", twitch_header)
160150
print("JSON Full Response: ", twitch_followers_json)
161151

162-
twitch_username = twitch_followers_json["data"][0]["to_name"]
163-
print("Username: ", twitch_username)
164152
twitch_followers = twitch_followers_json["total"]
165153
print("Followers: ", twitch_followers)
166-
print("Monotonic: ", time.monotonic()) # Board Up-Time seconds
167-
168-
print("\nFinished!")
154+
print("Finished!")
169155
print("Next Update in: ", time_calc(sleep_time))
170156
print("===============================")
171-
gc.collect()
172157

173158
except (ValueError, RuntimeError) as e:
174159
print("Failed to get data, retrying\n", e)

0 commit comments

Comments
 (0)