gmail_checker.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # -*- coding: utf-8 -*-
  2. import logging
  3. from gmail import Gmail
  4. from email.header import decode_header
  5. from core.NeuronModule import NeuronModule
  6. logging.basicConfig()
  7. logger = logging.getLogger("kalliope")
  8. class MissingParameterException(Exception):
  9. pass
  10. class Gmail_checker(NeuronModule):
  11. def __init__(self, **kwargs):
  12. super(Gmail_checker, self).__init__(**kwargs)
  13. # check if parameters have been provided
  14. username = kwargs.get('username', None)
  15. password = kwargs.get('password', None)
  16. if username is None:
  17. raise MissingParameterException("Username parameter required")
  18. if password is None:
  19. raise MissingParameterException("Password parameter required")
  20. # prepare a returned dict
  21. returned_dict = dict()
  22. g = Gmail()
  23. g.login(username, password)
  24. # check if login succeed
  25. logging.debug("Gmail loggin ok: %s" % g.logged_in) # Should be True, AuthenticationError if login fails
  26. # get unread mail
  27. unread = g.inbox().mail(unread=True)
  28. returned_dict["unread"] = len(unread)
  29. if len(unread) > 0:
  30. # add a list of subject
  31. subject_list = list()
  32. for email in unread:
  33. email.fetch()
  34. encoded_subject = email.subject
  35. subject = self._parse_subject(encoded_subject)
  36. subject_list.append(subject)
  37. returned_dict["subjects"] = subject_list
  38. logger.debug("gmail neuron returned dict: %s" % str(returned_dict))
  39. # logout of gmail
  40. g.logout()
  41. self.say(returned_dict)
  42. def _parse_subject(self, encoded_subject):
  43. dh = decode_header(encoded_subject)
  44. return ''.join([self.try_parse(t[0], t[1]) for t in dh])
  45. @staticmethod
  46. def try_parse(header, encoding):
  47. if encoding is None:
  48. encoding = 'ASCII'
  49. try:
  50. return unicode(header, encoding)
  51. except UnicodeDecodeError:
  52. try:
  53. return unicode(header, 'ISO-8859-1')
  54. except UnicodeDecodeError:
  55. return unicode(header, 'UTF-8')