1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2007-2012 Thomas Perl <thp.io/about>
4 # Copyright (C) 2010, 2011 Anaƫl Verrier <elghinn@free.fr>
5 # Copyright (C) 2014 kaliko <kaliko@azylum.org>
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, version 3 only.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
27 def botcmd(*args, **kwargs):
28 """Decorator for bot command functions"""
30 def decorate(func, hidden=False, name=None):
31 setattr(func, '_bot_command', True)
32 setattr(func, '_bot_command_hidden', hidden)
33 setattr(func, '_bot_command_name', name or func.__name__)
34 if func.__doc__ is None:
39 return decorate(args[0], **kwargs)
41 return lambda func: decorate(func, **kwargs)
44 class MUCBot(sleekxmpp.ClientXMPP):
48 def __init__(self, jid, password, room, nick, log_file=None,
49 log_level=logging.INFO):
50 super(MUCBot, self).__init__(jid, password)
52 self.log = logging.getLogger(__package__)
54 self.commands = dict()
57 self.__set_logger(log_file, log_level)
59 self.register_plugin('xep_0030') # Service Discovery
60 self.register_plugin('xep_0045') # Multi-User Chat
61 self.register_plugin('xep_0199') # self Ping
63 # The session_start event will be triggered when
64 # the bot establishes its connection with the server
65 # and the XML streams are ready for use. We want to
66 # listen for this event so that we we can initialize
68 self.add_event_handler('session_start', self.start)
70 # Handles MUC message and dispatch
71 self.add_event_handler('message', self.message)
72 self.add_event_handler('got_online', self._view)
74 # Discover bot internal command (ie. help)
75 for name, value in inspect.getmembers(self):
76 if inspect.ismethod(value) and getattr(value, '_bot_command', False):
77 name = getattr(value, '_bot_command_name')
78 self.log.debug('Registered command: %s' % name)
79 self.commands[name] = value
81 def __set_logger(self, log_file=None, log_level=logging.INFO):
82 """Create console/file handler"""
83 log_fd = open(log_file, 'w') if log_file else None
84 chandler = logging.StreamHandler(log_fd)
85 formatter = logging.Formatter(
86 '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
87 chandler.setFormatter(formatter)
88 self.log.addHandler(chandler)
89 self.log.setLevel(log_level)
90 self.log.debug('set logger, log level : %s' % log_level)
92 def message(self, msg):
93 if msg['type'] not in ('groupchat', 'chat'):
94 self.log.warning('Unhandled message')
96 if msg['mucnick'] == self.nick:
98 body = msg['body'].strip()
99 if not body.startswith(MUCBot.prefix):
101 if msg['from'] not in self.__seen:
102 self.log.warning('Will not handle message '
103 'from unseen jid: %s' % msg['from'])
105 args = body[1:].split()
107 if cmd not in self.commands:
109 self.log.debug('cmd: {0}'.format(cmd))
111 self.log.debug('arg: {0}'.format(args))
113 self.commands[cmd](msg, args)
114 except Exception as err:
115 reply = ''.join(traceback.format_exc())
116 self.log.exception('An error occurred processing: {0}: {1}'.format(body, reply))
117 if self.log.level < 10 and reply:
118 self.send_message(mto=msg['from'].bare, mbody=reply, mtype='groupchat')
120 def _view(self, pres):
122 status = (pres['type'], pres['status'])
123 self.__seen.update({nick: status})
125 def start(self, event):
127 Process the session_start event.
129 Typical actions for the session_start event are
130 requesting the roster and broadcasting an initial
134 event -- An empty dictionary. The session_start
135 event does not provide any additional
140 self.plugin['xep_0045'].joinMUC(self.room,
142 # If a room password is needed, use:
143 # password=the_room_password,
146 def register_bot_plugin(self, plugin_class):
147 self.plugins.append(plugin_class(self))
148 for name, value in inspect.getmembers(self.plugins[-1]):
149 if inspect.ismethod(value) and getattr(value, '_bot_command',
151 name = getattr(value, '_bot_command_name')
152 self.log.debug('Registered command: %s' % name)
153 self.commands[name] = value
155 def foreach_plugin(self, method, *args, **kwds):
156 for plugin in self.plugins:
157 self.log.debug('shuting down %s' % plugin.__str__)
158 getattr(plugin, method)(*args, **kwds)
160 def shutdown_plugins(self):
161 # TODO: why can't use event session_end|disconnected?
162 self.log.info('shuting down')
163 for plugin in self.plugins:
164 self.log.debug('shuting down %s' % plugin)
165 getattr(plugin, 'shutdown')()
168 def help(self, message, args):
169 """Returns a help string listing available options.
171 Automatically assigned to the "help" command."""
172 help_cmd = ('Type {}help <command name>'.format(self.prefix) +
173 ' to get more info about that specific command.')
176 description = self.__doc__.strip()
178 description = 'Available commands:'
181 for name, cmd in self.commands.items():
182 if name == 'help' or cmd._bot_command_hidden:
184 doc = (cmd.__doc__.strip() or 'undocumented').split('\n', 1)[0]
185 cmd_list.append('{0}: {1}'.format(name, doc))
187 usage = '\n'.join(cmd_list)
188 usage = usage + '\n\n' + help_cmd
189 text = '{}\n\n{}'.format(description, usage)
191 if args[0] in self.commands.keys():
192 text = self.commands[args[0]].__doc__.strip() or 'undocumented'
194 text = 'That command is not defined.'
195 if message['type'] == 'groupchat':
196 to = message['from'].bare
199 self.send_message(mto=to, mbody=text, mtype=message['type'])