Skip to content

Commit 0cd74f1

Browse files
authored
Merge pull request #163 from DJDevon3/DJDevon3-DiscordAPI
Update Discord Web Scrape Example with Connection Manager
2 parents d6006a3 + 095570e commit 0cd74f1

File tree

1 file changed

+66
-71
lines changed

1 file changed

+66
-71
lines changed
Lines changed: 66 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -1,110 +1,105 @@
1-
# SPDX-FileCopyrightText: 2023 DJDevon3
1+
# SPDX-FileCopyrightText: 2024 DJDevon3
22
# SPDX-License-Identifier: MIT
3-
# Coded for Circuit Python 8.2
4-
# DJDevon3 Adafruit Feather ESP32-S3 Discord API Example
5-
import json
3+
# Coded for Circuit Python 8.2.x
4+
"""Discord Web Scrape Example"""
5+
# pylint: disable=import-error
6+
67
import os
7-
import ssl
88
import time
99

10-
import socketpool
10+
import adafruit_connection_manager
1111
import wifi
1212

1313
import adafruit_requests
1414

15-
# Active Logged in User Account Required, no tokens required
15+
# Active Logged in User Account Required
1616
# WEB SCRAPE authorization key required. Visit URL below.
1717
# Learn how: https://github.com/lorenz234/Discord-Data-Scraping
1818

1919
# Ensure this is in settings.toml
20-
# "Discord_Authorization": "Request Header Auth here"
20+
# DISCORD_AUTHORIZATION = "Approximately 70 Character Hash Here"
2121

2222
# Get WiFi details, ensure these are setup in settings.toml
2323
ssid = os.getenv("CIRCUITPY_WIFI_SSID")
2424
password = os.getenv("CIRCUITPY_WIFI_PASSWORD")
25-
Discord_Auth = os.getenv("Discord_Authorization")
26-
27-
# Initialize WiFi Pool (There can be only 1 pool & top of script)
28-
pool = socketpool.SocketPool(wifi.radio)
25+
discord_auth = os.getenv("DISCORD_AUTHORIZATION")
2926

3027
# API Polling Rate
3128
# 900 = 15 mins, 1800 = 30 mins, 3600 = 1 hour
32-
sleep_time = 900
29+
SLEEP_TIME = 900
3330

31+
# Initalize Wifi, Socket Pool, Request Session
32+
pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio)
33+
ssl_context = adafruit_connection_manager.get_radio_ssl_context(wifi.radio)
34+
requests = adafruit_requests.Session(pool, ssl_context)
3435

