|
| 1 | +# SPDX-FileCopyrightText: 2022 Liz Clark for Adafruit Industries |
| 2 | +# SPDX-License-Identifier: MIT |
| 3 | + |
| 4 | +import os |
| 5 | +import re |
| 6 | +import time |
| 7 | +import ssl |
| 8 | +import wifi |
| 9 | +import socketpool |
| 10 | +import microcontroller |
| 11 | +import adafruit_requests |
| 12 | + |
| 13 | +# enter the hashtag that you want to follow |
| 14 | +hashtag = "CircuitPython" |
| 15 | + |
| 16 | +# connect to SSID |
| 17 | +wifi.radio.connect(os.getenv('WIFI_SSID'), os.getenv('WIFI_PASSWORD')) |
| 18 | + |
| 19 | +# add your mastodon token as 'mastodon_token' to your .env file |
| 20 | +headers = {'Authorization': 'Bearer ' + os.getenv('mastodon_token') + 'read:statuses'} |
| 21 | + |
| 22 | +pool = socketpool.SocketPool(wifi.radio) |
| 23 | +requests = adafruit_requests.Session(pool, ssl.create_default_context()) |
| 24 | + |
| 25 | +# initial request, gets most recent matching hashtag post |
| 26 | +# add your mastodon instance (mastodon.social, tech.lgbt, etc) to your .env file as mastodon_host |
| 27 | +r = requests.get("https://%s/api/v1/timelines/tag/%s?limit=1" % (os.getenv('mastodon_host'), hashtag), headers=headers) # pylint: disable=line-too-long |
| 28 | +json_data = r.json() |
| 29 | +post_id = str(json_data[0]['id']) |
| 30 | +print("A new #%s post from @%s:" % (hashtag, str(json_data[0]['account']['acct']))) |
| 31 | +print(re.sub('<[^>]+>', '', json_data[0]['content'])) |
| 32 | +print() |
| 33 | + |
| 34 | +while True: |
| 35 | + try: |
| 36 | + time.sleep(360) |
| 37 | + # compares post_id to see if a new post to the hashtag has been found |
| 38 | + r = requests.get("https://%s/api/v1/timelines/tag/%s?since_id=%s" % (os.getenv('mastodon_host'), hashtag, post_id), headers=headers) # pylint: disable=line-too-long |
| 39 | + json_data = r.json() |
| 40 | + json_length = len(json_data) |
| 41 | + # if the id's match, then the json array is empty (length of 0) |
| 42 | + # otherwise there is a new post |
| 43 | + if json_length > 0: |
| 44 | + post_id = str(json_data[0]['id']) |
| 45 | + print("A new #%s post from @%s:" % (hashtag, str(json_data[0]['account']['acct']))) |
| 46 | + print(re.sub('<[^>]+>', '', json_data[0]['content'])) |
| 47 | + print() |
| 48 | + else: |
| 49 | + print("no new #%s posts" % hashtag) |
| 50 | + print(json_length) |
| 51 | + print() |
| 52 | + |
| 53 | + except Exception as e: # pylint: disable=broad-except |
| 54 | + print("Error:\n", str(e)) |
| 55 | + print("Resetting microcontroller in 10 seconds") |
| 56 | + time.sleep(10) |
| 57 | + microcontroller.reset() |
0 commit comments