fortunes-spam-bot.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 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. def getSpam(section):
  15. cmd = ['fortune', '-o', section]
  16. process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  17. stdout, stderr = process.communicate()
  18. try:
  19. stdout = stdout.strip()
  20. stdout = stdout.decode('utf8')
  21. except:
  22. return 'uh-oh: something was wrong with the encoding of the can\'s label; try again'
  23. if process.returncode != 0:
  24. return 'something terrible is happening: exit code: %s, stderr: %s' % (
  25. process.returncode, stderr.decode('utf8'))
  26. if not stdout:
  27. return 'sadness: the spam can was empty; try again'
  28. return stdout
  29. def serve(section, bot, update):
  30. spam = getSpam(section)
  31. logging.info('%s wants some spam; serving:\n%s' % (update.message.from_user.name, spam))
  32. update.message.reply_text(spam)
  33. def en(bot, update):
  34. return serve('spam-o', bot, update)
  35. def it(bot, update):
  36. return serve('spam-ita-o', bot, update)
  37. def about(bot, update):
  38. logging.info('%s required more info' % update.message.from_user.name)
  39. update.message.reply_text('See https://github.com/alberanid/fortunes-spam')
  40. if __name__ == '__main__':
  41. if 'SPAMBOT_TOKEN' not in os.environ:
  42. print("Please specify the Telegram token in the SPAMBOT_TOKEN environment variable")
  43. logging.info('start serving delicious spam')
  44. updater = Updater(os.environ['SPAMBOT_TOKEN'])
  45. updater.dispatcher.add_handler(CommandHandler('en', en))
  46. updater.dispatcher.add_handler(CommandHandler('it', it))
  47. updater.dispatcher.add_handler(CommandHandler('about', about))
  48. updater.start_polling()
  49. updater.idle()