· 8 years ago · Apr 26, 2018, 09:20 AM
1from jabberbot import JabberBot, botcmd
2from datetime import datetime
3import re
4
5class MUCJabberBot(JabberBot):
6
7 ''' Add features in JabberBot to allow it to handle specific
8 caractheristics of multiple users chatroom (MUC). '''
9
10 def __init__(self, *args, **kwargs):
11 ''' Initialize variables. '''
12
13 # answer only direct messages or not?
14 self.only_direct = kwargs.get('only_direct', False)
15 try:
16 del kwargs['only_direct']
17 except KeyError:
18 pass
19
20 # initialize jabberbot
21 super(MUCJabberBot, self).__init__(*args, **kwargs)
22
23 # create a regex to check if a message is a direct message
24 user, domain = str(self.jid).split('@')
25 self.direct_message_re = re.compile('^%s(@%s)?[^\w]? ' \
26 % (user, domain))
27
28 def callback_message(self, conn, mess):
29 ''' Changes the behaviour of the JabberBot in order to allow
30 it to answer direct messages. This is used often when it is
31 connected in MUCs (multiple users chatroom). '''
32
33 message = mess.getBody()
34 if not message:
35 return
36
37 if self.direct_message_re.match(message):
38 mess.setBody(' '.join(message.split(' ', 1)[1:]))
39 return super(MUCJabberBot, self).callback_message(conn, mess)
40 elif not self.only_direct:
41 return super(MUCJabberBot, self).callback_message(conn, mess)
42
43
44class Example(MUCJabberBot):
45
46 @botcmd
47 def date(self, mess, args):
48 reply = datetime.now().strftime('%Y-%m-%d')
49 self.send_simple_reply(mess, reply)
50
51
52if __name__ == '__main__':
53
54 username = '****@gmail.com'
55 password = '**************'
56 nickname = 'lebot'
57 chatroom = 'lechat'
58
59 mucbot = Example(username, password, only_direct=True)
60 mucbot.join_room(chatroom, nickname)
61 mucbot.serve_forever()