]> kaliko git repositories - sid.git/blob - sid/sid.py
Fixed docstrings indentation
[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     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:
35             func.__doc__ = ''
36         return func
37
38     if len(args):
39         return decorate(args[0], **kwargs)
40     else:
41         return lambda func: decorate(func, **kwargs)
42
43
44 class MUCBot(slixmpp.ClientXMPP):
45
46     prefix = '!'
47
48     def __init__(self, jid, password, room, nick, log_file=None,
49                  log_level=logging.INFO):
50         super(MUCBot, self).__init__(jid, password)
51
52         self.log = logging.getLogger(__package__)
53         self.plugins = list()
54         self.commands = dict()
55         self.room = room
56         self.nick = nick
57         self.__set_logger(log_file, log_level)
58         self.__seen = dict()
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
63
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
68         # our roster.
69         self.add_event_handler('session_start', self.start)
70
71         # Handles MUC message and dispatch
72         self.add_event_handler('message', self.message)
73         self.add_event_handler('got_online', self._view)
74
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
81
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'
88             )
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)
93
94     def message(self, msg):
95         """Messages handler"""
96         if msg['type'] not in ('groupchat', 'chat'):
97             self.log.warning('Unhandled message')
98             return
99         if msg['mucnick'] == self.nick:
100             return
101         body = msg['body'].strip()
102         if not body.startswith(MUCBot.prefix):
103             return
104         if msg['from'] not in self.__seen:
105             self.log.warning('Will not handle message from unseen jid: %s', msg['from'])
106             #return
107         args = body[1:].split()
108         cmd = args.pop(0)
109         if cmd not in self.commands:
110             return
111         self.log.debug('cmd: %s', cmd)
112         if args:
113             self.log.debug('arg: %s', args)
114         try:
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')
121
122     def _view(self, pres):
123         """Track known nick"""
124         nick = pres['from']
125         status = (pres['type'], pres['status'])
126         self.__seen.update({nick: status})
127
128     def start(self, event):
129         """
130         Process the session_start event.
131
132         Typical actions for the session_start event are
133         requesting the roster and broadcasting an initial
134         presence stanza.
135
136         Arguments:
137             event -- An empty dictionary. The session_start
138                      event does not provide any additional
139                      data.
140         """
141         self.get_roster()
142         self.send_presence()
143         self.plugin['xep_0045'].join_muc(self.room,
144                                         self.nick,
145                                         # If a room password is needed, use:
146                                         # password=the_room_password,
147                                         wait=True)
148
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',
153                                                    False):
154                 name = getattr(value, '_bot_command_name')
155                 self.log.debug('Registered command: %s', name)
156                 self.commands[name] = value
157
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)
162
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')()
169
170     @botcmd
171     def help(self, message, args):
172         """Returns a help string listing available options.
173
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')
178         if not args:
179             if self.__doc__:
180                 description = self.__doc__.strip()
181             else:
182                 description = 'Available commands:'
183
184             cmd_list = list()
185             for name, cmd in self.commands.items():
186                 if name == 'help' or cmd._bot_command_hidden:
187                     continue
188                 doc = (cmd.__doc__.strip() or 'undocumented').split('\n', 1)[0]
189                 cmd_list.append('{0}: {1}'.format(name, doc))
190
191             usage = '\n'.join(cmd_list)
192             usage = usage + '\n\n' + help_cmd
193             text = '{}\n\n{}'.format(description, usage)
194         else:
195             if args[0] in self.commands.keys():
196                 text = self.commands[args[0]].__doc__ or 'undocumented'
197                 text = inspect.cleandoc(text)
198             else:
199                 text = 'That command is not defined.'
200         if message['type'] == 'groupchat':
201             to = message['from'].bare
202         else:
203             to = message['from']
204         self.send_message(mto=to, mbody=text, mtype=message['type'])