email.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import logging
  2. import requests
  3. import requests.exceptions
  4. import tts
  5. import ears
  6. import base
  7. _RECIPIENTS = {
  8. 'martin': 'martin@gerner.co',
  9. 'pointy': 'martin@pointy.com',
  10. 'georgina': 'georgina@pointy.com',
  11. }
  12. _MAILGUN_API_URL = 'https://api.mailgun.net/v3/mg.gerner.co'
  13. _MAILGUN_API_KEY = 'key-80245476ae35aa626d782556419280f9'
  14. _MAILGUN_SENDER_EMAIL = 'noreply@mg.gerner.co'
  15. def _send_by_sendgrid(recipient, subject, email_body):
  16. auth = ('api', _MAILGUN_API_KEY)
  17. body = {
  18. 'from': _MAILGUN_SENDER_EMAIL,
  19. 'to': recipient,
  20. 'subject': subject,
  21. 'text': email_body
  22. }
  23. resp = requests.post(_MAILGUN_API_URL + '/messages', data=body, auth=auth)
  24. if resp.status_code != 200:
  25. resp.raise_for_status()
  26. class Email(base.BaseFunction):
  27. def preferred_phrases(self):
  28. return _RECIPIENTS.keys()
  29. def _send(self, recipient):
  30. logging.info('email _send: %s', recipient)
  31. tts.tts(recipient)
  32. lines, terminator = ears.listen_until_terminated()
  33. if terminator == 'done':
  34. body = '\n'.join(lines)
  35. logging.info('Sending email: %s: %s', _RECIPIENTS[recipient], lines)
  36. try:
  37. _send_by_sendgrid(_RECIPIENTS[recipient], 'snowbody email', body)
  38. tts.tts('done')
  39. except requests.exceptions.HTTPError, e:
  40. tts.tts('error')
  41. logging.error(e)
  42. else:
  43. tts.tts('cancelled')
  44. def call(self, additional_tokens=None, **_):
  45. logging.info('email: %s', additional_tokens)
  46. for t in additional_tokens:
  47. t = t.lower()
  48. if t in _RECIPIENTS:
  49. self._send(t)
  50. return
  51. tts.tts('to whom?')
  52. recipient = ears.listen(pause_threshold=1, preferred_phrases=self.preferred_phrases())
  53. if recipient in _RECIPIENTS:
  54. self._send(recipient)