Skip to content

Commit

Permalink
Initial fork commit; squashing previous commits for cleanliness
Browse files Browse the repository at this point in the history
jsk root: Add backticks around jishaku version
jsk invite: Translate permissions input to lowercase and replace "server" with "guild" for ease of use
jsk python: Add support for a list of files or embeds
Change ReplResponseReactor(ctx.message) to ReplResponseReactor(ctx) so that errors and results are compatible with ContextEditor
  • Loading branch information
clari7744 committed Jan 25, 2024
1 parent 247537e commit f80d7c7
Show file tree
Hide file tree
Showing 10 changed files with 231 additions and 130 deletions.
1 change: 0 additions & 1 deletion jishaku/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,5 @@ def prefix(bot: commands.Bot, _: discord.Message) -> typing.List[str]:

asyncio.run(entry(bot, token))


if __name__ == '__main__':
entrypoint() # pylint: disable=no-value-for-parameter
36 changes: 21 additions & 15 deletions jishaku/exception_handling.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from discord.ext import commands

from jishaku.flags import Flags
from jishaku.types import ContextA


async def send_traceback(
Expand Down Expand Up @@ -49,9 +50,9 @@ async def send_traceback(
message = None

for page in paginator.pages:
if isinstance(destination, discord.Message):
if isinstance(destination, (discord.Message, commands.Context)):
message = await destination.reply(page)
else:
elif isinstance(destination, discord.abc.Messageable):
message = await destination.send(page)

return message
Expand All @@ -61,7 +62,9 @@ async def send_traceback(
P = typing.ParamSpec('P')


async def do_after_sleep(delay: float, coro: typing.Callable[P, typing.Awaitable[T]], *args: P.args, **kwargs: P.kwargs) -> T:
async def do_after_sleep(
delay: float, coro: typing.Callable[P, typing.Awaitable[T]], *args: P.args, **kwargs: P.kwargs
) -> T:
"""
Performs an action after a set amount of time.
Expand Down Expand Up @@ -99,11 +102,11 @@ class ReplResponseReactor: # pylint: disable=too-few-public-methods
"""
Extension of the ReactionProcedureTimer that absorbs errors, sending tracebacks.
"""
__slots__ = ('ctx', 'message', 'loop', 'handle', 'raised')

__slots__ = ('message', 'loop', 'handle', 'raised')

def __init__(self, message: discord.Message, loop: typing.Optional[asyncio.BaseEventLoop] = None):
self.message = message
def __init__(self, ctx: ContextA, loop: typing.Optional[asyncio.BaseEventLoop] = None):
self.ctx = ctx
self.message = ctx.message
self.loop = loop or asyncio.get_event_loop()
self.handle = None
self.raised = False
Expand Down Expand Up @@ -131,30 +134,33 @@ async def __aexit__(

if isinstance(exc_val, (SyntaxError, asyncio.TimeoutError, subprocess.TimeoutExpired)):
# short traceback, send to channel
destination = Flags.traceback_destination(self.message) or self.message.channel
destination = Flags.traceback_destination(self.ctx) or self.ctx

if destination != self.message.channel:
if destination != self.ctx:
await attempt_add_reaction(
self.message,
# timed out is alarm clock
# syntax error is single exclamation mark
"\N{HEAVY EXCLAMATION MARK SYMBOL}" if isinstance(exc_val, SyntaxError) else "\N{ALARM CLOCK}"
"\N{HEAVY EXCLAMATION MARK SYMBOL}" if isinstance(exc_val, SyntaxError) else "\N{ALARM CLOCK}",
)

await send_traceback(
self.message if destination == self.message.channel else destination,
0, exc_type, exc_val, exc_tb
destination,
0,
exc_type,
exc_val,
exc_tb,
)
else:
destination = Flags.traceback_destination(self.message) or self.message.author
destination = Flags.traceback_destination(self.ctx) or self.message.author

if destination != self.message.channel:
if destination != self.ctx:
# other error, double exclamation mark
await attempt_add_reaction(self.message, "\N{DOUBLE EXCLAMATION MARK}")

# this traceback likely needs more info, so increase verbosity, and DM it instead.
await send_traceback(
self.message if destination == self.message.channel else destination,
destination,
8, exc_type, exc_val, exc_tb
)

Expand Down
2 changes: 1 addition & 1 deletion jishaku/features/filesystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ async def jsk_curl(self, ctx: ContextA, url: str):
# remove embed maskers if present
url = url.lstrip("<").rstrip(">")

async with ReplResponseReactor(ctx.message):
async with ReplResponseReactor(ctx):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
data = await response.read()
Expand Down
33 changes: 12 additions & 21 deletions jishaku/features/invocation.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ class SlimUserConverter(UserIDConverter): # pylint: disable=too-few-public-meth

async def convert(self, ctx: ContextA, argument: str) -> typing.Union[discord.Member, discord.User]:
"""Converter method"""
match = self._get_id_match(argument) or re.match(r'<@!?([0-9]{15,20})>$', argument) # type: ignore
match = self._get_id_match(argument) or re.match(r"<@!?([0-9]{15,20})>$", argument) # type: ignore

if match is not None:
user_id = int(match.group(1))
Expand All @@ -63,7 +63,7 @@ class SlimChannelConverter(ChannelIDConverter): # pylint: disable=too-few-publi

async def convert(self, ctx: ContextA, argument: str) -> discord.TextChannel:
"""Converter method"""
match = self._get_id_match(argument) or re.match(r'<@!?([0-9]{15,20})>$', argument)
match = self._get_id_match(argument) or re.match(r"<@!?([0-9]{15,20})>$", argument)

if match is not None:
channel_id = int(match.group(1))
Expand All @@ -80,7 +80,7 @@ class SlimThreadConverter(ThreadIDConverter): # pylint: disable=too-few-public-

async def convert(self, ctx: ContextA, argument: str) -> discord.Thread:
"""Converter method"""
match = self._get_id_match(argument) or re.match(r'<@!?([0-9]{15,20})>$', argument)
match = self._get_id_match(argument) or re.match(r"<@!?([0-9]{15,20})>$", argument)

if match is not None:
thread_id = int(match.group(1))
Expand All @@ -98,13 +98,7 @@ class InvocationFeature(Feature):
OVERRIDE_SIGNATURE = typing.Union[SlimUserConverter, SlimChannelConverter, SlimThreadConverter]

@Feature.Command(parent="jsk", name="override", aliases=["execute", "exec", "override!", "execute!", "exec!"])
async def jsk_override(
self,
ctx: ContextT,
overrides: commands.Greedy[OVERRIDE_SIGNATURE],
*,
command_string: str
):
async def jsk_override(self, ctx: ContextT, overrides: commands.Greedy[OVERRIDE_SIGNATURE], *, command_string: str):
"""
Run a command with a different user, channel, or thread, optionally bypassing checks and cooldowns.
Expand All @@ -114,7 +108,7 @@ async def jsk_override(
kwargs: typing.Dict[str, typing.Any] = {}

if ctx.prefix:
kwargs["content"] = ctx.prefix + command_string.lstrip('/')
kwargs["content"] = ctx.prefix + command_string.lstrip("/")
else:
await ctx.send("Reparsing requires a prefix")
return
Expand Down Expand Up @@ -142,12 +136,12 @@ async def jsk_override(

if alt_ctx.command is None:
if alt_ctx.invoked_with is None:
await ctx.send('This bot has been hard-configured to ignore this user.')
await ctx.send("This bot has been hard-configured to ignore this user.")
return
await ctx.send(f'Command "{alt_ctx.invoked_with}" is not found')
return

if ctx.invoked_with and ctx.invoked_with.endswith('!'):
if ctx.invoked_with and ctx.invoked_with.endswith("!"):
await alt_ctx.command.reinvoke(alt_ctx)
return

Expand Down Expand Up @@ -193,7 +187,7 @@ async def jsk_debug(self, ctx: ContextT, *, command_string: str):

start = time.perf_counter()

async with ReplResponseReactor(ctx.message):
async with ReplResponseReactor(ctx):
with self.submit(ctx):
await alt_ctx.command.invoke(alt_ctx)

Expand Down Expand Up @@ -223,17 +217,14 @@ async def jsk_source(self, ctx: ContextA, *, command_name: str):
pass

# getsourcelines for some reason returns WITH line endings
source_text = ''.join(source_lines)
source_text = "".join(source_lines)

if use_file_check(ctx, len(source_text)): # File "full content" preview limit
await ctx.send(file=discord.File(
filename=filename,
fp=io.BytesIO(source_text.encode('utf-8'))
))
await ctx.send(file=discord.File(filename=filename, fp=io.BytesIO(source_text.encode("utf-8"))))
else:
paginator = WrappedPaginator(prefix='```py', suffix='```', max_size=1980)
paginator = WrappedPaginator(prefix="```py", suffix="```", max_size=1980)

paginator.add_line(source_text.replace('```', '``\N{zero width space}`'))
paginator.add_line(source_text.replace("```", "``\N{zero width space}`"))

interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
await interface.send_to(ctx)
2 changes: 2 additions & 0 deletions jishaku/features/management.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,8 @@ async def jsk_invite(self, ctx: ContextA, *perms: str):
permissions = discord.Permissions()

for perm in perms:
perm = perm.lower()
perm.replace("server", "guild")
if perm not in dict(permissions):
raise commands.BadArgument(f"Invalid permission: {perm}")

Expand Down
Loading

0 comments on commit f80d7c7

Please sign in to comment.