fortunes-spam-bot.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/usr/bin/env python3
  2. """Telegram bot for fortunes-spam.
  3. Build it with: docker build -t fortunes-spam-bot .
  4. Run it with something like: docker run -ti --rm -e SPAMBOT_TOKEN=your-telegram-token fortunes-spam-bot
  5. Copyright 2018-2021 Davide Alberani <da@erlug.linux.it> Apache 2.0 license
  6. """
  7. import os
  8. import logging
  9. import subprocess
  10. from telegram.ext import Updater, CommandHandler
  11. logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
  12. level=logging.INFO)
  13. logger = logging.getLogger(__name__)
  14. EXTERNAL_VOL = '/fortunes'
  15. def getSpam(section):
  16. extPath = os.path.join(EXTERNAL_VOL, section)
  17. if os.path.isfile(extPath):
  18. section = extPath
  19. cmd = ['fortune', '-o', section]
  20. process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  21. stdout, stderr = process.communicate()
  22. try:
  23. stdout = stdout.strip()
  24. stdout = stdout.decode('utf8')
  25. except:
  26. return 'uh-oh: something was wrong with the encoding of the can\'s label; try again'
  27. if process.returncode != 0:
  28. return 'something terrible is happening: exit code: %s, stderr: %s' % (
  29. process.returncode, stderr.decode('utf8'))
  30. if not stdout:
  31. return 'sadness: the spam can was empty; try again'
  32. return stdout
  33. def serve(section, update, context):
  34. spam = getSpam(section)
  35. logging.info('%s wants some spam; serving:\n%s' % (update.effective_user.username, spam))
  36. update.message.reply_text(spam)
  37. def en(update, context):
  38. return serve('spam-o', update, context)
  39. def it(update, context):
  40. return serve('spam-ita-o', update, context)
  41. def about(update, context):
  42. logging.info('%s required more info' % update.effective_user.username)
  43. update.message.reply_text('See https://github.com/alberanid/fortunes-spam')
  44. if __name__ == '__main__':
  45. if 'SPAMBOT_TOKEN' not in os.environ:
  46. print("Please specify the Telegram token in the SPAMBOT_TOKEN environment variable")
  47. logging.info('start serving delicious spam')
  48. updater = Updater(os.environ['SPAMBOT_TOKEN'])
  49. updater.dispatcher.add_handler(CommandHandler('en', en))
  50. updater.dispatcher.add_handler(CommandHandler('it', it))
  51. updater.dispatcher.add_handler(CommandHandler('about', about))
  52. updater.start_polling()
  53. updater.idle()