cli.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. # -*- coding: utf-8 -*-
  2. import os
  3. import sys
  4. from collections import OrderedDict
  5. import xmpp
  6. import argparse
  7. """
  8. Synopsis::
  9. xmpp-message --debug \
  10. --jabberid foobar@xmpp.domain.tld --password secret \
  11. --receiver bazqux@xmpp.domain.tld --message '☠☠☠ hello world ☠☠☠'
  12. """
  13. def send_message(jabberid, password, receiver, message, debug=False):
  14. """
  15. Connect to XMPP server and send message.
  16. """
  17. if debug:
  18. debug = ['always']
  19. jid = xmpp.protocol.JID(jabberid)
  20. connection = xmpp.Client(server=jid.getDomain(), debug=debug)
  21. connection.connect()
  22. retval = connection.auth(user=jid.getNode(), password=password, resource=jid.getResource())
  23. if retval is None:
  24. sys.stderr.write("ERROR: Authentication failed\n")
  25. sys.exit(1)
  26. connection.send(xmpp.protocol.Message(to=receiver, body=message))
  27. def read_xsend():
  28. """
  29. Read credentials from `~/.xsend` file.
  30. """
  31. params = OrderedDict()
  32. xsendfile = os.path.join(os.environ['HOME'], '.xsend')
  33. with open(xsendfile, "r") as f:
  34. for ln in f.readlines():
  35. ln = ln.strip()
  36. if not ln:
  37. continue
  38. if ln[0] not in ('#', ';'):
  39. key, val = ln.split('=', 1)
  40. params[key.lower()] = val
  41. return params
  42. def simple_message():
  43. """
  44. Send an XMPP message from the command line.
  45. """
  46. parser = argparse.ArgumentParser(description='Authenticate with XMPP server and send simple message')
  47. parser.add_argument('--jabberid', required=False, help='Jabber Identifier (JID) aka. username')
  48. parser.add_argument('--password', required=False, help='Password for Jabber Identifier (JID)')
  49. parser.add_argument('--receiver', required=True, help='Receiver address')
  50. parser.add_argument('--message', required=True, help='Message content')
  51. parser.add_argument('--debug', action='store_true', default=False, help='Enable debug messages')
  52. options = parser.parse_args()
  53. # Optionally, read credentials from `~/.xsend` file.
  54. if options.jabberid is None:
  55. try:
  56. params = read_xsend()
  57. except Exception as ex:
  58. sys.stderr.write("ERROR: Unable to read credentials from ~/.xsend file: %s\n" % ex)
  59. sys.exit(1)
  60. options.jabberid = params["jid"]
  61. options.password = params["password"]
  62. send_message(options.jabberid, options.password, options.receiver, options.message, debug=options.debug)