1
- # SPDX-FileCopyrightText: 2022 DJDevon3 for Adafruit Industries
1
+ # SPDX-FileCopyrightText: 2023 DJDevon3
2
2
# 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
6
7
import time
7
8
import ssl
8
9
import wifi
9
10
import socketpool
10
11
import adafruit_requests
11
12
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:
13
17
# Visit https://dev.twitch.tv/console to create an app
14
- # Ensure Twitch_ClientID & Twitch_Client_Secret are in secrets.py or .env
15
18
19
+ # Ensure these are in secrets.py or settings.toml
16
20
# "Twitch_ClientID": "Your Developer APP ID Here",
17
21
# "Twitch_Client_Secret": "APP ID secret here",
22
+ # "Twitch_UserID": "Your Twitch UserID here",
18
23
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" )
19
29
# For finding your Twitch User ID
20
30
# 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
25
32
26
33
# Time between API refreshes
27
34
# 900 = 15 mins, 1800 = 30 mins, 3600 = 1 hour
28
35
sleep_time = 900
29
36
30
- try :
31
- from secrets import secrets
32
- except ImportError :
33
- print ("Secrets File Import Error" )
34
- raise
35
37
36
-
37
- # Converts seconds in minutes/hours/days
38
+ # Converts seconds to minutes/hours/days
38
39
def time_calc (input_time ):
39
40
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"
55
47
56
48
57
49
# First we use Client ID & Client Secret to create a token with POST
@@ -63,21 +55,20 @@ def time_calc(input_time):
63
55
print ("\n ===============================" )
64
56
print ("Connecting to WiFi..." )
65
57
requests = adafruit_requests .Session (pool , ssl .create_default_context ())
66
- while not wifi .radio .ipv4_address :
58
+ while not wifi .radio .connected :
67
59
try :
68
- wifi .radio .connect (secrets [ " ssid" ], secrets [ "password" ] )
60
+ wifi .radio .connect (ssid , appw )
69
61
except ConnectionError as e :
70
62
print ("Connection Error:" , e )
71
63
print ("Retrying in 10 seconds" )
72
64
time .sleep (10 )
73
- gc .collect ()
74
65
print ("Connected!\n " )
75
66
76
67
while True :
77
68
try :
78
69
# ----------------------------- POST FOR BEARER TOKEN -----------------------
79
70
print (
80
- "\n Attempting to GENERATE Twitch Bearer Token!"
71
+ "Attempting Bearer Token Request !"
81
72
) # ---------------------------------------
82
73
# Print Request to Serial
83
74
debug_bearer_request = (
@@ -88,9 +79,9 @@ def time_calc(input_time):
88
79
print ("===============================" )
89
80
twitch_0auth_data = (
90
81
"&client_id="
91
- + secrets [ "Twitch_ClientID" ]
82
+ + twitch_client_id
92
83
+ "&client_secret="
93
- + secrets [ "Twitch_Client_Secret" ]
84
+ + twitch_client_secret
94
85
+ "&grant_type=client_credentials"
95
86
)
96
87
@@ -113,12 +104,12 @@ def time_calc(input_time):
113
104
print ("JSON Dump: " , twitch_0auth_json )
114
105
print ("Header: " , twitch_0auth_header )
115
106
print ("Access Token: " , twitch_access_token )
107
+ twitch_token_type = twitch_0auth_json ["token_type" ]
108
+ print ("Token Type: " , twitch_token_type )
116
109
110
+ print ("Board Uptime: " , time_calc (time .monotonic ()))
117
111
twitch_token_expiration = twitch_0auth_json ["expires_in" ]
118
112
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 ())
122
113
123
114
# ----------------------------- GET DATA -------------------------------------
124
115
# Bearer token is refreshed every time script runs :)
@@ -128,14 +119,13 @@ def time_calc(input_time):
128
119
# ----------------------------------------------------------------------------
129
120
twitch_header = {
130
121
"Authorization" : "Bearer " + twitch_access_token + "" ,
131
- "Client-Id" : "" + secrets [ "Twitch_ClientID" ] + "" ,
122
+ "Client-Id" : "" + twitch_client_id + "" ,
132
123
}
133
124
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
139
129
)
140
130
print (
141
131
"\n Attempting to GET TWITCH Stats!"
@@ -159,16 +149,11 @@ def time_calc(input_time):
159
149
print ("Header: " , twitch_header )
160
150
print ("JSON Full Response: " , twitch_followers_json )
161
151
162
- twitch_username = twitch_followers_json ["data" ][0 ]["to_name" ]
163
- print ("Username: " , twitch_username )
164
152
twitch_followers = twitch_followers_json ["total" ]
165
153
print ("Followers: " , twitch_followers )
166
- print ("Monotonic: " , time .monotonic ()) # Board Up-Time seconds
167
-
168
- print ("\n Finished!" )
154
+ print ("Finished!" )
169
155
print ("Next Update in: " , time_calc (sleep_time ))
170
156
print ("===============================" )
171
- gc .collect ()
172
157
173
158
except (ValueError , RuntimeError ) as e :
174
159
print ("Failed to get data, retrying\n " , e )
0 commit comments