async def uninstall(self, ctx, *, package): if pwd.getpwuid(os.getuid())[0] == "pi": code = codeblock_converter(f"pip3.9 uninstall -y {package}") await ctx.invoke(self.bot.get_command("jishaku shell"), **{"argument": code}) else: code = codeblock_converter(f"python3.9 -m pip uninstall -y {package}") await ctx.invoke(self.bot.get_command("jishaku shell"), **{"argument": code})
async def refresh(self, ctx): cog = self.client.get_cog("Jishaku") await cog.jsk_git(ctx, argument=codeblock_converter(f'stash')) await asyncio.sleep(2) await cog.jsk_git( ctx, argument=codeblock_converter( f'pull --ff-only https://github.com/ConchDev/Conch-Development-Bot master' )) await asyncio.sleep(2) restart = self.client.get_command('restart') await ctx.invoke(restart)
async def paste(self, ctx, *, paste: str = None): if not paste and not ctx.message.attachments: return await ctx.send("No Paste Data") elif not paste: attachments = ctx.message.attachments if attachments[0].height: return await ctx.send( "That file has a height, meaning it's probably an image. I can't paste those!") if attachments[0].size // 1000000 > 8: return await ctx.send("That's too large of a file!") split_attachment = attachments[0].filename.split(".") if split_attachment[1] in ["zip", "exe", "nbt"]: return await ctx.send( f"Invalid file type: `{split_attachment[1]}` is invalid.") file = await attachments[0].read() text = file.decode('UTF-8') url = await self.client.session.post("https://paste.daggy.tech/upload", data=text) js = await url.json() return await ctx.send(js["file"]) elif not ctx.message.attachments: paste = codeblocks.codeblock_converter(paste) lang = paste[0] or "" url = await self.client.session.post("https://paste.daggy.tech/upload", data=paste[1]) js = await url.json() return await ctx.send(f'{js["file"]}.{lang}')
async def paste(self, ctx, paste: str = None): """Pastes a file to mystbin, attempts to check for an attachment first, and if it cannot detect one, goes to text, and will error if it can't find that. You can also use codeblocks and it will detect text in that. Detects file extension.""" if not paste and not ctx.message.attachments: return await ctx.send("You didn't provide anything to paste") # Checking for attachment first elif not paste: attachments = ctx.message.attachments if attachments[0].height: return await ctx.send( "That file has a height, meaning it's probably an image. I can't paste those!" ) if attachments[0].size // 1000000 > 8: return await ctx.send("That's too large of a file!") split_attachment = attachments[0].filename.split(".") if split_attachment[1] in ["zip", "exe", "nbt"]: return await ctx.send( f"Invalid file type: `{split_attachment[1]}` is invalid.") file = await attachments[0].read() text = file.decode('UTF-8') url = await self.mystbin.post(text, syntax=split_attachment[1]) return await ctx.send(str(url)) # Checking for text elif not ctx.message.attachments: paste = codeblock_converter(paste) url = await self.mystbin.post(paste[1], syntax=paste[0]) return await ctx.send(str(url))
async def on_code(self, payload, lang, lang_name): data = dict(LanguageChoice=lang, Program=codeblock_converter( payload.message.content).content) r = await (await self.bot.session.post(self.rextester, data=data)).json() embed = discord.Embed(title=f"Code execution results | {lang_name}", color=0x7289DA) embed.description = str() errors, warnings, result, stats = r.get("Errors"), r.get( "Warnings"), r.get("Result"), r.get("Stats") result = (result or "<no result>")[:2000] if errors: embed.description += f"Errors:\n```prolog\n{errors}```\n" if warnings: embed.description += f"Warnings:\n```prolog\n{warnings}```\n" if result: embed.description += f"Result:\n```prolog\n{result}```\n" embed.set_footer( text=f"{stats} | Requested by {payload.member}", icon_url=payload.member.avatar_url_as(static_format="png")) try: await payload.channel.send(embed=embed) except discord.errors.HTTPException: await payload.channel.send( "That message was way too long.\n<*bin link soontm>")
async def jsk_update(self, ctx): """Updates jsk from the github repo. This is basically an alias for `jsk sh` but it runs the command for you.""" pip = 'pip' if psutil: if psutil.LINUX: pip = "pip3" elif psutil.MACOS: pip = "pip3" else: pip = "pip" cb = codeblock_converter( f'{pip} install -U git+https://github.com/dragdev-studios/jishaku@master' f'#egg=jishaku --upgrade') status = await ctx.invoke(self.bot.get_command('jsk sh'), argument=cb) if status in [0, 'done']: m = await ctx.send("Update successfully downloaded. applying...") try: self.bot.reload_extension('jishaku') except: await m.edit( content= "It looks like an error occurred while applying the update. your jishaku version" " has been reverted to pre-update to keep it working. try updating again in a few hours." ) else: await m.edit( content="Updates successfully applied. have a good time!")
async def _refresh(self, ctx): """Refresh the bot by invoking `jsk git pull` and `restart`""" cog = self.bot.get_cog("Jishaku") await cog.jsk_git(ctx, argument=codeblock_converter('pull')) await asyncio.sleep(2) # allow jsk git pull to finish restart = self.bot.get_command('restart') await ctx.invoke(restart)
async def convert(cls, ctx: Context, argument: str) -> discord.Embed: try: code = codeblock_converter(argument) return discord.Embed.from_dict(code.content) except Exception: raise commands.BadArgument( "Could not generate embed from supplied JSON.")
async def mystbin(self, ctx, *, code): """Post code to mystbin.""" code = codeblocks.codeblock_converter(code) language = "" if code[0]: language = code[0] elif not code[0]: language = "txt" url = await self.myst.post(code[1], syntax = language) await ctx.send(f"{ctx.author.mention} Here is your code <:join:736719688956117043> {str(url)}")
async def sql(self, ctx, *, query): """Makes an sql SELECT query""" query = codeblocks.codeblock_converter(query)[1] e = await self.bot.db.fetch(query) try: p = Simple(entries=e, per_page=10) await p.start(ctx) except menus.MenuError as f: await ctx.send(f)
async def embed(self, ctx, embedCode): """Makes an embed from JSON, use https://embedbuilder.nadekobot.me/ to make it. You can use codeblocks and it will get the JSON from them.""" embedCode = codeblocks.codeblock_converter(embedCode) try: embed = discord.Embed.from_dict(embedCode[0]) except Exception as e: return await ctx.send( f"An error occurred, probably because the embed was invalid ``` {e} ```" ) await ctx.send(embed=embed)
async def sql(self, ctx, *, query): """Makes an sql SELECT query""" query = codeblocks.codeblock_converter(query)[1] if not query.lower().startswith("select"): data = await self.bot.db.execute(query) return await ctx.send(data) else: e = await self.bot.db.fetch(query) try: p = self.bot.utils.SimpleMenu(entries=e, per_page=10) await p.start(ctx) except menus.MenuError as f: await ctx.send(f)
async def run_code_as(self, ctx: utils.TypedContext, cluster_id: int, *, code: str): response = await ctx.request_ws_data( "run_code", target=cluster_id, args={"run_code": { "code": codeblock_converter(code).content }}, ) if response is None: return return_value: str = response[0]["run_code"] if return_value: await ctx.send(return_value) else: await ctx.message.add_reaction(WHITE_CHECK_MARK)
async def cache_search(self, context, query: (lambda arg: re.compile(codeblock_converter(arg).content))): """Search all emotes that the bot can see using a regular expression. This is useful for gauging the nsfw threshold for a certain kind of emote or seeing if an emote should be preserved based on its name. """ await self.warn_if_no_external_emojis_permission(context) emotes = [] for e in sorted( (e for e in self.bot.emojis if e.is_usable() and query.search(e.name)), key=lambda e: (e.name.lower(), e.name, 0 if e.animated else 1), ): emotes.append(e) if len(emotes) == 10: await context.send(''.join(map(str, emotes))) emotes.clear() if emotes: await context.send(''.join(map(str, emotes))) await context.try_add_reaction(utils.SUCCESS_EMOJIS[True])
async def shell(self, ctx, *, command: str): cog = self.bot.get_cog("Jishaku") code = codeblock_converter(command) await cog.jsk_shell(ctx, argument=code)
async def eval(self, ctx, *, code: str): cog = self.bot.get_cog("Jishaku") res = codeblock_converter(code) await cog.jsk_python(ctx, argument=res)
def test_codeblock_converter(): text = """ ```py one ``` """ codeblock = codeblock_converter(inspect.cleandoc(text)) assert isinstance(codeblock, Codeblock) assert codeblock.content.strip() == 'one' assert codeblock.language == 'py' text = """ ```sql two ``` """ codeblock = codeblock_converter(inspect.cleandoc(text)) assert isinstance(codeblock, Codeblock) assert codeblock.content.strip() == 'two' assert codeblock.language == 'sql' text = """ ```txt three ``` """ codeblock = codeblock_converter(inspect.cleandoc(text)) assert isinstance(codeblock, Codeblock) assert codeblock.content.strip() == 'three' assert codeblock.language == 'txt' text = """ ``` four ``` """ codeblock = codeblock_converter(inspect.cleandoc(text)) assert isinstance(codeblock, Codeblock) assert codeblock.content.strip() == 'four' assert not codeblock.language text = "five" codeblock = codeblock_converter(inspect.cleandoc(text)) assert isinstance(codeblock, Codeblock) assert codeblock.content.strip() == 'five' assert not codeblock.language text = """ six ``` """ codeblock = codeblock_converter(inspect.cleandoc(text)) assert isinstance(codeblock, Codeblock) assert codeblock.content.strip() == 'six\n```' assert not codeblock.language text = "" codeblock = codeblock_converter(inspect.cleandoc(text)) assert isinstance(codeblock, Codeblock) assert codeblock.content.strip() == '' assert not codeblock.language text = """ ``` se``ven ``` """ codeblock = codeblock_converter(inspect.cleandoc(text)) assert isinstance(codeblock, Codeblock) assert codeblock.content.strip() == 'se``ven' assert not codeblock.language text = "``ei`ght``" codeblock = codeblock_converter(text) assert isinstance(codeblock, Codeblock) assert codeblock.content.strip() == 'ei`ght' assert not codeblock.language text = "`nine`" codeblock = codeblock_converter(text) assert isinstance(codeblock, Codeblock) assert codeblock.content.strip() == 'nine' assert not codeblock.language
async def journalctl(self, ctx): await ctx.invoke( self.bot.get_command('jsk sh'), argument=codeblocks.codeblock_converter("journalctl -u penguin"))
async def shell(self, ctx, *, arg: str = None): if str is None: return await ctx.send('No arg given') await ctx.invoke(self.bot.get_command('jsk shell'), argument=codeblocks.codeblock_converter(arg))
async def eval(self, ctx, *, code: str = None): if code is None: return await ctx.send('No arg given') await ctx.invoke(self.bot.get_command('jsk py'), argument=codeblocks.codeblock_converter(code))
async def proc(self, ctx, *, args): """Check supervisorctl on the shell.""" conv = codeblock_converter(f"/usr/local/bin/supervisorctl {args}") await ctx.invoke(ctx.bot.get_command("jsk sh"), argument=conv)
def remove_codeblocks(self, page: str): """Removes the prefix and suffix to replace them properly""" _, content = codeblocks.codeblock_converter(page) return content.strip()