megafono.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. from mastodon import Mastodon
  2. from dotenv import load_dotenv
  3. from pathlib import Path
  4. import os
  5. import time
  6. def megafono():
  7. """
  8. Toot only one line from ANNOUNCEMENT_FILE gradually or random if RANDOM is set.
  9. It's useful configure a crontab for invocation
  10. """
  11. load_dotenv()
  12. INSTANCE_BASE = os.getenv('INSTANCE_BASE')
  13. CLIENT_ID = os.getenv('CLIENT_ID')
  14. CLIENT_SECRET = os.getenv('CLIENT_SECRET')
  15. ACCESS_TOKEN = os.getenv('ACCESS_TOKEN')
  16. ANNOUNCEMENT_FILE = os.getenv('ANNOUNCEMENT_FILE')
  17. RANDOM = os.getenv('RANDOM')
  18. IS_DOCKER = os.getenv('IS_DOCKER', False)
  19. if IS_DOCKER:
  20. last_id_file = str(Path('/data') / 'last_id')
  21. ANNOUNCEMENT_FILE = str(Path('/data') / ANNOUNCEMENT_FILE)
  22. else:
  23. last_id_file = str(Path('./txt') / 'last_id.txt')
  24. ANNOUNCEMENT_FILE = str(Path('./txt') / ANNOUNCEMENT_FILE)
  25. mastodon = Mastodon(
  26. client_id=CLIENT_ID,
  27. client_secret=CLIENT_SECRET,
  28. access_token=ACCESS_TOKEN,
  29. api_base_url=INSTANCE_BASE)
  30. if int(RANDOM):
  31. import random
  32. toot = random.choice(list(open(ANNOUNCEMENT_FILE, 'r')))
  33. else:
  34. last_id = 0
  35. with open(last_id_file) as f:
  36. last_id = int(f.read())
  37. with open(ANNOUNCEMENT_FILE, 'r') as a:
  38. toot = a.readlines()[last_id]
  39. with open(ANNOUNCEMENT_FILE, 'r') as a:
  40. length = len(a.readlines())
  41. last_id += 1
  42. last_id %= length
  43. with open(last_id_file, 'w+') as f:
  44. f.write(str(last_id))
  45. if toot.startswith('IMG='):
  46. msg = toot.split(' ', 1)
  47. img = mastodon.media_post(msg[0].split('=')[1], "image/jpeg")
  48. mastodon.status_post(msg[1].replace('\\n','\n'), media_ids=img['id'], visibility='unlisted')
  49. else:
  50. mastodon.status_post(toot.replace('\\n','\n'), visibility='unlisted')
  51. megafono()