]> kaliko git repositories - sid.git/blob - sid/sid.py
f475bd4f9224cdbe9e9739c00c5519cf1491389b
[sid.git] / sid / sid.py
1 # -*- coding: utf-8 -*-
2
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>
6
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.
10
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.
15
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/>.
18
19
20 import inspect
21 import logging
22 import traceback
23
24 import slixmpp
25
26
27 def botcmd(*args, **kwargs):
28     """Decorator for bot command functions
29
30     :param bool hidden: is the command hidden in global help
31     :param str name: command name, default to decorated function name
32     """
33
34     def decorate(func, hidden=False, name=None):
35         setattr(func, '_bot_command', True)
36         setattr(func, '_bot_command_hidden', hidden)
37         setattr(func, '_bot_command_name', name or func.__name__)
38         if func.__doc__ is None:
39             func.__doc__ = ''
40         return func
41
42     if len(args):
43         return decorate(args[0], **kwargs)
44     else:
45         return lambda func: decorate(func, **kwargs)
46
47
48 class MUCBot(slixmpp.ClientXMPP):
49     """
50     :param str jid: jid to log with
51     :param str password: jid password
52     :param str room: conference room to join
53     :param str nick: Nickname to use in the room
54     """
55
56     #: Class attribute to define bot's command prefix
57     #:
58     #: Defaults to "!"
59     prefix = '!'
60
61     def __init__(self, jid, password, room, nick, log_file=None,
62                  log_level=logging.INFO):
63         super(MUCBot, self).__init__(jid, password)
64
65         # Clean sphinx autodoc for self documentation
66         # (cf. MUCBot.help)
67         self.__doc__ = None
68         self.log = logging.getLogger(__package__)
69         self.plugins = list()
70         self.commands = dict()
71         self.room = room
72         self.nick = nick
73         self.__set_logger(log_file, log_level)
74         self.__seen = dict()
75         self.register_plugin('xep_0030')  # Service Discovery
76         self.register_plugin('xep_0045')  # Multi-User Chat
77         self.register_plugin('xep_0071')  # xhtml-im
78         self.register_plugin('xep_0199')  # self Ping
79
80         # The session_start event will be triggered when
81         # the bot establishes its connection with the server
82         # and the XML streams are ready for use. We want to
83         # listen for this event so that we we can initialize
84         # our roster.
85         self.add_event_handler('session_start', self.start)
86
87         # Handles MUC message and dispatch
88         self.add_event_handler('message', self.message)
89         self.add_event_handler('got_online', self._view)
90
91         # Discover bot internal command (ie. help)
92         for name, value in inspect.getmembers(self):
93             if inspect.ismethod(value) and getattr(value, '_bot_command', False):
94                 name = getattr(value, '_bot_command_name')
95                 self.log.debug('Registered command: %s', name)
96                 self.commands[name] = value
97
98     def __set_logger(self, log_file=None, log_level=logging.INFO):
99         """Create console/file handler"""
100         log_fd = open(log_file, 'w') if log_file else None
101         chandler = logging.StreamHandler(log_fd)
102         formatter = logging.Formatter(
103             '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
104             )
105         chandler.setFormatter(formatter)
106         self.log.addHandler(chandler)
107         self.log.setLevel(log_level)
108         self.log.debug('set logger, log level : %s', log_level)
109
110     def message(self, msg):
111         """Messages handler
112
113         Parses message received to detect :py:obj:`prefix`
114         """
115         if msg['type'] not in ('groupchat', 'chat'):
116             self.log.warning('Unhandled message')
117             return
118         if msg['mucnick'] == self.nick:
119             return
120         body = msg['body'].strip()
121         if not body.startswith(MUCBot.prefix):
122             return
123         if msg['from'] not in self.__seen:
124             self.log.warning('Will not handle message from unseen jid: %s', msg['from'])
125             #return
126         args = body[1:].split()
127         cmd = args.pop(0)
128         if cmd not in self.commands:
129             return
130         self.log.debug('cmd: %s', cmd)
131         if args:
132             self.log.debug('arg: %s', args)
133         try:
134             self.commands[cmd](msg, args)
135         except Exception as err:
136             reply = ''.join(traceback.format_exc())
137             self.log.exception('An error occurred processing: %s: %s', body, reply)
138             if self.log.level < 10 and reply:
139                 self.send_message(mto=msg['from'].bare, mbody=reply, mtype='groupchat')
140
141     def _view(self, pres):
142         """Track known nick"""
143         nick = pres['from']
144         status = (pres['type'], pres['status'])
145         self.__seen.update({nick: status})
146
147     def start(self, event):
148         """
149         Process the session_start event.
150
151         Typical actions for the session_start event are
152         requesting the roster and broadcasting an initial
153         presence stanza.
154
155         :param dict event: An empty dictionary. The session_start
156                      event does not provide any additional data.
157         """
158         self.get_roster()
159         self.send_presence()
160         self.plugin['xep_0045'].join_muc(self.room,
161                                         self.nick,
162                                         # If a room password is needed, use:
163                                         # password=the_room_password,
164                                         wait=True)
165
166         :param `sid.plugin.Plugin` plugin_cls: A :py:obj:`sid.plugin.Plugin` class
167         """
168         self.plugins.append(plugin_cls(self))
169         for name, value in inspect.getmembers(self.plugins[-1]):
170             if inspect.ismethod(value) and getattr(value, '_bot_command',
171                                                    False):
172                 name = getattr(value, '_bot_command_name')
173                 self.log.debug('Registered command: %s', name)
174                 self.commands[name] = value
175
176     def foreach_plugin(self, method, *args, **kwds):
177         for plugin in self.plugins:
178             self.log.debug('shuting down %s', plugin.__str__)
179             getattr(plugin, method)(*args, **kwds)
180
181     def shutdown_plugins(self):
182         # TODO: why can't use event session_end|disconnected?
183         self.log.info('shuting down')
184         for plugin in self.plugins:
185             self.log.debug('shuting down %s', plugin)
186             getattr(plugin, 'shutdown')()
187
188     @botcmd
189     def help(self, message, args):
190         """Returns a help string listing available options.
191
192         Automatically assigned to the "help" command."""
193         help_cmd = ('Type {}help <command name>'.format(self.prefix) +
194                     ' to get more info about that specific command.\n\n'+
195                     'SRC: http://git.kaliko.me/sid.git')
196         if not args:
197             if self.__doc__:
198                 description = self.__doc__.strip()
199             else:
200                 description = 'Available commands:'
201
202             cmd_list = list()
203             for name, cmd in self.commands.items():
204                 if name == 'help' or cmd._bot_command_hidden:
205                     continue
206                 doc = (cmd.__doc__.strip() or 'undocumented').split('\n', 1)[0]
207                 cmd_list.append('{0}: {1}'.format(name, doc))
208
209             usage = '\n'.join(cmd_list)
210             usage = usage + '\n\n' + help_cmd
211             text = '{}\n\n{}'.format(description, usage)
212         else:
213             if args[0] in self.commands.keys():
214                 text = self.commands[args[0]].__doc__ or 'undocumented'
215                 text = inspect.cleandoc(text)
216             else:
217                 text = 'That command is not defined.'
218         if message['type'] == 'groupchat':
219             to = message['from'].bare
220         else:
221             to = message['from']
222         self.send_message(mto=to, mbody=text, mtype=message['type'])