]> kaliko git repositories - sid.git/blob - sid/sid.py
Fixed traceback logging
[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 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 sleekxmpp
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(sleekxmpp.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(__name__)
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.register_plugin('xep_0030') # Service Discovery
59         self.register_plugin('xep_0045') # Multi-User Chat
60         self.register_plugin('xep_0199') # self Ping
61
62         # The session_start event will be triggered when
63         # the bot establishes its connection with the server
64         # and the XML streams are ready for use. We want to
65         # listen for this event so that we we can initialize
66         # our roster.
67         self.add_event_handler("session_start", self.start)
68
69         # Handles MUC message and dispatch
70         self.add_event_handler("groupchat_message", self.muc_message)
71
72         # Discover bot internal command (ie. help)
73         for name, value in inspect.getmembers(self):
74             if inspect.ismethod(value) and getattr(value, '_bot_command', False):
75                 name = getattr(value, '_bot_command_name')
76                 self.log.debug('Registered command: %s' % name)
77                 self.commands[name] = value
78
79     def __set_logger(self, log_file=None, log_level=logging.INFO):
80         """Create console/file handler"""
81         log_fd = open(log_file, 'w') if log_file else None
82         chandler = logging.StreamHandler(log_fd)
83         formatter = logging.Formatter(
84             '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
85         chandler.setFormatter(formatter)
86         self.log.addHandler(chandler)
87         self.log.setLevel(log_level)
88         self.log.debug('set logger, log level : %s' % log_level)
89
90     def muc_message(self, msg):
91         # ignore message from self
92         body = msg['body']
93         mucfrom = msg['mucnic']
94         if msg['mucnick'] == self.nick:
95             return
96         if not body.startswith(MUCBot.prefix):
97             return
98         args = body[1:].split()
99         cmd = args.pop(0)
100         if cmd not in self.commands:
101             return
102         self.log.debug('cmd: {0}'.format(cmd))
103         if args:
104             self.log.debug('arg: {0}'.format(args))
105         try:
106             reply = self.commands[cmd](msg, args)
107         except Exception as err:
108             reply = ''.join(traceback.format_exc())
109             self.log.exception('An error occurred processing: {0}: {1}'.format(body, reply))
110         self.send_message(mto=msg['from'].bare, mbody=reply, mtype='groupchat')
111
112     def start(self, event):
113         """
114         Process the session_start event.
115
116         Typical actions for the session_start event are
117         requesting the roster and broadcasting an initial
118         presence stanza.
119
120         Arguments:
121             event -- An empty dictionary. The session_start
122                      event does not provide any additional
123                      data.
124         """
125         self.get_roster()
126         self.send_presence()
127         self.plugin['xep_0045'].joinMUC(self.room,
128                                         self.nick,
129                                         # If a room password is needed, use:
130                                         # password=the_room_password,
131                                         wait=True)
132
133     def register_bot_plugin(self, plugin_class):
134         self.plugins.append(plugin_class(self))
135         for name, value in inspect.getmembers(self.plugins[-1]):
136             if inspect.ismethod(value) and getattr(value, '_bot_command',
137                                                    False):
138                 name = getattr(value, '_bot_command_name')
139                 self.log.debug('Registered command: %s' % name)
140                 self.commands[name] = value
141
142     def foreach_plugin(self, method, *args, **kwds):
143         for plugin in self.plugins:
144             self.log.debug('shuting down %s' % plugin.__str__)
145             getattr(plugin, method)(*args, **kwds)
146
147     def shutdown_plugins(self):
148         # TODO: why can't use event session_end|disconnected?
149         self.log.info('shuting down')
150         for plugin in self.plugins:
151             self.log.debug('shuting down %s' % plugin)
152             getattr(plugin, 'shutdown')()
153
154     @botcmd
155     def help(self, message, args):
156         """Returns a help string listing available options.
157
158         Automatically assigned to the "help" command."""
159         help_cmd = ('Type {}help <command name>'.format(self.prefix) +
160                     ' to get more info about that specific command.')
161         if not args:
162             if self.__doc__:
163                 description = self.__doc__.strip()
164             else:
165                 description = 'Available commands:'
166
167             cmd_list = list()
168             for name, cmd in self.commands.items():
169                 if name == 'help' or cmd._bot_command_hidden:
170                     continue
171                 doc = (cmd.__doc__.strip() or 'undocumented').split('\n', 1)[0]
172                 cmd_list.append('{0}: {1}'.format(name, doc))
173
174             usage = '\n'.join(cmd_list)
175             usage = usage + '\n\n' + help_cmd
176             text = '{}\n\n{}'.format(description, usage)
177         else:
178             if args[0] in self.commands.keys():
179                 text = self.commands[args[0]].__doc__.strip() or 'undocumented'
180             else:
181                 text = 'That command is not defined.'
182         return text