onthisday-mastodon-bot.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. import os
  4. import sys
  5. import subprocess
  6. from mastodon import Mastodon
  7. API_URL = 'https://botsin.space/'
  8. sys.stdout = open(sys.stdout.fileno(), mode='w', encoding='utf8', buffering=1)
  9. def getEvents():
  10. cmd = ['python3', '-m', 'onthisday']
  11. if len(sys.argv) > 1:
  12. cmd += sys.argv[1:]
  13. process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  14. stdout, stderr = process.communicate()
  15. try:
  16. stdout = stdout.strip()
  17. stdout = stdout.decode('utf8')
  18. except:
  19. return 'uh-oh: something was wrong with the encoding of the events; try again'
  20. if process.returncode != 0:
  21. return 'something terrible is happening: exit code: %s, stderr: %s' % (
  22. process.returncode, stderr.decode('utf8'))
  23. if not stdout:
  24. return 'sadness: the list of events is empty; try again'
  25. return stdout
  26. def serve(token):
  27. events = getEvents()
  28. print('On this day:\n\n%s' % events)
  29. mastodon = Mastodon(access_token=token, api_base_url=API_URL)
  30. mastodon.status_post(events)
  31. if __name__ == '__main__':
  32. if 'EVENTS_TOKEN' not in os.environ:
  33. print("Please specify the Mastodon token in the EVENTS_TOKEN environment variable")
  34. sys.exit(1)
  35. serve(token=os.environ['EVENTS_TOKEN'])