Add a base class for MUCs and a usage example
[jabberbot/examples.git] / examples / muc.py
blob3459a29879a3a59b8b87a8133f5933fcc25f5115
1 #!/usr/bin/env python
2 # coding: utf-8
4 # Copyright (C) 2010 Arthur Furlan <afurlan@afurlan.org>
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
11 # On Debian systems, you can find the full text of the license in
12 # /usr/share/common-licenses/GPL-3
15 from jabberbot import JabberBot, botcmd
16 from datetime import datetime
17 import re
19 class MUCJabberBot(JabberBot):
21 ''' Add features in JabberBot to allow it to handle specific
22 caractheristics of multiple users chatroom (MUC). '''
24 def __init__(self, *args, **kwargs):
25 ''' Initialize variables. '''
27 # answer only direct messages or not?
28 self.only_direct = kwargs.get('only_direct', False)
29 try:
30 del kwargs['only_direct']
31 except KeyError:
32 pass
34 # initialize jabberbot
35 super(MUCJabberBot, self).__init__(*args, **kwargs)
37 # create a regex to check if a message is a direct message
38 user, domain = str(self.jid).split('@')
39 self.direct_message_re = re.compile('^%s(@%s)?[^\w]? ' \
40 % (user, domain))
42 def callback_message(self, conn, mess):
43 ''' Changes the behaviour of the JabberBot in order to allow
44 it to answer direct messages. This is used often when it is
45 connected in MUCs (multiple users chatroom). '''
47 message = mess.getBody()
48 if not message:
49 return
51 if self.direct_message_re.match(message):
52 mess.setBody(' '.join(message.split(' ', 1)[1:]))
53 return super(MUCJabberBot, self).callback_message(conn, mess)
54 elif not self.only_direct:
55 return super(MUCJabberBot, self).callback_message(conn, mess)
58 class Example(MUCJabberBot):
60 @botcmd
61 def date(self, mess, args):
62 reply = datetime.now().strftime('%Y-%m-%d')
63 self.send_simple_reply(mess, reply)
66 if __name__ == '__main__':
68 username = 'username'
69 password = 'password'
70 nickname = 'nickname'
71 chatroom = 'chatroom'
73 mucbot = Example(username, password, only_direct=True)
74 mucbot.join_room(chatroom, nickname)
75 mucbot.serve_forever()