diff options
Diffstat (limited to 'examples')
33 files changed, 1320 insertions, 1848 deletions
diff --git a/examples/IoT_TestDevice.py b/examples/IoT_TestDevice.py index b85a0b7c..b9546017 100755 --- a/examples/IoT_TestDevice.py +++ b/examples/IoT_TestDevice.py @@ -1,43 +1,35 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ - SleekXMPP: The Sleek XMPP Library + Slixmpp: The Slick XMPP Library Implementation of xeps for Internet of Things http://wiki.xmpp.org/web/Tech_pages/IoT_systems Copyright (C) 2013 Sustainable Innovation, Joachim.lindborg@sust.se - This file is part of SleekXMPP. + This file is part of Slixmpp. See the file LICENSE for copying permission. """ -import getpass import logging -import sys -from optparse import OptionParser +from os.path import basename, join as pjoin +from argparse import ArgumentParser from urllib import urlopen +from getpass import getpass -import sleekxmpp -# Python versions before 3.0 do not use UTF-8 encoding -# by default. To ensure that Unicode is handled properly -# throughout SleekXMPP, we will set the default encoding -# ourselves to UTF-8. -if sys.version_info < (3, 0): - from sleekxmpp.util.misc_ops import setdefaultencoding - setdefaultencoding('utf8') -else: - raw_input = input +import slixmpp +from slixmpp.plugins.xep_0323.device import Device -from sleekxmpp.plugins.xep_0323.device import Device +#from slixmpp.exceptions import IqError, IqTimeout -class IoT_TestDevice(sleekxmpp.ClientXMPP): +class IoT_TestDevice(slixmpp.ClientXMPP): """ A simple IoT device that can act as server or client """ def __init__(self, jid, password): - sleekxmpp.ClientXMPP.__init__(self, jid, password) + slixmpp.ClientXMPP.__init__(self, jid, password) self.add_event_handler("session_start", self.session_start) self.add_event_handler("message", self.message) self.device=None @@ -115,47 +107,44 @@ if __name__ == '__main__': # # "client" an IoT device or other party that would like to get data from another device - optp = OptionParser() + parser = ArgumentParser() # Output verbosity options. - optp.add_option('-q', '--quiet', help='set logging to ERROR', - action='store_const', dest='loglevel', - const=logging.ERROR, default=logging.INFO) - optp.add_option('-d', '--debug', help='set logging to DEBUG', - action='store_const', dest='loglevel', - const=logging.DEBUG, default=logging.INFO) - optp.add_option('-v', '--verbose', help='set logging to COMM', - action='store_const', dest='loglevel', - const=5, default=logging.INFO) - optp.add_option('-t', '--pingto', help='set jid to ping', - action='store', type='string', dest='pingjid', - default=None) + parser.add_argument("-q", "--quiet", help="set logging to ERROR", + action="store_const", dest="loglevel", + const=logging.ERROR, default=logging.INFO) + parser.add_argument("-d", "--debug", help="set logging to DEBUG", + action="store_const", dest="loglevel", + const=logging.DEBUG, default=logging.INFO) + parser.add_argument("-t", "--pingto", help="set jid to ping", + action="store", type="string", dest="pingjid", + default=None) # JID and password options. - optp.add_option("-j", "--jid", dest="jid", - help="JID to use") - optp.add_option("-p", "--password", dest="password", - help="password to use") + parser.add_argument("-j", "--jid", dest="jid", + help="JID to use") + parser.add_argument("-p", "--password", dest="password", + help="password to use") # IoT test - optp.add_option("-c", "--sensorjid", dest="sensorjid", - help="Another device to call for data on", default=None) - optp.add_option("-n", "--nodeid", dest="nodeid", - help="I am a device get ready to be called", default=None) + parser.add_argument("-c", "--sensorjid", dest="sensorjid", + help="Another device to call for data on", default=None) + parser.add_argument("-n", "--nodeid", dest="nodeid", + help="I am a device get ready to be called", default=None) - opts, args = optp.parse_args() + args = parser.parse_args() # Setup logging. - logging.basicConfig(level=opts.loglevel, + logging.basicConfig(level=args.loglevel, format='%(levelname)-8s %(message)s') - if opts.jid is None: - opts.jid = raw_input("Username: ") - if opts.password is None: - opts.password = getpass.getpass("Password: ") + if args.jid is None: + args.jid = input("Username: ") + if args.password is None: + args.password = getpass("Password: ") - xmpp = IoT_TestDevice(opts.jid,opts.password) + xmpp = IoT_TestDevice(args.jid,args.password) xmpp.register_plugin('xep_0030') #xmpp['xep_0030'].add_feature(feature='urn:xmpp:iot:sensordata', # node=None, @@ -163,31 +152,31 @@ if __name__ == '__main__': xmpp.register_plugin('xep_0323') xmpp.register_plugin('xep_0325') - if opts.nodeid: + if args.nodeid: # xmpp['xep_0030'].add_feature(feature='urn:xmpp:sn', - # node=opts.nodeid, + # node=args.nodeid, # jid=xmpp.boundjid.full) - myDevice = TheDevice(opts.nodeid) + myDevice = TheDevice(args.nodeid); # myDevice._add_field(name="Relay", typename="numeric", unit="Bool"); myDevice._add_field(name="Temperature", typename="numeric", unit="C") myDevice._set_momentary_timestamp("2013-03-07T16:24:30") myDevice._add_field_momentary_data("Temperature", "23.4", flags={"automaticReadout": "true"}) - xmpp['xep_0323'].register_node(nodeId=opts.nodeid, device=myDevice, commTimeout=10) + xmpp['xep_0323'].register_node(nodeId=args.nodeid, device=myDevice, commTimeout=10); xmpp.beClientOrServer(server=True) while not(xmpp.testForRelease()): xmpp.connect() xmpp.process(block=True) logging.debug("lost connection") - if opts.sensorjid: + if args.sensorjid: logging.debug("will try to call another device for data") - xmpp.beClientOrServer(server=False,clientJID=opts.sensorjid) + xmpp.beClientOrServer(server=False,clientJID=args.sensorjid) xmpp.connect() xmpp.process(block=True) logging.debug("ready ending") else: - print "noopp didn't happen" + print("noopp didn't happen") diff --git a/examples/adhoc_provider.py b/examples/adhoc_provider.py index 86a575c9..72259555 100755 --- a/examples/adhoc_provider.py +++ b/examples/adhoc_provider.py @@ -1,41 +1,30 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ - SleekXMPP: The Sleek XMPP Library + Slixmpp: The Slick XMPP Library Copyright (C) 2010 Nathanael C. Fritz - This file is part of SleekXMPP. + This file is part of Slixmpp. See the file LICENSE for copying permission. """ -import sys import logging -import getpass -from optparse import OptionParser +from getpass import getpass +from argparse import ArgumentParser -import sleekxmpp +import slixmpp -# Python versions before 3.0 do not use UTF-8 encoding -# by default. To ensure that Unicode is handled properly -# throughout SleekXMPP, we will set the default encoding -# ourselves to UTF-8. -if sys.version_info < (3, 0): - from sleekxmpp.util.misc_ops import setdefaultencoding - setdefaultencoding('utf8') -else: - raw_input = input - -class CommandBot(sleekxmpp.ClientXMPP): +class CommandBot(slixmpp.ClientXMPP): """ - A simple SleekXMPP bot that provides a basic + A simple Slixmpp bot that provides a basic adhoc command. """ def __init__(self, jid, password): - sleekxmpp.ClientXMPP.__init__(self, jid, password) + slixmpp.ClientXMPP.__init__(self, jid, password) # The session_start event will be triggered when # the bot establishes its connection with the server @@ -143,62 +132,42 @@ class CommandBot(sleekxmpp.ClientXMPP): if __name__ == '__main__': # Setup the command line arguments. - optp = OptionParser() + parser = ArgumentParser() # Output verbosity options. - optp.add_option('-q', '--quiet', help='set logging to ERROR', - action='store_const', dest='loglevel', - const=logging.ERROR, default=logging.INFO) - optp.add_option('-d', '--debug', help='set logging to DEBUG', - action='store_const', dest='loglevel', - const=logging.DEBUG, default=logging.INFO) - optp.add_option('-v', '--verbose', help='set logging to COMM', - action='store_const', dest='loglevel', - const=5, default=logging.INFO) + parser.add_argument("-q", "--quiet", help="set logging to ERROR", + action="store_const", dest="loglevel", + const=logging.ERROR, default=logging.INFO) + parser.add_argument("-d", "--debug", help="set logging to DEBUG", + action="store_const", dest="loglevel", + const=logging.DEBUG, default=logging.INFO) # JID and password options. - optp.add_option("-j", "--jid", dest="jid", - help="JID to use") - optp.add_option("-p", "--password", dest="password", - help="password to use") + parser.add_argument("-j", "--jid", dest="jid", + help="JID to use") + parser.add_argument("-p", "--password", dest="password", + help="password to use") - opts, args = optp.parse_args() + args = parser.parse_args() # Setup logging. - logging.basicConfig(level=opts.loglevel, + logging.basicConfig(level=args.loglevel, format='%(levelname)-8s %(message)s') - if opts.jid is None: - opts.jid = raw_input("Username: ") - if opts.password is None: - opts.password = getpass.getpass("Password: ") + if args.jid is None: + args.jid = input("Username: ") + if args.password is None: + args.password = getpass("Password: ") # Setup the CommandBot and register plugins. Note that while plugins may # have interdependencies, the order in which you register them does # not matter. - xmpp = CommandBot(opts.jid, opts.password) + xmpp = CommandBot(args.jid, args.password) xmpp.register_plugin('xep_0030') # Service Discovery xmpp.register_plugin('xep_0004') # Data Forms xmpp.register_plugin('xep_0050') # Adhoc Commands xmpp.register_plugin('xep_0199', {'keepalive': True, 'frequency':15}) - # If you are working with an OpenFire server, you may need - # to adjust the SSL version used: - # xmpp.ssl_version = ssl.PROTOCOL_SSLv3 - - # If you want to verify the SSL certificates offered by a server: - # xmpp.ca_certs = "path/to/ca/cert" - # Connect to the XMPP server and start processing XMPP stanzas. - if xmpp.connect(): - # If you do not have the dnspython library installed, you will need - # to manually specify the name of the server if it does not match - # the one in the JID. For example, to use Google Talk you would - # need to use: - # - # if xmpp.connect(('talk.google.com', 5222)): - # ... - xmpp.process(block=True) - print("Done") - else: - print("Unable to connect.") + xmpp.connect() + xmpp.process() diff --git a/examples/adhoc_user.py b/examples/adhoc_user.py index 7df9f793..91e2e1ac 100755 --- a/examples/adhoc_user.py +++ b/examples/adhoc_user.py @@ -1,41 +1,30 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ - SleekXMPP: The Sleek XMPP Library + Slixmpp: The Slick XMPP Library Copyright (C) 2010 Nathanael C. Fritz - This file is part of SleekXMPP. + This file is part of Slixmpp. See the file LICENSE for copying permission. """ -import sys import logging -import getpass -from optparse import OptionParser +from getpass import getpass +from argparse import ArgumentParser -import sleekxmpp +import slixmpp -# Python versions before 3.0 do not use UTF-8 encoding -# by default. To ensure that Unicode is handled properly -# throughout SleekXMPP, we will set the default encoding -# ourselves to UTF-8. -if sys.version_info < (3, 0): - from sleekxmpp.util.misc_ops import setdefaultencoding - setdefaultencoding('utf8') -else: - raw_input = input - -class CommandUserBot(sleekxmpp.ClientXMPP): +class CommandUserBot(slixmpp.ClientXMPP): """ - A simple SleekXMPP bot that uses the adhoc command + A simple Slixmpp bot that uses the adhoc command provided by the adhoc_provider.py example. """ def __init__(self, jid, password, other, greeting): - sleekxmpp.ClientXMPP.__init__(self, jid, password) + slixmpp.ClientXMPP.__init__(self, jid, password) self.command_provider = other self.greeting = greeting @@ -142,69 +131,49 @@ class CommandUserBot(sleekxmpp.ClientXMPP): if __name__ == '__main__': # Setup the command line arguments. - optp = OptionParser() + parser = ArgumentParser() # Output verbosity options. - optp.add_option('-q', '--quiet', help='set logging to ERROR', - action='store_const', dest='loglevel', - const=logging.ERROR, default=logging.INFO) - optp.add_option('-d', '--debug', help='set logging to DEBUG', - action='store_const', dest='loglevel', - const=logging.DEBUG, default=logging.INFO) - optp.add_option('-v', '--verbose', help='set logging to COMM', - action='store_const', dest='loglevel', - const=5, default=logging.INFO) + parser.add_argument("-q", "--quiet", help="set logging to ERROR", + action="store_const", dest="loglevel", + const=logging.ERROR, default=logging.INFO) + parser.add_argument("-d", "--debug", help="set logging to DEBUG", + action="store_const", dest="loglevel", + const=logging.DEBUG, default=logging.INFO) # JID and password options. - optp.add_option("-j", "--jid", dest="jid", - help="JID to use") - optp.add_option("-p", "--password", dest="password", - help="password to use") - optp.add_option("-o", "--other", dest="other", - help="JID providing commands") - optp.add_option("-g", "--greeting", dest="greeting", - help="Greeting") + parser.add_argument("-j", "--jid", dest="jid", + help="JID to use") + parser.add_argument("-p", "--password", dest="password", + help="password to use") + parser.add_argument("-o", "--other", dest="other", + help="JID providing commands") + parser.add_argument("-g", "--greeting", dest="greeting", + help="Greeting") - opts, args = optp.parse_args() + args = parser.parse_args() # Setup logging. - logging.basicConfig(level=opts.loglevel, + logging.basicConfig(level=args.loglevel, format='%(levelname)-8s %(message)s') - if opts.jid is None: - opts.jid = raw_input("Username: ") - if opts.password is None: - opts.password = getpass.getpass("Password: ") - if opts.other is None: - opts.other = raw_input("JID Providing Commands: ") - if opts.greeting is None: - opts.greeting = raw_input("Greeting: ") + if args.jid is None: + args.jid = input("Username: ") + if args.password is None: + args.password = getpass("Password: ") + if args.other is None: + args.other = input("JID Providing Commands: ") + if args.greeting is None: + args.greeting = input("Greeting: ") # Setup the CommandBot and register plugins. Note that while plugins may # have interdependencies, the order in which you register them does # not matter. - xmpp = CommandUserBot(opts.jid, opts.password, opts.other, opts.greeting) + xmpp = CommandUserBot(args.jid, args.password, args.other, args.greeting) xmpp.register_plugin('xep_0030') # Service Discovery xmpp.register_plugin('xep_0004') # Data Forms xmpp.register_plugin('xep_0050') # Adhoc Commands - # If you are working with an OpenFire server, you may need - # to adjust the SSL version used: - # xmpp.ssl_version = ssl.PROTOCOL_SSLv3 - - # If you want to verify the SSL certificates offered by a server: - # xmpp.ca_certs = "path/to/ca/cert" - # Connect to the XMPP server and start processing XMPP stanzas. - if xmpp.connect(): - # If you do not have the dnspython library installed, you will need - # to manually specify the name of the server if it does not match - # the one in the JID. For example, to use Google Talk you would - # need to use: - # - # if xmpp.connect(('talk.google.com', 5222)): - # ... - xmpp.process(block=True) - print("Done") - else: - print("Unable to connect.") + xmpp.connect() + xmpp.process() diff --git a/examples/admin_commands.py b/examples/admin_commands.py index 5d9bf841..72577f87 100755 --- a/examples/admin_commands.py +++ b/examples/admin_commands.py @@ -1,41 +1,30 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ - SleekXMPP: The Sleek XMPP Library + Slixmpp: The Slick XMPP Library Copyright (C) 2010 Nathanael C. Fritz - This file is part of SleekXMPP. + This file is part of Slixmpp. See the file LICENSE for copying permission. """ -import sys import logging -import getpass -from optparse import OptionParser +from getpass import getpass +from argparse import ArgumentParser -import sleekxmpp +import slixmpp -# Python versions before 3.0 do not use UTF-8 encoding -# by default. To ensure that Unicode is handled properly -# throughout SleekXMPP, we will set the default encoding -# ourselves to UTF-8. -if sys.version_info < (3, 0): - from sleekxmpp.util.misc_ops import setdefaultencoding - setdefaultencoding('utf8') -else: - raw_input = input - -class AdminCommands(sleekxmpp.ClientXMPP): +class AdminCommands(slixmpp.ClientXMPP): """ - A simple SleekXMPP bot that uses admin commands to + A simple Slixmpp bot that uses admin commands to add a new user to a server. """ def __init__(self, jid, password, command): - sleekxmpp.ClientXMPP.__init__(self, jid, password) + slixmpp.ClientXMPP.__init__(self, jid, password) self.command = command @@ -81,13 +70,13 @@ class AdminCommands(sleekxmpp.ClientXMPP): for var, field in form['fields'].items(): if var != 'FORM_TYPE': if field['type'] == 'boolean': - answers[var] = raw_input('%s (y/n): ' % field['label']) + answers[var] = input('%s (y/n): ' % field['label']) if answers[var].lower() in ('1', 'true', 'y', 'yes'): answers[var] = '1' else: answers[var] = '0' else: - answers[var] = raw_input('%s: ' % field['label']) + answers[var] = input('%s: ' % field['label']) else: answers['FORM_TYPE'] = field['value'] form['type'] = 'submit' @@ -116,63 +105,43 @@ class AdminCommands(sleekxmpp.ClientXMPP): if __name__ == '__main__': # Setup the command line arguments. - optp = OptionParser() + parser = ArgumentParser() # Output verbosity options. - optp.add_option('-q', '--quiet', help='set logging to ERROR', - action='store_const', dest='loglevel', - const=logging.ERROR, default=logging.INFO) - optp.add_option('-d', '--debug', help='set logging to DEBUG', - action='store_const', dest='loglevel', - const=logging.DEBUG, default=logging.INFO) - optp.add_option('-v', '--verbose', help='set logging to COMM', - action='store_const', dest='loglevel', - const=5, default=logging.INFO) + parser.add_argument("-q", "--quiet", help="set logging to ERROR", + action="store_const", dest="loglevel", + const=logging.ERROR, default=logging.INFO) + parser.add_argument("-d", "--debug", help="set logging to DEBUG", + action="store_const", dest="loglevel", + const=logging.DEBUG, default=logging.INFO) # JID and password options. - optp.add_option("-j", "--jid", dest="jid", - help="JID to use") - optp.add_option("-p", "--password", dest="password", - help="password to use") - optp.add_option("-c", "--command", dest="command", - help="admin command to use") + parser.add_argument("-j", "--jid", dest="jid", + help="JID to use") + parser.add_argument("-p", "--password", dest="password", + help="password to use") + parser.add_argument("-c", "--command", dest="command", + help="admin command to use") - opts, args = optp.parse_args() + args = parser.parse_args() # Setup logging. - logging.basicConfig(level=opts.loglevel, + logging.basicConfig(level=args.loglevel, format='%(levelname)-8s %(message)s') - if opts.jid is None: - opts.jid = raw_input("Username: ") - if opts.password is None: - opts.password = getpass.getpass("Password: ") - if opts.command is None: - opts.command = raw_input("Admin command: ") + if args.jid is None: + args.jid = input("Username: ") + if args.password is None: + args.password = getpass("Password: ") + if args.command is None: + args.command = input("Admin command: ") # Setup the CommandBot and register plugins. Note that while plugins may # have interdependencies, the order in which you register them does # not matter. - xmpp = AdminCommands(opts.jid, opts.password, opts.command) + xmpp = AdminCommands(args.jid, args.password, args.command) xmpp.register_plugin('xep_0133') # Service Administration - # If you are working with an OpenFire server, you may need - # to adjust the SSL version used: - # xmpp.ssl_version = ssl.PROTOCOL_SSLv3 - - # If you want to verify the SSL certificates offered by a server: - # xmpp.ca_certs = "path/to/ca/cert" - # Connect to the XMPP server and start processing XMPP stanzas. - if xmpp.connect(): - # If you do not have the dnspython library installed, you will need - # to manually specify the name of the server if it does not match - # the one in the JID. For example, to use Google Talk you would - # need to use: - # - # if xmpp.connect(('talk.google.com', 5222)): - # ... - xmpp.process(block=True) - print("Done") - else: - print("Unable to connect.") + xmpp.connect() + xmpp.process() diff --git a/examples/custom_stanzas/custom_stanza_provider.py b/examples/custom_stanzas/custom_stanza_provider.py index 0ebdb77e..9927c449 100755 --- a/examples/custom_stanzas/custom_stanza_provider.py +++ b/examples/custom_stanzas/custom_stanza_provider.py @@ -1,48 +1,37 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ - SleekXMPP: The Sleek XMPP Library + Slixmpp: The Slick XMPP Library Copyright (C) 2010 Nathanael C. Fritz - This file is part of SleekXMPP. + This file is part of Slixmpp. See the file LICENSE for copying permission. """ -import sys import logging -import getpass -from optparse import OptionParser +from getpass import getpass +from argparse import ArgumentParser -import sleekxmpp +import slixmpp -from sleekxmpp import ClientXMPP, Iq -from sleekxmpp.exceptions import IqError, IqTimeout, XMPPError -from sleekxmpp.xmlstream import register_stanza_plugin -from sleekxmpp.xmlstream.handler import Callback -from sleekxmpp.xmlstream.matcher import StanzaPath +from slixmpp import ClientXMPP, Iq +from slixmpp.exceptions import IqError, IqTimeout, XMPPError +from slixmpp.xmlstream import register_stanza_plugin +from slixmpp.xmlstream.handler import Callback +from slixmpp.xmlstream.matcher import StanzaPath from stanza import Action -# Python versions before 3.0 do not use UTF-8 encoding -# by default. To ensure that Unicode is handled properly -# throughout SleekXMPP, we will set the default encoding -# ourselves to UTF-8. -if sys.version_info < (3, 0): - from sleekxmpp.util.misc_ops import setdefaultencoding - setdefaultencoding('utf8') -else: - raw_input = input - -class ActionBot(sleekxmpp.ClientXMPP): +class ActionBot(slixmpp.ClientXMPP): """ - A simple SleekXMPP bot that receives a custom stanza + A simple Slixmpp bot that receives a custom stanza from another client. """ def __init__(self, jid, password): - sleekxmpp.ClientXMPP.__init__(self, jid, password) + slixmpp.ClientXMPP.__init__(self, jid, password) # The session_start event will be triggered when # the bot establishes its connection with the server @@ -57,8 +46,7 @@ class ActionBot(sleekxmpp.ClientXMPP): self._handle_action)) self.add_event_handler('custom_action', - self._handle_action_event, - threaded=True) + self._handle_action_event) register_stanza_plugin(Iq, Action) @@ -88,10 +76,6 @@ class ActionBot(sleekxmpp.ClientXMPP): def _handle_action_event(self, iq): """ Respond to the custom action event. - - Since one of the actions is to disconnect, this - event handler needs to be run in threaded mode, by - using `threaded=True` in the `add_event_handler` call. """ method = iq['action']['method'] param = iq['action']['param'] @@ -112,62 +96,42 @@ class ActionBot(sleekxmpp.ClientXMPP): if __name__ == '__main__': # Setup the command line arguments. - optp = OptionParser() + parser = ArgumentParser() # Output verbosity options. - optp.add_option('-q', '--quiet', help='set logging to ERROR', - action='store_const', dest='loglevel', - const=logging.ERROR, default=logging.INFO) - optp.add_option('-d', '--debug', help='set logging to DEBUG', - action='store_const', dest='loglevel', - const=logging.DEBUG, default=logging.INFO) - optp.add_option('-v', '--verbose', help='set logging to COMM', - action='store_const', dest='loglevel', - const=5, default=logging.INFO) + parser.add_argument("-q", "--quiet", help="set logging to ERROR", + action="store_const", dest="loglevel", + const=logging.ERROR, default=logging.INFO) + parser.add_argument("-d", "--debug", help="set logging to DEBUG", + action="store_const", dest="loglevel", + const=logging.DEBUG, default=logging.INFO) # JID and password options. - optp.add_option("-j", "--jid", dest="jid", - help="JID to use") - optp.add_option("-p", "--password", dest="password", - help="password to use") + parser.add_argument("-j", "--jid", dest="jid", + help="JID to use") + parser.add_argument("-p", "--password", dest="password", + help="password to use") - opts, args = optp.parse_args() + args = parser.parse_args() # Setup logging. - logging.basicConfig(level=opts.loglevel, + logging.basicConfig(level=args.loglevel, format='%(levelname)-8s %(message)s') - if opts.jid is None: - opts.jid = raw_input("Username: ") - if opts.password is None: - opts.password = getpass.getpass("Password: ") + if args.jid is None: + args.jid = input("Username: ") + if args.password is None: + args.password = getpass("Password: ") # Setup the CommandBot and register plugins. Note that while plugins may # have interdependencies, the order in which you register them does # not matter. - xmpp = ActionBot(opts.jid, opts.password) + xmpp = ActionBot(args.jid, args.password) xmpp.register_plugin('xep_0030') # Service Discovery xmpp.register_plugin('xep_0004') # Data Forms xmpp.register_plugin('xep_0050') # Adhoc Commands xmpp.register_plugin('xep_0199', {'keepalive': True, 'frequency':15}) - # If you are working with an OpenFire server, you may need - # to adjust the SSL version used: - # xmpp.ssl_version = ssl.PROTOCOL_SSLv3 - - # If you want to verify the SSL certificates offered by a server: - # xmpp.ca_certs = "path/to/ca/cert" - # Connect to the XMPP server and start processing XMPP stanzas. - if xmpp.connect(): - # If you do not have the dnspython library installed, you will need - # to manually specify the name of the server if it does not match - # the one in the JID. For example, to use Google Talk you would - # need to use: - # - # if xmpp.connect(('talk.google.com', 5222)): - # ... - xmpp.process(block=True) - print("Done") - else: - print("Unable to connect.") + xmpp.connect() + xmpp.process() diff --git a/examples/custom_stanzas/custom_stanza_user.py b/examples/custom_stanzas/custom_stanza_user.py index 418e3218..c5630584 100755 --- a/examples/custom_stanzas/custom_stanza_user.py +++ b/examples/custom_stanzas/custom_stanza_user.py @@ -1,46 +1,35 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ - SleekXMPP: The Sleek XMPP Library + Slixmpp: The Slick XMPP Library Copyright (C) 2010 Nathanael C. Fritz - This file is part of SleekXMPP. + This file is part of Slixmpp. See the file LICENSE for copying permission. """ -import sys import logging -import getpass -from optparse import OptionParser +from getpass import getpass +from argparse import ArgumentParser -import sleekxmpp -from sleekxmpp import Iq -from sleekxmpp.exceptions import XMPPError -from sleekxmpp.xmlstream import register_stanza_plugin +import slixmpp +from slixmpp import Iq +from slixmpp.exceptions import XMPPError +from slixmpp.xmlstream import register_stanza_plugin from stanza import Action -# Python versions before 3.0 do not use UTF-8 encoding -# by default. To ensure that Unicode is handled properly -# throughout SleekXMPP, we will set the default encoding -# ourselves to UTF-8. -if sys.version_info < (3, 0): - from sleekxmpp.util.misc_ops import setdefaultencoding - setdefaultencoding('utf8') -else: - raw_input = input - -class ActionUserBot(sleekxmpp.ClientXMPP): +class ActionUserBot(slixmpp.ClientXMPP): """ - A simple SleekXMPP bot that sends a custom action stanza + A simple Slixmpp bot that sends a custom action stanza to another client. """ def __init__(self, jid, password, other): - sleekxmpp.ClientXMPP.__init__(self, jid, password) + slixmpp.ClientXMPP.__init__(self, jid, password) self.action_provider = other @@ -49,7 +38,7 @@ class ActionUserBot(sleekxmpp.ClientXMPP): # and the XML streams are ready for use. We want to # listen for this event so that we we can initialize # our roster. - self.add_event_handler("session_start", self.start, threaded=True) + self.add_event_handler("session_start", self.start) self.add_event_handler("message", self.message) register_stanza_plugin(Iq, Action) @@ -93,10 +82,8 @@ class ActionUserBot(sleekxmpp.ClientXMPP): iq2['type'] = 'set' iq2['action']['method'] = 'bye' iq2.send(block=False) - - # The wait=True delays the disconnect until the queue - # of stanzas to be sent becomes empty. - self.disconnect(wait=True) + + self.disconnect() except XMPPError: print('There was an error sending the custom action.') @@ -111,65 +98,45 @@ class ActionUserBot(sleekxmpp.ClientXMPP): if __name__ == '__main__': # Setup the command line arguments. - optp = OptionParser() + parser = ArgumentParser() # Output verbosity options. - optp.add_option('-q', '--quiet', help='set logging to ERROR', - action='store_const', dest='loglevel', - const=logging.ERROR, default=logging.INFO) - optp.add_option('-d', '--debug', help='set logging to DEBUG', - action='store_const', dest='loglevel', - const=logging.DEBUG, default=logging.INFO) - optp.add_option('-v', '--verbose', help='set logging to COMM', - action='store_const', dest='loglevel', - const=5, default=logging.INFO) + parser.add_argument("-q", "--quiet", help="set logging to ERROR", + action="store_const", dest="loglevel", + const=logging.ERROR, default=logging.INFO) + parser.add_argument("-d", "--debug", help="set logging to DEBUG", + action="store_const", dest="loglevel", + const=logging.DEBUG, default=logging.INFO) # JID and password options. - optp.add_option("-j", "--jid", dest="jid", - help="JID to use") - optp.add_option("-p", "--password", dest="password", - help="password to use") - optp.add_option("-o", "--other", dest="other", - help="JID providing custom stanza") + parser.add_argument("-j", "--jid", dest="jid", + help="JID to use") + parser.add_argument("-p", "--password", dest="password", + help="password to use") + parser.add_argument("-o", "--other", dest="other", + help="JID providing custom stanza") - opts, args = optp.parse_args() + args = parser.parse_args() # Setup logging. - logging.basicConfig(level=opts.loglevel, + logging.basicConfig(level=args.loglevel, format='%(levelname)-8s %(message)s') - if opts.jid is None: - opts.jid = raw_input("Username: ") - if opts.password is None: - opts.password = getpass.getpass("Password: ") - if opts.other is None: - opts.other = raw_input("JID Providing custom stanza: ") + if args.jid is None: + args.jid = input("Username: ") + if args.password is None: + args.password = getpass("Password: ") + if args.other is None: + args.other = input("JID Providing custom stanza: ") # Setup the CommandBot and register plugins. Note that while plugins may # have interdependencies, the order in which you register them does # not matter. - xmpp = ActionUserBot(opts.jid, opts.password, opts.other) + xmpp = ActionUserBot(args.jid, args.password, args.other) xmpp.register_plugin('xep_0030') # Service Discovery xmpp.register_plugin('xep_0004') # Data Forms xmpp.register_plugin('xep_0050') # Adhoc Commands - # If you are working with an OpenFire server, you may need - # to adjust the SSL version used: - # xmpp.ssl_version = ssl.PROTOCOL_SSLv3 - - # If you want to verify the SSL certificates offered by a server: - # xmpp.ca_certs = "path/to/ca/cert" - # Connect to the XMPP server and start processing XMPP stanzas. - if xmpp.connect(): - # If you do not have the dnspython library installed, you will need - # to manually specify the name of the server if it does not match - # the one in the JID. For example, to use Google Talk you would - # need to use: - # - # if xmpp.connect(('talk.google.com', 5222)): - # ... - xmpp.process(block=True) - print("Done") - else: - print("Unable to connect.") + xmpp.connect() + xmpp.process() diff --git a/examples/custom_stanzas/stanza.py b/examples/custom_stanzas/stanza.py index 50d0f9f2..b2c6f766 100644 --- a/examples/custom_stanzas/stanza.py +++ b/examples/custom_stanzas/stanza.py @@ -1,30 +1,30 @@ -from sleekxmpp.xmlstream import ElementBase +from slixmpp.xmlstream import ElementBase class Action(ElementBase): """ A stanza class for XML content of the form: - <action xmlns="sleekxmpp:custom:actions"> + <action xmlns="slixmpp:custom:actions"> <method>X</method> <param>X</param> <status>X</status> </action> """ - + #: The `name` field refers to the basic XML tag name of the #: stanza. Here, the tag name will be 'action'. name = 'action' #: The namespace of the main XML tag. - namespace = 'sleekxmpp:custom:actions' + namespace = 'slixmpp:custom:actions' #: The `plugin_attrib` value is the name that can be used #: with a parent stanza to access this stanza. For example #: from an Iq stanza object, accessing: - #: + #: #: iq['action'] - #: + #: #: would reference an Action object, and will even create #: an Action object and append it to the Iq stanza if #: one doesn't already exist. @@ -49,8 +49,8 @@ class Action(ElementBase): #: the sub_interfaces set. For example, here all interfaces #: are marked as sub_interfaces, and so the XML produced will #: look like: - #: - #: <action xmlns="sleekxmpp:custom:actions"> + #: + #: <action xmlns="slixmpp:custom:actions"> #: <method>foo</method> #: </action> sub_interfaces = interfaces diff --git a/examples/disco_browser.py b/examples/disco_browser.py index 78626e7c..a9e8711f 100755 --- a/examples/disco_browser.py +++ b/examples/disco_browser.py @@ -1,35 +1,24 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ - SleekXMPP: The Sleek XMPP Library + Slixmpp: The Slick XMPP Library Copyright (C) 2010 Nathanael C. Fritz - This file is part of SleekXMPP. + This file is part of Slixmpp. See the file LICENSE for copying permission. """ -import sys import logging -import getpass -from optparse import OptionParser +from getpass import getpass +from argparse import ArgumentParser -import sleekxmpp -from sleekxmpp.exceptions import IqError, IqTimeout +import slixmpp +from slixmpp.exceptions import IqError, IqTimeout +from slixmpp.xmlstream.asyncio import asyncio -# Python versions before 3.0 do not use UTF-8 encoding -# by default. To ensure that Unicode is handled properly -# throughout SleekXMPP, we will set the default encoding -# ourselves to UTF-8. -if sys.version_info < (3, 0): - from sleekxmpp.util.misc_ops import setdefaultencoding - setdefaultencoding('utf8') -else: - raw_input = input - - -class Disco(sleekxmpp.ClientXMPP): +class Disco(slixmpp.ClientXMPP): """ A demonstration for using basic service discovery. @@ -42,7 +31,7 @@ class Disco(sleekxmpp.ClientXMPP): """ def __init__(self, jid, password, target_jid, target_node='', get=''): - sleekxmpp.ClientXMPP.__init__(self, jid, password) + slixmpp.ClientXMPP.__init__(self, jid, password) # Using service discovery requires the XEP-0030 plugin. self.register_plugin('xep_0030') @@ -63,8 +52,9 @@ class Disco(sleekxmpp.ClientXMPP): # and the XML streams are ready for use. We want to # listen for this event so that we we can initialize # our roster. - self.add_event_handler("session_start", self.start, threaded=True) + self.add_event_handler("session_start", self.start) + @asyncio.coroutine def start(self, event): """ Process the session_start event. @@ -86,22 +76,16 @@ class Disco(sleekxmpp.ClientXMPP): try: if self.get in self.info_types: - # By using block=True, the result stanza will be - # returned. Execution will block until the reply is - # received. Non-blocking options would be to listen - # for the disco_info event, or passing a handler # function using the callback parameter. - info = self['xep_0030'].get_info(jid=self.target_jid, - node=self.target_node, - block=True) + info = yield from self['xep_0030'].get_info(jid=self.target_jid, + node=self.target_node) if self.get in self.items_types: # The same applies from above. Listen for the # disco_items event or pass a callback function # if you need to process a non-blocking request. - items = self['xep_0030'].get_items(jid=self.target_jid, - node=self.target_node, - block=True) - else: + items = yield from self['xep_0030'].get_items(jid=self.target_jid, + node=self.target_node) + if self.get not in self.info_types and self.get not in self.items_types: logging.error("Invalid disco request type.") return except IqError as e: @@ -136,69 +120,42 @@ class Disco(sleekxmpp.ClientXMPP): if __name__ == '__main__': # Setup the command line arguments. - optp = OptionParser() - optp.version = '%%prog 0.1' - optp.usage = "Usage: %%prog [options] %s <jid> [<node>]" % \ - 'all|info|items|identities|features' - - optp.add_option('-q','--quiet', help='set logging to ERROR', - action='store_const', - dest='loglevel', - const=logging.ERROR, - default=logging.ERROR) - optp.add_option('-d','--debug', help='set logging to DEBUG', - action='store_const', - dest='loglevel', - const=logging.DEBUG, - default=logging.ERROR) - optp.add_option('-v','--verbose', help='set logging to COMM', - action='store_const', - dest='loglevel', - const=5, - default=logging.ERROR) + parser = ArgumentParser(description=Disco.__doc__) + + parser.add_argument("-q","--quiet", help="set logging to ERROR", + action="store_const", + dest="loglevel", + const=logging.ERROR, + default=logging.ERROR) + parser.add_argument("-d","--debug", help="set logging to DEBUG", + action="store_const", + dest="loglevel", + const=logging.DEBUG, + default=logging.ERROR) # JID and password options. - optp.add_option("-j", "--jid", dest="jid", - help="JID to use") - optp.add_option("-p", "--password", dest="password", - help="password to use") - opts,args = optp.parse_args() + parser.add_argument("-j", "--jid", dest="jid", + help="JID to use") + parser.add_argument("-p", "--password", dest="password", + help="password to use") + parser.add_argument("query", choices=["all", "info", "items", "identities", "features"]) + parser.add_argument("target_jid") + parser.add_argument("node", nargs='?') + + args = parser.parse_args() # Setup logging. - logging.basicConfig(level=opts.loglevel, + logging.basicConfig(level=args.loglevel, format='%(levelname)-8s %(message)s') - if len(args) < 2: - optp.print_help() - exit() - - if len(args) == 2: - args = (args[0], args[1], '') - - if opts.jid is None: - opts.jid = raw_input("Username: ") - if opts.password is None: - opts.password = getpass.getpass("Password: ") + if args.jid is None: + args.jid = input("Username: ") + if args.password is None: + args.password = getpass("Password: ") # Setup the Disco browser. - xmpp = Disco(opts.jid, opts.password, args[1], args[2], args[0]) - - # If you are working with an OpenFire server, you may need - # to adjust the SSL version used: - # xmpp.ssl_version = ssl.PROTOCOL_SSLv3 - - # If you want to verify the SSL certificates offered by a server: - # xmpp.ca_certs = "path/to/ca/cert" + xmpp = Disco(args.jid, args.password, args.target_jid, args.node, args.query) # Connect to the XMPP server and start processing XMPP stanzas. - if xmpp.connect(): - # If you do not have the dnspython library installed, you will need - # to manually specify the name of the server if it does not match - # the one in the JID. For example, to use Google Talk you would - # need to use: - # - # if xmpp.connect(('talk.google.com', 5222)): - # ... - xmpp.process(block=True) - else: - print("Unable to connect.") + xmpp.connect() + xmpp.process(forever=False) diff --git a/examples/download_avatars.py b/examples/download_avatars.py index 64300cff..408c2146 100755 --- a/examples/download_avatars.py +++ b/examples/download_avatars.py @@ -1,33 +1,21 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ - SleekXMPP: The Sleek XMPP Library + Slixmpp: The Slick XMPP Library Copyright (C) 2012 Nathanael C. Fritz - This file is part of SleekXMPP. + This file is part of Slixmpp. See the file LICENSE for copying permission. """ -import sys import logging -import getpass -import threading -from optparse import OptionParser +from getpass import getpass +from argparse import ArgumentParser -import sleekxmpp -from sleekxmpp.exceptions import XMPPError - - -# Python versions before 3.0 do not use UTF-8 encoding -# by default. To ensure that Unicode is handled properly -# throughout SleekXMPP, we will set the default encoding -# ourselves to UTF-8. -if sys.version_info < (3, 0): - from sleekxmpp.util.misc_ops import setdefaultencoding - setdefaultencoding('utf8') -else: - raw_input = input +import slixmpp +from slixmpp.exceptions import XMPPError +from slixmpp import asyncio FILE_TYPES = { @@ -37,23 +25,29 @@ FILE_TYPES = { } -class AvatarDownloader(sleekxmpp.ClientXMPP): +class AvatarDownloader(slixmpp.ClientXMPP): """ A basic script for downloading the avatars for a user's contacts. """ def __init__(self, jid, password): - sleekxmpp.ClientXMPP.__init__(self, jid, password) - self.add_event_handler("session_start", self.start, threaded=True) + slixmpp.ClientXMPP.__init__(self, jid, password) + self.add_event_handler("session_start", self.start) self.add_event_handler("changed_status", self.wait_for_presences) self.add_event_handler('vcard_avatar_update', self.on_vcard_avatar) self.add_event_handler('avatar_metadata_publish', self.on_avatar) self.received = set() - self.presences_received = threading.Event() + self.presences_received = asyncio.Event() + self.roster_received = asyncio.Event() + + def roster_received_cb(self, event): + self.roster_received.set() + self.presences_received.clear() + @asyncio.coroutine def start(self, event): """ Process the session_start event. @@ -68,16 +62,20 @@ class AvatarDownloader(sleekxmpp.ClientXMPP): data. """ self.send_presence() - self.get_roster() + self.get_roster(callback=self.roster_received_cb) print('Waiting for presence updates...\n') - self.presences_received.wait(15) - self.disconnect(wait=True) + yield from self.roster_received.wait() + print('Roster received') + yield from self.presences_received.wait() + self.disconnect() + @asyncio.coroutine def on_vcard_avatar(self, pres): print("Received vCard avatar update from %s" % pres['from'].bare) try: - result = self['xep_0054'].get_vcard(pres['from'], cached=True) + result = yield from self['xep_0054'].get_vcard(pres['from'].bare, cached=True, + timeout=5) except XMPPError: print("Error retrieving avatar for %s" % pres['from']) return @@ -88,16 +86,18 @@ class AvatarDownloader(sleekxmpp.ClientXMPP): pres['from'].bare, pres['vcard_temp_update']['photo'], filetype) - with open(filename, 'w+') as img: + with open(filename, 'wb+') as img: img.write(avatar['BINVAL']) + @asyncio.coroutine def on_avatar(self, msg): print("Received avatar update from %s" % msg['from']) metadata = msg['pubsub_event']['items']['item']['avatar_metadata'] for info in metadata['items']: if not info['url']: try: - result = self['xep_0084'].retrieve_avatar(msg['from'], info['id']) + result = yield from self['xep_0084'].retrieve_avatar(msg['from'].bare, info['id'], + timeout=5) except XMPPError: print("Error retrieving avatar for %s" % msg['from']) return @@ -106,7 +106,7 @@ class AvatarDownloader(sleekxmpp.ClientXMPP): filetype = FILE_TYPES.get(metadata['type'], 'png') filename = 'avatar_%s_%s.%s' % (msg['from'].bare, info['id'], filetype) - with open(filename, 'w+') as img: + with open(filename, 'wb+') as img: img.write(avatar['value']) else: # We could retrieve the avatar via HTTP, etc here instead. @@ -117,6 +117,7 @@ class AvatarDownloader(sleekxmpp.ClientXMPP): Wait to receive updates from all roster contacts. """ self.received.add(pres['from'].bare) + print((len(self.received), len(self.client_roster.keys()))) if len(self.received) >= len(self.client_roster.keys()): self.presences_received.set() else: @@ -125,60 +126,40 @@ class AvatarDownloader(sleekxmpp.ClientXMPP): if __name__ == '__main__': # Setup the command line arguments. - optp = OptionParser() - optp.add_option('-q','--quiet', help='set logging to ERROR', - action='store_const', - dest='loglevel', - const=logging.ERROR, - default=logging.ERROR) - optp.add_option('-d','--debug', help='set logging to DEBUG', - action='store_const', - dest='loglevel', - const=logging.DEBUG, - default=logging.ERROR) - optp.add_option('-v','--verbose', help='set logging to COMM', - action='store_const', - dest='loglevel', - const=5, - default=logging.ERROR) + parser = ArgumentParser() + parser.add_argument("-q","--quiet", help="set logging to ERROR", + action="store_const", + dest="loglevel", + const=logging.ERROR, + default=logging.ERROR) + parser.add_argument("-d","--debug", help="set logging to DEBUG", + action="store_const", + dest="loglevel", + const=logging.DEBUG, + default=logging.ERROR) # JID and password options. - optp.add_option("-j", "--jid", dest="jid", - help="JID to use") - optp.add_option("-p", "--password", dest="password", - help="password to use") - opts,args = optp.parse_args() + parser.add_argument("-j", "--jid", dest="jid", + help="JID to use") + parser.add_argument("-p", "--password", dest="password", + help="password to use") + + args = parser.parse_args() # Setup logging. - logging.basicConfig(level=opts.loglevel, + logging.basicConfig(level=args.loglevel, format='%(levelname)-8s %(message)s') - if opts.jid is None: - opts.jid = raw_input("Username: ") - if opts.password is None: - opts.password = getpass.getpass("Password: ") + if args.jid is None: + args.jid = input("Username: ") + if args.password is None: + args.password = getpass("Password: ") - xmpp = AvatarDownloader(opts.jid, opts.password) + xmpp = AvatarDownloader(args.jid, args.password) xmpp.register_plugin('xep_0054') xmpp.register_plugin('xep_0153') xmpp.register_plugin('xep_0084') - # If you are working with an OpenFire server, you may need - # to adjust the SSL version used: - # xmpp.ssl_version = ssl.PROTOCOL_SSLv3 - - # If you want to verify the SSL certificates offered by a server: - # xmpp.ca_certs = "path/to/ca/cert" - # Connect to the XMPP server and start processing XMPP stanzas. - if xmpp.connect(): - # If you do not have the dnspython library installed, you will need - # to manually specify the name of the server if it does not match - # the one in the JID. For example, to use Google Talk you would - # need to use: - # - # if xmpp.connect(('talk.google.com', 5222)): - # ... - xmpp.process(block=True) - else: - print("Unable to connect.") + xmpp.connect() + xmpp.process() diff --git a/examples/echo_client.py b/examples/echo_client.py index f2d38847..820ca014 100755 --- a/examples/echo_client.py +++ b/examples/echo_client.py @@ -1,41 +1,30 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ - SleekXMPP: The Sleek XMPP Library + Slixmpp: The Slick XMPP Library Copyright (C) 2010 Nathanael C. Fritz - This file is part of SleekXMPP. + This file is part of Slixmpp. See the file LICENSE for copying permission. """ -import sys import logging -import getpass -from optparse import OptionParser +from getpass import getpass +from argparse import ArgumentParser -import sleekxmpp +import slixmpp -# Python versions before 3.0 do not use UTF-8 encoding -# by default. To ensure that Unicode is handled properly -# throughout SleekXMPP, we will set the default encoding -# ourselves to UTF-8. -if sys.version_info < (3, 0): - from sleekxmpp.util.misc_ops import setdefaultencoding - setdefaultencoding('utf8') -else: - raw_input = input - -class EchoBot(sleekxmpp.ClientXMPP): +class EchoBot(slixmpp.ClientXMPP): """ - A simple SleekXMPP bot that will echo messages it + A simple Slixmpp bot that will echo messages it receives, along with a short thank you message. """ def __init__(self, jid, password): - sleekxmpp.ClientXMPP.__init__(self, jid, password) + slixmpp.ClientXMPP.__init__(self, jid, password) # The session_start event will be triggered when # the bot establishes its connection with the server @@ -83,75 +72,42 @@ class EchoBot(sleekxmpp.ClientXMPP): if __name__ == '__main__': # Setup the command line arguments. - optp = OptionParser() + parser = ArgumentParser(description=EchoBot.__doc__) # Output verbosity options. - optp.add_option('-q', '--quiet', help='set logging to ERROR', - action='store_const', dest='loglevel', - const=logging.ERROR, default=logging.INFO) - optp.add_option('-d', '--debug', help='set logging to DEBUG', - action='store_const', dest='loglevel', - const=logging.DEBUG, default=logging.INFO) - optp.add_option('-v', '--verbose', help='set logging to COMM', - action='store_const', dest='loglevel', - const=5, default=logging.INFO) + parser.add_argument("-q", "--quiet", help="set logging to ERROR", + action="store_const", dest="loglevel", + const=logging.ERROR, default=logging.INFO) + parser.add_argument("-d", "--debug", help="set logging to DEBUG", + action="store_const", dest="loglevel", + const=logging.DEBUG, default=logging.INFO) # JID and password options. - optp.add_option("-j", "--jid", dest="jid", - help="JID to use") - optp.add_option("-p", "--password", dest="password", - help="password to use") + parser.add_argument("-j", "--jid", dest="jid", + help="JID to use") + parser.add_argument("-p", "--password", dest="password", + help="password to use") - opts, args = optp.parse_args() + args = parser.parse_args() # Setup logging. - logging.basicConfig(level=opts.loglevel, + logging.basicConfig(level=args.loglevel, format='%(levelname)-8s %(message)s') - if opts.jid is None: - opts.jid = raw_input("Username: ") - if opts.password is None: - opts.password = getpass.getpass("Password: ") + if args.jid is None: + args.jid = input("Username: ") + if args.password is None: + args.password = getpass("Password: ") # Setup the EchoBot and register plugins. Note that while plugins may # have interdependencies, the order in which you register them does # not matter. - xmpp = EchoBot(opts.jid, opts.password) + xmpp = EchoBot(args.jid, args.password) xmpp.register_plugin('xep_0030') # Service Discovery xmpp.register_plugin('xep_0004') # Data Forms xmpp.register_plugin('xep_0060') # PubSub xmpp.register_plugin('xep_0199') # XMPP Ping - # If you are connecting to Facebook and wish to use the - # X-FACEBOOK-PLATFORM authentication mechanism, you will need - # your API key and an access token. Then you'll set: - # xmpp.credentials['api_key'] = 'THE_API_KEY' - # xmpp.credentials['access_token'] = 'THE_ACCESS_TOKEN' - - # If you are connecting to MSN, then you will need an - # access token, and it does not matter what JID you - # specify other than that the domain is 'messenger.live.com', - # so '_@messenger.live.com' will work. You can specify - # the access token as so: - # xmpp.credentials['access_token'] = 'THE_ACCESS_TOKEN' - - # If you are working with an OpenFire server, you may need - # to adjust the SSL version used: - # xmpp.ssl_version = ssl.PROTOCOL_SSLv3 - - # If you want to verify the SSL certificates offered by a server: - # xmpp.ca_certs = "path/to/ca/cert" - # Connect to the XMPP server and start processing XMPP stanzas. - if xmpp.connect(): - # If you do not have the dnspython library installed, you will need - # to manually specify the name of the server if it does not match - # the one in the JID. For example, to use Google Talk you would - # need to use: - # - # if xmpp.connect(('talk.google.com', 5222)): - # ... - xmpp.process(block=True) - print("Done") - else: - print("Unable to connect.") + xmpp.connect() + xmpp.process() diff --git a/examples/echo_component.py b/examples/echo_component.py index 9a24f2fa..664fe311 100755 --- a/examples/echo_component.py +++ b/examples/echo_component.py @@ -1,37 +1,26 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ - SleekXMPP: The Sleek XMPP Library + Slixmpp: The Slick XMPP Library Copyright (C) 2010 Nathanael C. Fritz - This file is part of SleekXMPP. + This file is part of Slixmpp. See the file LICENSE for copying permission. """ -import sys import logging -import getpass -from optparse import OptionParser +from getpass import getpass +from argparse import ArgumentParser -import sleekxmpp -from sleekxmpp.componentxmpp import ComponentXMPP - -# Python versions before 3.0 do not use UTF-8 encoding -# by default. To ensure that Unicode is handled properly -# throughout SleekXMPP, we will set the default encoding -# ourselves to UTF-8. -if sys.version_info < (3, 0): - from sleekxmpp.util.misc_ops import setdefaultencoding - setdefaultencoding('utf8') -else: - raw_input = input +import slixmpp +from slixmpp.componentxmpp import ComponentXMPP class EchoComponent(ComponentXMPP): """ - A simple SleekXMPP component that echoes messages. + A simple Slixmpp component that echoes messages. """ def __init__(self, jid, secret, server, port): @@ -67,56 +56,50 @@ class EchoComponent(ComponentXMPP): if __name__ == '__main__': # Setup the command line arguments. - optp = OptionParser() + parser = ArgumentParser(description=EchoComponent.__doc__) # Output verbosity options. - optp.add_option('-q', '--quiet', help='set logging to ERROR', - action='store_const', dest='loglevel', - const=logging.ERROR, default=logging.INFO) - optp.add_option('-d', '--debug', help='set logging to DEBUG', - action='store_const', dest='loglevel', - const=logging.DEBUG, default=logging.INFO) - optp.add_option('-v', '--verbose', help='set logging to COMM', - action='store_const', dest='loglevel', - const=5, default=logging.INFO) + parser.add_argument("-q", "--quiet", help="set logging to ERROR", + action="store_const", dest="loglevel", + const=logging.ERROR, default=logging.INFO) + parser.add_argument("-d", "--debug", help="set logging to DEBUG", + action="store_const", dest="loglevel", + const=logging.DEBUG, default=logging.INFO) # JID and password options. - optp.add_option("-j", "--jid", dest="jid", - help="JID to use") - optp.add_option("-p", "--password", dest="password", - help="password to use") - optp.add_option("-s", "--server", dest="server", - help="server to connect to") - optp.add_option("-P", "--port", dest="port", - help="port to connect to") - - opts, args = optp.parse_args() - - if opts.jid is None: - opts.jid = raw_input("Component JID: ") - if opts.password is None: - opts.password = getpass.getpass("Password: ") - if opts.server is None: - opts.server = raw_input("Server: ") - if opts.port is None: - opts.port = int(raw_input("Port: ")) + parser.add_argument("-j", "--jid", dest="jid", + help="JID to use") + parser.add_argument("-p", "--password", dest="password", + help="password to use") + parser.add_argument("-s", "--server", dest="server", + help="server to connect to") + parser.add_argument("-P", "--port", dest="port", + help="port to connect to") + + args = parser.parse_args() + + if args.jid is None: + args.jid = input("Component JID: ") + if args.password is None: + args.password = getpass("Password: ") + if args.server is None: + args.server = input("Server: ") + if args.port is None: + args.port = int(input("Port: ")) # Setup logging. - logging.basicConfig(level=opts.loglevel, + logging.basicConfig(level=args.loglevel, format='%(levelname)-8s %(message)s') # Setup the EchoComponent and register plugins. Note that while plugins # may have interdependencies, the order in which you register them does # not matter. - xmpp = EchoComponent(opts.jid, opts.password, opts.server, opts.port) - xmpp.registerPlugin('xep_0030') # Service Discovery - xmpp.registerPlugin('xep_0004') # Data Forms - xmpp.registerPlugin('xep_0060') # PubSub - xmpp.registerPlugin('xep_0199') # XMPP Ping + xmpp = EchoComponent(args.jid, args.password, args.server, args.port) + xmpp.register_plugin('xep_0030') # Service Discovery + xmpp.register_plugin('xep_0004') # Data Forms + xmpp.register_plugin('xep_0060') # PubSub + xmpp.register_plugin('xep_0199') # XMPP Ping # Connect to the XMPP server and start processing XMPP stanzas. - if xmpp.connect(): - xmpp.process(block=True) - print("Done") - else: - print("Unable to connect.") + xmpp.connect() + xmpp.process() diff --git a/examples/gtalk_custom_domain.py b/examples/gtalk_custom_domain.py index c974fc55..d25a5786 100755 --- a/examples/gtalk_custom_domain.py +++ b/examples/gtalk_custom_domain.py @@ -1,46 +1,34 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ - SleekXMPP: The Sleek XMPP Library + Slixmpp: The Slick XMPP Library Copyright (C) 2010 Nathanael C. Fritz - This file is part of SleekXMPP. + This file is part of Slixmpp. See the file LICENSE for copying permission. """ -import sys import logging -import getpass -from optparse import OptionParser +from getpass import getpass +from argparse import ArgumentParser -import sleekxmpp +import slixmpp import ssl -from sleekxmpp.xmlstream import cert +from slixmpp.xmlstream import cert -# Python versions before 3.0 do not use UTF-8 encoding -# by default. To ensure that Unicode is handled properly -# throughout SleekXMPP, we will set the default encoding -# ourselves to UTF-8. -if sys.version_info < (3, 0): - from sleekxmpp.util.misc_ops import setdefaultencoding - setdefaultencoding('utf8') -else: - raw_input = input - - -class GTalkBot(sleekxmpp.ClientXMPP): +class GTalkBot(slixmpp.ClientXMPP): """ - A demonstration of using SleekXMPP with accounts from a Google Apps + A demonstration of using Slixmpp with accounts from a Google Apps account with a custom domain, because it requires custom certificate validation. """ def __init__(self, jid, password): - sleekxmpp.ClientXMPP.__init__(self, jid, password) + slixmpp.ClientXMPP.__init__(self, jid, password) # The session_start event will be triggered when # the bot establishes its connection with the server @@ -104,62 +92,42 @@ class GTalkBot(sleekxmpp.ClientXMPP): if __name__ == '__main__': # Setup the command line arguments. - optp = OptionParser() + parser = ArgumentParser() # Output verbosity options. - optp.add_option('-q', '--quiet', help='set logging to ERROR', - action='store_const', dest='loglevel', - const=logging.ERROR, default=logging.INFO) - optp.add_option('-d', '--debug', help='set logging to DEBUG', - action='store_const', dest='loglevel', - const=logging.DEBUG, default=logging.INFO) - optp.add_option('-v', '--verbose', help='set logging to COMM', - action='store_const', dest='loglevel', - const=5, default=logging.INFO) + parser.add_argument("-q", "--quiet", help="set logging to ERROR", + action="store_const", dest="loglevel", + const=logging.ERROR, default=logging.INFO) + parser.add_argument("-d", "--debug", help="set logging to DEBUG", + action="store_const", dest="loglevel", + const=logging.DEBUG, default=logging.INFO) # JID and password options. - optp.add_option("-j", "--jid", dest="jid", - help="JID to use") - optp.add_option("-p", "--password", dest="password", - help="password to use") + parser.add_argument("-j", "--jid", dest="jid", + help="JID to use") + parser.add_argument("-p", "--password", dest="password", + help="password to use") - opts, args = optp.parse_args() + args = parser.parse_args() # Setup logging. - logging.basicConfig(level=opts.loglevel, + logging.basicConfig(level=args.loglevel, format='%(levelname)-8s %(message)s') - if opts.jid is None: - opts.jid = raw_input("Username: ") - if opts.password is None: - opts.password = getpass.getpass("Password: ") + if args.jid is None: + args.jid = input("Username: ") + if args.password is None: + args.password = getpass("Password: ") # Setup the GTalkBot and register plugins. Note that while plugins may # have interdependencies, the order in which you register them does # not matter. - xmpp = GTalkBot(opts.jid, opts.password) + xmpp = GTalkBot(args.jid, args.password) xmpp.register_plugin('xep_0030') # Service Discovery xmpp.register_plugin('xep_0004') # Data Forms xmpp.register_plugin('xep_0060') # PubSub xmpp.register_plugin('xep_0199') # XMPP Ping - # If you are working with an OpenFire server, you may need - # to adjust the SSL version used: - # xmpp.ssl_version = ssl.PROTOCOL_SSLv3 - - # If you want to verify the SSL certificates offered by a server: - # xmpp.ca_certs = "path/to/ca/cert" - # Connect to the XMPP server and start processing XMPP stanzas. - if xmpp.connect(): - # If you do not have the dnspython library installed, you will need - # to manually specify the name of the server if it does not match - # the one in the JID. For example, to use Google Talk you would - # need to use: - # - # if xmpp.connect(('talk.google.com', 5222)): - # ... - xmpp.process(block=True) - print("Done") - else: - print("Unable to connect.") + xmpp.connect() + xmpp.process() diff --git a/examples/http_over_xmpp.py b/examples/http_over_xmpp.py index a2fbf664..73e4a612 100644 --- a/examples/http_over_xmpp.py +++ b/examples/http_over_xmpp.py @@ -1,17 +1,17 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ - SleekXMPP: The Sleek XMPP Library + Slixmpp: The Slick XMPP Library Implementation of HTTP over XMPP transport http://xmpp.org/extensions/xep-0332.html Copyright (C) 2015 Riptide IO, sangeeth@riptideio.com - This file is part of SleekXMPP. + This file is part of slixmpp. See the file LICENSE for copying permission. """ -from sleekxmpp import ClientXMPP +from slixmpp import ClientXMPP from optparse import OptionParser import logging @@ -32,14 +32,14 @@ class HTTPOverXMPPClient(ClientXMPP): pass def http_response_received(self, iq): - print 'HTTP Response Received : ', iq - print 'From : ', iq['from'] - print 'To : ', iq['to'] - print 'Type : ', iq['type'] - print 'Headers : ', iq['resp']['headers'] - print 'Code : ', iq['resp']['code'] - print 'Message : ', iq['resp']['message'] - print 'Data : ', iq['resp']['data'] + print('HTTP Response Received : %s' % iq) + print('From : %s' % iq['from']) + print('To : %s' % iq['to']) + print('Type : %s' % iq['type']) + print('Headers : %s' % iq['resp']['headers']) + print('Code : %s' % iq['resp']['code']) + print('Message : %s' % iq['resp']['message']) + print('Data : %s' % iq['resp']['data']) def session_start(self, event): # TODO: Fill in the blanks @@ -87,15 +87,11 @@ if __name__ == '__main__': format='%(levelname)-8s %(message)s') if opts.jid is None: - opts.jid = raw_input('Username: ') + opts.jid = input('Username: ') if opts.password is None: opts.password = getpass.getpass('Password: ') xmpp = HTTPOverXMPPClient(opts.jid, opts.password) - if xmpp.connect((opts.ipaddr, int(opts.port))): - print 'Connected!' - xmpp.process(block=True) - else: - print 'Not connected!' - print 'Goodbye....' + xmpp.connect() + xmpp.process() diff --git a/examples/ibb_transfer/ibb_receiver.py b/examples/ibb_transfer/ibb_receiver.py index 6aba98e3..e934f295 100755 --- a/examples/ibb_transfer/ibb_receiver.py +++ b/examples/ibb_transfer/ibb_receiver.py @@ -1,45 +1,31 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ - SleekXMPP: The Sleek XMPP Library + Slixmpp: The Slick XMPP Library Copyright (C) 2010 Nathanael C. Fritz - This file is part of SleekXMPP. + This file is part of Slixmpp. See the file LICENSE for copying permission. """ -import sys import logging -import getpass -from optparse import OptionParser +from getpass import getpass +from argparse import ArgumentParser -import sleekxmpp +import slixmpp -# Python versions before 3.0 do not use UTF-8 encoding -# by default. To ensure that Unicode is handled properly -# throughout SleekXMPP, we will set the default encoding -# ourselves to UTF-8. -if sys.version_info < (3, 0): - from sleekxmpp.util.misc_ops import setdefaultencoding - setdefaultencoding('utf8') -else: - raw_input = input - -class IBBReceiver(sleekxmpp.ClientXMPP): +class IBBReceiver(slixmpp.ClientXMPP): """ A basic example of creating and using an in-band bytestream. """ - def __init__(self, jid, password): - sleekxmpp.ClientXMPP.__init__(self, jid, password) + def __init__(self, jid, password, filename): + slixmpp.ClientXMPP.__init__(self, jid, password) - self.register_plugin('xep_0030') # Service Discovery - self.register_plugin('xep_0047', { - 'auto_accept': True - }) # In-band Bytestreams + self.file = open(filename, 'wb') # The session_start event will be triggered when # the bot establishes its connection with the server @@ -48,8 +34,9 @@ class IBBReceiver(sleekxmpp.ClientXMPP): # our roster. self.add_event_handler("session_start", self.start) - self.add_event_handler("ibb_stream_start", self.stream_opened, threaded=True) + self.add_event_handler("ibb_stream_start", self.stream_opened) self.add_event_handler("ibb_stream_data", self.stream_data) + self.add_event_handler("ibb_stream_end", self.stream_closed) def start(self, event): """ @@ -67,81 +54,59 @@ class IBBReceiver(sleekxmpp.ClientXMPP): self.send_presence() self.get_roster() - def accept_stream(self, iq): - """ - Check that it is ok to accept a stream request. - - Controlling stream acceptance can be done via either: - - setting 'auto_accept' to False in the plugin - configuration. The default is True. - - setting 'accept_stream' to a function which accepts - an Iq stanza as its argument, like this one. - - The accept_stream function will be used if it exists, and the - auto_accept value will be used otherwise. - """ - return True - def stream_opened(self, stream): print('Stream opened: %s from %s' % (stream.sid, stream.peer_jid)) - # You could run a loop reading from the stream using stream.recv(), - # or use the ibb_stream_data event. + def stream_data(self, stream): + self.file.write(stream.read()) - def stream_data(self, event): - print(event['data']) + def stream_closed(self, stream): + print('Stream closed: %s from %s' % (stream.sid, stream.peer_jid)) + self.file.close() + self.disconnect() if __name__ == '__main__': # Setup the command line arguments. - optp = OptionParser() + parser = ArgumentParser() # Output verbosity options. - optp.add_option('-q', '--quiet', help='set logging to ERROR', - action='store_const', dest='loglevel', - const=logging.ERROR, default=logging.INFO) - optp.add_option('-d', '--debug', help='set logging to DEBUG', - action='store_const', dest='loglevel', - const=logging.DEBUG, default=logging.INFO) - optp.add_option('-v', '--verbose', help='set logging to COMM', - action='store_const', dest='loglevel', - const=5, default=logging.INFO) + parser.add_argument("-q", "--quiet", help="set logging to ERROR", + action="store_const", dest="loglevel", + const=logging.ERROR, default=logging.INFO) + parser.add_argument("-d", "--debug", help="set logging to DEBUG", + action="store_const", dest="loglevel", + const=logging.DEBUG, default=logging.INFO) # JID and password options. - optp.add_option("-j", "--jid", dest="jid", - help="JID to use") - optp.add_option("-p", "--password", dest="password", - help="password to use") + parser.add_argument("-j", "--jid", dest="jid", + help="JID to use") + parser.add_argument("-p", "--password", dest="password", + help="password to use") + parser.add_argument("-o", "--out", dest="filename", + help="file to save to") - opts, args = optp.parse_args() + args = parser.parse_args() # Setup logging. - logging.basicConfig(level=opts.loglevel, + logging.basicConfig(level=args.loglevel, format='%(levelname)-8s %(message)s') - if opts.jid is None: - opts.jid = raw_input("Username: ") - if opts.password is None: - opts.password = getpass.getpass("Password: ") - - xmpp = IBBReceiver(opts.jid, opts.password) - - # If you are working with an OpenFire server, you may need - # to adjust the SSL version used: - # xmpp.ssl_version = ssl.PROTOCOL_SSLv3 - - # If you want to verify the SSL certificates offered by a server: - # xmpp.ca_certs = "path/to/ca/cert" + if args.jid is None: + args.jid = input("Username: ") + if args.password is None: + args.password = getpass("Password: ") + if args.filename is None: + args.filename = input("File path: ") + + # Setup the IBBReceiver and register plugins. Note that while plugins may + # have interdependencies, the order in which you register them does + # not matter. + xmpp = IBBReceiver(args.jid, args.password, args.filename) + xmpp.register_plugin('xep_0030') # Service Discovery + xmpp.register_plugin('xep_0047', { + 'auto_accept': True + }) # In-band Bytestreams # Connect to the XMPP server and start processing XMPP stanzas. - if xmpp.connect(): - # If you do not have the dnspython library installed, you will need - # to manually specify the name of the server if it does not match - # the one in the JID. For example, to use Google Talk you would - # need to use: - # - # if xmpp.connect(('talk.google.com', 5222)): - # ... - xmpp.process(block=True) - print("Done") - else: - print("Unable to connect.") + xmpp.connect() + xmpp.process(forever=False) diff --git a/examples/ibb_transfer/ibb_sender.py b/examples/ibb_transfer/ibb_sender.py index 7c380b68..f1c0cab2 100755 --- a/examples/ibb_transfer/ibb_sender.py +++ b/examples/ibb_transfer/ibb_sender.py @@ -1,43 +1,36 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ - SleekXMPP: The Sleek XMPP Library + Slixmpp: The Slick XMPP Library Copyright (C) 2010 Nathanael C. Fritz - This file is part of SleekXMPP. + This file is part of Slixmpp. See the file LICENSE for copying permission. """ -import sys +import asyncio import logging -import getpass -from optparse import OptionParser +from getpass import getpass +from argparse import ArgumentParser -import sleekxmpp +import slixmpp +from slixmpp.exceptions import IqError, IqTimeout -# Python versions before 3.0 do not use UTF-8 encoding -# by default. To ensure that Unicode is handled properly -# throughout SleekXMPP, we will set the default encoding -# ourselves to UTF-8. -if sys.version_info < (3, 0): - from sleekxmpp.util.misc_ops import setdefaultencoding - setdefaultencoding('utf8') -else: - raw_input = input - -class IBBSender(sleekxmpp.ClientXMPP): +class IBBSender(slixmpp.ClientXMPP): """ A basic example of creating and using an in-band bytestream. """ - def __init__(self, jid, password, receiver, filename): - sleekxmpp.ClientXMPP.__init__(self, jid, password) + def __init__(self, jid, password, receiver, filename, use_messages=False): + slixmpp.ClientXMPP.__init__(self, jid, password) self.receiver = receiver - self.filename = filename + + self.file = open(filename, 'rb') + self.use_messages = use_messages # The session_start event will be triggered when # the bot establishes its connection with the server @@ -46,6 +39,7 @@ class IBBSender(sleekxmpp.ClientXMPP): # our roster. self.add_event_handler("session_start", self.start) + @asyncio.coroutine def start(self, event): """ Process the session_start event. @@ -62,84 +56,70 @@ class IBBSender(sleekxmpp.ClientXMPP): self.send_presence() self.get_roster() - # For the purpose of demonstration, we'll set a very small block - # size. The default block size is 4096. We'll also use a window - # allowing sending multiple blocks at a time; in this case, three - # block transfers may be in progress at any time. - stream = self['xep_0047'].open_stream(self.receiver) + try: + # Open the IBB stream in which to write to. + stream = yield from self['xep_0047'].open_stream(self.receiver, use_messages=self.use_messages) + + # If you want to send in-memory bytes, use stream.sendall() instead. + yield from stream.sendfile(self.file, timeout=10) - with open(self.filename) as f: - data = f.read() - stream.sendall(data) + # And finally close the stream. + yield from stream.close(timeout=10) + except (IqError, IqTimeout): + print('File transfer errored') + else: + print('File transfer finished') + finally: + self.file.close() + self.disconnect() if __name__ == '__main__': # Setup the command line arguments. - optp = OptionParser() + parser = ArgumentParser() # Output verbosity options. - optp.add_option('-q', '--quiet', help='set logging to ERROR', - action='store_const', dest='loglevel', - const=logging.ERROR, default=logging.INFO) - optp.add_option('-d', '--debug', help='set logging to DEBUG', - action='store_const', dest='loglevel', - const=logging.DEBUG, default=logging.INFO) - optp.add_option('-v', '--verbose', help='set logging to COMM', - action='store_const', dest='loglevel', - const=5, default=logging.INFO) + parser.add_argument("-q", "--quiet", help="set logging to ERROR", + action="store_const", dest="loglevel", + const=logging.ERROR, default=logging.INFO) + parser.add_argument("-d", "--debug", help="set logging to DEBUG", + action="store_const", dest="loglevel", + const=logging.DEBUG, default=logging.INFO) # JID and password options. - optp.add_option("-j", "--jid", dest="jid", - help="JID to use") - optp.add_option("-p", "--password", dest="password", - help="password to use") - optp.add_option("-r", "--receiver", dest="receiver", - help="JID to use") - optp.add_option("-f", "--file", dest="filename", - help="JID to use") - - opts, args = optp.parse_args() + parser.add_argument("-j", "--jid", dest="jid", + help="JID to use") + parser.add_argument("-p", "--password", dest="password", + help="password to use") + parser.add_argument("-r", "--receiver", dest="receiver", + help="JID of the receiver") + parser.add_argument("-f", "--file", dest="filename", + help="file to send") + parser.add_argument("-m", "--use-messages", action="store_true", + help="use messages instead of iqs for file transfer") + + args = parser.parse_args() # Setup logging. - logging.basicConfig(level=opts.loglevel, + logging.basicConfig(level=args.loglevel, format='%(levelname)-8s %(message)s') - if opts.jid is None: - opts.jid = raw_input("Username: ") - if opts.password is None: - opts.password = getpass.getpass("Password: ") - if opts.receiver is None: - opts.receiver = raw_input("Receiver: ") - if opts.filename is None: - opts.filename = raw_input("File path: ") + if args.jid is None: + args.jid = input("Username: ") + if args.password is None: + args.password = getpass("Password: ") + if args.receiver is None: + args.receiver = input("Receiver: ") + if args.filename is None: + args.filename = input("File path: ") - # Setup the EchoBot and register plugins. Note that while plugins may + # Setup the IBBSender and register plugins. Note that while plugins may # have interdependencies, the order in which you register them does # not matter. - xmpp = IBBSender(opts.jid, opts.password, opts.receiver, opts.filename) + xmpp = IBBSender(args.jid, args.password, args.receiver, args.filename, args.use_messages) xmpp.register_plugin('xep_0030') # Service Discovery - xmpp.register_plugin('xep_0004') # Data Forms xmpp.register_plugin('xep_0047') # In-band Bytestreams - xmpp.register_plugin('xep_0060') # PubSub - xmpp.register_plugin('xep_0199') # XMPP Ping - - # If you are working with an OpenFire server, you may need - # to adjust the SSL version used: - # xmpp.ssl_version = ssl.PROTOCOL_SSLv3 - - # If you want to verify the SSL certificates offered by a server: - # xmpp.ca_certs = "path/to/ca/cert" # Connect to the XMPP server and start processing XMPP stanzas. - if xmpp.connect(): - # If you do not have the dnspython library installed, you will need - # to manually specify the name of the server if it does not match - # the one in the JID. For example, to use Google Talk you would - # need to use: - # - # if xmpp.connect(('talk.google.com', 5222)): - # ... - xmpp.process(block=True) - print("Done") - else: - print("Unable to connect.") + xmpp.connect() + xmpp.process(forever=False) diff --git a/examples/migrate_roster.py b/examples/migrate_roster.py index 9f679523..d599b10c 100755 --- a/examples/migrate_roster.py +++ b/examples/migrate_roster.py @@ -1,68 +1,55 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import logging -import getpass -from optparse import OptionParser +from getpass import getpass +from argparse import ArgumentParser -import sleekxmpp - -# Python versions before 3.0 do not use UTF-8 encoding -# by default. To ensure that Unicode is handled properly -# throughout SleekXMPP, we will set the default encoding -# ourselves to UTF-8. -if sys.version_info < (3, 0): - from sleekxmpp.util.misc_ops import setdefaultencoding - setdefaultencoding('utf8') -else: - raw_input = input +import slixmpp # Setup the command line arguments. -optp = OptionParser() +parser = ArgumentParser() # Output verbosity options. -optp.add_option('-q', '--quiet', help='set logging to ERROR', - action='store_const', dest='loglevel', - const=logging.ERROR, default=logging.INFO) -optp.add_option('-d', '--debug', help='set logging to DEBUG', - action='store_const', dest='loglevel', - const=logging.DEBUG, default=logging.INFO) -optp.add_option('-v', '--verbose', help='set logging to COMM', - action='store_const', dest='loglevel', - const=5, default=logging.INFO) +parser.add_argument("-q", "--quiet", help="set logging to ERROR", + action="store_const", dest="loglevel", + const=logging.ERROR, default=logging.INFO) +parser.add_argument("-d", "--debug", help="set logging to DEBUG", + action="store_const", dest="loglevel", + const=logging.DEBUG, default=logging.INFO) # JID and password options. -optp.add_option("--oldjid", dest="old_jid", - help="JID of the old account") -optp.add_option("--oldpassword", dest="old_password", - help="password of the old account") +parser.add_argument("--oldjid", dest="old_jid", + help="JID of the old account") +parser.add_argument("--oldpassword", dest="old_password", + help="password of the old account") -optp.add_option("--newjid", dest="new_jid", - help="JID of the old account") -optp.add_option("--newpassword", dest="new_password", - help="password of the old account") +parser.add_argument("--newjid", dest="new_jid", + help="JID of the old account") +parser.add_argument("--newpassword", dest="new_password", + help="password of the old account") -opts, args = optp.parse_args() +args = parser.parse_args() # Setup logging. -logging.basicConfig(level=opts.loglevel, +logging.basicConfig(level=args.loglevel, format='%(levelname)-8s %(message)s') -if opts.old_jid is None: - opts.old_jid = raw_input("Old JID: ") -if opts.old_password is None: - opts.old_password = getpass.getpass("Old Password: ") +if args.old_jid is None: + args.old_jid = input("Old JID: ") +if args.old_password is None: + args.old_password = getpass("Old Password: ") -if opts.new_jid is None: - opts.new_jid = raw_input("New JID: ") -if opts.new_password is None: - opts.new_password = getpass.getpass("New Password: ") +if args.new_jid is None: + args.new_jid = input("New JID: ") +if args.new_password is None: + args.new_password = getpass("New Password: ") -old_xmpp = sleekxmpp.ClientXMPP(opts.old_jid, opts.old_password) +old_xmpp = slixmpp.ClientXMPP(args.old_jid, args.old_password) # If you are connecting to Facebook and wish to use the # X-FACEBOOK-PLATFORM authentication mechanism, you will need @@ -98,7 +85,7 @@ if not roster: print('No roster to migrate') sys.exit() -new_xmpp = sleekxmpp.ClientXMPP(opts.new_jid, opts.new_password) +new_xmpp = slixmpp.ClientXMPP(args.new_jid, args.new_password) def on_session2(event): new_xmpp.get_roster() new_xmpp.send_presence() @@ -116,5 +103,5 @@ def on_session2(event): new_xmpp.disconnect() new_xmpp.add_event_handler('session_start', on_session2) -if new_xmpp.connect(): - new_xmpp.process(block=True) +new_xmpp.connect() +new_xmpp.process() diff --git a/examples/muc.py b/examples/muc.py index 5b5c764c..5f18a143 100755 --- a/examples/muc.py +++ b/examples/muc.py @@ -1,42 +1,31 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ - SleekXMPP: The Sleek XMPP Library + Slixmpp: The Slick XMPP Library Copyright (C) 2010 Nathanael C. Fritz - This file is part of SleekXMPP. + This file is part of Slixmpp. See the file LICENSE for copying permission. """ -import sys import logging -import getpass -from optparse import OptionParser +from getpass import getpass +from argparse import ArgumentParser -import sleekxmpp +import slixmpp -# Python versions before 3.0 do not use UTF-8 encoding -# by default. To ensure that Unicode is handled properly -# throughout SleekXMPP, we will set the default encoding -# ourselves to UTF-8. -if sys.version_info < (3, 0): - from sleekxmpp.util.misc_ops import setdefaultencoding - setdefaultencoding('utf8') -else: - raw_input = input - -class MUCBot(sleekxmpp.ClientXMPP): +class MUCBot(slixmpp.ClientXMPP): """ - A simple SleekXMPP bot that will greets those + A simple Slixmpp bot that will greets those who enter the room, and acknowledge any messages that mentions the bot's nickname. """ def __init__(self, jid, password, room, nick): - sleekxmpp.ClientXMPP.__init__(self, jid, password) + slixmpp.ClientXMPP.__init__(self, jid, password) self.room = room self.nick = nick @@ -132,62 +121,49 @@ class MUCBot(sleekxmpp.ClientXMPP): if __name__ == '__main__': # Setup the command line arguments. - optp = OptionParser() + parser = ArgumentParser() # Output verbosity options. - optp.add_option('-q', '--quiet', help='set logging to ERROR', - action='store_const', dest='loglevel', - const=logging.ERROR, default=logging.INFO) - optp.add_option('-d', '--debug', help='set logging to DEBUG', - action='store_const', dest='loglevel', - const=logging.DEBUG, default=logging.INFO) - optp.add_option('-v', '--verbose', help='set logging to COMM', - action='store_const', dest='loglevel', - const=5, default=logging.INFO) + parser.add_argument("-q", "--quiet", help="set logging to ERROR", + action="store_const", dest="loglevel", + const=logging.ERROR, default=logging.INFO) + parser.add_argument("-d", "--debug", help="set logging to DEBUG", + action="store_const", dest="loglevel", + const=logging.DEBUG, default=logging.INFO) # JID and password options. - optp.add_option("-j", "--jid", dest="jid", - help="JID to use") - optp.add_option("-p", "--password", dest="password", - help="password to use") - optp.add_option("-r", "--room", dest="room", - help="MUC room to join") - optp.add_option("-n", "--nick", dest="nick", - help="MUC nickname") + parser.add_argument("-j", "--jid", dest="jid", + help="JID to use") + parser.add_argument("-p", "--password", dest="password", + help="password to use") + parser.add_argument("-r", "--room", dest="room", + help="MUC room to join") + parser.add_argument("-n", "--nick", dest="nick", + help="MUC nickname") - opts, args = optp.parse_args() + args = parser.parse_args() # Setup logging. - logging.basicConfig(level=opts.loglevel, + logging.basicConfig(level=args.loglevel, format='%(levelname)-8s %(message)s') - if opts.jid is None: - opts.jid = raw_input("Username: ") - if opts.password is None: - opts.password = getpass.getpass("Password: ") - if opts.room is None: - opts.room = raw_input("MUC room: ") - if opts.nick is None: - opts.nick = raw_input("MUC nickname: ") + if args.jid is None: + args.jid = input("Username: ") + if args.password is None: + args.password = getpass("Password: ") + if args.room is None: + args.room = input("MUC room: ") + if args.nick is None: + args.nick = input("MUC nickname: ") # Setup the MUCBot and register plugins. Note that while plugins may # have interdependencies, the order in which you register them does # not matter. - xmpp = MUCBot(opts.jid, opts.password, opts.room, opts.nick) + xmpp = MUCBot(args.jid, args.password, args.room, args.nick) xmpp.register_plugin('xep_0030') # Service Discovery xmpp.register_plugin('xep_0045') # Multi-User Chat xmpp.register_plugin('xep_0199') # XMPP Ping # Connect to the XMPP server and start processing XMPP stanzas. - if xmpp.connect(): - # If you do not have the dnspython library installed, you will need - # to manually specify the name of the server if it does not match - # the one in the JID. For example, to use Google Talk you would - # need to use: - # - # if xmpp.connect(('talk.google.com', 5222)): - # ... - xmpp.process(block=True) - print("Done") - else: - print("Unable to connect.") + xmpp.connect() + xmpp.process() diff --git a/examples/ping.py b/examples/ping.py index 1a1c2e94..39118ac4 100755 --- a/examples/ping.py +++ b/examples/ping.py @@ -1,41 +1,32 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ - SleekXMPP: The Sleek XMPP Library + Slixmpp: The Slick XMPP Library Copyright (C) 2010 Nathanael C. Fritz - This file is part of SleekXMPP. + This file is part of Slixmpp. See the file LICENSE for copying permission. """ -import sys import logging -import getpass -from optparse import OptionParser +from getpass import getpass +from argparse import ArgumentParser +from slixmpp.exceptions import IqError, IqTimeout +from slixmpp import asyncio -import sleekxmpp +import slixmpp -# Python versions before 3.0 do not use UTF-8 encoding -# by default. To ensure that Unicode is handled properly -# throughout SleekXMPP, we will set the default encoding -# ourselves to UTF-8. -if sys.version_info < (3, 0): - from sleekxmpp.util.misc_ops import setdefaultencoding - setdefaultencoding('utf8') -else: - raw_input = input - -class PingTest(sleekxmpp.ClientXMPP): +class PingTest(slixmpp.ClientXMPP): """ - A simple SleekXMPP bot that will send a ping request + A simple Slixmpp bot that will send a ping request to a given JID. """ def __init__(self, jid, password, pingjid): - sleekxmpp.ClientXMPP.__init__(self, jid, password) + slixmpp.ClientXMPP.__init__(self, jid, password) if pingjid is None: pingjid = self.boundjid.bare self.pingjid = pingjid @@ -45,8 +36,9 @@ class PingTest(sleekxmpp.ClientXMPP): # and the XML streams are ready for use. We want to # listen for this event so that we we can initialize # our roster. - self.add_event_handler("session_start", self.start, threaded=True) + self.add_event_handler("session_start", self.start) + @asyncio.coroutine def start(self, event): """ Process the session_start event. @@ -64,8 +56,8 @@ class PingTest(sleekxmpp.ClientXMPP): self.get_roster() try: - rtt = self['xep_0199'].ping(self.pingjid, - timeout=10) + rtt = yield from self['xep_0199'].ping(self.pingjid, + timeout=10) logging.info("Success! RTT: %s", rtt) except IqError as e: logging.info("Error pinging %s: %s", @@ -79,65 +71,44 @@ class PingTest(sleekxmpp.ClientXMPP): if __name__ == '__main__': # Setup the command line arguments. - optp = OptionParser() + parser = ArgumentParser() # Output verbosity options. - optp.add_option('-q', '--quiet', help='set logging to ERROR', - action='store_const', dest='loglevel', - const=logging.ERROR, default=logging.INFO) - optp.add_option('-d', '--debug', help='set logging to DEBUG', - action='store_const', dest='loglevel', - const=logging.DEBUG, default=logging.INFO) - optp.add_option('-v', '--verbose', help='set logging to COMM', - action='store_const', dest='loglevel', - const=5, default=logging.INFO) - optp.add_option('-t', '--pingto', help='set jid to ping', - action='store', type='string', dest='pingjid', - default=None) + parser.add_argument("-q", "--quiet", help="set logging to ERROR", + action="store_const", dest="loglevel", + const=logging.ERROR, default=logging.INFO) + parser.add_argument("-d", "--debug", help="set logging to DEBUG", + action="store_const", dest="loglevel", + const=logging.DEBUG, default=logging.INFO) + parser.add_argument("-t", "--pingto", help="set jid to ping", + dest="pingjid", default=None) # JID and password options. - optp.add_option("-j", "--jid", dest="jid", - help="JID to use") - optp.add_option("-p", "--password", dest="password", - help="password to use") + parser.add_argument("-j", "--jid", dest="jid", + help="JID to use") + parser.add_argument("-p", "--password", dest="password", + help="password to use") - opts, args = optp.parse_args() + args = parser.parse_args() # Setup logging. - logging.basicConfig(level=opts.loglevel, + logging.basicConfig(level=args.loglevel, format='%(levelname)-8s %(message)s') - if opts.jid is None: - opts.jid = raw_input("Username: ") - if opts.password is None: - opts.password = getpass.getpass("Password: ") + if args.jid is None: + args.jid = input("Username: ") + if args.password is None: + args.password = getpass("Password: ") # Setup the PingTest and register plugins. Note that while plugins may # have interdependencies, the order in which you register them does # not matter. - xmpp = PingTest(opts.jid, opts.password, opts.pingjid) + xmpp = PingTest(args.jid, args.password, args.pingjid) xmpp.register_plugin('xep_0030') # Service Discovery xmpp.register_plugin('xep_0004') # Data Forms xmpp.register_plugin('xep_0060') # PubSub xmpp.register_plugin('xep_0199') # XMPP Ping - # If you are working with an OpenFire server, you may need - # to adjust the SSL version used: - # xmpp.ssl_version = ssl.PROTOCOL_SSLv3 - - # If you want to verify the SSL certificates offered by a server: - # xmpp.ca_certs = "path/to/ca/cert" - # Connect to the XMPP server and start processing XMPP stanzas. - if xmpp.connect(): - # If you do not have the dnspython library installed, you will need - # to manually specify the name of the server if it does not match - # the one in the JID. For example, to use Google Talk you would - # need to use: - # - # if xmpp.connect(('talk.google.com', 5222)): - # ... - xmpp.process(block=True) - print("Done") - else: - print("Unable to connect.") + xmpp.connect() + xmpp.process() diff --git a/examples/proxy_echo_client.py b/examples/proxy_echo_client.py index 98935b9c..b149de31 100755 --- a/examples/proxy_echo_client.py +++ b/examples/proxy_echo_client.py @@ -1,41 +1,30 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ - SleekXMPP: The Sleek XMPP Library + Slixmpp: The Slick XMPP Library Copyright (C) 2010 Nathanael C. Fritz - This file is part of SleekXMPP. + This file is part of Slixmpp. See the file LICENSE for copying permission. """ -import sys import logging -import getpass -from optparse import OptionParser +from getpass import getpass +from argparse import ArgumentParser -import sleekxmpp +import slixmpp -# Python versions before 3.0 do not use UTF-8 encoding -# by default. To ensure that Unicode is handled properly -# throughout SleekXMPP, we will set the default encoding -# ourselves to UTF-8. -if sys.version_info < (3, 0): - from sleekxmpp.util.misc_ops import setdefaultencoding - setdefaultencoding('utf8') -else: - raw_input = input - -class EchoBot(sleekxmpp.ClientXMPP): +class EchoBot(slixmpp.ClientXMPP): """ - A simple SleekXMPP bot that will echo messages it + A simple Slixmpp bot that will echo messages it receives, along with a short thank you message. """ def __init__(self, jid, password): - sleekxmpp.ClientXMPP.__init__(self, jid, password) + slixmpp.ClientXMPP.__init__(self, jid, password) # The session_start event will be triggered when # the bot establishes its connection with the server @@ -82,87 +71,65 @@ class EchoBot(sleekxmpp.ClientXMPP): if __name__ == '__main__': # Setup the command line arguments. - optp = OptionParser() + parser = ArgumentParser() # Output verbosity options. - optp.add_option('-q', '--quiet', help='set logging to ERROR', - action='store_const', dest='loglevel', - const=logging.ERROR, default=logging.INFO) - optp.add_option('-d', '--debug', help='set logging to DEBUG', - action='store_const', dest='loglevel', - const=logging.DEBUG, default=logging.INFO) - optp.add_option('-v', '--verbose', help='set logging to COMM', - action='store_const', dest='loglevel', - const=5, default=logging.INFO) + parser.add_argument("-q", "--quiet", help="set logging to ERROR", + action="store_const", dest="loglevel", + const=logging.ERROR, default=logging.INFO) + parser.add_argument("-d", "--debug", help="set logging to DEBUG", + action="store_const", dest="loglevel", + const=logging.DEBUG, default=logging.INFO) # JID and password options. - optp.add_option("-j", "--jid", dest="jid", - help="JID to use") - optp.add_option("-p", "--password", dest="password", - help="password to use") - optp.add_option("--phost", dest="proxy_host", - help="Proxy hostname") - optp.add_option("--pport", dest="proxy_port", - help="Proxy port") - optp.add_option("--puser", dest="proxy_user", - help="Proxy username") - optp.add_option("--ppass", dest="proxy_pass", - help="Proxy password") - - - - opts, args = optp.parse_args() + parser.add_argument("-j", "--jid", dest="jid", + help="JID to use") + parser.add_argument("-p", "--password", dest="password", + help="password to use") + parser.add_argument("--phost", dest="proxy_host", + help="Proxy hostname") + parser.add_argument("--pport", dest="proxy_port", + help="Proxy port") + parser.add_argument("--puser", dest="proxy_user", + help="Proxy username") + parser.add_argument("--ppass", dest="proxy_pass", + help="Proxy password") + + args = parser.parse_args() # Setup logging. - logging.basicConfig(level=opts.loglevel, + logging.basicConfig(level=args.loglevel, format='%(levelname)-8s %(message)s') - if opts.jid is None: - opts.jid = raw_input("Username: ") - if opts.password is None: - opts.password = getpass.getpass("Password: ") - if opts.proxy_host is None: - opts.proxy_host = raw_input("Proxy host: ") - if opts.proxy_port is None: - opts.proxy_port = raw_input("Proxy port: ") - if opts.proxy_user is None: - opts.proxy_user = raw_input("Proxy username: ") - if opts.proxy_pass is None and opts.proxy_user: - opts.proxy_pass = getpass.getpass("Proxy password: ") + if args.jid is None: + args.jid = input("Username: ") + if args.password is None: + args.password = getpass("Password: ") + if args.proxy_host is None: + args.proxy_host = input("Proxy host: ") + if args.proxy_port is None: + args.proxy_port = input("Proxy port: ") + if args.proxy_user is None: + args.proxy_user = input("Proxy username: ") + if args.proxy_pass is None and args.proxy_user: + args.proxy_pass = getpass("Proxy password: ") # Setup the EchoBot and register plugins. Note that while plugins may # have interdependencies, the order in which you register them does # not matter. - xmpp = EchoBot(opts.jid, opts.password) + xmpp = EchoBot(args.jid, args.password) xmpp.register_plugin('xep_0030') # Service Discovery xmpp.register_plugin('xep_0004') # Data Forms xmpp.register_plugin('xep_0060') # PubSub xmpp.register_plugin('xep_0199') # XMPP Ping - # If you are working with an OpenFire server, you may need - # to adjust the SSL version used: - # xmpp.ssl_version = ssl.PROTOCOL_SSLv3 - - # If you want to verify the SSL certificates offered by a server: - # xmpp.ca_certs = "path/to/ca/cert" - xmpp.use_proxy = True xmpp.proxy_config = { - 'host': opts.proxy_host, - 'port': int(opts.proxy_port), - 'username': opts.proxy_user, - 'password': opts.proxy_pass} + 'host': args.proxy_host, + 'port': int(args.proxy_port), + 'username': args.proxy_user, + 'password': args.proxy_pass} # Connect to the XMPP server and start processing XMPP stanzas. - if xmpp.connect(): - # If you do not have the dnspython library installed, you will need - # to manually specify the name of the server if it does not match - # the one in the JID. For example, to use Google Talk you would - # need to use: - # - # if xmpp.connect(('talk.google.com', 5222)): - # ... - xmpp.process(block=True) - print("Done") - else: - print("Unable to connect.") + xmpp.connect() + xmpp.process() diff --git a/examples/pubsub_client.py b/examples/pubsub_client.py index 9a65553b..c5688750 100755 --- a/examples/pubsub_client.py +++ b/examples/pubsub_client.py @@ -1,30 +1,20 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: utf-8 -*- -import sys import logging -import getpass -from optparse import OptionParser +from getpass import getpass +from argparse import ArgumentParser -import sleekxmpp -from sleekxmpp.xmlstream import ET, tostring +import asyncio +import slixmpp +from slixmpp.exceptions import XMPPError +from slixmpp.xmlstream import ET, tostring -# Python versions before 3.0 do not use UTF-8 encoding -# by default. To ensure that Unicode is handled properly -# throughout SleekXMPP, we will set the default encoding -# ourselves to UTF-8. -if sys.version_info < (3, 0): - from sleekxmpp.util.misc_ops import setdefaultencoding - setdefaultencoding('utf8') -else: - raw_input = input - - -class PubsubClient(sleekxmpp.ClientXMPP): +class PubsubClient(slixmpp.ClientXMPP): def __init__(self, jid, password, server, - node=None, action='list', data=''): + node=None, action='nodes', data=''): super(PubsubClient, self).__init__(jid, password) self.register_plugin('xep_0030') @@ -40,162 +30,137 @@ class PubsubClient(sleekxmpp.ClientXMPP): self.data = data self.pubsub_server = server - self.add_event_handler('session_start', self.start, threaded=True) + self.add_event_handler('session_start', self.start) + @asyncio.coroutine def start(self, event): self.get_roster() self.send_presence() try: - getattr(self, self.action)() + yield from getattr(self, self.action)() except: - logging.error('Could not execute: %s' % self.action) + logging.error('Could not execute: %s', self.action) self.disconnect() def nodes(self): try: - result = self['xep_0060'].get_nodes(self.pubsub_server, self.node) + result = yield from self['xep_0060'].get_nodes(self.pubsub_server, self.node) for item in result['disco_items']['items']: - print(' - %s' % str(item)) - except: - logging.error('Could not retrieve node list.') + logging.info(' - %s', str(item)) + except XMPPError as error: + logging.error('Could not retrieve node list: %s', error.format()) def create(self): try: - self['xep_0060'].create_node(self.pubsub_server, self.node) - except: - logging.error('Could not create node: %s' % self.node) + yield from self['xep_0060'].create_node(self.pubsub_server, self.node) + logging.info('Created node %s', self.node) + except XMPPError as error: + logging.error('Could not create node %s: %s', self.node, error.format()) def delete(self): try: - self['xep_0060'].delete_node(self.pubsub_server, self.node) - print('Deleted node: %s' % self.node) - except: - logging.error('Could not delete node: %s' % self.node) + yield from self['xep_0060'].delete_node(self.pubsub_server, self.node) + logging.info('Deleted node %s', self.node) + except XMPPError as error: + logging.error('Could not delete node %s: %s', self.node, error.format()) def publish(self): payload = ET.fromstring("<test xmlns='test'>%s</test>" % self.data) try: - result = self['xep_0060'].publish(self.pubsub_server, self.node, payload=payload) - id = result['pubsub']['publish']['item']['id'] - print('Published at item id: %s' % id) - except: - logging.error('Could not publish to: %s' % self.node) + result = yield from self['xep_0060'].publish(self.pubsub_server, self.node, payload=payload) + logging.info('Published at item id: %s', result['pubsub']['publish']['item']['id']) + except XMPPError as error: + logging.error('Could not publish to %s: %s', self.node, error.format()) def get(self): try: - result = self['xep_0060'].get_item(self.pubsub_server, self.node, self.data) + result = yield from self['xep_0060'].get_item(self.pubsub_server, self.node, self.data) for item in result['pubsub']['items']['substanzas']: - print('Retrieved item %s: %s' % (item['id'], tostring(item['payload']))) - except: - logging.error('Could not retrieve item %s from node %s' % (self.data, self.node)) + logging.info('Retrieved item %s: %s', item['id'], tostring(item['payload'])) + except XMPPError as error: + logging.error('Could not retrieve item %s from node %s: %s', self.data, self.node, error.format()) def retract(self): try: - result = self['xep_0060'].retract(self.pubsub_server, self.node, self.data) - print('Retracted item %s from node %s' % (self.data, self.node)) - except: - logging.error('Could not retract item %s from node %s' % (self.data, self.node)) + yield from self['xep_0060'].retract(self.pubsub_server, self.node, self.data) + logging.info('Retracted item %s from node %s', self.data, self.node) + except XMPPError as error: + logging.error('Could not retract item %s from node %s: %s', self.data, self.node, error.format()) def purge(self): try: - result = self['xep_0060'].purge(self.pubsub_server, self.node) - print('Purged all items from node %s' % self.node) - except: - logging.error('Could not purge items from node %s' % self.node) + yield from self['xep_0060'].purge(self.pubsub_server, self.node) + logging.info('Purged all items from node %s', self.node) + except XMPPError as error: + logging.error('Could not purge items from node %s: %s', self.node, error.format()) def subscribe(self): try: - result = self['xep_0060'].subscribe(self.pubsub_server, self.node) - print('Subscribed %s to node %s' % (self.boundjid.bare, self.node)) - except: - logging.error('Could not subscribe %s to node %s' % (self.boundjid.bare, self.node)) + iq = yield from self['xep_0060'].subscribe(self.pubsub_server, self.node) + subscription = iq['pubsub']['subscription'] + logging.info('Subscribed %s to node %s', subscription['jid'], subscription['node']) + except XMPPError as error: + logging.error('Could not subscribe %s to node %s: %s', self.boundjid.bare, self.node, error.format()) def unsubscribe(self): try: - result = self['xep_0060'].unsubscribe(self.pubsub_server, self.node) - print('Unsubscribed %s from node %s' % (self.boundjid.bare, self.node)) - except: - logging.error('Could not unsubscribe %s from node %s' % (self.boundjid.bare, self.node)) + yield from self['xep_0060'].unsubscribe(self.pubsub_server, self.node) + logging.info('Unsubscribed %s from node %s', self.boundjid.bare, self.node) + except XMPPError as error: + logging.error('Could not unsubscribe %s from node %s: %s', self.boundjid.bare, self.node, error.format()) if __name__ == '__main__': # Setup the command line arguments. - optp = OptionParser() - optp.version = '%%prog 0.1' - optp.usage = "Usage: %%prog [options] <jid> " + \ + parser = ArgumentParser() + parser.version = '%%prog 0.1' + parser.usage = "Usage: %%prog [options] <jid> " + \ 'nodes|create|delete|purge|subscribe|unsubscribe|publish|retract|get' + \ ' [<node> <data>]' - optp.add_option('-q','--quiet', help='set logging to ERROR', - action='store_const', - dest='loglevel', - const=logging.ERROR, - default=logging.ERROR) - optp.add_option('-d','--debug', help='set logging to DEBUG', - action='store_const', - dest='loglevel', - const=logging.DEBUG, - default=logging.ERROR) - optp.add_option('-v','--verbose', help='set logging to COMM', - action='store_const', - dest='loglevel', - const=5, - default=logging.ERROR) + parser.add_argument("-q","--quiet", help="set logging to ERROR", + action="store_const", + dest="loglevel", + const=logging.ERROR, + default=logging.INFO) + parser.add_argument("-d","--debug", help="set logging to DEBUG", + action="store_const", + dest="loglevel", + const=logging.DEBUG, + default=logging.INFO) # JID and password options. - optp.add_option("-j", "--jid", dest="jid", - help="JID to use") - optp.add_option("-p", "--password", dest="password", - help="password to use") - opts,args = optp.parse_args() - - # Setup logging. - logging.basicConfig(level=opts.loglevel, - format='%(levelname)-8s %(message)s') + parser.add_argument("-j", "--jid", dest="jid", + help="JID to use") + parser.add_argument("-p", "--password", dest="password", + help="password to use") - if len(args) < 2: - optp.print_help() - exit() + parser.add_argument("server") + parser.add_argument("action", choices=["nodes", "create", "delete", "purge", "subscribe", "unsubscribe", "publish", "retract", "get"]) + parser.add_argument("node", nargs='?') + parser.add_argument("data", nargs='?') - if opts.jid is None: - opts.jid = raw_input("Username: ") - if opts.password is None: - opts.password = getpass.getpass("Password: ") + args = parser.parse_args() - if len(args) == 2: - args = (args[0], args[1], '', '', '') - elif len(args) == 3: - args = (args[0], args[1], args[2], '', '') - elif len(args) == 4: - args = (args[0], args[1], args[2], args[3], '') + # Setup logging. + logging.basicConfig(level=args.loglevel, + format='%(levelname)-8s %(message)s') + if args.jid is None: + args.jid = input("Username: ") + if args.password is None: + args.password = getpass("Password: ") # Setup the Pubsub client - xmpp = PubsubClient(opts.jid, opts.password, - server=args[0], - node=args[2], - action=args[1], - data=args[3]) - - # If you are working with an OpenFire server, you may need - # to adjust the SSL version used: - # xmpp.ssl_version = ssl.PROTOCOL_SSLv3 - - # If you want to verify the SSL certificates offered by a server: - # xmpp.ca_certs = "path/to/ca/cert" + xmpp = PubsubClient(args.jid, args.password, + server=args.server, + node=args.node, + action=args.action, + data=args.data) # Connect to the XMPP server and start processing XMPP stanzas. - if xmpp.connect(): - # If you do not have the dnspython library installed, you will need - # to manually specify the name of the server if it does not match - # the one in the JID. For example, to use Google Talk you would - # need to use: - # - # if xmpp.connect(('talk.google.com', 5222)): - # ... - xmpp.process(block=True) - else: - print("Unable to connect.") + xmpp.connect() + xmpp.process(forever=False) diff --git a/examples/pubsub_events.py b/examples/pubsub_events.py index 12c33a76..369d7114 100755 --- a/examples/pubsub_events.py +++ b/examples/pubsub_events.py @@ -1,29 +1,17 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: utf-8 -*- -import sys import logging -import getpass -from optparse import OptionParser +from getpass import getpass +from argparse import ArgumentParser -import sleekxmpp -from sleekxmpp.xmlstream import ET, tostring -from sleekxmpp.xmlstream.matcher import StanzaPath -from sleekxmpp.xmlstream.handler import Callback +import slixmpp +from slixmpp.xmlstream import ET, tostring +from slixmpp.xmlstream.matcher import StanzaPath +from slixmpp.xmlstream.handler import Callback -# Python versions before 3.0 do not use UTF-8 encoding -# by default. To ensure that Unicode is handled properly -# throughout SleekXMPP, we will set the default encoding -# ourselves to UTF-8. -if sys.version_info < (3, 0): - from sleekxmpp.util.misc_ops import setdefaultencoding - setdefaultencoding('utf8') -else: - raw_input = input - - -class PubsubEvents(sleekxmpp.ClientXMPP): +class PubsubEvents(slixmpp.ClientXMPP): def __init__(self, jid, password): super(PubsubEvents, self).__init__(jid, password) @@ -96,59 +84,39 @@ class PubsubEvents(sleekxmpp.ClientXMPP): if __name__ == '__main__': # Setup the command line arguments. - optp = OptionParser() + parser = ArgumentParser() # Output verbosity options. - optp.add_option('-q', '--quiet', help='set logging to ERROR', - action='store_const', dest='loglevel', - const=logging.ERROR, default=logging.INFO) - optp.add_option('-d', '--debug', help='set logging to DEBUG', - action='store_const', dest='loglevel', - const=logging.DEBUG, default=logging.INFO) - optp.add_option('-v', '--verbose', help='set logging to COMM', - action='store_const', dest='loglevel', - const=5, default=logging.INFO) + parser.add_argument("-q", "--quiet", help="set logging to ERROR", + action="store_const", dest="loglevel", + const=logging.ERROR, default=logging.INFO) + parser.add_argument("-d", "--debug", help="set logging to DEBUG", + action="store_const", dest="loglevel", + const=logging.DEBUG, default=logging.INFO) # JID and password options. - optp.add_option("-j", "--jid", dest="jid", - help="JID to use") - optp.add_option("-p", "--password", dest="password", - help="password to use") + parser.add_argument("-j", "--jid", dest="jid", + help="JID to use") + parser.add_argument("-p", "--password", dest="password", + help="password to use") - opts, args = optp.parse_args() + args = parser.parse_args() # Setup logging. - logging.basicConfig(level=opts.loglevel, + logging.basicConfig(level=args.loglevel, format='%(levelname)-8s %(message)s') - if opts.jid is None: - opts.jid = raw_input("Username: ") - if opts.password is None: - opts.password = getpass.getpass("Password: ") + if args.jid is None: + args.jid = input("Username: ") + if args.password is None: + args.password = getpass("Password: ") logging.info("Run this in conjunction with the pubsub_client.py " + \ "example to watch events happen as you give commands.") # Setup the PubsubEvents listener - xmpp = PubsubEvents(opts.jid, opts.password) - - # If you are working with an OpenFire server, you may need - # to adjust the SSL version used: - # xmpp.ssl_version = ssl.PROTOCOL_SSLv3 - - # If you want to verify the SSL certificates offered by a server: - # xmpp.ca_certs = "path/to/ca/cert" + xmpp = PubsubEvents(args.jid, args.password) # Connect to the XMPP server and start processing XMPP stanzas. - if xmpp.connect(): - # If you do not have the dnspython library installed, you will need - # to manually specify the name of the server if it does not match - # the one in the JID. For example, to use Google Talk you would - # need to use: - # - # if xmpp.connect(('talk.google.com', 5222)): - # ... - xmpp.process(block=True) - print("Done") - else: - print("Unable to connect.") + xmpp.connect() + xmpp.process() diff --git a/examples/register_account.py b/examples/register_account.py index 422e5602..8ec238e9 100755 --- a/examples/register_account.py +++ b/examples/register_account.py @@ -1,34 +1,23 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ - SleekXMPP: The Sleek XMPP Library + Slixmpp: The Slick XMPP Library Copyright (C) 2010 Nathanael C. Fritz - This file is part of SleekXMPP. + This file is part of Slixmpp. See the file LICENSE for copying permission. """ -import sys import logging -import getpass -from optparse import OptionParser +from getpass import getpass +from argparse import ArgumentParser -import sleekxmpp -from sleekxmpp.exceptions import IqError, IqTimeout +import slixmpp +from slixmpp.exceptions import IqError, IqTimeout -# Python versions before 3.0 do not use UTF-8 encoding -# by default. To ensure that Unicode is handled properly -# throughout SleekXMPP, we will set the default encoding -# ourselves to UTF-8. -if sys.version_info < (3, 0): - from sleekxmpp.util.misc_ops import setdefaultencoding - setdefaultencoding('utf8') -else: - raw_input = input - -class RegisterBot(sleekxmpp.ClientXMPP): +class RegisterBot(slixmpp.ClientXMPP): """ A basic bot that will attempt to register an account @@ -40,23 +29,23 @@ class RegisterBot(sleekxmpp.ClientXMPP): """ def __init__(self, jid, password): - sleekxmpp.ClientXMPP.__init__(self, jid, password) + slixmpp.ClientXMPP.__init__(self, jid, password) # The session_start event will be triggered when # the bot establishes its connection with the server # and the XML streams are ready for use. We want to # listen for this event so that we we can initialize # our roster. - self.add_event_handler("session_start", self.start, threaded=True) + self.add_event_handler("session_start", self.start) # The register event provides an Iq result stanza with # a registration form from the server. This may include # the basic registration fields, a data form, an # out-of-band URL, or any combination. For more advanced # cases, you will need to examine the fields provided - # and respond accordingly. SleekXMPP provides plugins + # and respond accordingly. Slixmpp provides plugins # for data forms and OOB links that will make that easier. - self.add_event_handler("register", self.register, threaded=True) + self.add_event_handler("register", self.register) def start(self, event): """ @@ -101,7 +90,7 @@ class RegisterBot(sleekxmpp.ClientXMPP): resp['register']['password'] = self.password try: - resp.send(now=True) + yield from resp.send() logging.info("Account created for %s!" % self.boundjid) except IqError as e: logging.error("Could not register account: %s" % @@ -114,40 +103,37 @@ class RegisterBot(sleekxmpp.ClientXMPP): if __name__ == '__main__': # Setup the command line arguments. - optp = OptionParser() + parser = ArgumentParser() # Output verbosity options. - optp.add_option('-q', '--quiet', help='set logging to ERROR', - action='store_const', dest='loglevel', - const=logging.ERROR, default=logging.INFO) - optp.add_option('-d', '--debug', help='set logging to DEBUG', - action='store_const', dest='loglevel', - const=logging.DEBUG, default=logging.INFO) - optp.add_option('-v', '--verbose', help='set logging to COMM', - action='store_const', dest='loglevel', - const=5, default=logging.INFO) + parser.add_argument("-q", "--quiet", help="set logging to ERROR", + action="store_const", dest="loglevel", + const=logging.ERROR, default=logging.INFO) + parser.add_argument("-d", "--debug", help="set logging to DEBUG", + action="store_const", dest="loglevel", + const=logging.DEBUG, default=logging.INFO) # JID and password options. - optp.add_option("-j", "--jid", dest="jid", - help="JID to use") - optp.add_option("-p", "--password", dest="password", - help="password to use") + parser.add_argument("-j", "--jid", dest="jid", + help="JID to use") + parser.add_argument("-p", "--password", dest="password", + help="password to use") - opts, args = optp.parse_args() + args = parser.parse_args() # Setup logging. - logging.basicConfig(level=opts.loglevel, + logging.basicConfig(level=args.loglevel, format='%(levelname)-8s %(message)s') - if opts.jid is None: - opts.jid = raw_input("Username: ") - if opts.password is None: - opts.password = getpass.getpass("Password: ") + if args.jid is None: + args.jid = input("Username: ") + if args.password is None: + args.password = getpass("Password: ") # Setup the RegisterBot and register plugins. Note that while plugins may # have interdependencies, the order in which you register them does # not matter. - xmpp = RegisterBot(opts.jid, opts.password) + xmpp = RegisterBot(args.jid, args.password) xmpp.register_plugin('xep_0030') # Service Discovery xmpp.register_plugin('xep_0004') # Data forms xmpp.register_plugin('xep_0066') # Out-of-band Data @@ -157,23 +143,6 @@ if __name__ == '__main__': # though they allow it. If this applies to your server, use: xmpp['xep_0077'].force_registration = True - # If you are working with an OpenFire server, you may need - # to adjust the SSL version used: - # xmpp.ssl_version = ssl.PROTOCOL_SSLv3 - - # If you want to verify the SSL certificates offered by a server: - # xmpp.ca_certs = "path/to/ca/cert" - # Connect to the XMPP server and start processing XMPP stanzas. - if xmpp.connect(): - # If you do not have the dnspython library installed, you will need - # to manually specify the name of the server if it does not match - # the one in the JID. For example, to use Google Talk you would - # need to use: - # - # if xmpp.connect(('talk.google.com', 5222)): - # ... - xmpp.process(block=True) - print("Done") - else: - print("Unable to connect.") + xmpp.connect() + xmpp.process() diff --git a/examples/roster_browser.py b/examples/roster_browser.py index a16de24c..eb92ad2a 100755 --- a/examples/roster_browser.py +++ b/examples/roster_browser.py @@ -1,36 +1,24 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ - SleekXMPP: The Sleek XMPP Library + Slixmpp: The Slick XMPP Library Copyright (C) 2011 Nathanael C. Fritz - This file is part of SleekXMPP. + This file is part of Slixmpp. See the file LICENSE for copying permission. """ -import sys import logging -import getpass -import threading -from optparse import OptionParser +from getpass import getpass +from argparse import ArgumentParser -import sleekxmpp -from sleekxmpp.exceptions import IqError, IqTimeout +import slixmpp +from slixmpp.exceptions import IqError, IqTimeout +from slixmpp.xmlstream.asyncio import asyncio -# Python versions before 3.0 do not use UTF-8 encoding -# by default. To ensure that Unicode is handled properly -# throughout SleekXMPP, we will set the default encoding -# ourselves to UTF-8. -if sys.version_info < (3, 0): - from sleekxmpp.util.misc_ops import setdefaultencoding - setdefaultencoding('utf8') -else: - raw_input = input - - -class RosterBrowser(sleekxmpp.ClientXMPP): +class RosterBrowser(slixmpp.ClientXMPP): """ A basic script for dumping a client's roster to @@ -38,20 +26,19 @@ class RosterBrowser(sleekxmpp.ClientXMPP): """ def __init__(self, jid, password): - sleekxmpp.ClientXMPP.__init__(self, jid, password) + slixmpp.ClientXMPP.__init__(self, jid, password) # The session_start event will be triggered when # the bot establishes its connection with the server # and the XML streams are ready for use. We want to # listen for this event so that we we can initialize - # our roster. We need threaded=True so that the - # session_start handler doesn't block event processing - # while we wait for presence stanzas to arrive. - self.add_event_handler("session_start", self.start, threaded=True) + # our roster. + self.add_event_handler("session_start", self.start) self.add_event_handler("changed_status", self.wait_for_presences) self.received = set() - self.presences_received = threading.Event() + self.presences_received = asyncio.Event() + @asyncio.coroutine def start(self, event): """ Process the session_start event. @@ -65,8 +52,12 @@ class RosterBrowser(sleekxmpp.ClientXMPP): event does not provide any additional data. """ + future = asyncio.Future() + def callback(result): + future.set_result(None) try: - self.get_roster() + self.get_roster(callback=callback) + yield from future except IqError as err: print('Error: %s' % err.iq['error']['condition']) except IqTimeout: @@ -75,7 +66,7 @@ class RosterBrowser(sleekxmpp.ClientXMPP): print('Waiting for presence updates...\n') - self.presences_received.wait(5) + yield from asyncio.sleep(10) print('Roster for %s' % self.boundjid.bare) groups = self.client_roster.groups() @@ -115,58 +106,37 @@ class RosterBrowser(sleekxmpp.ClientXMPP): if __name__ == '__main__': # Setup the command line arguments. - optp = OptionParser() - optp.add_option('-q','--quiet', help='set logging to ERROR', - action='store_const', - dest='loglevel', - const=logging.ERROR, - default=logging.ERROR) - optp.add_option('-d','--debug', help='set logging to DEBUG', - action='store_const', - dest='loglevel', - const=logging.DEBUG, - default=logging.ERROR) - optp.add_option('-v','--verbose', help='set logging to COMM', - action='store_const', - dest='loglevel', - const=5, - default=logging.ERROR) + parser = ArgumentParser() + parser.add_argument("-q","--quiet", help="set logging to ERROR", + action="store_const", + dest="loglevel", + const=logging.ERROR, + default=logging.ERROR) + parser.add_argument("-d","--debug", help="set logging to DEBUG", + action="store_const", + dest="loglevel", + const=logging.DEBUG, + default=logging.ERROR) # JID and password options. - optp.add_option("-j", "--jid", dest="jid", - help="JID to use") - optp.add_option("-p", "--password", dest="password", - help="password to use") - opts,args = optp.parse_args() + parser.add_argument("-j", "--jid", dest="jid", + help="JID to use") + parser.add_argument("-p", "--password", dest="password", + help="password to use") + + args = parser.parse_args() # Setup logging. - logging.basicConfig(level=opts.loglevel, + logging.basicConfig(level=args.loglevel, format='%(levelname)-8s %(message)s') - if opts.jid is None: - opts.jid = raw_input("Username: ") - if opts.password is None: - opts.password = getpass.getpass("Password: ") + if args.jid is None: + args.jid = input("Username: ") + if args.password is None: + args.password = getpass("Password: ") - xmpp = RosterBrowser(opts.jid, opts.password) - - # If you are working with an OpenFire server, you may need - # to adjust the SSL version used: - # xmpp.ssl_version = ssl.PROTOCOL_SSLv3 - - # If you want to verify the SSL certificates offered by a server: - # xmpp.ca_certs = "path/to/ca/cert" + xmpp = RosterBrowser(args.jid, args.password) # Connect to the XMPP server and start processing XMPP stanzas. - if xmpp.connect(): - # If you do not have the dnspython library installed, you will need - # to manually specify the name of the server if it does not match - # the one in the JID. For example, to use Google Talk you would - # need to use: - # - # if xmpp.connect(('talk.google.com', 5222)): - # ... - xmpp.process(block=True) - else: - print("Unable to connect.") - + xmpp.connect() + xmpp.process() diff --git a/examples/rpc_async.py b/examples/rpc_async.py index e3e23b69..f773a8d1 100755 --- a/examples/rpc_async.py +++ b/examples/rpc_async.py @@ -1,15 +1,15 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ - SleekXMPP: The Sleek XMPP Library + Slixmpp: The Slick XMPP Library Copyright (C) 2011 Dann Martens - This file is part of SleekXMPP. + This file is part of Slixmpp. See the file LICENSE for copying permission. """ -from sleekxmpp.plugins.xep_0009.remote import Endpoint, remote, Remote, \ +from slixmpp.plugins.xep_0009.remote import Endpoint, remote, Remote, \ ANY_ALL, Future import time @@ -20,7 +20,7 @@ class Boomerang(Endpoint): @remote def throw(self): - print "Duck!" + print("Duck!") diff --git a/examples/rpc_client_side.py b/examples/rpc_client_side.py index e792fc94..0a4ba015 100755 --- a/examples/rpc_client_side.py +++ b/examples/rpc_client_side.py @@ -1,15 +1,15 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ - SleekXMPP: The Sleek XMPP Library + Slixmpp: The Slick XMPP Library Copyright (C) 2011 Dann Martens - This file is part of SleekXMPP. + This file is part of Slixmpp. See the file LICENSE for copying permission. """ -from sleekxmpp.plugins.xep_0009.remote import Endpoint, remote, Remote, \ +from slixmpp.plugins.xep_0009.remote import Endpoint, remote, Remote, \ ANY_ALL import threading import time diff --git a/examples/rpc_server_side.py b/examples/rpc_server_side.py index 9e8b48d6..b973e53b 100755 --- a/examples/rpc_server_side.py +++ b/examples/rpc_server_side.py @@ -1,15 +1,15 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ - SleekXMPP: The Sleek XMPP Library + Slixmpp: The Slick XMPP Library Copyright (C) 2011 Dann Martens - This file is part of SleekXMPP. + This file is part of Slixmpp. See the file LICENSE for copying permission. """ -from sleekxmpp.plugins.xep_0009.remote import Endpoint, remote, Remote, \ +from slixmpp.plugins.xep_0009.remote import Endpoint, remote, Remote, \ ANY_ALL import threading diff --git a/examples/s5b_transfer/s5b_receiver.py b/examples/s5b_transfer/s5b_receiver.py new file mode 100755 index 00000000..bedeaa04 --- /dev/null +++ b/examples/s5b_transfer/s5b_receiver.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" + Slixmpp: The Slick XMPP Library + Copyright (C) 2015 Emmanuel Gil Peyrot + This file is part of Slixmpp. + + See the file LICENSE for copying permission. +""" + +import asyncio +import logging +from getpass import getpass +from argparse import ArgumentParser + +import slixmpp + + +class S5BReceiver(slixmpp.ClientXMPP): + + """ + A basic example of creating and using a SOCKS5 bytestream. + """ + + def __init__(self, jid, password, filename): + slixmpp.ClientXMPP.__init__(self, jid, password) + + self.file = open(filename, 'wb') + + self.add_event_handler("socks5_connected", self.stream_opened) + self.add_event_handler("socks5_data", self.stream_data) + self.add_event_handler("socks5_closed", self.stream_closed) + + def stream_opened(self, sid): + logging.info('Stream opened. %s', sid) + + def stream_data(self, data): + self.file.write(data) + + def stream_closed(self, exception): + logging.info('Stream closed. %s', exception) + self.file.close() + self.disconnect() + +if __name__ == '__main__': + # Setup the command line arguments. + parser = ArgumentParser() + + # Output verbosity options. + parser.add_argument("-q", "--quiet", help="set logging to ERROR", + action="store_const", dest="loglevel", + const=logging.ERROR, default=logging.INFO) + parser.add_argument("-d", "--debug", help="set logging to DEBUG", + action="store_const", dest="loglevel", + const=logging.DEBUG, default=logging.INFO) + + # JID and password options. + parser.add_argument("-j", "--jid", dest="jid", + help="JID to use") + parser.add_argument("-p", "--password", dest="password", + help="password to use") + parser.add_argument("-o", "--out", dest="filename", + help="file to save to") + + args = parser.parse_args() + + # Setup logging. + logging.basicConfig(level=args.loglevel, + format='%(levelname)-8s %(message)s') + + if args.jid is None: + args.jid = input("Username: ") + if args.password is None: + args.password = getpass("Password: ") + if args.filename is None: + args.filename = input("File path: ") + + # Setup the S5BReceiver and register plugins. Note that while plugins may + # have interdependencies, the order in which you register them does + # not matter. + xmpp = S5BReceiver(args.jid, args.password, args.filename) + xmpp.register_plugin('xep_0030') # Service Discovery + xmpp.register_plugin('xep_0065', { + 'auto_accept': True + }) # SOCKS5 Bytestreams + + # Connect to the XMPP server and start processing XMPP stanzas. + xmpp.connect() + xmpp.process(forever=False) diff --git a/examples/s5b_transfer/s5b_sender.py b/examples/s5b_transfer/s5b_sender.py new file mode 100755 index 00000000..70a9704f --- /dev/null +++ b/examples/s5b_transfer/s5b_sender.py @@ -0,0 +1,124 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" + Slixmpp: The Slick XMPP Library + Copyright (C) 2015 Emmanuel Gil Peyrot + This file is part of Slixmpp. + + See the file LICENSE for copying permission. +""" + +import asyncio +import logging +from getpass import getpass +from argparse import ArgumentParser + +import slixmpp +from slixmpp.exceptions import IqError, IqTimeout + + +class S5BSender(slixmpp.ClientXMPP): + + """ + A basic example of creating and using a SOCKS5 bytestream. + """ + + def __init__(self, jid, password, receiver, filename): + slixmpp.ClientXMPP.__init__(self, jid, password) + + self.receiver = receiver + + self.file = open(filename, 'rb') + + # The session_start event will be triggered when + # the bot establishes its connection with the server + # and the XML streams are ready for use. + self.add_event_handler("session_start", self.start) + + @asyncio.coroutine + def start(self, event): + """ + Process the session_start event. + + Typical actions for the session_start event are + requesting the roster and broadcasting an initial + presence stanza. + + Arguments: + event -- An empty dictionary. The session_start + event does not provide any additional + data. + """ + + try: + # Open the S5B stream in which to write to. + proxy = yield from self['xep_0065'].handshake(self.receiver) + + # Send the entire file. + while True: + data = self.file.read(1048576) + if not data: + break + yield from proxy.write(data) + + # And finally close the stream. + proxy.transport.write_eof() + except (IqError, IqTimeout): + print('File transfer errored') + else: + print('File transfer finished') + finally: + self.file.close() + self.disconnect() + + +if __name__ == '__main__': + # Setup the command line arguments. + parser = ArgumentParser() + + # Output verbosity options. + parser.add_argument("-q", "--quiet", help="set logging to ERROR", + action="store_const", dest="loglevel", + const=logging.ERROR, default=logging.INFO) + parser.add_argument("-d", "--debug", help="set logging to DEBUG", + action="store_const", dest="loglevel", + const=logging.DEBUG, default=logging.INFO) + + # JID and password options. + parser.add_argument("-j", "--jid", dest="jid", + help="JID to use") + parser.add_argument("-p", "--password", dest="password", + help="password to use") + parser.add_argument("-r", "--receiver", dest="receiver", + help="JID of the receiver") + parser.add_argument("-f", "--file", dest="filename", + help="file to send") + parser.add_argument("-m", "--use-messages", action="store_true", + help="use messages instead of iqs for file transfer") + + args = parser.parse_args() + + # Setup logging. + logging.basicConfig(level=args.loglevel, + format='%(levelname)-8s %(message)s') + + if args.jid is None: + args.jid = input("Username: ") + if args.password is None: + args.password = getpass("Password: ") + if args.receiver is None: + args.receiver = input("Receiver: ") + if args.filename is None: + args.filename = input("File path: ") + + # Setup the S5BSender and register plugins. Note that while plugins may + # have interdependencies, the order in which you register them does + # not matter. + xmpp = S5BSender(args.jid, args.password, args.receiver, args.filename) + xmpp.register_plugin('xep_0030') # Service Discovery + xmpp.register_plugin('xep_0065') # SOCKS5 Bytestreams + + # Connect to the XMPP server and start processing XMPP stanzas. + xmpp.connect() + xmpp.process(forever=False) diff --git a/examples/send_client.py b/examples/send_client.py index 192469ae..6e3e5865 100755 --- a/examples/send_client.py +++ b/examples/send_client.py @@ -1,41 +1,30 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ - SleekXMPP: The Sleek XMPP Library + Slixmpp: The Slick XMPP Library Copyright (C) 2010 Nathanael C. Fritz - This file is part of SleekXMPP. + This file is part of Slixmpp. See the file LICENSE for copying permission. """ -import sys import logging -import getpass -from optparse import OptionParser +from getpass import getpass +from argparse import ArgumentParser -import sleekxmpp +import slixmpp -# Python versions before 3.0 do not use UTF-8 encoding -# by default. To ensure that Unicode is handled properly -# throughout SleekXMPP, we will set the default encoding -# ourselves to UTF-8. -if sys.version_info < (3, 0): - from sleekxmpp.util.misc_ops import setdefaultencoding - setdefaultencoding('utf8') -else: - raw_input = input - -class SendMsgBot(sleekxmpp.ClientXMPP): +class SendMsgBot(slixmpp.ClientXMPP): """ - A basic SleekXMPP bot that will log in, send a message, + A basic Slixmpp bot that will log in, send a message, and then log out. """ def __init__(self, jid, password, recipient, message): - sleekxmpp.ClientXMPP.__init__(self, jid, password) + slixmpp.ClientXMPP.__init__(self, jid, password) # The message we wish to send, and the JID that # will receive it. @@ -47,7 +36,7 @@ class SendMsgBot(sleekxmpp.ClientXMPP): # and the XML streams are ready for use. We want to # listen for this event so that we we can initialize # our roster. - self.add_event_handler("session_start", self.start, threaded=True) + self.add_event_handler("session_start", self.start) def start(self, event): """ @@ -69,75 +58,53 @@ class SendMsgBot(sleekxmpp.ClientXMPP): mbody=self.msg, mtype='chat') - # Using wait=True ensures that the send queue will be - # emptied before ending the session. - self.disconnect(wait=True) + self.disconnect() if __name__ == '__main__': # Setup the command line arguments. - optp = OptionParser() + parser = ArgumentParser(description=SendMsgBot.__doc__) # Output verbosity options. - optp.add_option('-q', '--quiet', help='set logging to ERROR', - action='store_const', dest='loglevel', - const=logging.ERROR, default=logging.INFO) - optp.add_option('-d', '--debug', help='set logging to DEBUG', - action='store_const', dest='loglevel', - const=logging.DEBUG, default=logging.INFO) - optp.add_option('-v', '--verbose', help='set logging to COMM', - action='store_const', dest='loglevel', - const=5, default=logging.INFO) + parser.add_argument("-q", "--quiet", help="set logging to ERROR", + action="store_const", dest="loglevel", + const=logging.ERROR, default=logging.INFO) + parser.add_argument("-d", "--debug", help="set logging to DEBUG", + action="store_const", dest="loglevel", + const=logging.DEBUG, default=logging.INFO) # JID and password options. - optp.add_option("-j", "--jid", dest="jid", - help="JID to use") - optp.add_option("-p", "--password", dest="password", - help="password to use") - optp.add_option("-t", "--to", dest="to", - help="JID to send the message to") - optp.add_option("-m", "--message", dest="message", - help="message to send") + parser.add_argument("-j", "--jid", dest="jid", + help="JID to use") + parser.add_argument("-p", "--password", dest="password", + help="password to use") + parser.add_argument("-t", "--to", dest="to", + help="JID to send the message to") + parser.add_argument("-m", "--message", dest="message", + help="message to send") - opts, args = optp.parse_args() + args = parser.parse_args() # Setup logging. - logging.basicConfig(level=opts.loglevel, + logging.basicConfig(level=args.loglevel, format='%(levelname)-8s %(message)s') - if opts.jid is None: - opts.jid = raw_input("Username: ") - if opts.password is None: - opts.password = getpass.getpass("Password: ") - if opts.to is None: - opts.to = raw_input("Send To: ") - if opts.message is None: - opts.message = raw_input("Message: ") + if args.jid is None: + args.jid = input("Username: ") + if args.password is None: + args.password = getpass("Password: ") + if args.to is None: + args.to = input("Send To: ") + if args.message is None: + args.message = input("Message: ") # Setup the EchoBot and register plugins. Note that while plugins may # have interdependencies, the order in which you register them does # not matter. - xmpp = SendMsgBot(opts.jid, opts.password, opts.to, opts.message) + xmpp = SendMsgBot(args.jid, args.password, args.to, args.message) xmpp.register_plugin('xep_0030') # Service Discovery xmpp.register_plugin('xep_0199') # XMPP Ping - # If you are working with an OpenFire server, you may need - # to adjust the SSL version used: - # xmpp.ssl_version = ssl.PROTOCOL_SSLv3 - - # If you want to verify the SSL certificates offered by a server: - # xmpp.ca_certs = "path/to/ca/cert" - # Connect to the XMPP server and start processing XMPP stanzas. - if xmpp.connect(): - # If you do not have the dnspython library installed, you will need - # to manually specify the name of the server if it does not match - # the one in the JID. For example, to use Google Talk you would - # need to use: - # - # if xmpp.connect(('talk.google.com', 5222)): - # ... - xmpp.process(block=True) - print("Done") - else: - print("Unable to connect.") + xmpp.connect() + xmpp.process() diff --git a/examples/set_avatar.py b/examples/set_avatar.py index 08e0b664..f9641b1e 100755 --- a/examples/set_avatar.py +++ b/examples/set_avatar.py @@ -1,50 +1,39 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ - SleekXMPP: The Sleek XMPP Library + Slixmpp: The Slick XMPP Library Copyright (C) 2012 Nathanael C. Fritz - This file is part of SleekXMPP. + This file is part of Slixmpp. See the file LICENSE for copying permission. """ import os -import sys import imghdr import logging -import getpass +from getpass import getpass import threading -from optparse import OptionParser +from argparse import ArgumentParser -import sleekxmpp -from sleekxmpp.exceptions import XMPPError +import slixmpp +from slixmpp.exceptions import XMPPError +from slixmpp import asyncio - -# Python versions before 3.0 do not use UTF-8 encoding -# by default. To ensure that Unicode is handled properly -# throughout SleekXMPP, we will set the default encoding -# ourselves to UTF-8. -if sys.version_info < (3, 0): - from sleekxmpp.util.misc_ops import setdefaultencoding - setdefaultencoding('utf8') -else: - raw_input = input - - -class AvatarSetter(sleekxmpp.ClientXMPP): +class AvatarSetter(slixmpp.ClientXMPP): """ A basic script for downloading the avatars for a user's contacts. """ def __init__(self, jid, password, filepath): - sleekxmpp.ClientXMPP.__init__(self, jid, password) + slixmpp.ClientXMPP.__init__(self, jid, password) - self.add_event_handler("session_start", self.start, threaded=True) + self.add_event_handler("session_start", self.start) self.filepath = filepath + @asyncio.coroutine def start(self, event): """ Process the session_start event. @@ -77,32 +66,31 @@ class AvatarSetter(sleekxmpp.ClientXMPP): avatar_file.close() used_xep84 = False - try: - print('Publish XEP-0084 avatar data') - self['xep_0084'].publish_avatar(avatar) - used_xep84 = True - except XMPPError: + + print('Publish XEP-0084 avatar data') + result = yield from self['xep_0084'].publish_avatar(avatar) + if isinstance(result, XMPPError): print('Could not publish XEP-0084 avatar') + else: + used_xep84 = True - try: - print('Update vCard with avatar') - self['xep_0153'].set_avatar(avatar=avatar, mtype=avatar_type) - except XMPPError: + print('Update vCard with avatar') + result = yield from self['xep_0153'].set_avatar(avatar=avatar, mtype=avatar_type) + if isinstance(result, XMPPError): print('Could not set vCard avatar') if used_xep84: - try: - print('Advertise XEP-0084 avatar metadata') - self['xep_0084'].publish_avatar_metadata([ - {'id': avatar_id, - 'type': avatar_type, - 'bytes': avatar_bytes} - # We could advertise multiple avatars to provide - # options in image type, source (HTTP vs pubsub), - # size, etc. - # {'id': ....} - ]) - except XMPPError: + print('Advertise XEP-0084 avatar metadata') + result = yield from self['xep_0084'].publish_avatar_metadata([ + {'id': avatar_id, + 'type': avatar_type, + 'bytes': avatar_bytes} + # We could advertise multiple avatars to provide + # options in image type, source (HTTP vs pubsub), + # size, etc. + # {'id': ....} + ]) + if isinstance(result, XMPPError): print('Could not publish XEP-0084 metadata') print('Wait for presence updates to propagate...') @@ -111,64 +99,44 @@ class AvatarSetter(sleekxmpp.ClientXMPP): if __name__ == '__main__': # Setup the command line arguments. - optp = OptionParser() - optp.add_option('-q','--quiet', help='set logging to ERROR', - action='store_const', - dest='loglevel', - const=logging.ERROR, - default=logging.ERROR) - optp.add_option('-d','--debug', help='set logging to DEBUG', - action='store_const', - dest='loglevel', - const=logging.DEBUG, - default=logging.ERROR) - optp.add_option('-v','--verbose', help='set logging to COMM', - action='store_const', - dest='loglevel', - const=5, - default=logging.ERROR) + parser = ArgumentParser() + parser.add_argument("-q","--quiet", help="set logging to ERROR", + action="store_const", + dest="loglevel", + const=logging.ERROR, + default=logging.ERROR) + parser.add_argument("-d","--debug", help="set logging to DEBUG", + action="store_const", + dest="loglevel", + const=logging.DEBUG, + default=logging.ERROR) # JID and password options. - optp.add_option("-j", "--jid", dest="jid", - help="JID to use") - optp.add_option("-p", "--password", dest="password", - help="password to use") - optp.add_option("-f", "--file", dest="filepath", - help="path to the avatar file") - opts,args = optp.parse_args() + parser.add_argument("-j", "--jid", dest="jid", + help="JID to use") + parser.add_argument("-p", "--password", dest="password", + help="password to use") + parser.add_argument("-f", "--file", dest="filepath", + help="path to the avatar file") + + args = parser.parse_args() # Setup logging. - logging.basicConfig(level=opts.loglevel, + logging.basicConfig(level=args.loglevel, format='%(levelname)-8s %(message)s') - if opts.jid is None: - opts.jid = raw_input("Username: ") - if opts.password is None: - opts.password = getpass.getpass("Password: ") - if opts.filepath is None: - opts.filepath = raw_input("Avatar file location: ") + if args.jid is None: + args.jid = input("Username: ") + if args.password is None: + args.password = getpass("Password: ") + if args.filepath is None: + args.filepath = input("Avatar file location: ") - xmpp = AvatarSetter(opts.jid, opts.password, opts.filepath) + xmpp = AvatarSetter(args.jid, args.password, args.filepath) xmpp.register_plugin('xep_0054') xmpp.register_plugin('xep_0153') xmpp.register_plugin('xep_0084') - # If you are working with an OpenFire server, you may need - # to adjust the SSL version used: - # xmpp.ssl_version = ssl.PROTOCOL_SSLv3 - - # If you want to verify the SSL certificates offered by a server: - # xmpp.ca_certs = "path/to/ca/cert" - # Connect to the XMPP server and start processing XMPP stanzas. - if xmpp.connect(): - # If you do not have the dnspython library installed, you will need - # to manually specify the name of the server if it does not match - # the one in the JID. For example, to use Google Talk you would - # need to use: - # - # if xmpp.connect(('talk.google.com', 5222)): - # ... - xmpp.process(block=True) - else: - print("Unable to connect.") + xmpp.connect() + xmpp.process() diff --git a/examples/thirdparty_auth.py b/examples/thirdparty_auth.py index f4d5c400..4129fa91 100755 --- a/examples/thirdparty_auth.py +++ b/examples/thirdparty_auth.py @@ -1,18 +1,18 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ - SleekXMPP: The Sleek XMPP Library + Slixmpp: The Slick XMPP Library Copyright (C) 2010 Nathanael C. Fritz - This file is part of SleekXMPP. + This file is part of Slixmpp. See the file LICENSE for copying permission. """ import sys import logging -import getpass -from optparse import OptionParser +from getpass import getpass +from argparse import ArgumentParser try: from httplib import HTTPSConnection @@ -21,24 +21,14 @@ except ImportError: from urllib.parse import urlencode from http.client import HTTPSConnection -import sleekxmpp -from sleekxmpp.xmlstream import JID +import slixmpp +from slixmpp.xmlstream import JID -# Python versions before 3.0 do not use UTF-8 encoding -# by default. To ensure that Unicode is handled properly -# throughout SleekXMPP, we will set the default encoding -# ourselves to UTF-8. -if sys.version_info < (3, 0): - from sleekxmpp.util.misc_ops import setdefaultencoding - setdefaultencoding('utf8') -else: - raw_input = input - -class ThirdPartyAuthBot(sleekxmpp.ClientXMPP): +class ThirdPartyAuthBot(slixmpp.ClientXMPP): """ - A simple SleekXMPP bot that will echo messages it + A simple Slixmpp bot that will echo messages it receives, along with a short thank you message. This version uses a thirdpary service for authentication, @@ -46,7 +36,7 @@ class ThirdPartyAuthBot(sleekxmpp.ClientXMPP): """ def __init__(self, jid, password): - sleekxmpp.ClientXMPP.__init__(self, jid, password) + slixmpp.ClientXMPP.__init__(self, jid, password) # The X-GOOGLE-TOKEN mech is ranked lower than PLAIN # due to Google only allowing a single SASL attempt per @@ -55,7 +45,7 @@ class ThirdPartyAuthBot(sleekxmpp.ClientXMPP): # X-GOOGLE-TOKEN with a TLS connection, explicitly select # it using: # - # sleekxmpp.ClientXMPP.__init__(self, jid, password, + # slixmpp.ClientXMPP.__init__(self, jid, password, # sasl_mech="X-GOOGLE-TOKEN") # The session_start event will be triggered when @@ -104,37 +94,34 @@ class ThirdPartyAuthBot(sleekxmpp.ClientXMPP): if __name__ == '__main__': # Setup the command line arguments. - optp = OptionParser() + parser = ArgumentParser() # Output verbosity options. - optp.add_option('-q', '--quiet', help='set logging to ERROR', - action='store_const', dest='loglevel', - const=logging.ERROR, default=logging.INFO) - optp.add_option('-d', '--debug', help='set logging to DEBUG', - action='store_const', dest='loglevel', - const=logging.DEBUG, default=logging.INFO) - optp.add_option('-v', '--verbose', help='set logging to COMM', - action='store_const', dest='loglevel', - const=5, default=logging.INFO) + parser.add_argument("-q", "--quiet", help="set logging to ERROR", + action="store_const", dest="loglevel", + const=logging.ERROR, default=logging.INFO) + parser.add_argument("-d", "--debug", help="set logging to DEBUG", + action="store_const", dest="loglevel", + const=logging.DEBUG, default=logging.INFO) # JID and password options. - optp.add_option("-j", "--jid", dest="jid", - help="JID to use") - optp.add_option("-p", "--password", dest="password", - help="password to use") + parser.add_argument("-j", "--jid", dest="jid", + help="JID to use") + parser.add_argument("-p", "--password", dest="password", + help="password to use") - opts, args = optp.parse_args() + args = parser.parse_args() # Setup logging. - logging.basicConfig(level=opts.loglevel, + logging.basicConfig(level=args.loglevel, format='%(levelname)-8s %(message)s') - if opts.jid is None: - opts.jid = raw_input("Username: ") - if opts.password is None: - opts.password = getpass.getpass("Password: ") + if args.jid is None: + args.jid = input("Username: ") + if args.password is None: + args.password = getpass("Password: ") + - access_token = None # Since documentation on how to work with Google tokens @@ -156,11 +143,11 @@ if __name__ == '__main__': params = urlencode({ 'accountType': 'GOOGLE', 'service': 'mail', - 'Email': JID(opts.jid).bare, - 'Passwd': opts.password + 'Email': JID(args.jid).bare, + 'Passwd': args.password }) headers = { - 'Content-Type': 'application/x-www-form-urlencoded' + 'Content-Type': 'application/x-www-form-urlencoded' } try: conn.request('POST', '/accounts/ClientLogin', params, headers) @@ -208,12 +195,12 @@ if __name__ == '__main__': # We're using an access token instead of a password, so we'll use `''` as # a password argument filler. - xmpp = ThirdPartyAuthBot(opts.jid, '') + xmpp = ThirdPartyAuthBot(args.jid, '') xmpp.credentials['access_token'] = access_token # The credentials dictionary is used to provide additional authentication # information beyond just a password. - + xmpp.register_plugin('xep_0030') # Service Discovery xmpp.register_plugin('xep_0004') # Data Forms xmpp.register_plugin('xep_0060') # PubSub @@ -231,17 +218,7 @@ if __name__ == '__main__': # xmpp.ca_certs = "path/to/ca/cert" # Connect to the XMPP server and start processing XMPP stanzas. - # Google only allows one SASL attempt per connection, so in order to + # Google only allows one SASL attempt per connection, so in order to # enable the X-GOOGLE-TOKEN mechanism, we'll disable TLS. - if xmpp.connect(use_tls=False): - # If you do not have the dnspython library installed, you will need - # to manually specify the name of the server if it does not match - # the one in the JID. For example, to use Google Talk you would - # need to use: - # - # if xmpp.connect(('talk.google.com', 5222)): - # ... - xmpp.process(block=True) - print("Done") - else: - print("Unable to connect.") + xmpp.connect() + xmpp.process() diff --git a/examples/user_location.py b/examples/user_location.py index 2a64cada..5a30f7af 100755 --- a/examples/user_location.py +++ b/examples/user_location.py @@ -1,9 +1,9 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 import sys import logging -import getpass -from optparse import OptionParser +from getpass import getpass +from argparse import ArgumentParser try: import json @@ -16,7 +16,7 @@ except ImportError: print('This demo requires the requests package for using HTTP.') sys.exit() -from sleekxmpp import ClientXMPP +from slixmpp import ClientXMPP class LocationBot(ClientXMPP): @@ -24,8 +24,8 @@ class LocationBot(ClientXMPP): def __init__(self, jid, password): super(LocationBot, self).__init__(jid, password) - self.add_event_handler('session_start', self.start, threaded=True) - self.add_event_handler('user_location_publish', + self.add_event_handler('session_start', self.start) + self.add_event_handler('user_location_publish', self.user_location_publish) self.register_plugin('xep_0004') @@ -71,55 +71,35 @@ class LocationBot(ClientXMPP): if __name__ == '__main__': # Setup the command line arguments. - optp = OptionParser() + parser = ArgumentParser() # Output verbosity options. - optp.add_option('-q', '--quiet', help='set logging to ERROR', - action='store_const', dest='loglevel', - const=logging.ERROR, default=logging.INFO) - optp.add_option('-d', '--debug', help='set logging to DEBUG', - action='store_const', dest='loglevel', - const=logging.DEBUG, default=logging.INFO) - optp.add_option('-v', '--verbose', help='set logging to COMM', - action='store_const', dest='loglevel', - const=5, default=logging.INFO) + parser.add_argument("-q", "--quiet", help="set logging to ERROR", + action="store_const", dest="loglevel", + const=logging.ERROR, default=logging.INFO) + parser.add_argument("-d", "--debug", help="set logging to DEBUG", + action="store_const", dest="loglevel", + const=logging.DEBUG, default=logging.INFO) # JID and password options. - optp.add_option("-j", "--jid", dest="jid", - help="JID to use") - optp.add_option("-p", "--password", dest="password", - help="password to use") + parser.add_argument("-j", "--jid", dest="jid", + help="JID to use") + parser.add_argument("-p", "--password", dest="password", + help="password to use") - opts, args = optp.parse_args() + args = parser.parse_args() # Setup logging. - logging.basicConfig(level=opts.loglevel, + logging.basicConfig(level=args.loglevel, format='%(levelname)-8s %(message)s') - if opts.jid is None: - opts.jid = raw_input("Username: ") - if opts.password is None: - opts.password = getpass.getpass("Password: ") + if args.jid is None: + args.jid = input("Username: ") + if args.password is None: + args.password = getpass("Password: ") - xmpp = LocationBot(opts.jid, opts.password) - - # If you are working with an OpenFire server, you may need - # to adjust the SSL version used: - # xmpp.ssl_version = ssl.PROTOCOL_SSLv3 - - # If you want to verify the SSL certificates offered by a server: - # xmpp.ca_certs = "path/to/ca/cert" + xmpp = LocationBot(args.jid, args.password) # Connect to the XMPP server and start processing XMPP stanzas. - if xmpp.connect(): - # If you do not have the dnspython library installed, you will need - # to manually specify the name of the server if it does not match - # the one in the JID. For example, to use Google Talk you would - # need to use: - # - # if xmpp.connect(('talk.google.com', 5222)): - # ... - xmpp.process(block=True) - print("Done") - else: - print("Unable to connect.") + xmpp.connect() + xmpp.process() diff --git a/examples/user_tune.py b/examples/user_tune.py index 09e050f0..3f5e1c9e 100755 --- a/examples/user_tune.py +++ b/examples/user_tune.py @@ -1,9 +1,9 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 import sys import logging -import getpass -from optparse import OptionParser +from getpass import getpass +from argparse import ArgumentParser try: from appscript import * @@ -11,7 +11,7 @@ except ImportError: print('This demo requires the appscript package to interact with iTunes.') sys.exit() -from sleekxmpp import ClientXMPP +from slixmpp import ClientXMPP class TuneBot(ClientXMPP): @@ -83,55 +83,35 @@ class TuneBot(ClientXMPP): if __name__ == '__main__': # Setup the command line arguments. - optp = OptionParser() + parser = ArgumentParser() # Output verbosity options. - optp.add_option('-q', '--quiet', help='set logging to ERROR', - action='store_const', dest='loglevel', - const=logging.ERROR, default=logging.INFO) - optp.add_option('-d', '--debug', help='set logging to DEBUG', - action='store_const', dest='loglevel', - const=logging.DEBUG, default=logging.INFO) - optp.add_option('-v', '--verbose', help='set logging to COMM', - action='store_const', dest='loglevel', - const=5, default=logging.INFO) + parser.add_argument("-q", "--quiet", help="set logging to ERROR", + action="store_const", dest="loglevel", + const=logging.ERROR, default=logging.INFO) + parser.add_argument("-d", "--debug", help="set logging to DEBUG", + action="store_const", dest="loglevel", + const=logging.DEBUG, default=logging.INFO) # JID and password options. - optp.add_option("-j", "--jid", dest="jid", - help="JID to use") - optp.add_option("-p", "--password", dest="password", - help="password to use") + parser.add_argument("-j", "--jid", dest="jid", + help="JID to use") + parser.add_argument("-p", "--password", dest="password", + help="password to use") - opts, args = optp.parse_args() + args = parser.parse_args() # Setup logging. - logging.basicConfig(level=opts.loglevel, + logging.basicConfig(level=args.loglevel, format='%(levelname)-8s %(message)s') - if opts.jid is None: - opts.jid = raw_input("Username: ") - if opts.password is None: - opts.password = getpass.getpass("Password: ") + if args.jid is None: + args.jid = input("Username: ") + if args.password is None: + args.password = getpass("Password: ") - xmpp = TuneBot(opts.jid, opts.password) - - # If you are working with an OpenFire server, you may need - # to adjust the SSL version used: - # xmpp.ssl_version = ssl.PROTOCOL_SSLv3 - - # If you want to verify the SSL certificates offered by a server: - # xmpp.ca_certs = "path/to/ca/cert" + xmpp = TuneBot(args.jid, args.password) # Connect to the XMPP server and start processing XMPP stanzas. - if xmpp.connect(): - # If you do not have the dnspython library installed, you will need - # to manually specify the name of the server if it does not match - # the one in the JID. For example, to use Google Talk you would - # need to use: - # - # if xmpp.connect(('talk.google.com', 5222)): - # ... - xmpp.process(block=True) - print("Done") - else: - print("Unable to connect.") + xmpp.connect() + xmpp.process() |