Skip to content

Commit df308da

Browse files
committed
Use more of discord provided datas
1 parent 1d22e56 commit df308da

File tree

4 files changed

+34
-50
lines changed

4 files changed

+34
-50
lines changed

discord_slash/client.py

Lines changed: 27 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ def __init__(self,
5353
if not isinstance(client, commands.Bot) and not isinstance(client, commands.AutoShardedBot) and not override_type:
5454
self.logger.info("Detected discord.Client! It is highly recommended to use `commands.Bot`.")
5555
original_sock_event = self._discord.on_socket_response
56-
56+
5757
def wrap(*args):
5858
original_sock_event(*args)
5959
self.on_socket_response(*args)
@@ -263,7 +263,7 @@ async def sync_all_commands(self, delete_from_unused_guilds=True):
263263
This is done with a `put` request.
264264
If ``auto_register`` and ``auto_delete`` are ``True`` then this will be automatically called.
265265
266-
:param delete_from_unused_guilds: If the bot should make a request to set no commands for guilds that haven't got any commands regestered in :class:``SlashCommand``
266+
:param delete_from_unused_guilds: If the bot should make a request to set no commands for guilds that haven't got any commands registered in :class:``SlashCommand``
267267
"""
268268
commands = await self.to_dict()
269269
self.logger.info("Syncing commands...")
@@ -615,27 +615,19 @@ def wrapper(cmd):
615615

616616
return wrapper
617617

618-
async def process_options(self, guild: discord.Guild, options: list, auto_convert: dict) -> typing.Union[list, dict]:
618+
async def process_options(self, guild: discord.Guild, options: list) -> dict:
619619
"""
620620
Processes Role, User, and Channel option types to discord.py's models.
621621
622622
:param guild: Guild of the command message.
623623
:type guild: discord.Guild
624624
:param options: Dict of options.
625625
:type options: list
626-
:param auto_convert: Dictionary of how to convert option values.
627-
:type auto_convert: dict
628626
:return: Union[list, dict]
629627
"""
630-
if not guild:
631-
self.logger.info("This command invoke is missing guild. Skipping option process.")
632-
return [x["value"] for x in options]
633628

634-
if not isinstance(guild, discord.Guild):
635-
return [x["value"] for x in options]
636-
637-
if not auto_convert:
638-
return [x["value"] for x in options]
629+
if not guild or not isinstance(guild, discord.Guild):
630+
return {x["name"]: x["value"] for x in options}
639631

640632
converters = [
641633
# If extra converters are added and some needs to fetch it,
@@ -667,30 +659,26 @@ async def process_options(self, guild: discord.Guild, options: list, auto_conver
667659
to_return = {}
668660

669661
for x in options:
670-
selected = x
671-
if selected["name"] in auto_convert:
672-
processed = None # This isn't the best way, but we should to reduce duplicate lines.
673-
if auto_convert[selected["name"]] not in types:
674-
processed = selected["value"]
675-
else:
676-
loaded_converter = converters[types[auto_convert[selected["name"]]]]
677-
if isinstance(loaded_converter, list): # For user type.
678-
cache_first = loaded_converter[0](int(selected["value"]))
679-
if cache_first:
680-
processed = cache_first
681-
else:
682-
loaded_converter = loaded_converter[1]
683-
if not processed:
684-
try:
685-
processed = await loaded_converter(int(selected["value"])) \
686-
if iscoroutinefunction(loaded_converter) else \
687-
loaded_converter(int(selected["value"]))
688-
except (discord.Forbidden, discord.HTTPException, discord.NotFound): # Just in case.
689-
self.logger.warning("Failed fetching discord object! Passing ID instead.")
690-
processed = int(selected["value"])
691-
to_return[selected["name"]] = processed
662+
processed = None # This isn't the best way, but we should to reduce duplicate lines.
663+
if x["type"] not in types:
664+
processed = x["value"]
692665
else:
693-
to_return[selected["name"]] = selected["value"]
666+
loaded_converter = converters[types[x["type"]]]
667+
if isinstance(loaded_converter, list): # For user type.
668+
cache_first = loaded_converter[0](int(x["value"]))
669+
if cache_first:
670+
processed = cache_first
671+
else:
672+
loaded_converter = loaded_converter[1]
673+
if not processed:
674+
try:
675+
processed = await loaded_converter(int(x["value"])) \
676+
if iscoroutinefunction(loaded_converter) else \
677+
loaded_converter(int(x["value"]))
678+
except (discord.Forbidden, discord.HTTPException, discord.NotFound): # Just in case.
679+
self.logger.warning("Failed fetching discord object! Passing ID instead.")
680+
processed = int(x["value"])
681+
to_return[x["name"]] = processed
694682
return to_return
695683

696684
async def invoke_command(self, func, ctx, args):
@@ -754,7 +742,7 @@ async def on_socket_response(self, msg):
754742
if "value" not in x:
755743
return await self.handle_subcommand(ctx, to_use)
756744

757-
args = await self.process_options(ctx.guild, to_use["data"]["options"], selected_cmd.auto_convert) \
745+
args = await self.process_options(ctx.guild, to_use["data"]["options"]) \
758746
if "options" in to_use["data"] else []
759747

760748
self._discord.dispatch("slash_command", ctx)
@@ -787,13 +775,13 @@ async def handle_subcommand(self, ctx: context.SlashContext, data: dict):
787775
return
788776
ctx.subcommand_group = sub_group
789777
selected = base[sub_name][sub_group]
790-
args = await self.process_options(ctx.guild, x["options"], selected.auto_convert) \
778+
args = await self.process_options(ctx.guild, x["options"]) \
791779
if "options" in x else []
792780
self._discord.dispatch("slash_command", ctx)
793781
await self.invoke_command(selected, ctx, args)
794782
return
795783
selected = base[sub_name]
796-
args = await self.process_options(ctx.guild, sub_opts, selected.auto_convert) \
784+
args = await self.process_options(ctx.guild, sub_opts) \
797785
if "options" in sub else []
798786
self._discord.dispatch("slash_command", ctx)
799787
await self.invoke_command(selected, ctx, args)

discord_slash/context.py

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ class SlashContext:
2929
:ivar guild_id: Guild ID of the command message. If the command was invoked in DM, then it is ``None``
3030
:ivar author_id: User ID representing author of the command message.
3131
:ivar channel_id: Channel ID representing channel of the command message.
32+
:ivar author: User or Member instance of the command invoke.
3233
"""
3334

3435
def __init__(self,
@@ -50,6 +51,10 @@ def __init__(self,
5051
self.guild_id = int(_json["guild_id"]) if "guild_id" in _json.keys() else None
5152
self.author_id = int(_json["member"]["user"]["id"] if "member" in _json.keys() else _json["user"]["id"])
5253
self.channel_id = int(_json["channel_id"])
54+
if self.guild:
55+
self.author = discord.Member(data=_json["member"], state=self.bot._connection, guild=self.guild)
56+
else:
57+
self.author = discord.User(data=_json["user"], state=self.bot._connection)
5358

5459
@property
5560
def guild(self) -> typing.Optional[discord.Guild]:
@@ -60,16 +65,6 @@ def guild(self) -> typing.Optional[discord.Guild]:
6065
"""
6166
return self.bot.get_guild(self.guild_id) if self.guild_id else None
6267

63-
@property
64-
def author(self) -> typing.Optional[typing.Union[discord.Member, discord.User]]:
65-
"""
66-
User or Member instance of the command invoke.
67-
68-
:return: Optional[Union[discord.Member, discord.User]]
69-
"""
70-
guild = self.guild
71-
return guild.get_member(self.author_id) if guild else self.bot.get_user(self.author_id)
72-
7368
@property
7469
def channel(self) -> typing.Optional[typing.Union[discord.abc.GuildChannel, discord.abc.PrivateChannel]]:
7570
"""

docs/conf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@
4747
# List of patterns, relative to source directory, that match files and
4848
# directories to ignore when looking for source files.
4949
# This pattern also affects html_static_path and html_extra_path.
50-
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', "test.py", "test2.py", ".idea", "setup.py"]
50+
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', "test.py", "test2.py", "test3.py", ".idea", "setup.py"]
5151

5252
# This should fix wrong sort
5353
autodoc_member_order = 'bysource'

docs/discord_slash.model.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,4 @@ discord\_slash.model module
55
:members:
66
:undoc-members:
77
:show-inheritance:
8+
:inherited-members: Message

0 commit comments

Comments
 (0)