PageRenderTime 53ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/examples/roster_browser.py

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