license
[errbot-exec.git] / exec.py
1 # -*- coding: utf-8 -*-
2 import os, re, subprocess
3 from errbot import BotPlugin, botcmd, re_botcmd
4 from errbot.utils import ValidationException
5
6 class Exec(BotPlugin):
7     """
8     Execute a command when the bot is talked to
9     """
10
11     config_template = {
12         'command': u'echo'
13     }
14
15     def activate(self):
16         """
17         Load configuration from config.by
18         """
19         super(Exec, self).activate()
20         if (self.config == None and self.bot_config.EXEC):
21             self.check_configuration(self.bot_config.EXEC)
22             self.configure(self.bot_config.EXEC)
23
24     def executable_exists(self, name):
25         """
26         Check if an executable exists
27         """
28         if len(name) == 0:
29             raise ValidationException('Command is empty')
30
31         if os.path.exists(name):
32             return
33
34         found = False
35         for path in os.environ['PATH'].split(os.pathsep):
36             fullpath = path + os.sep + name
37             if os.path.exists(fullpath):
38                 found = True
39                 break
40         if not found:
41             raise ValidationException('Command not in PATH')
42
43     def get_configuration_template(self):
44         """
45         Defines the configuration structure this plugin supports
46         """
47         return self.config_template
48
49     def check_configuration(self, configuration):
50         """
51         Triggers when the configuration is checked, shortly before activation
52         """
53         super(Exec, self).check_configuration(configuration)
54         self.executable_exists(configuration['command'])
55
56     @re_botcmd(pattern=r".*", prefixed=False)
57     def runexec(self, msg, match):
58         """
59         Execute the commmand
60         """
61         try:
62             output = subprocess.check_output(
63                 [self.config['command'], unicode(msg.body), unicode(msg.frm)],
64                 stderr=subprocess.STDOUT
65             )
66             if len(output) > 0:
67                 return unicode(output, 'utf-8')
68             else:
69                 return "OK\n"
70         except subprocess.CalledProcessError as err:
71             if len(err.output):
72                 return unicode(err.output, 'utf-8')
73             else:
74                 return "Error"