/examples/roster_browser.py

https://github.com/poezio/slixmpp · Python · 133 lines · 106 code · 8 blank · 19 comment · 4 complexity · 91c8cd93301aeff64e4d1dd3e4f12f4a MD5 · raw file

  1. #!/usr/bin/env python3
  2. # Slixmpp: The Slick XMPP Library
  3. # Copyright (C) 2011 Nathanael C. Fritz
  4. # This file is part of Slixmpp.
  5. # See the file LICENSE for copying permission.
  6. import logging
  7. from getpass import getpass
  8. from argparse import ArgumentParser
  9. import slixmpp
  10. from slixmpp.exceptions import IqError, IqTimeout
  11. from slixmpp.xmlstream.asyncio import asyncio
  12. class RosterBrowser(slixmpp.ClientXMPP):
  13. """
  14. A basic script for dumping a client's roster to
  15. the command line.
  16. """
  17. def __init__(self, jid, password):
  18. slixmpp.ClientXMPP.__init__(self, jid, password)
  19. # The session_start event will be triggered when
  20. # the bot establishes its connection with the server
  21. # and the XML streams are ready for use. We want to
  22. # listen for this event so that we we can initialize
  23. # our roster.
  24. self.add_event_handler("session_start", self.start)
  25. self.add_event_handler("changed_status", self.wait_for_presences)
  26. self.received = set()
  27. self.presences_received = asyncio.Event()
  28. async def start(self, event):
  29. """
  30. Process the session_start event.
  31. Typical actions for the session_start event are
  32. requesting the roster and broadcasting an initial
  33. presence stanza.
  34. Arguments:
  35. event -- An empty dictionary. The session_start
  36. event does not provide any additional
  37. data.
  38. """
  39. try:
  40. await self.get_roster()
  41. except IqError as err:
  42. print('Error: %s' % err.iq['error']['condition'])
  43. except IqTimeout:
  44. print('Error: Request timed out')
  45. self.send_presence()
  46. print('Waiting for presence updates...\n')
  47. await asyncio.sleep(10)
  48. print('Roster for %s' % self.boundjid.bare)
  49. groups = self.client_roster.groups()
  50. for group in groups:
  51. print('\n%s' % group)
  52. print('-' * 72)
  53. for jid in groups[group]:
  54. sub = self.client_roster[jid]['subscription']
  55. name = self.client_roster[jid]['name']
  56. if self.client_roster[jid]['name']:
  57. print(' %s (%s) [%s]' % (name, jid, sub))
  58. else:
  59. print(' %s [%s]' % (jid, sub))
  60. connections = self.client_roster.presence(jid)
  61. for res, pres in connections.items():
  62. show = 'available'
  63. if pres['show']:
  64. show = pres['show']
  65. print(' - %s (%s)' % (res, show))
  66. if pres['status']:
  67. print(' %s' % pres['status'])
  68. self.disconnect()
  69. def wait_for_presences(self, pres):
  70. """
  71. Track how many roster entries have received presence updates.
  72. """
  73. self.received.add(pres['from'].bare)
  74. if len(self.received) >= len(self.client_roster.keys()):
  75. self.presences_received.set()
  76. else:
  77. self.presences_received.clear()
  78. if __name__ == '__main__':
  79. # Setup the command line arguments.
  80. parser = ArgumentParser()
  81. parser.add_argument("-q","--quiet", help="set logging to ERROR",
  82. action="store_const",
  83. dest="loglevel",
  84. const=logging.ERROR,
  85. default=logging.ERROR)
  86. parser.add_argument("-d","--debug", help="set logging to DEBUG",
  87. action="store_const",
  88. dest="loglevel",
  89. const=logging.DEBUG,
  90. default=logging.ERROR)
  91. # JID and password options.
  92. parser.add_argument("-j", "--jid", dest="jid",
  93. help="JID to use")
  94. parser.add_argument("-p", "--password", dest="password",
  95. help="password to use")
  96. args = parser.parse_args()
  97. # Setup logging.
  98. logging.basicConfig(level=args.loglevel,
  99. format='%(levelname)-8s %(message)s')
  100. if args.jid is None:
  101. args.jid = input("Username: ")
  102. if args.password is None:
  103. args.password = getpass("Password: ")
  104. xmpp = RosterBrowser(args.jid, args.password)
  105. # Connect to the XMPP server and start processing XMPP stanzas.
  106. xmpp.connect()
  107. xmpp.process(forever=False)