Remove google modules from setup.py file
[slixmpp.git] / examples / set_avatar.py
blob647bbd8c371841d9a1fc25fda394404ffd7bdb38
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
4 """
5 Slixmpp: The Slick XMPP Library
6 Copyright (C) 2012 Nathanael C. Fritz
7 This file is part of Slixmpp.
9 See the file LICENSE for copying permission.
10 """
12 import os
13 import sys
14 import imghdr
15 import logging
16 import getpass
17 import threading
18 from optparse import OptionParser
20 import slixmpp
21 from slixmpp.exceptions import XMPPError
24 # Python versions before 3.0 do not use UTF-8 encoding
25 # by default. To ensure that Unicode is handled properly
26 # throughout Slixmpp, we will set the default encoding
27 # ourselves to UTF-8.
28 if sys.version_info < (3, 0):
29 from slixmpp.util.misc_ops import setdefaultencoding
30 setdefaultencoding('utf8')
31 else:
32 raw_input = input
35 class AvatarSetter(slixmpp.ClientXMPP):
37 """
38 A basic script for downloading the avatars for a user's contacts.
39 """
41 def __init__(self, jid, password, filepath):
42 slixmpp.ClientXMPP.__init__(self, jid, password)
44 self.add_event_handler("session_start", self.start, threaded=True)
46 self.filepath = filepath
48 def start(self, event):
49 """
50 Process the session_start event.
52 Typical actions for the session_start event are
53 requesting the roster and broadcasting an initial
54 presence stanza.
56 Arguments:
57 event -- An empty dictionary. The session_start
58 event does not provide any additional
59 data.
60 """
61 self.send_presence()
62 self.get_roster()
64 avatar_file = None
65 try:
66 avatar_file = open(os.path.expanduser(self.filepath))
67 except IOError:
68 print('Could not find file: %s' % self.filepath)
69 return self.disconnect()
71 avatar = avatar_file.read()
73 avatar_type = 'image/%s' % imghdr.what('', avatar)
74 avatar_id = self['xep_0084'].generate_id(avatar)
75 avatar_bytes = len(avatar)
77 avatar_file.close()
79 used_xep84 = False
80 try:
81 print('Publish XEP-0084 avatar data')
82 self['xep_0084'].publish_avatar(avatar)
83 used_xep84 = True
84 except XMPPError:
85 print('Could not publish XEP-0084 avatar')
87 try:
88 print('Update vCard with avatar')
89 self['xep_0153'].set_avatar(avatar=avatar, mtype=avatar_type)
90 except XMPPError:
91 print('Could not set vCard avatar')
93 if used_xep84:
94 try:
95 print('Advertise XEP-0084 avatar metadata')
96 self['xep_0084'].publish_avatar_metadata([
97 {'id': avatar_id,
98 'type': avatar_type,
99 'bytes': avatar_bytes}
100 # We could advertise multiple avatars to provide
101 # options in image type, source (HTTP vs pubsub),
102 # size, etc.
103 # {'id': ....}
105 except XMPPError:
106 print('Could not publish XEP-0084 metadata')
108 print('Wait for presence updates to propagate...')
109 self.schedule('end', 5, self.disconnect, kwargs={'wait': True})
112 if __name__ == '__main__':
113 # Setup the command line arguments.
114 optp = OptionParser()
115 optp.add_option('-q','--quiet', help='set logging to ERROR',
116 action='store_const',
117 dest='loglevel',
118 const=logging.ERROR,
119 default=logging.ERROR)
120 optp.add_option('-d','--debug', help='set logging to DEBUG',
121 action='store_const',
122 dest='loglevel',
123 const=logging.DEBUG,
124 default=logging.ERROR)
125 optp.add_option('-v','--verbose', help='set logging to COMM',
126 action='store_const',
127 dest='loglevel',
128 const=5,
129 default=logging.ERROR)
131 # JID and password options.
132 optp.add_option("-j", "--jid", dest="jid",
133 help="JID to use")
134 optp.add_option("-p", "--password", dest="password",
135 help="password to use")
136 optp.add_option("-f", "--file", dest="filepath",
137 help="path to the avatar file")
138 opts,args = optp.parse_args()
140 # Setup logging.
141 logging.basicConfig(level=opts.loglevel,
142 format='%(levelname)-8s %(message)s')
144 if opts.jid is None:
145 opts.jid = raw_input("Username: ")
146 if opts.password is None:
147 opts.password = getpass.getpass("Password: ")
148 if opts.filepath is None:
149 opts.filepath = raw_input("Avatar file location: ")
151 xmpp = AvatarSetter(opts.jid, opts.password, opts.filepath)
152 xmpp.register_plugin('xep_0054')
153 xmpp.register_plugin('xep_0153')
154 xmpp.register_plugin('xep_0084')
156 # If you are working with an OpenFire server, you may need
157 # to adjust the SSL version used:
158 # xmpp.ssl_version = ssl.PROTOCOL_SSLv3
160 # If you want to verify the SSL certificates offered by a server:
161 # xmpp.ca_certs = "path/to/ca/cert"
163 # Connect to the XMPP server and start processing XMPP stanzas.
164 if xmpp.connect():
165 # If you do not have the dnspython library installed, you will need
166 # to manually specify the name of the server if it does not match
167 # the one in the JID. For example, to use Google Talk you would
168 # need to use:
170 # if xmpp.connect(('talk.google.com', 5222)):
171 # ...
172 xmpp.process(block=True)
173 else:
174 print("Unable to connect.")