]> kaliko git repositories - sid.git/blob - sid/sid.py
Initial import
[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             self.log.debug('ignoring message from me')
96             return
97         if not body.startswith(MUCBot.prefix):
98             return
99         args = body[1:].split()
100         cmd= args.pop(0)
101         if cmd not in self.commands:
102             return
103         self.log.debug('cmd: {0}'.format(cmd))
104         if args:
105             self.log.debug('arg: {0}'.format(args))
106         try:
107             reply = self.commands[cmd](msg, args)
108         except Exception as err:
109             reply = traceback.format_exc(err)
110             self.log.exception('An error occurred processing: {0}: {1}'.format(body, reply))
111         self.log.debug(reply)
112         self.send_message(mto=msg['from'].bare, mbody=reply, mtype='groupchat')
113
114     def start(self, event):
115         """
116         Process the session_start event.
117
118         Typical actions for the session_start event are
119         requesting the roster and broadcasting an initial
120         presence stanza.
121
122         Arguments:
123             event -- An empty dictionary. The session_start
124                      event does not provide any additional
125                      data.
126         """
127         self.get_roster()
128         self.send_presence()
129         self.plugin['xep_0045'].joinMUC(self.room,
130                                         self.nick,
131                                         # If a room password is needed, use:
132                                         # password=the_room_password,
133                                         wait=True)
134
135     def register_bot_plugin(self, plugin_class):
136         self.plugins.append(plugin_class(self))
137         for name, value in inspect.getmembers(self.plugins[-1]):
138             if inspect.ismethod(value) and getattr(value, '_bot_command',
139                                                    False):
140                 name = getattr(value, '_bot_command_name')
141                 self.log.debug('Registered command: %s' % name)
142                 self.commands[name] = value
143
144     def foreach_plugin(self, method, *args, **kwds):
145         for plugin in self.plugins:
146             self.log.debug('shuting down %s' % plugin.__str__)
147             getattr(plugin, method)(*args, **kwds)
148
149     def shutdown_plugins(self):
150         # TODO: why can't use event session_end|disconnected?
151         self.log.info('shuting down')
152         for plugin in self.plugins:
153             self.log.debug('shuting down %s' % plugin)
154             getattr(plugin, 'shutdown')()
155
156     @botcmd
157     def help(self, message, args):
158         """Returns a help string listing available options.
159
160         Automatically assigned to the "help" command."""
161         self.log.info(args)
162         help_cmd = ('Type {}help <command name>'.format(self.prefix) +
163                     ' to get more info about that specific command.')
164         if not args:
165             if self.__doc__:
166                 description = self.__doc__.strip()
167             else:
168                 description = 'Available commands:'
169
170             cmd_list = list()
171             for name, cmd in self.commands.items():
172                 if name == 'help' or cmd._bot_command_hidden:
173                     continue
174                 doc = (cmd.__doc__.strip() or 'undocumented').split('\n', 1)[0]
175                 cmd_list.append('{0}: {1}'.format(name, doc))
176
177             usage = '\n'.join(cmd_list)
178             usage = usage + '\n\n' + help_cmd
179             text = '{}\n\n{}'.format(description, usage)
180         else:
181             self.log.debug(args[0])
182             self.log.debug(args[0] in self.commands.keys())
183             if args[0] in self.commands.keys():
184                 text = self.commands[args[0]].__doc__.strip() or 'undocumented'
185             else:
186                 text = 'That command is not defined.'
187         return text