Skip to content

Commit 330080e

Browse files
committed
update Discord API Example to Settings.toml
One API at a time. This should not affect any learn guides. This is the web scrape example that requires you to get the auth key from the request header with a browser developer tool. Still works fine.
1 parent 1259b73 commit 330080e

File tree

1 file changed

+40
-40
lines changed

1 file changed

+40
-40
lines changed

examples/requests_api_discord.py

Lines changed: 40 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
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 Discord_API_Example"""
5-
import gc
3+
# Coded for Circuit Python 8.2
4+
# DJDevon3 Adafruit Feather ESP32-S3 Discord API Example
5+
import os
66
import time
77
import ssl
88
import json
@@ -14,36 +14,38 @@
1414
# WEB SCRAPE authorization key required. Visit URL below.
1515
# Learn how: https://github.com/lorenz234/Discord-Data-Scraping
1616

17-
# Ensure this is in secrets.py or .env
18-
# "Discord_Authorization": "Discord Authorization from browser console"
17+
# Ensure this is in settings.toml
18+
# "Discord_Authorization": "Request Header Auth here"
19+
20+
# Uses settings.toml for credentials
21+
ssid = os.getenv("CIRCUITPY_WIFI_SSID")
22+
appw = os.getenv("CIRCUITPY_WIFI_PASSWORD")
23+
Discord_Auth = os.getenv("Discord_Authorization")
1924

2025
# Initialize WiFi Pool (There can be only 1 pool & top of script)
2126
pool = socketpool.SocketPool(wifi.radio)
2227

23-
# Time between API refreshes
28+
# API Polling Rate
2429
# 900 = 15 mins, 1800 = 30 mins, 3600 = 1 hour
2530
sleep_time = 900
2631

27-
try:
28-
from secrets import secrets
29-
except ImportError:
30-
print("Secrets File Import Error")
31-
raise
32-
33-
if sleep_time < 60:
34-
sleep_time_conversion = "seconds"
35-
sleep_int = sleep_time
36-
elif 60 <= sleep_time < 3600:
37-
sleep_int = sleep_time / 60
38-
sleep_time_conversion = "minutes"
39-
elif 3600 <= sleep_time < 86400:
40-
sleep_int = sleep_time / 60 / 60
41-
sleep_time_conversion = "hours"
42-
else:
43-
sleep_int = sleep_time / 60 / 60 / 24
44-
sleep_time_conversion = "days"
32+
# Converts seconds to human readable minutes/hours/days
33+
def time_calc(input_time): # input_time in seconds
34+
if input_time < 60:
35+
sleep_int = input_time
36+
time_output = f"{sleep_int:.0f} seconds"
37+
elif 60 <= input_time < 3600:
38+
sleep_int = input_time / 60
39+
time_output = f"{sleep_int:.0f} minutes"
40+
elif 3600 <= input_time < 86400:
41+
sleep_int = input_time / 60 / 60
42+
time_output = f"{sleep_int:.1f} hours"
43+
else:
44+
sleep_int = input_time / 60 / 60 / 24
45+
time_output = f"{sleep_int:.1f} days"
46+
return time_output
4547

46-
discord_header = {"Authorization": "" + secrets["Discord_Authorization"]}
48+
discord_header = {"Authorization": "" + Discord_Auth}
4749
ADA_SOURCE = (
4850
"https://discord.com/api/v10/guilds/"
4951
+ "327254708534116352" # Adafruit Discord ID
@@ -56,21 +58,20 @@
5658
requests = adafruit_requests.Session(pool, ssl.create_default_context())
5759
while not wifi.radio.ipv4_address:
5860
try:
59-
wifi.radio.connect(secrets["ssid"], secrets["password"])
61+
wifi.radio.connect(ssid, appw)
6062
except ConnectionError as e:
6163
print("Connection Error:", e)
6264
print("Retrying in 10 seconds")
6365
time.sleep(10)
64-
gc.collect()
65-
print("Connected!\n")
66+
print("Connected!✅")
6667

6768
while True:
6869
try:
6970
print(
70-
"\nAttempting to GET DISCORD PREVIEW!"
71+
"\nAttempting to GET Discord Data!"
7172
) # --------------------------------
72-
# Print Request to Serial
73-
debug_request = False # Set true to see full request
73+
# STREAMER WARNING this will show your credentials!
74+
debug_request = False # Set True to see full request
7475
if debug_request:
7576
print("Full API GET URL: ", ADA_SOURCE)
7677
print("===============================")
@@ -81,29 +82,28 @@
8182
print("Retrying in 10 seconds")
8283

8384
# Print Full JSON to Serial
84-
discord_debug_response = False # Change to true to see full response
85+
discord_debug_response = False # Set True to see full response
8586
if discord_debug_response:
8687
ada_discord_dump_object = json.dumps(ada_res)
8788
print("JSON Dump: ", ada_discord_dump_object)
8889

8990
# Print keys to Serial
90-
discord_debug_keys = True # Set to True to print Serial data
91+
discord_debug_keys = True # Set True to print Serial data
9192
if discord_debug_keys:
9293
ada_discord_all_members = ada_res["approximate_member_count"]
9394
print("Members: ", ada_discord_all_members)
9495

9596
ada_discord_all_members_online = ada_res["approximate_presence_count"]
9697
print("Online: ", ada_discord_all_members_online)
9798

98-
print("Monotonic: ", time.monotonic())
99-
100-
print("\nFinished!")
101-
print("Next Update in %s %s" % (int(sleep_int), sleep_time_conversion))
99+
print("Finished ✅")
100+
print("Board Uptime: ", time_calc(time.monotonic()))
101+
print("Next Update: ", time_calc(sleep_time))
102102
print("===============================")
103-
gc.collect()
104103

105-
except (ValueError, RuntimeError) as e:
104+
except (ConnectionError, ValueError, NameError) as e:
106105
print("Failed to get data, retrying\n", e)
107106
time.sleep(60)
108107
continue
109108
time.sleep(sleep_time)
109+

0 commit comments

Comments
 (0)