35-
# Converts seconds to human readable minutes/hours/days
36-
def time_calc(input_time): # input_time in seconds
36+
37+
def time_calc(input_time):
38+
"""Converts seconds to minutes/hours/days"""
3739
if input_time < 60:
38-
sleep_int = input_time
39-
time_output = f"{sleep_int:.0f} seconds"
40-
elif 60 <= input_time < 3600:
41-
sleep_int = input_time / 60
42-
time_output = f"{sleep_int:.0f} minutes"
43-
elif 3600 <= input_time < 86400:
44-
sleep_int = input_time / 60 / 60
45-
time_output = f"{sleep_int:.1f} hours"
46-
else:
47-
sleep_int = input_time / 60 / 60 / 24
48-
time_output = f"{sleep_int:.1f} days"
49-
return time_output
50-
51-
52-
discord_header = {"Authorization": "" + Discord_Auth}
53-
ADA_SOURCE = (
40+
return f"{input_time:.0f} seconds"
41+
if input_time < 3600:
42+
return f"{input_time / 60:.0f} minutes"
43+
if input_time < 86400:
44+
return f"{input_time / 60 / 60:.0f} hours"
45+
return f"{input_time / 60 / 60 / 24:.1f} days"
46+
47+
48+
DISCORD_HEADER = {"Authorization": "" + discord_auth}
49+
DISCORD_SOURCE = (
5450
"https://discord.com/api/v10/guilds/"
5551
+ "327254708534116352" # Adafruit Discord ID
5652
+ "/preview"
5753
)
5854

59-
# Connect to Wi-Fi
60-
print("\n===============================")
61-
print("Connecting to WiFi...")
62-
requests = adafruit_requests.Session(pool, ssl.create_default_context())
63-
while not wifi.radio.ipv4_address:
64-
try:
65-
wifi.radio.connect(ssid, password)
66-
except ConnectionError as e:
67-
print("Connection Error:", e)
68-
print("Retrying in 10 seconds")
69-
time.sleep(10)
70-
print("Connected!✅")
71-
7255
while True:
56+
# Connect to Wi-Fi
57+
print("\nConnecting to WiFi...")
58+
while not wifi.radio.ipv4_address:
59+
try:
60+
wifi.radio.connect(ssid, password)
61+
except ConnectionError as e:
62+
print("❌ Connection Error:", e)
63+
print("Retrying in 10 seconds")
64+
print("✅ Wifi!")
7365
try:
74-
print("\nAttempting to GET Discord Data!") # --------------------------------
75-
# STREAMER WARNING this will show your credentials!
76-
debug_request = False # Set True to see full request
77-
if debug_request:
78-
print("Full API GET URL: ", ADA_SOURCE)
79-
print("===============================")
66+
print(" | Attempting to GET Discord JSON!")
67+
# Set debug to True for full JSON response.
68+
# WARNING: may include visible credentials
69+
# MICROCONTROLLER WARNING: might crash by returning too much data
70+
DEBUG_RESPONSE = False
71+
8072
try:
81-
ada_res = requests.get(url=ADA_SOURCE, headers=discord_header).json()
73+
discord_response = requests.get(url=DISCORD_SOURCE, headers=DISCORD_HEADER)
74+
discord_json = discord_response.json()
8275
except ConnectionError as e:
83-
print("Connection Error:", e)
76+
print(f"Connection Error: {e}")
8477
print("Retrying in 10 seconds")
78+
print(" | ✅ Discord JSON!")
79+
80+
if DEBUG_RESPONSE:
81+
print(f" | | Full API GET URL: {DISCORD_SOURCE}")
82+
print(f" | | JSON Dump: {discord_json}")
83+
84+
discord_name = discord_json["name"]
85+
print(f" | | Name: {discord_name}")
8586

86-
# Print Full JSON to Serial
87-
discord_debug_response = False # Set True to see full response
88-
if discord_debug_response:
89-
ada_discord_dump_object = json.dumps(ada_res)
90-
print("JSON Dump: ", ada_discord_dump_object)
87+
discord_description = discord_json["description"]
88+
print(f" | | Description: {discord_description}")
9189

92-
# Print keys to Serial
93-
discord_debug_keys = True # Set True to print Serial data
94-
if discord_debug_keys:
95-
ada_discord_all_members = ada_res["approximate_member_count"]
96-
print("Members: ", ada_discord_all_members)
90+
discord_all_members = discord_json["approximate_member_count"]
91+
print(f" | | Members: {discord_all_members}")
9792

98-
ada_discord_all_members_online = ada_res["approximate_presence_count"]
99-
print("Online: ", ada_discord_all_members_online)
93+
discord_all_members_online = discord_json["approximate_presence_count"]
94+
print(f" | | Online: {discord_all_members_online}")
10095

101-
print("Finished ✅")
102-
print("Board Uptime: ", time_calc(time.monotonic()))
103-
print("Next Update: ", time_calc(sleep_time))
96+
print("\nFinished!")
97+
print(f"Board Uptime: {time.monotonic()}")
98+
print(f"Next Update: {time_calc(SLEEP_TIME)}")
10499
print("===============================")
105100

106-
except (ConnectionError, ValueError, NameError) as e:
107-
print("Failed to get data, retrying\n", e)
101+
except (ValueError, RuntimeError) as e:
102+
print(f"Failed to get data, retrying\n {e}")
108103
time.sleep(60)
109-
continue
110-
time.sleep(sleep_time)
104+
break
105+
time.sleep(SLEEP_TIME)

0 commit comments

Comments
 (0)