code.py
1 # SPDX-FileCopyrightText: 2022 Liz Clark for Adafruit Industries 2 # 3 # SPDX-License-Identifier: MIT 4 5 import time 6 import os 7 import ssl 8 import wifi 9 import socketpool 10 import microcontroller 11 import adafruit_requests 12 13 # query URL for tweets. looking for tweets from Adafruit that have the text "NEW GUIDE" 14 # disabling line-too-long because queries for tweet_query & TIME_URL cannot have line breaks 15 # pylint: disable=line-too-long 16 tweet_query = 'https://api.twitter.com/2/tweets/search/recent?query=NEW GUIDE from:adafruit&tweet.fields=created_at' 17 18 headers = {'Authorization': 'Bearer ' + os.getenv('bearer_token')} 19 20 wifi.radio.connect(os.getenv('WIFI_SSID'), os.getenv('WIFI_PASSWORD')) 21 22 pool = socketpool.SocketPool(wifi.radio) 23 requests = adafruit_requests.Session(pool, ssl.create_default_context()) 24 25 last_id = 0 # checks last tweet's ID 26 check = 0 # time.monotonic() holder 27 28 while True: 29 try: 30 if (check + 30) < time.monotonic(): 31 # updates current time 32 # get tweets from rpilocator containing in stock at adafruit 33 twitter_response = requests.get(url=tweet_query, headers=headers) 34 # gets data portion of json 35 twitter_json = twitter_response.json() 36 twitter_json = twitter_json['data'] 37 # to see the entire json feed, uncomment 'print(twitter_json)' 38 # print(twitter_json) 39 # tweet ID number 40 tweet_id = twitter_json[0]['id'] 41 # tweet text 42 tweet = twitter_json[0]['text'] 43 # timestamp 44 timestamp = twitter_json[0]['created_at'] 45 if last_id != tweet_id: 46 print("New Learn Guide!") 47 print(tweet) 48 print(timestamp) 49 last_id = tweet_id 50 check = time.monotonic() 51 # pylint: disable=broad-except 52 # any errors, reset Pico W 53 except Exception as e: 54 print("Error:\n", str(e)) 55 print("Resetting microcontroller in 10 seconds") 56 time.sleep(10) 57 microcontroller.reset()