Skip to content

Commit 90f7d1a

Browse files
committed
Create requests_api_youtube.py
Example script for YouTube API. Includes some error correction and time based requests. Returns basic channel stats. Amount of serial prints configurable with debugger booleans.
1 parent a5d56f3 commit 90f7d1a

File tree

1 file changed

+120
-0
lines changed

1 file changed

+120
-0
lines changed

examples/requests_api_youtube.py

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
# SPDX-FileCopyrightText: 2022 DJDevon3
2+
# SPDX-License-Identifier: MIT
3+
# Coded for Circuit Python 8.0
4+
"""DJDevon3 Adafruit Feather ESP32-S2 YouTube_API_Example"""
5+
# pylint: disable=line-too-long
6+
import gc
7+
import time
8+
import ssl
9+
import wifi
10+
import json
11+
import socketpool
12+
import adafruit_requests
13+
14+
# Ensure these are uncommented and in secrets.py or .env
15+
# "YT_username": "Your YouTube Username",
16+
# "YT_token" : "Your long API developer token",
17+
18+
# Initialize WiFi Pool (There can be only 1 pool & top of script)
19+
pool = socketpool.SocketPool(wifi.radio)
20+
21+
# Time between API refreshes
22+
# 900 = 15 mins, 1800 = 30 mins, 3600 = 1 hour
23+
sleep_time = 900
24+
25+
try:
26+
from secrets import secrets
27+
except ImportError:
28+
print("Secrets File Import Error")
29+
raise
30+
31+
if sleep_time < 60:
32+
sleep_time_conversion = "seconds"
33+
sleep_int = sleep_time
34+
elif 60 <= sleep_time < 3600:
35+
sleep_int = sleep_time / 60
36+
sleep_time_conversion = "minutes"
37+
elif 3600 <= sleep_time < 86400:
38+
sleep_int = sleep_time / 60 / 60
39+
sleep_time_conversion = "hours"
40+
else:
41+
sleep_int = sleep_time / 60 / 60 / 24
42+
sleep_time_conversion = "days"
43+
44+
# https://youtube.googleapis.com/youtube/v3/channels?part=statistics&forUsername=[YOUR_USERNAME]&key=[YOUR_API_KEY]
45+
YT_SOURCE = (
46+
"https://youtube.googleapis.com/youtube/v3/channels?"
47+
+ "part=statistics"
48+
+ "&forUsername="
49+
+ secrets["YT_username"]
50+
+ "&key="
51+
+ secrets["YT_token"]
52+
)
53+
54+
# Connect to Wi-Fi
55+
print("\n===============================")
56+
print("Connecting to WiFi...")
57+
requests = adafruit_requests.Session(pool, ssl.create_default_context())
58+
while not wifi.radio.ipv4_address:
59+
try:
60+
wifi.radio.connect(secrets['ssid'], secrets['password'])
61+
except ConnectionError as e:
62+
print("Connection Error:", e)
63+
print("Retrying in 10 seconds")
64+
time.sleep(10)
65+
gc.collect()
66+
print("Connected!\n")
67+
68+
while True:
69+
try:
70+
print("Attempting to GET YouTube Stats!") # ----------------------------------
71+
debug_request = False # Set true to see full request
72+
if debug_request:
73+
print("Full API GET URL: ", YT_SOURCE)
74+
print("===============================")
75+
try:
76+
response = requests.get(YT_SOURCE).json()
77+
except ConnectionError as e:
78+
print("Connection Error:", e)
79+
print("Retrying in 10 seconds")
80+
81+
# Print Full JSON to Serial
82+
debug_response = False # Set true to see full response
83+
if debug_response:
84+
dump_object = json.dumps(response)
85+
print("JSON Dump: ", dump_object)
86+
87+
# Print to Serial
88+
yt_debug_keys = True # Set to True to print Serial data
89+
if yt_debug_keys:
90+
print("Matching Results: ", response['pageInfo']['totalResults'])
91+
92+
YT_request_kind = response['items'][0]['kind']
93+
print("Request Kind: ", YT_request_kind)
94+
95+
YT_response_kind = response['kind']
96+
print("Response Kind: ", YT_response_kind)
97+
98+
YT_channel_id = response['items'][0]['id']
99+
print("Channel ID: ", YT_channel_id)
100+
101+
YT_videoCount = response['items'][0]['statistics']['videoCount']
102+
print("Videos: ", YT_videoCount)
103+
104+
YT_viewCount = response['items'][0]['statistics']['viewCount']
105+
print("Views: ", YT_viewCount)
106+
107+
YT_subsCount = response['items'][0]['statistics']['subscriberCount']
108+
print("Subscribers: ", YT_subsCount)
109+
print("Monotonic: ", time.monotonic())
110+
111+
print("\nFinished!")
112+
print("Next Update in %s %s" % (int(sleep_int), sleep_time_conversion))
113+
print("===============================")
114+
gc.collect()
115+
# pylint: disable=broad-except
116+
except (ValueError, RuntimeError) as e:
117+
print("Failed to get data, retrying\n", e)
118+
time.sleep(60)
119+
continue
120+
time.sleep(sleep_time)

0 commit comments

Comments
 (0)