Make xmlstream use an asyncio loop
[slixmpp.git] / examples / user_location.py
blob1ef78666c2b3c8354b995489f2ee74dfec9b9790
1 #!/usr/bin/env python
3 import sys
4 import logging
5 import getpass
6 from optparse import OptionParser
8 try:
9 import json
10 except ImportError:
11 import simplejson as json
13 try:
14 import requests
15 except ImportError:
16 print('This demo requires the requests package for using HTTP.')
17 sys.exit()
19 from slixmpp import ClientXMPP
22 class LocationBot(ClientXMPP):
24 def __init__(self, jid, password):
25 super(LocationBot, self).__init__(jid, password)
27 self.add_event_handler('session_start', self.start, threaded=True)
28 self.add_event_handler('user_location_publish',
29 self.user_location_publish)
31 self.register_plugin('xep_0004')
32 self.register_plugin('xep_0030')
33 self.register_plugin('xep_0060')
34 self.register_plugin('xep_0115')
35 self.register_plugin('xep_0128')
36 self.register_plugin('xep_0163')
37 self.register_plugin('xep_0080')
39 self.current_tune = None
41 def start(self, event):
42 self.send_presence()
43 self.get_roster()
44 self['xep_0115'].update_caps()
46 print("Using freegeoip.net to get geolocation.")
47 r = requests.get('http://freegeoip.net/json/')
48 try:
49 data = json.loads(r.text)
50 except:
51 print("Could not retrieve user location.")
52 self.disconnect()
53 return
55 self['xep_0080'].publish_location(
56 lat=data['latitude'],
57 lon=data['longitude'],
58 locality=data['city'],
59 region=data['region_name'],
60 country=data['country_name'],
61 countrycode=data['country_code'],
62 postalcode=data['zipcode'])
64 def user_location_publish(self, msg):
65 geo = msg['pubsub_event']['items']['item']['geoloc']
66 print("%s is at:" % msg['from'])
67 for key, val in geo.values.items():
68 if val:
69 print(" %s: %s" % (key, val))
72 if __name__ == '__main__':
73 # Setup the command line arguments.
74 optp = OptionParser()
76 # Output verbosity options.
77 optp.add_option('-q', '--quiet', help='set logging to ERROR',
78 action='store_const', dest='loglevel',
79 const=logging.ERROR, default=logging.INFO)
80 optp.add_option('-d', '--debug', help='set logging to DEBUG',
81 action='store_const', dest='loglevel',
82 const=logging.DEBUG, default=logging.INFO)
83 optp.add_option('-v', '--verbose', help='set logging to COMM',
84 action='store_const', dest='loglevel',
85 const=5, default=logging.INFO)
87 # JID and password options.
88 optp.add_option("-j", "--jid", dest="jid",
89 help="JID to use")
90 optp.add_option("-p", "--password", dest="password",
91 help="password to use")
93 opts, args = optp.parse_args()
95 # Setup logging.
96 logging.basicConfig(level=opts.loglevel,
97 format='%(levelname)-8s %(message)s')
99 if opts.jid is None:
100 opts.jid = raw_input("Username: ")
101 if opts.password is None:
102 opts.password = getpass.getpass("Password: ")
104 xmpp = LocationBot(opts.jid, opts.password)
106 # If you are working with an OpenFire server, you may need
107 # to adjust the SSL version used:
108 # xmpp.ssl_version = ssl.PROTOCOL_SSLv3
110 # If you want to verify the SSL certificates offered by a server:
111 # xmpp.ca_certs = "path/to/ca/cert"
113 # Connect to the XMPP server and start processing XMPP stanzas.
114 if xmpp.connect():
115 # If you do not have the dnspython library installed, you will need
116 # to manually specify the name of the server if it does not match
117 # the one in the JID. For example, to use Google Talk you would
118 # need to use:
120 # if xmpp.connect(('talk.google.com', 5222)):
121 # ...
122 xmpp.process(block=True)
123 print("Done")
124 else:
125 print("Unable to connect.")