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, 2015, 2020 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(slixmpp.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_0071') # xhtml-im
62 self.register_plugin('xep_0199') # self Ping
64 # The session_start event will be triggered when
65 # the bot establishes its connection with the server
66 # and the XML streams are ready for use. We want to
67 # listen for this event so that we we can initialize
69 self.add_event_handler('session_start', self.start)
71 # Handles MUC message and dispatch
72 self.add_event_handler('message', self.message)
73 self.add_event_handler('got_online', self._view)
75 # Discover bot internal command (ie. help)
76 for name, value in inspect.getmembers(self):
77 if inspect.ismethod(value) and getattr(value, '_bot_command', False):
78 name = getattr(value, '_bot_command_name')
79 self.log.debug('Registered command: %s', name)
80 self.commands[name] = value
82 def __set_logger(self, log_file=None, log_level=logging.INFO):
83 """Create console/file handler"""
84 log_fd = open(log_file, 'w') if log_file else None
85 chandler = logging.StreamHandler(log_fd)
86 formatter = logging.Formatter(
87 '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
89 chandler.setFormatter(formatter)
90 self.log.addHandler(chandler)
91 self.log.setLevel(log_level)
92 self.log.debug('set logger, log level : %s', log_level)
94 def message(self, msg):
95 """Messages handler"""
96 if msg['type'] not in ('groupchat', 'chat'):
97 self.log.warning('Unhandled message')
99 if msg['mucnick'] == self.nick:
101 body = msg['body'].strip()
102 if not body.startswith(MUCBot.prefix):
104 if msg['from'] not in self.__seen:
105 self.log.warning('Will not handle message from unseen jid: %s', msg['from'])
107 args = body[1:].split()
109 if cmd not in self.commands:
111 self.log.debug('cmd: %s', cmd)
113 self.log.debug('arg: %s', args)
115 self.commands[cmd](msg, args)
116 except Exception as err:
117 reply = ''.join(traceback.format_exc())
118 self.log.exception('An error occurred processing: %s: %s', body, reply)
119 if self.log.level < 10 and reply:
120 self.send_message(mto=msg['from'].bare, mbody=reply, mtype='groupchat')
122 def _view(self, pres):
123 """Track known nick"""
125 status = (pres['type'], pres['status'])
126 self.__seen.update({nick: status})
128 def start(self, event):
130 Process the session_start event.
132 Typical actions for the session_start event are
133 requesting the roster and broadcasting an initial
137 event -- An empty dictionary. The session_start
138 event does not provide any additional
143 self.plugin['xep_0045'].join_muc(self.room,
145 # If a room password is needed, use:
146 # password=the_room_password,
149 def register_bot_plugin(self, plugin_class):
150 self.plugins.append(plugin_class(self))
151 for name, value in inspect.getmembers(self.plugins[-1]):
152 if inspect.ismethod(value) and getattr(value, '_bot_command',
154 name = getattr(value, '_bot_command_name')
155 self.log.debug('Registered command: %s', name)
156 self.commands[name] = value
158 def foreach_plugin(self, method, *args, **kwds):
159 for plugin in self.plugins:
160 self.log.debug('shuting down %s', plugin.__str__)
161 getattr(plugin, method)(*args, **kwds)
163 def shutdown_plugins(self):
164 # TODO: why can't use event session_end|disconnected?
165 self.log.info('shuting down')
166 for plugin in self.plugins:
167 self.log.debug('shuting down %s', plugin)
168 getattr(plugin, 'shutdown')()
171 def help(self, message, args):
172 """Returns a help string listing available options.
174 Automatically assigned to the "help" command."""
175 help_cmd = ('Type {}help <command name>'.format(self.prefix) +
176 ' to get more info about that specific command.\n\n'+
177 'SRC: http://git.kaliko.me/sid.git')
180 description = self.__doc__.strip()
182 description = 'Available commands:'
185 for name, cmd in self.commands.items():
186 if name == 'help' or cmd._bot_command_hidden:
188 doc = (cmd.__doc__.strip() or 'undocumented').split('\n', 1)[0]
189 cmd_list.append('{0}: {1}'.format(name, doc))
191 usage = '\n'.join(cmd_list)
192 usage = usage + '\n\n' + help_cmd
193 text = '{}\n\n{}'.format(description, usage)
195 if args[0] in self.commands.keys():
196 text = self.commands[args[0]].__doc__ or 'undocumented'
197 text = inspect.cleandoc(text)
199 text = 'That command is not defined.'
200 if message['type'] == 'groupchat':
201 to = message['from'].bare
204 self.send_message(mto=to, mbody=text, mtype=message['type'])