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