Skip to content

Commit 6b1b92e

Browse files
committed
Update Discord Web Scrape Example with Connection Manager
1 parent 9544d1f commit 6b1b92e

File tree

1 file changed

+66
-73
lines changed

1 file changed

+66
-73
lines changed
Lines changed: 66 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -1,110 +1,103 @@
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
9-
10-
import socketpool
9+
import adafruit_connection_manager
1110
import wifi
12-
1311
import adafruit_requests
1412

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

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

2220
# Get WiFi details, ensure these are setup in settings.toml
2321
ssid = os.getenv("CIRCUITPY_WIFI_SSID")
2422
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)
23+
discord_auth = os.getenv("DISCORD_AUTHORIZATION")
2924

3025
# API Polling Rate
3126
# 900 = 15 mins, 1800 = 30 mins, 3600 = 1 hour
32-
sleep_time = 900
27+
SLEEP_TIME = 900
3328

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

35-
# Converts seconds to human readable minutes/hours/days
36-
def time_calc(input_time): # input_time in seconds
34+
35+
def time_calc(input_time):
36+
"""Converts seconds to minutes/hours/days"""
3737
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 = (
38+
return f"{input_time:.0f} seconds"
39+
if input_time < 3600:
40+
return f"{input_time / 60:.0f} minutes"
41+
if input_time < 86400:
42+
return f"{input_time / 60 / 60:.0f} hours"
43+
return f"{input_time / 60 / 60 / 24:.1f} days"
44+
45+
46+
DISCORD_HEADER = {"Authorization": "" + discord_auth}
47+
DISCORD_SOURCE = (
5448
"https://discord.com/api/v10/guilds/"
5549
+ "327254708534116352" # Adafruit Discord ID
5650
+ "/preview"
5751
)
5852

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-
7253
while True:
54+
# Connect to Wi-Fi
55+
print("\nConnecting to WiFi...")
56+
while not wifi.radio.ipv4_address:
57+
try:
58+
wifi.radio.connect(ssid, password)
59+
except ConnectionError as e:
60+
print("❌ Connection Error:", e)
61+
print("Retrying in 10 seconds")
62+
print("✅ Wifi!")
7363
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("===============================")
64+
print(" | Attempting to GET Discord JSON!")
65+
# Set debug to True for full JSON response.
66+
# WARNING: may include visible credentials
67+
# MICROCONTROLLER WARNING: might crash by returning too much data
68+
DEBUG_RESPONSE = False
69+
8070
try:
81-
ada_res = requests.get(url=ADA_SOURCE, headers=discord_header).json()
71+
discord_response = requests.get(url=DISCORD_SOURCE, headers=DISCORD_HEADER)
72+
discord_json = discord_response.json()
8273
except ConnectionError as e:
83-
print("Connection Error:", e)
74+
print(f"Connection Error: {e}")
8475
print("Retrying in 10 seconds")
76+
print(" | ✅ Discord JSON!")
77+
78+
if DEBUG_RESPONSE:
79+
print(f" | | Full API GET URL: {DISCORD_SOURCE}")
80+
print(f" | | JSON Dump: {discord_json}")
81+
82+
discord_name = discord_json["name"]
83+
print(f" | | Name: {discord_name}")
8584

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)
85+
discord_description = discord_json["description"]
86+
print(f" | | Description: {discord_description}")
9187

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)
88+
discord_all_members = discord_json["approximate_member_count"]
89+
print(f" | | Members: {discord_all_members}")
9790

98-
ada_discord_all_members_online = ada_res["approximate_presence_count"]
99-
print("Online: ", ada_discord_all_members_online)
91+
discord_all_members_online = discord_json["approximate_presence_count"]
92+
print(f" | | Online: {discord_all_members_online}")
10093

101-
print("Finished ✅")
102-
print("Board Uptime: ", time_calc(time.monotonic()))
103-
print("Next Update: ", time_calc(sleep_time))
94+
print("\nFinished!")
95+
print(f"Board Uptime: {time.monotonic()}")
96+
print(f"Next Update: {time_calc(SLEEP_TIME)}")
10497
print("===============================")
10598

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

0 commit comments

Comments
 (0)