From b71e17086d7bcef8ced16665a510605852813909 Mon Sep 17 00:00:00 2001 From: un1xx Date: Fri, 8 Mar 2024 23:17:48 +0530 Subject: [PATCH] update --- .gitignore | 3 +- botclass.py | 13 ++- exts/REPL.py | 194 ++++++++++++++++++++++++++++++++++++++++ utils/ansiblocks.py | 17 ++++ utils/base.py | 57 ++++++++++++ utils/buttons/delete.py | 24 +++++ utils/checks.py | 21 +++++ utils/funcs.py | 32 +++++++ utils/paginator.py | 194 ++++++++++++++++++++++++++++++++++++++++ 9 files changed, 553 insertions(+), 2 deletions(-) create mode 100644 exts/REPL.py create mode 100644 utils/ansiblocks.py create mode 100644 utils/base.py create mode 100644 utils/buttons/delete.py create mode 100644 utils/checks.py create mode 100644 utils/funcs.py create mode 100644 utils/paginator.py diff --git a/.gitignore b/.gitignore index 6fd0fed..1dc4524 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ .python-version -__pycache__ \ No newline at end of file +__pycache__ +store \ No newline at end of file diff --git a/botclass.py b/botclass.py index d799e68..1bc25c2 100644 --- a/botclass.py +++ b/botclass.py @@ -7,14 +7,25 @@ import aiohttp import discord import jishaku from discord.ext.commands import Bot, Context +from utils.paginator import Paginator, WebhookPaginator -OWNER = [407135783678640128, 341958485724102668] +ownerid = json.load(open("store/cfg.json"))["ReplOwners"] class CustomCtx(Context): def __init__(self, **kwargs): super().__init__(**kwargs) + self.Paginator = Paginator + self.WebhookPaginator = WebhookPaginator self.session = aiohttp.ClientSession(loop=self.bot.loop) + + async def paginate( + self, + pages: List[discord.Embed | str], + pagetype: Optional[Literal["embed", "text"]] = "embed", + **kwargs, + ): + await self.Paginator(pages=pages, pagetype=pagetype).start(ctx=self, **kwargs) diff --git a/exts/REPL.py b/exts/REPL.py new file mode 100644 index 0000000..baa8176 --- /dev/null +++ b/exts/REPL.py @@ -0,0 +1,194 @@ +import asyncio +import datetime +import inspect +import io +import json +import math +import os +import sys +import textwrap +import time +import traceback +from contextlib import redirect_stdout + +import aiofiles +import aiohttp +import discord +from discord.ext import commands +from utils.paginator import Paginator + +ownerid = json.load(open("store/cfg.json"))["ReplOwners"] + + +class REPL(commands.Cog): + def __init__(self, bot: commands.Bot): + self.bot = bot + self._last_result = None + self.sessions = set() + self.session = aiohttp.ClientSession(loop=bot.loop) + + def cleanup_code(self, content): + "Automatically removes code blocks from the code." + if content.startswith("```") and content.endswith("```"): + return "\n".join(content.split("\n")[1:(-1)]) + return content.strip("` \n") + + def get_syntax_error(self, e): + if e.text is None: + return "```py\n{0.__class__.__name__}: {0}\n```".format(e) + return "```py\n{0.text}{1:>{0.offset}}\n{2}: {0}```".format( + e, "^", type(e).__name__ + ) + + @commands.command(hidden=True, name="exec", aliases=["ev", "eval", "e"]) + @commands.is_owner() + async def _eval(self, ctx, *, body: str): + env = { + "bot": self.bot, + "ctx": ctx, + "channel": ctx.channel, + "author": ctx.author, + "guild": ctx.guild, + "message": ctx.message, + "_": self._last_result, + "session": self.session, + } + env.update(globals()) + body = self.cleanup_code(body) + stdout = io.StringIO() + to_compile = "async def func():\n%s" % textwrap.indent(body, " ") + paginator = commands.Paginator(prefix="```py\n", suffix="\n```", max_size=2000) + try: + exec(to_compile, env) + except SyntaxError as e: + return await ctx.send(self.get_syntax_error(e)) + func = env["func"] + try: + with redirect_stdout(stdout): + ret = await func() + except Exception as e: + value = stdout.getvalue() + for line in "{}{}".format(value, traceback.format_exc()).splitlines(): + paginator.add_line(line) + else: + value = stdout.getvalue() + try: + await ctx.message.add_reaction("☑") + except: + pass + if ret is None: + if value: + for line in value.splitlines(): + paginator.add_line(line) + else: + self._last_result = ret + for line in ("%s%s" % (value, ret)).splitlines(): + try: + paginator.add_line(line) + except RuntimeError: + splitted = [ + line[i : i + 1988] for i in range(0, len(line), 1988) + ] + for part in splitted: + paginator.add_line(part) + pages = [] + for page in paginator.pages: + pages.append(page) + if len(pages) == 1: + await ctx.send(pages[0]) + return + + pgn = Paginator(pages=pages, pagetype="text") + await pgn.start(ctx=ctx) + + @commands.command(hidden=True) + @commands.is_owner() + async def repl(self, ctx): + msg = ctx.message + variables = { + "ctx": ctx, + "bot": self.bot, + "message": msg, + "guild": msg.guild, + "channel": msg.channel, + "author": msg.author, + "_": None, + "session": self.session, + } + paginator = commands.Paginator(prefix="```py\n", suffix="\n```", max_size=2000) + if msg.channel.id in self.sessions: + await ctx.send( + "Already running a REPL session in this channel. Exit it with `quit`." + ) + return + self.sessions.add(msg.channel.id) + await ctx.send("Enter code to execute or evaluate. `exit()` or `quit` to exit.") + while True: + response = await self.bot.wait_for( + "message", + check=(lambda m: m.content.startswith("`") and m.author.id in ownerid), + ) + cleaned = self.cleanup_code(response.content) + if cleaned in ("quit", "exit", "exit()"): + await ctx.send("Exiting.") + self.sessions.remove(msg.channel.id) + return + executor = exec + if cleaned.count("\n") == 0: + try: + code = compile(cleaned, "", "eval") + except SyntaxError: + pass + else: + executor = eval + if executor is exec: + try: + code = compile(cleaned, "", "exec") + except SyntaxError as e: + await ctx.send(self.get_syntax_error(e)) + continue + variables["message"] = response + fmt = None + stdout = io.StringIO() + try: + with redirect_stdout(stdout): + result = executor(code, variables) + if inspect.isawaitable(result): + result = await result + except Exception as e: + value = stdout.getvalue() + fmt = "{}{}".format(value, traceback.format_exc()) + else: + value = stdout.getvalue() + if result is not None: + fmt = "{}{!r}".format(value, result) + variables["_"] = result + elif value: + fmt = "{}".format(value) + try: + if fmt is not None: + for line in fmt.splitlines(): + try: + paginator.add_line(line) + except RuntimeError: + splitted = [ + line[i : i + 1988] for i in range(0, len(line), 1988) + ] + for part in splitted: + paginator.add_line(part) + pages = [] + for page in paginator.pages: + pages.append(page) + if len(pages) == 1: + await ctx.send(pages[0]) + return + pgn = Paginator(pages=pages, pagetype="text") + await pgn.start(ctx=ctx) + except discord.Forbidden: + pass + except discord.HTTPException as e: + await msg.channel.send("Unexpected error: `{}`".format(e)) + + +async def setup(bot): + await bot.add_cog(REPL(bot)) diff --git a/utils/ansiblocks.py b/utils/ansiblocks.py new file mode 100644 index 0000000..be618c8 --- /dev/null +++ b/utils/ansiblocks.py @@ -0,0 +1,17 @@ +# ansi code blocks for pretty text + + +class AnsiBlocks: + gray = "\u001b[0;30m{}\u001b[0;0m" + red = "\u001b[0;31m{}\u001b[0;0m" + green = "\u001b[0;32m{}\u001b[0;0m" + yellow = "\u001b[0;33m{}\u001b[0;0m" + blue = "\u001b[0;34m{}\u001b[0;0m" + pink = "\u001b[0;35m{}\u001b[0;0m" + cyan = "\u001b[0;36m{}\u001b[0;0m" + white = "\u001b[0;37m{}\u001b[0;0m" + + def wrap(self, color: str, text: str, bold: bool = False): + if bold: + color.replace("[0", "[1") + return "```ansi\n" + color.format(text) + "\n```" diff --git a/utils/base.py b/utils/base.py new file mode 100644 index 0000000..0769841 --- /dev/null +++ b/utils/base.py @@ -0,0 +1,57 @@ +from typing import Optional + +import discord +from discord.ext.commands import Bot + + +class BasicView(discord.ui.View): + def __init__(self, timeout: Optional[float] = 60.0, clear: Optional[bool] = False): + """Basic View with author checks and timeout actions + + Parameters + ----------- + timeout: :class:`float` + Time after view performs tiemout checks + clear: :class:`bool` + Whether to delete items in view after timeout + + Usage + --------- + set the following attributes to View for checks: + + View.author : discord.User | discord.Member + View.mesaage : discord.Message | discord.InteractionMessage + """ + + super().__init__(timeout=timeout) + self.clear = clear + + self.message: Optional[discord.Message | discord.InteractionMessage] = None + self.author: Optional[discord.Member | discord.User] = None + self.bot: Optional[Bot] = None + + async def interaction_check(self, interaction: discord.Interaction) -> bool: + if not self.author: + return True + # anyone can interact with View + + if self.author.id != interaction.user.id: + await interaction.response.send_message( + "only command invoker can do this", ephemeral=True + ) + return self.author.id == interaction.user.id + + async def on_timeout(self) -> None: + if not self.children: + return + + if self.clear: + self.clear_items() + else: + for item in self.children: + item.disabled = True + if self.message is not None: + try: + await self.message.edit(view=self) + except discord.HTTPException: + ... diff --git a/utils/buttons/delete.py b/utils/buttons/delete.py new file mode 100644 index 0000000..718b470 --- /dev/null +++ b/utils/buttons/delete.py @@ -0,0 +1,24 @@ +from typing import Optional + +import discord +from utils.base import BasicView + + +class DeleteButton(BasicView): + def __init__(self, timeout: Optional[float] = 60.0): + super().__init__(timeout=timeout, clear=True) + + async def interaction_check(self, i: discord.Interaction): + if i.message.channel.permissions_for(i.user).manage_messages: + return True + return await super().interaction_check(i) + + async def on_timeout(self): + await super().on_timeout() + + @discord.ui.button( + emoji="<:trash:1066023933662466080>", style=discord.ButtonStyle.red + ) + async def delete(self, interaction: discord.Interaction, button: discord.ui.Button): + """delete a message""" + await interaction.message.delete() diff --git a/utils/checks.py b/utils/checks.py new file mode 100644 index 0000000..8608d2b --- /dev/null +++ b/utils/checks.py @@ -0,0 +1,21 @@ +import json +from typing import List + +import discord +from discord.ext import commands + +OWNER = json.load(open("exts/cfg.json"))["ReplOwners"] + + +def is_owner() -> bool: + def predicate(ctx: commands.Context): + return ctx.author.id in OWNER + + return commands.check(predicate) + + +def guild_specific(guilds: List[discord.Object]) -> bool: + def predicate(ctx: commands.Context): + return ctx.guild.id in guilds + + return commands.check(predicate) diff --git a/utils/funcs.py b/utils/funcs.py new file mode 100644 index 0000000..5ae9362 --- /dev/null +++ b/utils/funcs.py @@ -0,0 +1,32 @@ +import asyncio +import base64 +import os +from typing import List, Union + +import aiohttp +import discord + +TESTID = 356099868638445578 +ID = int(base64.b64decode(os.getenv("TOKEN").split(".")[0])) + + +async def get_webhook( + channel: Union[discord.TextChannel, discord.ForumChannel, discord.VoiceChannel] +) -> discord.Webhook: + """Get a webhook created by bot in the channel""" + if ID != TESTID: + wname = "ゼロ" + else: + wname = "ゼロ~" + + hooks: List[discord.Webhook] = await channel.webhooks() + for hook in hooks: + if hook.name == wname: + return hook + # if it doesn't exist create one + hook = await channel.create_webhook(name=wname) + return hook + + +def discord_bg_embed(desc: str = "\u200b") -> discord.Embed: + return discord.Embed(color=0x36393E, description=desc) diff --git a/utils/paginator.py b/utils/paginator.py new file mode 100644 index 0000000..cb853d5 --- /dev/null +++ b/utils/paginator.py @@ -0,0 +1,194 @@ +import asyncio +from typing import List, Literal, Optional, Union + +from discord import ButtonStyle, Embed, Interaction, Message, TextStyle, Webhook +from discord.ext.commands import Bot, Context, errors +from discord.ui import Button, Item, Modal, Select, TextInput, button +from utils.base import BasicView + + +class Paginator(BasicView): + def __init__( + self, + pages: List[Embed | str], + pagetype: Literal["text", "embed"] = "embed", + ): + """ + Params + --------- + pages: List[Embed | str] + a list of Embeds or strings. + pagetype: Literal['text', 'embed] + determines type of data we are paginating + """ + super().__init__(timeout=120, clear=True) + self.pages = pages + self.pagetype = pagetype + + self.current_page = 0 + self.length = len(self.pages) + + async def update_page(self, i: Interaction): + """update the page and edit the view""" + self.first.disabled = self.prev.disabled = self.current_page == 0 + self.last.disabled = self.next.disabled = self.current_page == self.length - 1 + + labelstr = f"\U0001F4C4 {self.current_page+1}:{self.length}" + self.page_info.label = labelstr + + kwargs = {} + kwargs["view"] = self + if self.pagetype == "text": + kwargs["content"] = self.pages[self.current_page] + else: + kwargs["embed"] = self.pages[self.current_page] + + if i.response.is_done(): + await i.followup.edit_message(self.message.id, **kwargs) + else: + await i.response.edit_message(**kwargs) + + @button( + emoji="<:leftdoublearrow:1066024551575715870>", style=ButtonStyle.gray, row=0 + ) + async def first(self, i: Interaction, b: Button): + self.current_page = 0 + await self.update_page(i) + + @button(emoji="<:arrowleft:1066016302398984265>", style=ButtonStyle.gray, row=0) + async def prev(self, i: Interaction, b: Button): + self.current_page -= 1 + await self.update_page(i) + + @button(label="\U0001f4cb", style=ButtonStyle.gray, row=0) + async def page_info(self, i: Interaction, b: Button): + self.stop() + await i.response.edit_message(view=None) + + @button(emoji="<:arrowright:1066016298238230628>", style=ButtonStyle.gray, row=0) + async def next(self, i: Interaction, b: Button): + self.current_page += 1 + await self.update_page(i) + + @button( + emoji="<:rightdoublearrow:1066024556449517678>", style=ButtonStyle.gray, row=0 + ) + async def last(self, i: Interaction, b: Button): + self.current_page = self.length - 1 + await self.update_page(i) + + @button(emoji="<:trash:1066023933662466080>", style=ButtonStyle.red, row=1) + async def delete(self, i: Interaction, b: Button): + await self.message.delete() + + class JumpToPage(Modal, title="jump to page"): + page_number = TextInput( + label="page number", style=TextStyle.short, max_length=4 + ) + + def __init__(self, p: "Paginator"): + super().__init__(timeout=20) + self.p = p + self.length = p.length + + async def on_submit(self, interaction: Interaction) -> None: + try: + if not self.page_number.value: + raise ValueError("no number entered") + pn = int(self.page_number.value) + if not (1 <= pn <= self.length): + raise ValueError("page number not in range") + self.p.current_page = pn - 1 + except ValueError: + await interaction.response.send_message( + "invalid/no response or page number not in range", ephemeral=True + ) + else: + await self.p.update_page(interaction) + + @button(label="jump to a page", emoji="\U0001f3af", style=ButtonStyle.grey, row=1) + async def jump(self, i: Interaction, b: button): + await i.response.send_modal(self.JumpToPage(self)) + + async def start( + self, + interaction: Optional[Interaction] = None, + ephemeral: bool = False, + ctx: Optional[Context] = None, + # bot: Optional[Bot] = None, + custom_items: List[Union[Button, Select]] = [], + ): + # self.bot = bot + if not self.length: + raise ValueError("No pages") + + info_label = ( + "\U0001F4C4 page" + if self.length == 1 + else (f"\U0001F4C4 {self.current_page + 1}:{self.length}") + ) + + for item in custom_items: + self.add_item(item) + + self.first.disabled = self.prev.disabled = True + + if self.length == 1: + self.remove_item(self.prev) + self.remove_item(self.first) + self.remove_item(self.next) + self.remove_item(self.last) + self.delete.label = None + self.remove_item(self.page_info) + if self.length < 5: + self.remove_item(self.jump) + self.page_info.label = info_label + + kwargs = {} + kwargs["view"] = self + if self.pagetype == "embed": + kwargs["embed"] = self.pages[0] + else: + kwargs["content"] = self.pages[0] + + if interaction: + await interaction.response.send_message(**kwargs, ephemeral=ephemeral) + self.message = await interaction.original_response() + self.author = interaction.user + else: + self.message = await ctx.send(**kwargs) + self.author = ctx.author + await self.wait() + + +class WebhookPaginator(Paginator): + def __init__( + self, pages: List[Embed | str], pagetype: Literal["text", "embed"] = "embed" + ): + super().__init__(pages=pages, pagetype=pagetype) + + async def start(self, webhook: Webhook, **whargs): + if not self.length: + raise ValueError("No pages") + + info_label = ( + "\U0001F4C4" + if self.length == 1 + else (f"\U0001F4C4 {self.current_page + 1}:{self.length}") + ) + + self.first.disabled = self.prev.disabled = True + + if self.length == 1: + self.next.disabled = self.last.disabled = True + self.page_info.label = info_label + + kwargs = {} + kwargs["view"] = self + if self.pagetype == "embed": + kwargs["embed"] = self.pages[0] + else: + kwargs["content"] = self.pages[0] + + self.message = await webhook.send(**kwargs, **whargs) + await self.wait()