· 4 years ago · Jun 15, 2021, 06:58 PM
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4"""
5 SleekXMPP: The Sleek XMPP Library
6 Copyright (C) 2010 Nathanael C. Fritz
7 This file is part of SleekXMPP.
8
9 See the file LICENSE for copying permission.
10"""
11
12import sys
13import logging
14import getpass
15from optparse import OptionParser
16
17import sleekxmpp
18
19# Python versions before 3.0 do not use UTF-8 encoding
20# by default. To ensure that Unicode is handled properly
21# throughout SleekXMPP, we will set the default encoding
22# ourselves to UTF-8.
23if sys.version_info < (3, 0):
24 from sleekxmpp.util.misc_ops import setdefaultencoding
25 setdefaultencoding('utf8')
26else:
27 raw_input = input
28
29
30class EchoBot(sleekxmpp.ClientXMPP):
31
32 """
33 A simple SleekXMPP bot that will echo messages it
34 receives, along with a short thank you message.
35 """
36
37 def __init__(self, jid, password):
38 sleekxmpp.ClientXMPP.__init__(self, jid, password)
39
40 # The session_start event will be triggered when
41 # the bot establishes its connection with the server
42 # and the XML streams are ready for use. We want to
43 # listen for this event so that we we can initialize
44 # our roster.
45 self.add_event_handler("session_start", self.start)
46
47 # The message event is triggered whenever a message
48 # stanza is received. Be aware that that includes
49 # MUC messages and error messages.
50 self.add_event_handler("message", self.message)
51
52 def start(self, event):
53 """
54 Process the session_start event.
55
56 Typical actions for the session_start event are
57 requesting the roster and broadcasting an initial
58 presence stanza.
59
60 Arguments:
61 event -- An empty dictionary. The session_start
62 event does not provide any additional
63 data.
64 """
65 self.send_presence()
66 self.get_roster()
67
68 def message(self, msg):
69 """
70 Process incoming message stanzas. Be aware that this also
71 includes MUC messages and error messages. It is usually
72 a good idea to check the messages's type before processing
73 or sending replies.
74
75 Arguments:
76 msg -- The received message stanza. See the documentation
77 for stanza objects and the Message stanza to see
78 how it may be used.
79 """
80 if msg['type'] in ('chat', 'normal'):
81 msg.reply("Thanks for sending\n%(body)s" % msg).send()
82
83
84if __name__ == '__main__':
85 # Setup the command line arguments.
86 optp = OptionParser()
87
88 # Output verbosity options.
89 optp.add_option('-q', '--quiet', help='set logging to ERROR',
90 action='store_const', dest='loglevel',
91 const=logging.ERROR, default=logging.INFO)
92 optp.add_option('-d', '--debug', help='set logging to DEBUG',
93 action='store_const', dest='loglevel',
94 const=logging.DEBUG, default=logging.INFO)
95 optp.add_option('-v', '--verbose', help='set logging to COMM',
96 action='store_const', dest='loglevel',
97 const=5, default=logging.INFO)
98
99 # JID and password options.
100 optp.add_option("-j", "--jid", dest="jid",
101 help="JID to use")
102 optp.add_option("-p", "--password", dest="password",
103 help="password to use")
104
105 opts, args = optp.parse_args()
106
107 # Setup logging.
108 logging.basicConfig(level=opts.loglevel,
109 format='%(levelname)-8s %(message)s')
110
111 if opts.jid is None:
112 opts.jid = raw_input("Username: ")
113 if opts.password is None:
114 opts.password = getpass.getpass("Password: ")
115
116 # Setup the EchoBot and register plugins. Note that while plugins may
117 # have interdependencies, the order in which you register them does
118 # not matter.
119 xmpp = EchoBot(opts.jid, opts.password)
120 xmpp.register_plugin('xep_0030') # Service Discovery
121 xmpp.register_plugin('xep_0004') # Data Forms
122 xmpp.register_plugin('xep_0060') # PubSub
123 xmpp.register_plugin('xep_0199') # XMPP Ping
124
125 # If you are connecting to Facebook and wish to use the
126 # X-FACEBOOK-PLATFORM authentication mechanism, you will need
127 # your API key and an access token. Then you'll set:
128 # xmpp.credentials['api_key'] = 'THE_API_KEY'
129 # xmpp.credentials['access_token'] = 'THE_ACCESS_TOKEN'
130
131 # If you are connecting to MSN, then you will need an
132 # access token, and it does not matter what JID you
133 # specify other than that the domain is 'messenger.live.com',
134 # so '_@messenger.live.com' will work. You can specify
135 # the access token as so:
136 # xmpp.credentials['access_token'] = 'THE_ACCESS_TOKEN'
137
138 # If you are working with an OpenFire server, you may need
139 # to adjust the SSL version used:
140 # xmpp.ssl_version = ssl.PROTOCOL_SSLv3
141
142 # If you want to verify the SSL certificates offered by a server:
143 # xmpp.ca_certs = "path/to/ca/cert"
144
145 # Connect to the XMPP server and start processing XMPP stanzas.
146 if xmpp.connect():
147 # If you do not have the dnspython library installed, you will need
148 # to manually specify the name of the server if it does not match
149 # the one in the JID. For example, to use Google Talk you would
150 # need to use:
151 #
152 # if xmpp.connect(('talk.google.com', 5222)):
153 # ...
154 xmpp.process(block=False)
155 print("Done")
156 else:
157 print("Unable to connect.")