Skip to content

Update Requests Discord API example to use settings.toml #136

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 21, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 42 additions & 43 deletions examples/requests_api_discord.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# SPDX-FileCopyrightText: 2022 DJDevon3 for Adafruit Industries
# SPDX-FileCopyrightText: 2023 DJDevon3
# SPDX-License-Identifier: MIT
# Coded for Circuit Python 8.0
"""DJDevon3 Adafruit Feather ESP32-S2 Discord_API_Example"""
import gc
# Coded for Circuit Python 8.2
# DJDevon3 Adafruit Feather ESP32-S3 Discord API Example
import os
import time
import ssl
import json
Expand All @@ -14,36 +14,40 @@
# WEB SCRAPE authorization key required. Visit URL below.
# Learn how: https://github.com/lorenz234/Discord-Data-Scraping

# Ensure this is in secrets.py or .env
# "Discord_Authorization": "Discord Authorization from browser console"
# Ensure this is in settings.toml
# "Discord_Authorization": "Request Header Auth here"

# Uses settings.toml for credentials
ssid = os.getenv("CIRCUITPY_WIFI_SSID")
appw = os.getenv("CIRCUITPY_WIFI_PASSWORD")
Discord_Auth = os.getenv("Discord_Authorization")

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

# Time between API refreshes
# API Polling Rate
# 900 = 15 mins, 1800 = 30 mins, 3600 = 1 hour
sleep_time = 900

try:
from secrets import secrets
except ImportError:
print("Secrets File Import Error")
raise

if sleep_time < 60:
sleep_time_conversion = "seconds"
sleep_int = sleep_time
elif 60 <= sleep_time < 3600:
sleep_int = sleep_time / 60
sleep_time_conversion = "minutes"
elif 3600 <= sleep_time < 86400:
sleep_int = sleep_time / 60 / 60
sleep_time_conversion = "hours"
else:
sleep_int = sleep_time / 60 / 60 / 24
sleep_time_conversion = "days"

discord_header = {"Authorization": "" + secrets["Discord_Authorization"]}

# Converts seconds to human readable minutes/hours/days
def time_calc(input_time): # input_time in seconds
if input_time < 60:
sleep_int = input_time
time_output = f"{sleep_int:.0f} seconds"
elif 60 <= input_time < 3600:
sleep_int = input_time / 60
time_output = f"{sleep_int:.0f} minutes"
elif 3600 <= input_time < 86400:
sleep_int = input_time / 60 / 60
time_output = f"{sleep_int:.1f} hours"
else:
sleep_int = input_time / 60 / 60 / 24
time_output = f"{sleep_int:.1f} days"
return time_output


discord_header = {"Authorization": "" + Discord_Auth}
ADA_SOURCE = (
"https://discord.com/api/v10/guilds/"
+ "327254708534116352" # Adafruit Discord ID
Expand All @@ -56,21 +60,18 @@
requests = adafruit_requests.Session(pool, ssl.create_default_context())
while not wifi.radio.ipv4_address:
try:
wifi.radio.connect(secrets["ssid"], secrets["password"])
wifi.radio.connect(ssid, appw)
except ConnectionError as e:
print("Connection Error:", e)
print("Retrying in 10 seconds")
time.sleep(10)
gc.collect()
print("Connected!\n")
print("Connected!✅")

while True:
try:
print(
"\nAttempting to GET DISCORD PREVIEW!"
) # --------------------------------
# Print Request to Serial
debug_request = False # Set true to see full request
print("\nAttempting to GET Discord Data!") # --------------------------------
# STREAMER WARNING this will show your credentials!
debug_request = False # Set True to see full request
if debug_request:
print("Full API GET URL: ", ADA_SOURCE)
print("===============================")
Expand All @@ -81,28 +82,26 @@
print("Retrying in 10 seconds")

# Print Full JSON to Serial
discord_debug_response = False # Change to true to see full response
discord_debug_response = False # Set True to see full response
if discord_debug_response:
ada_discord_dump_object = json.dumps(ada_res)
print("JSON Dump: ", ada_discord_dump_object)

# Print keys to Serial
discord_debug_keys = True # Set to True to print Serial data
discord_debug_keys = True # Set True to print Serial data
if discord_debug_keys:
ada_discord_all_members = ada_res["approximate_member_count"]
print("Members: ", ada_discord_all_members)

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

print("Monotonic: ", time.monotonic())

print("\nFinished!")
print("Next Update in %s %s" % (int(sleep_int), sleep_time_conversion))
print("Finished ✅")
print("Board Uptime: ", time_calc(time.monotonic()))
print("Next Update: ", time_calc(sleep_time))
print("===============================")
gc.collect()

except (ValueError, RuntimeError) as e:
except (ConnectionError, ValueError, NameError) as e:
print("Failed to get data, retrying\n", e)
time.sleep(60)
continue
Expand Down