Messenger.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import sys
  4. import logging
  5. import getpass
  6. import time
  7. import ssl
  8. import configparser as config
  9. from xmppy.gpg_holder import Gpg
  10. from optparse import OptionParser
  11. import sleekxmpp
  12. if sys.version_info < (3, 0):
  13. from sleekxmpp.util.misc_ops import setdefaultencoding
  14. setdefaultencoding('utf8')
  15. else:
  16. raw_input = input
  17. class Client(sleekxmpp.ClientXMPP):
  18. def __init__(self, jid, password, recipient, msg_function, reply_function, freq=120, msg_t=True, rpl_t=True, wait=False):
  19. if jid == "file":
  20. tmp = config.ConfigParser()
  21. check = tmp.read(password)
  22. if check == []:
  23. print("empty {}".format(password))
  24. exit()
  25. data = tmp["configfile"]
  26. if "jid" in data.keys() and "password" in data.keys():
  27. self.j = data["jid"]
  28. self.p = data["password"]
  29. else:
  30. print("Missing data in {}".format(password))
  31. exit()
  32. if recipient is None and msg_t:
  33. if "recipient" in data.keys():
  34. self.recipient = data["recipient"]
  35. else:
  36. print("Missing recipient in {}".format(password))
  37. exit()
  38. else:
  39. self.recipient = recipient
  40. else:
  41. self.j = jid
  42. self.p = password
  43. self.recipient = recipient
  44. self.msg_function = msg_function
  45. self.reply_function = reply_function
  46. self.msg_t = msg_t
  47. self.rpl_t = rpl_t
  48. self.mm = []
  49. self.gpg_encryption = False
  50. self.ntime = freq # seconds
  51. self.run(wait)
  52. def run(self, wait):
  53. if not wait:
  54. sleekxmpp.ClientXMPP.__init__(self, self.j, self.p)
  55. self.add_event_handler("session_start", self.start)
  56. if self.rpl_t:
  57. self.add_event_handler("message", self.message)
  58. self.register_plugin('xep_0030') # Service Discovery
  59. self.register_plugin('xep_0004') # Data Forms
  60. self.register_plugin('xep_0060') # PubSub
  61. self.register_plugin('xep_0199') # XMPP Ping
  62. self.ssl_version = ssl.PROTOCOL_TLSv1_2
  63. if self.connect():
  64. self.process(block=True)
  65. print("Done")
  66. else:
  67. print("Unable to connect.")
  68. @classmethod
  69. def receiveMessage(cls, jid, password, reply):
  70. logging.basicConfig(
  71. level=logging.ERROR, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  72. instance = cls(jid, password, None, None, reply,
  73. freq=-1, msg_t=False, rpl_t=True)
  74. return instance
  75. @classmethod
  76. def sendMessage(cls, jid, password, recipient, message, freq=-1):
  77. logging.basicConfig(
  78. level=logging.ERROR, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  79. instance = cls(jid, password, recipient, message,
  80. None, freq, msg_t=True, rpl_t=False)
  81. return instance
  82. @classmethod
  83. def initialize(cls, jid, password, recipient, message, reply, freq=10, wait=False):
  84. logging.basicConfig(
  85. level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  86. instance = cls(jid, password, recipient, message, reply,
  87. freq=freq, msg_t=True, rpl_t=True, wait=wait)
  88. return instance
  89. def start(self, event):
  90. self.send_presence()
  91. self.get_roster()
  92. if self.msg_t:
  93. print("start() --msg_t->True")
  94. self._start_thread("chat_send", self.monitor)
  95. def monitor(self):
  96. while True:
  97. time.sleep(1)
  98. if int(time.time()) % self.ntime == 0 and self.ntime > 0:
  99. print("Sending...{}".format(self.MSG()))
  100. self.send_message(mto=self.recipient,
  101. mbody=self.MSG(), mtype='chat')
  102. elif self.ntime < 0:
  103. self.send_message(mto=self.recipient,
  104. mbody=self.MSG(), mtype='chat')
  105. self.disconnect(wait=True)
  106. break
  107. def message(self, msg):
  108. if msg['type'] in ('chat', 'normal'):
  109. msg.reply(self.RPL(msg["body"])).send()
  110. print(str(msg["body"]))
  111. self.mm = msg
  112. def enableGPG(self, uid, gpghome=''):
  113. self.gpg = Gpg(gpghome)
  114. self.uid = uid
  115. self.gpg_encryption = True
  116. return None
  117. def GPG(func):
  118. def wrap(self, *args, **kwargs):
  119. if self.gpg_encryption:
  120. message = self.gpg.encrypt(
  121. func(self, *args, **kwargs), uids=self.uid)
  122. else:
  123. message = func(self, *args, **kwargs)
  124. return message
  125. return wrap
  126. @GPG
  127. def MSG(self):
  128. return self.msg_function()
  129. @GPG
  130. def RPL(self, msg):
  131. return self.reply_function(msg)
  132. def main():
  133. optp = OptionParser()
  134. optp.add_option('-q', '--quiet', help='set logging to ERROR',
  135. action='store_const', dest='loglevel',
  136. const=logging.ERROR, default=logging.INFO)
  137. optp.add_option('-d', '--debug', help='set logging to DEBUG',
  138. action='store_const', dest='loglevel',
  139. const=logging.DEBUG, default=logging.INFO)
  140. optp.add_option('-v', '--verbose', help='set logging to COMM',
  141. action='store_const', dest='loglevel',
  142. const=5, default=logging.INFO)
  143. # JID and password options.
  144. optp.add_option("-j", "--jid", dest="jid",
  145. help="JID to use")
  146. optp.add_option("-p", "--password", dest="password",
  147. help="password to use")
  148. optp.add_option("-t", "--to", dest="to",
  149. help="JID to send the message to")
  150. optp.add_option("-m", "--message", dest="message",
  151. help="message to send")
  152. opts, args = optp.parse_args()
  153. logging.basicConfig(level=opts.loglevel,
  154. format='%(levelname)-8s %(message)s')
  155. if opts.jid is None:
  156. opts.jid = raw_input("Username: ")
  157. if opts.password is None:
  158. opts.password = getpass.getpass("Password: ")
  159. xmpp = Client.sendMessage(opts.jid, opts.password,
  160. opts.to, lambda: opts.message)