|
| 1 | +import importlib |
| 2 | +import os |
| 3 | +import shutil |
| 4 | +import stat |
| 5 | +import subprocess |
| 6 | + |
| 7 | +from colorama import Fore, Style |
| 8 | +from discord.ext import commands |
| 9 | + |
| 10 | +from core.models import Bot |
| 11 | + |
| 12 | + |
| 13 | +class DownloadError(Exception): |
| 14 | + pass |
| 15 | + |
| 16 | + |
| 17 | +class Plugins: |
| 18 | + """Plugins expand Mod Mail functionality by allowing third-party addons. |
| 19 | +
|
| 20 | + These addons could have a range of features from moderation to simply |
| 21 | + making your life as a moderator easier! |
| 22 | + Learn how to create a plugin yourself here: |
| 23 | + https://github.com/kyb3r/modmail/wiki/Plugins |
| 24 | + """ |
| 25 | + def __init__(self, bot: Bot): |
| 26 | + self.bot = bot |
| 27 | + self.bot.loop.create_task(self.download_initial_plugins()) |
| 28 | + |
| 29 | + def _asubprocess_run(self, cmd): |
| 30 | + return subprocess.run(cmd, shell=True, check=True, |
| 31 | + capture_output=True) |
| 32 | + |
| 33 | + @staticmethod |
| 34 | + def parse_plugin(name): |
| 35 | + # returns: (username, repo, plugin_name) |
| 36 | + try: |
| 37 | + result = name.split('/') |
| 38 | + result[2] = '/'.join(result[2:]) |
| 39 | + except IndexError: |
| 40 | + return None |
| 41 | + return tuple(result) |
| 42 | + |
| 43 | + async def download_initial_plugins(self): |
| 44 | + await self.bot._connected.wait() |
| 45 | + for i in self.bot.config.plugins: |
| 46 | + parsed_plugin = self.parse_plugin(i) |
| 47 | + |
| 48 | + try: |
| 49 | + await self.download_plugin_repo(*parsed_plugin[:-1]) |
| 50 | + except DownloadError as exc: |
| 51 | + msg = f'{parsed_plugin[0]}/{parsed_plugin[1]} - {exc}' |
| 52 | + print(Fore.RED + msg + Style.RESET_ALL) |
| 53 | + else: |
| 54 | + try: |
| 55 | + await self.load_plugin(*parsed_plugin) |
| 56 | + except DownloadError as exc: |
| 57 | + msg = f'{parsed_plugin[0]}/{parsed_plugin[1]} - {exc}' |
| 58 | + print(Fore.RED + msg + Style.RESET_ALL) |
| 59 | + |
| 60 | + async def download_plugin_repo(self, username, repo): |
| 61 | + try: |
| 62 | + cmd = f'git clone https://github.com/{username}/{repo} ' |
| 63 | + cmd += f'plugins/{username}-{repo} -q' |
| 64 | + await self.bot.loop.run_in_executor( |
| 65 | + None, |
| 66 | + self._asubprocess_run, |
| 67 | + cmd |
| 68 | + ) |
| 69 | + # -q (quiet) so there's no terminal output unless there's an error |
| 70 | + except subprocess.CalledProcessError as exc: |
| 71 | + error = exc.stderr.decode('utf-8').strip() |
| 72 | + if not error.endswith('already exists and is ' |
| 73 | + 'not an empty directory.'): |
| 74 | + # don't raise error if the plugin folder exists |
| 75 | + raise DownloadError(error) from exc |
| 76 | + |
| 77 | + async def load_plugin(self, username, repo, plugin_name): |
| 78 | + ext = f'plugins.{username}-{repo}.{plugin_name}.{plugin_name}' |
| 79 | + dirname = f'plugins/{username}-{repo}/{plugin_name}' |
| 80 | + if 'requirements.txt' in os.listdir(dirname): |
| 81 | + # Install PIP requirements |
| 82 | + try: |
| 83 | + await self.bot.loop.run_in_executor( |
| 84 | + None, self._asubprocess_run, |
| 85 | + f'python3 -m pip install -U -r {dirname}/' |
| 86 | + 'requirements.txt --user -q -q' |
| 87 | + ) |
| 88 | + # -q -q (quiet) |
| 89 | + # so there's no terminal output unless there's an error |
| 90 | + except subprocess.CalledProcessError as exc: |
| 91 | + error = exc.stderr.decode('utf8').strip() |
| 92 | + if error: |
| 93 | + raise DownloadError( |
| 94 | + f'Unable to download requirements: ```\n{error}\n```' |
| 95 | + ) from exc |
| 96 | + |
| 97 | + try: |
| 98 | + self.bot.load_extension(ext) |
| 99 | + except ModuleNotFoundError as exc: |
| 100 | + raise DownloadError('Invalid plugin structure') from exc |
| 101 | + else: |
| 102 | + msg = f'Loaded plugins.{username}-{repo}.{plugin_name}' |
| 103 | + print(Fore.LIGHTCYAN_EX + msg + Style.RESET_ALL) |
| 104 | + |
| 105 | + @commands.group(aliases=['plugins']) |
| 106 | + @commands.is_owner() |
| 107 | + async def plugin(self, ctx): |
| 108 | + """Plugin handler. Controls the plugins in the bot.""" |
| 109 | + if ctx.invoked_subcommand is None: |
| 110 | + cmd = self.bot.get_command('help') |
| 111 | + await ctx.invoke(cmd, command='plugin') |
| 112 | + |
| 113 | + @plugin.command() |
| 114 | + async def add(self, ctx, *, plugin_name): |
| 115 | + """Adds a plugin""" |
| 116 | + if plugin_name in self.bot.config.plugins: |
| 117 | + return await ctx.send('Plugin already installed') |
| 118 | + if plugin_name in self.bot.cogs.keys(): |
| 119 | + # another class with the same name |
| 120 | + return await ctx.send('Another cog exists with the same name') |
| 121 | + |
| 122 | + message = await ctx.send('Downloading plugin...') |
| 123 | + async with ctx.typing(): |
| 124 | + if len(plugin_name.split('/')) >= 3: |
| 125 | + parsed_plugin = self.parse_plugin(plugin_name) |
| 126 | + |
| 127 | + try: |
| 128 | + await self.download_plugin_repo(*parsed_plugin[:-1]) |
| 129 | + except DownloadError as exc: |
| 130 | + return await ctx.send( |
| 131 | + f'Unable to fetch plugin from Github: {exc}' |
| 132 | + ) |
| 133 | + |
| 134 | + importlib.invalidate_caches() |
| 135 | + try: |
| 136 | + await self.load_plugin(*parsed_plugin) |
| 137 | + except DownloadError as exc: |
| 138 | + return await ctx.send(f'Unable to load plugin: `{exc}`') |
| 139 | + |
| 140 | + # if it makes it here, it has passed all checks and should |
| 141 | + # be entered into the config |
| 142 | + |
| 143 | + self.bot.config.plugins.append(plugin_name) |
| 144 | + await self.bot.config.update() |
| 145 | + |
| 146 | + await message.edit(content='Plugin installed. Any plugin that ' |
| 147 | + 'you install is of your OWN RISK.') |
| 148 | + else: |
| 149 | + await message.edit(content='Invalid plugin name format. ' |
| 150 | + 'Use username/repo/plugin.') |
| 151 | + |
| 152 | + @plugin.command() |
| 153 | + async def remove(self, ctx, *, plugin_name): |
| 154 | + """Removes a certain plugin""" |
| 155 | + if plugin_name in self.bot.config.plugins: |
| 156 | + username, repo, name = self.parse_plugin(plugin_name) |
| 157 | + self.bot.unload_extension( |
| 158 | + f'plugins.{username}-{repo}.{name}.{name}' |
| 159 | + ) |
| 160 | + |
| 161 | + self.bot.config.plugins.remove(plugin_name) |
| 162 | + |
| 163 | + try: |
| 164 | + if not any(i.startswith(f'{username}/{repo}') |
| 165 | + for i in self.bot.config.plugins): |
| 166 | + # if there are no more of such repos, delete the folder |
| 167 | + def onerror(func, path, exc_info): |
| 168 | + if not os.access(path, os.W_OK): |
| 169 | + # Is the error an access error? |
| 170 | + os.chmod(path, stat.S_IWUSR) |
| 171 | + func(path) |
| 172 | + |
| 173 | + shutil.rmtree(f'plugins/{username}-{repo}', |
| 174 | + onerror=onerror) |
| 175 | + except Exception as exc: |
| 176 | + print(exc) |
| 177 | + self.bot.config.plugins.append(plugin_name) |
| 178 | + raise exc |
| 179 | + |
| 180 | + await self.bot.config.update() |
| 181 | + await ctx.send('Plugin uninstalled and ' |
| 182 | + 'all related data is erased.') |
| 183 | + else: |
| 184 | + await ctx.send('Plugin not installed.') |
| 185 | + |
| 186 | + @plugin.command() |
| 187 | + async def update(self, ctx, *, plugin_name): |
| 188 | + """Updates a certain plugin""" |
| 189 | + if plugin_name not in self.bot.config.plugins: |
| 190 | + return await ctx.send('Plugin not installed') |
| 191 | + |
| 192 | + async with ctx.typing(): |
| 193 | + username, repo, name = self.parse_plugin(plugin_name) |
| 194 | + try: |
| 195 | + cmd = f'cd plugins/{username}-{repo} && git pull' |
| 196 | + cmd = await self.bot.loop.run_in_executor( |
| 197 | + None, |
| 198 | + self._asubprocess_run, |
| 199 | + cmd |
| 200 | + ) |
| 201 | + except subprocess.CalledProcessError as exc: |
| 202 | + error = exc.stderr.decode('utf8').strip() |
| 203 | + await ctx.send(f'Error while updating: {error}') |
| 204 | + else: |
| 205 | + output = cmd.stdout.decode('utf8').strip() |
| 206 | + await ctx.send(f'```\n{output}\n```') |
| 207 | + |
| 208 | + if output != 'Already up to date.': |
| 209 | + # repo was updated locally, now perform the cog reload |
| 210 | + ext = f'plugins.{username}-{repo}.{name}.{name}' |
| 211 | + importlib.reload(importlib.import_module(ext)) |
| 212 | + |
| 213 | + try: |
| 214 | + await self.load_plugin(username, repo, name) |
| 215 | + except DownloadError as exc: |
| 216 | + await ctx.send(f'Unable to start plugin: `{exc}`') |
| 217 | + |
| 218 | + @plugin.command(name='list') |
| 219 | + async def list_(self, ctx): |
| 220 | + """Shows a list of currently enabled plugins""" |
| 221 | + if self.bot.config.plugins: |
| 222 | + msg = '```\n' + '\n'.join(self.bot.config.plugins) + '\n```' |
| 223 | + await ctx.send(msg) |
| 224 | + else: |
| 225 | + await ctx.send('No plugins installed') |
| 226 | + |
| 227 | + |
| 228 | +def setup(bot): |
| 229 | + bot.add_cog(Plugins(bot)) |
0 commit comments