telegram-onthisday.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #!/usr/bin/env python3
  2. """Telegram bot for onthisday.
  3. Build it with: docker build -t telegram-onthisday .
  4. Run it with something like: docker run -ti --rm -e EVENTS_TOKEN=your-telegram-token telegram-onthisday
  5. Copyright 2019 Davide Alberani <da@erlug.linux.it> Apache 2.0 license
  6. """
  7. import os
  8. import sys
  9. import time
  10. import logging
  11. import subprocess
  12. from telegram.ext import Updater, CommandHandler
  13. logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
  14. level=logging.INFO)
  15. logger = logging.getLogger(__name__)
  16. def getEvents(day=None):
  17. cmd = ['python3', '/onthisday/onthisday.py']
  18. if day:
  19. try:
  20. time.strptime(day, '%m/%d')
  21. cmd += ['--date', day]
  22. except Exception:
  23. pass
  24. if len(sys.argv) > 1:
  25. cmd += sys.argv[1:]
  26. process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  27. stdout, stderr = process.communicate()
  28. try:
  29. stdout = stdout.strip()
  30. stdout = stdout.decode('utf8')
  31. except:
  32. return 'uh-oh: something was wrong with the encoding of the events; try again'
  33. if process.returncode != 0:
  34. return 'something terrible is happening: exit code: %s, stderr: %s' % (
  35. process.returncode, stderr.decode('utf8'))
  36. if not stdout:
  37. return 'sadness: the events list is empty; try again'
  38. return stdout
  39. def events(bot, update, args=None):
  40. day = None
  41. if args and args[0]:
  42. day = args[0].strip()
  43. events = getEvents(day)
  44. logging.info('%s wants some news; serving:\n%s' % (update.message.from_user.name, events))
  45. update.message.reply_text(events)
  46. def about(bot, update):
  47. logging.info('%s required more info' % update.message.from_user.name)
  48. update.message.reply_text('See https://github.com/alberanid/onthisday\n\n/today to use the current date\n\n/date 07/30 for July 30')
  49. if __name__ == '__main__':
  50. if 'EVENTS_TOKEN' not in os.environ:
  51. print("Please specify the Telegram token in the EVENTS_TOKEN environment variable")
  52. logging.info('start serving very important facts')
  53. updater = Updater(os.environ['EVENTS_TOKEN'])
  54. updater.dispatcher.add_handler(CommandHandler('today', events, pass_args=True))
  55. updater.dispatcher.add_handler(CommandHandler('start', events, pass_args=True))
  56. updater.dispatcher.add_handler(CommandHandler('date', events, pass_args=True))
  57. updater.dispatcher.add_handler(CommandHandler('about', about))
  58. updater.dispatcher.add_handler(CommandHandler('help', about))
  59. updater.start_polling()
  60. updater.idle()