Skip to content

Commit 36f1bb0

Browse files
authored
Merge pull request #136 from DJDevon3/WorkingBranch
Update Requests Discord API example to use settings.toml
2 parents e09c3bd + b62fc36 commit 36f1bb0

File tree

1 file changed

+42
-43
lines changed

1 file changed

+42
-43
lines changed

examples/requests_api_discord.py

Lines changed: 42 additions & 43 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,40 @@
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"
45-
46-
discord_header = {"Authorization": "" + secrets["Discord_Authorization"]}
32+
33+
# Converts seconds to human readable minutes/hours/days
34+
def time_calc(input_time): # input_time in seconds
35+
if input_time < 60:
36+
sleep_int = input_time
37+
time_output = f"{sleep_int:.0f} seconds"
38+
elif 60 <= input_time < 3600:
39+
sleep_int = input_time / 60
40+
time_output = f"{sleep_int:.0f} minutes"
41+
elif 3600 <= input_time < 86400:
42+
sleep_int = input_time / 60 / 60
43+
time_output = f"{sleep_int:.1f} hours"
44+
else:
45+
sleep_int = input_time / 60 / 60 / 24
46+
time_output = f"{sleep_int:.1f} days"
47+
return time_output
48+
49+
50+
discord_header = {"Authorization": "" + Discord_Auth}
4751
ADA_SOURCE = (
4852
"https://discord.com/api/v10/guilds/"
4953
+ "327254708534116352" # Adafruit Discord ID
@@ -56,21 +60,18 @@
5660
requests = adafruit_requests.Session(pool, ssl.create_default_context())
5761
while not wifi.radio.ipv4_address:
5862
try:
59-
wifi.radio.connect(secrets["ssid"], secrets["password"])
63+
wifi.radio.connect(ssid, appw)
6064
except ConnectionError as e:
6165
print("Connection Error:", e)
6266
print("Retrying in 10 seconds")
6367
time.sleep(10)
64-
gc.collect()
65-
print("Connected!\n")
68+
print("Connected!✅")
6669

6770
while True:
6871
try:
69-
print(
70-
"\nAttempting to GET DISCORD PREVIEW!"
71-
) # --------------------------------
72-
# Print Request to Serial
73-
debug_request = False # Set true to see full request
72+
print("\nAttempting to GET Discord Data!") # --------------------------------
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,28 +82,26 @@
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

0 commit comments

Comments
 (0)