/ MagTag_Twitter / code.py
code.py
1 # SPDX-FileCopyrightText: 2019 Dave Astels for Adafruit Industries. 2 # SPDX-FileCopyrightText: 2020 Brent Rubell for Adafruit Industries. 3 # 4 # SPDX-License-Identifier: Unlicense 5 import time 6 from adafruit_magtag.magtag import MagTag 7 8 try: 9 from secrets import secrets 10 except ImportError: 11 print( 12 """WiFi settings are kept in secrets.py, please add them there! 13 the secrets dictionary must contain 'ssid' and 'password' at a minimum""" 14 ) 15 raise 16 17 # Set to the twitter username you'd like to fetch tweets from 18 TWITTER_USERNAME = "adafruit" 19 20 # Set to the amount of time to deep sleep for, in minutes 21 SLEEP_TIME = 15 22 23 # Set up where we'll be fetching data from 24 DATA_SOURCE = ( 25 "https://api.twitter.com/1.1/statuses/user_timeline.json?" 26 "screen_name=%s&count=1&tweet_mode=extended" % TWITTER_USERNAME 27 ) 28 TWEET_TEXT = [0, "full_text"] 29 TWEET_FULL_NAME = [0, "user", "name"] 30 TWEET_HANDLE = [0, "user", "screen_name"] 31 32 magtag = MagTag(url=DATA_SOURCE, json_path=(TWEET_FULL_NAME, TWEET_HANDLE, TWEET_TEXT)) 33 # Set Twitter OAuth2.0 Bearer Token 34 bearer_token = secrets["twitter_bearer_token"] 35 magtag.set_headers({"Authorization": "Bearer " + bearer_token}) 36 37 # Display setup 38 magtag.set_background("/images/background.bmp") 39 40 # Twitter name 41 magtag.add_text( 42 text_position=(70, 10), 43 text_font="/fonts/Arial-Bold-12.pcf", 44 ) 45 46 # Twitter handle (@username) 47 magtag.add_text( 48 text_position=(70, 30), 49 text_font="/fonts/Arial-12.bdf", 50 text_transform=lambda x: "@%s" % x, 51 ) 52 53 # Tweet text 54 magtag.add_text( 55 text_font="/fonts/Arial-Bold-12.pcf", 56 text_wrap=30, 57 text_maxlen=160, 58 text_position=( 59 5, 60 (magtag.graphics.display.height // 2) + 20, 61 ), 62 line_spacing=0.75, 63 ) 64 65 # preload characters 66 magtag.preload_font() 67 68 try: 69 value = magtag.fetch() 70 print("Response is", value) 71 except (ValueError, RuntimeError, ConnectionError, OSError) as e: 72 print("Some error occured, retrying! -", e) 73 74 time.sleep(2) 75 print("Sleeping!") 76 magtag.exit_and_deep_sleep(SLEEP_TIME * 60)