Skip to content

Commit 2c38b16

Browse files
committed
Create requests_api_twitter.py
Example script for Twitter API. Includes some error correction and time based requests. Returns basic stats. Amount of serial prints configurable with debugger booleans.
1 parent 90f7d1a commit 2c38b16

File tree

1 file changed

+119
-0
lines changed

1 file changed

+119
-0
lines changed

examples/requests_api_twitter.py

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
# SPDX-FileCopyrightText: 2022 DJDevon3
2+
# SPDX-License-Identifier: MIT
3+
# Coded for Circuit Python 8.0
4+
"""DJDevon3 Adafruit Feather ESP32-S2 Twitter_API_Example"""
5+
# pylint: disable=line-too-long
6+
import gc
7+
import time
8+
import ssl
9+
import wifi
10+
import json
11+
import socketpool
12+
import adafruit_requests
13+
14+
# Twitter developer account bearer token required.
15+
# Ensure these are uncommented and in secrets.py or .env
16+
# "TW_userid": "Your Twitter user id", # numerical id not username
17+
# "TW_bearer_token": "Your long API Bearer token",
18+
19+
# Initialize WiFi Pool (There can be only 1 pool & top of script)
20+
pool = socketpool.SocketPool(wifi.radio)
21+
22+
# Time between API refreshes
23+
# 900 = 15 mins, 1800 = 30 mins, 3600 = 1 hour
24+
sleep_time = 900
25+
26+
try:
27+
from secrets import secrets
28+
except ImportError:
29+
print("Secrets File Import Error")
30+
raise
31+
32+
if sleep_time < 60:
33+
sleep_time_conversion = "seconds"
34+
sleep_int = sleep_time
35+
elif 60 <= sleep_time < 3600:
36+
sleep_int = sleep_time / 60
37+
sleep_time_conversion = "minutes"
38+
elif 3600 <= sleep_time < 86400:
39+
sleep_int = sleep_time / 60 / 60
40+
sleep_time_conversion = "hours"
41+
else:
42+
sleep_int = sleep_time / 60 / 60 / 24
43+
sleep_time_conversion = "days"
44+
45+
# Used with any Twitter 0auth request.
46+
twitter_header = {'Authorization': 'Bearer ' + secrets["TW_bearer_token"]}
47+
TW_SOURCE = (
48+
"https://api.twitter.com/2/users/"
49+
+ secrets["TW_userid"]
50+
+ "?user.fields=public_metrics,created_at,pinned_tweet_id"
51+
+ "&expansions=pinned_tweet_id"
52+
+ "&tweet.fields=created_at,public_metrics,source,context_annotations,entities"
53+
)
54+
55+
# Connect to Wi-Fi
56+
print("\n===============================")
57+
print("Connecting to WiFi...")
58+
requests = adafruit_requests.Session(pool, ssl.create_default_context())
59+
while not wifi.radio.ipv4_address:
60+
try:
61+
wifi.radio.connect(secrets['ssid'], secrets['password'])
62+
except ConnectionError as e:
63+
print("Connection Error:", e)
64+
print("Retrying in 10 seconds")
65+
time.sleep(10)
66+
gc.collect()
67+
print("Connected!\n")
68+
69+
while True:
70+
try:
71+
print("\nAttempting to GET Twitter Stats!") # --------------------------------
72+
debug_request = False # Set true to see full request
73+
if debug_request:
74+
print("Full API GET URL: ", TW_SOURCE)
75+
print("===============================")
76+
try:
77+
twitter_response = requests.get(url=TW_SOURCE, headers=twitter_header)
78+
tw_json = twitter_response.json()
79+
except ConnectionError as e:
80+
print("Connection Error:", e)
81+
print("Retrying in 10 seconds")
82+
83+
# Print Full JSON to Serial
84+
debug_response = False # Set true to see full response
85+
if debug_response:
86+
dump_object = json.dumps(tw_json)
87+
print("JSON Dump: ", dump_object)
88+
89+
# Print to Serial
90+
tw_debug_keys = True # Set true to print Serial data
91+
if tw_debug_keys:
92+
93+
tw_userid = tw_json['data']['id']
94+
print("User ID: ", tw_userid)
95+
96+
tw_username = tw_json['data']['name']
97+
print("Name: ", tw_username)
98+
99+
tw_join_date = tw_json['data']['created_at']
100+
print("Member Since: ", tw_join_date)
101+
102+
tw_tweets = tw_json['data']['public_metrics']['tweet_count']
103+
print("Tweets: ", tw_tweets)
104+
105+
tw_followers = tw_json['data']['public_metrics']['followers_count']
106+
print("Followers: ", tw_followers)
107+
108+
print("Monotonic: ", time.monotonic())
109+
110+
print("\nFinished!")
111+
print("Next Update in %s %s" % (int(sleep_int), sleep_time_conversion))
112+
print("===============================")
113+
gc.collect()
114+
# pylint: disable=broad-except
115+
except (ValueError, RuntimeError) as e:
116+
print("Failed to get data, retrying\n", e)
117+
time.sleep(60)
118+
continue
119+
time.sleep(sleep_time)

0 commit comments

Comments
 (0)