telegram-bot.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #!/usr/bin/env python3
  2. """Telegram bot for Thoughts & Prayers.
  3. Build it with: docker build -f Dockerfile.telegram -t telegram-tap .
  4. Run it with something like: docker run -ti --rm -e TAPBOT_TOKEN=your-telegram-token telegram-tap
  5. Copyright 2018 Davide Alberani <da@erlug.linux.it> Apache 2.0 license
  6. """
  7. import os
  8. import sys
  9. import logging
  10. import subprocess
  11. from telegram.ext import Updater, CommandHandler
  12. sys.stdout = open(sys.stdout.fileno(), mode='w', encoding='utf8', buffering=1)
  13. logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
  14. level=logging.INFO)
  15. logger = logging.getLogger(__name__)
  16. def getThoughtsAndPrayers():
  17. cmd = ['/cry-a-lot']
  18. process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  19. stdout, stderr = process.communicate()
  20. try:
  21. stdout = stdout.strip()
  22. stdout = stdout.decode('utf8')
  23. except:
  24. return 'uh-oh: something was wrong with the encoding of the prayer; try again'
  25. if process.returncode != 0:
  26. return 'something terrible is happening: exit code: %s, stderr: %s' % (
  27. process.returncode, stderr.decode('utf8'))
  28. if not stdout:
  29. return 'sadness: the Thoughts & Prayers bottle was empty; try again'
  30. return stdout
  31. def tap(bot, update):
  32. a_tap = getThoughtsAndPrayers()
  33. logging.info('%s wants some Thoughts & Prayers; serving:\n%s' % (update.message.from_user.name, a_tap))
  34. update.message.reply_text(a_tap)
  35. def about(bot, update):
  36. logging.info('%s required more info' % update.message.from_user.name)
  37. update.message.reply_text('See https://github.com/alberanid/thoughts-and-prayers')
  38. if __name__ == '__main__':
  39. if 'TAPBOT_TOKEN' not in os.environ:
  40. print("Please specify the Telegram token in the TAPBOT_TOKEN environment variable")
  41. logging.info('start serving Thoughts & Prayers')
  42. updater = Updater(os.environ['TAPBOT_TOKEN'])
  43. updater.dispatcher.add_handler(CommandHandler('tap', tap))
  44. updater.dispatcher.add_handler(CommandHandler('about', about))
  45. updater.start_polling()
  46. updater.idle()