fortunes-spam-bot.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  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. def getSpam(sections=('spam-o', 'spam-ita-o')):
  9. cmd = ['fortune', '-o', *sections]
  10. process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  11. stdout, stderr = process.communicate()
  12. try:
  13. stdout = stdout.strip()
  14. stdout = stdout.decode('utf8')
  15. except:
  16. return 'uh-oh: something was wrong with the encoding of the can\'s label; try again'
  17. if process.returncode != 0:
  18. return 'something terrible is happening: exit code: %s, stderr: %s' % (
  19. process.returncode, stderr.decode('utf8'))
  20. if not stdout:
  21. return 'sadness: the spam can was empty; try again'
  22. return stdout
  23. def serve(token):
  24. spam = getSpam()
  25. print('serving:\n%s' % spam)
  26. mastodon = Mastodon(access_token=token, api_base_url=API_URL)
  27. mastodon.status_post(spam, sensitive=True, spoiler_text='NSFW')
  28. if __name__ == '__main__':
  29. if 'SPAMBOT_TOKEN' not in os.environ:
  30. print("Please specify the Mastodon token in the SPAMBOT_TOKEN environment variable")
  31. sys.exit(1)
  32. serve(token=os.environ['SPAMBOT_TOKEN'])