Skip to content

Commit

Permalink
Implement attachments into InteractionMessageBuilder
Browse files Browse the repository at this point in the history
  • Loading branch information
tandemdude committed Jan 20, 2022
1 parent aa9bcdd commit f0c8167
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 9 deletions.
6 changes: 3 additions & 3 deletions hikari/impl/interaction_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@


class _Response:
__slots__: typing.Sequence[str] = ("_headers", "_payload", "_status_code")
__slots__: typing.Sequence[str] = ("_headers", "_payload", "_attachments", "_status_code")

def __init__(
self,
Expand Down Expand Up @@ -358,15 +358,15 @@ async def on_interaction(self, body: bytes, signature: bytes, timestamp: bytes)
_LOGGER.debug("Dispatching interaction %s", interaction.id)
try:
result = await listener(interaction)
payload = self._dumps(result.build(self._entity_factory))
payload, attachments = result.build(self._entity_factory)

except Exception as exc:
asyncio.get_running_loop().call_exception_handler(
{"message": "Exception occurred during interaction dispatch", "exception": exc}
)
return _Response(_INTERNAL_SERVER_ERROR_STATUS, b"Exception occurred during interaction dispatch")

return _Response(_OK_STATUS, payload.encode(), content_type=_JSON_TYPE_WITH_CHARSET)
return _Response(_OK_STATUS, self._dumps(payload).encode(), content_type=_JSON_TYPE_WITH_CHARSET)

_LOGGER.debug(
"Ignoring interaction %s of type %s without registered listener", interaction.id, interaction.type
Expand Down
2 changes: 1 addition & 1 deletion hikari/impl/rest.py
Original file line number Diff line number Diff line change
Expand Up @@ -1252,7 +1252,7 @@ async def _create_message(
) -> messages_.Message:
...

async def _create_message(
async def _create_message( # noqa: C901
self,
route: routes.CompiledRoute,
body: data_binding.JSONObjectBuilder,
Expand Down
22 changes: 17 additions & 5 deletions hikari/impl/special_endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -775,6 +775,7 @@ class InteractionMessageBuilder(special_endpoints.InteractionMessageBuilder):
] = attr.field(default=undefined.UNDEFINED, kw_only=True)
_components: typing.List[special_endpoints.ComponentBuilder] = attr.field(factory=list, kw_only=True)
_embeds: typing.List[embeds_.Embed] = attr.field(factory=list, kw_only=True)
_attachments: typing.List[files.Resourceish] = attr.field(factory=list, kw_only=True)

@property
def content(self) -> undefined.UndefinedOr[str]:
Expand Down Expand Up @@ -826,6 +827,12 @@ def add_embed(self: _InteractionMessageBuilderT, embed: embeds_.Embed, /) -> _In
self._embeds.append(embed)
return self

def add_attachment(
self: _InteractionMessageBuilderT, attachment: files.Resourceish, /
) -> _InteractionMessageBuilderT:
self._attachments.append(attachment)
return self

def set_content(
self: _InteractionMessageBuilderT, content: undefined.UndefinedOr[str], /
) -> _InteractionMessageBuilderT:
Expand Down Expand Up @@ -868,15 +875,20 @@ def set_user_mentions(
self._user_mentions = user_mentions
return self

def build(self, entity_factory: entity_factory_.EntityFactory, /) -> data_binding.JSONObject:
def build(
self, entity_factory: entity_factory_.EntityFactory, /
) -> typing.Tuple[data_binding.JSONObject, typing.Optional[typing.Dict[str, files.Resource[files.AsyncReader]]]]:
data = data_binding.JSONObjectBuilder()
data.put("content", self.content)

attachments: typing.List[files.Resource[files.AsyncReader]] = []
if self._attachments:
attachments.extend([files.ensure_resource(a) for a in self._attachments])

if self._embeds:
embeds: typing.List[data_binding.JSONObject] = []
for embed, attachments in map(entity_factory.serialize_embed, self._embeds):
if attachments:
raise ValueError("Cannot send an embed with attachments in a slash command's initial response")

attachments.extend(attachments)
embeds.append(embed)

data["embeds"] = embeds
Expand All @@ -890,7 +902,7 @@ def build(self, entity_factory: entity_factory_.EntityFactory, /) -> data_bindin
self.mentions_everyone, undefined.UNDEFINED, self.user_mentions, self.role_mentions
)

return {"type": self._type, "data": data}
return {"type": self._type, "data": data}, {a.filename: a for a in attachments} or None


@attr_extensions.with_copy
Expand Down
8 changes: 8 additions & 0 deletions tests/hikari/interactions/test_base_interactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,17 @@ async def test_create_initial_response_with_optional_args(self, mock_message_res
mock_embed_2 = object()
mock_component = object()
mock_components = object(), object()
mock_attachment = object()
mock_attachments = object(), object()
await mock_message_response_mixin.create_initial_response(
base_interactions.ResponseType.MESSAGE_CREATE,
"content",
tts=True,
embed=mock_embed_1,
flags=64,
embeds=[mock_embed_2],
attachment=mock_attachment,
attachments=mock_attachments,
component=mock_component,
components=mock_components,
mentions_everyone=False,
Expand All @@ -97,6 +101,8 @@ async def test_create_initial_response_with_optional_args(self, mock_message_res
flags=64,
embed=mock_embed_1,
embeds=[mock_embed_2],
attachment=mock_attachment,
attachments=mock_attachments,
component=mock_component,
components=mock_components,
mentions_everyone=False,
Expand All @@ -119,6 +125,8 @@ async def test_create_initial_response_without_optional_args(self, mock_message_
tts=undefined.UNDEFINED,
embed=undefined.UNDEFINED,
embeds=undefined.UNDEFINED,
attachment=undefined.UNDEFINED,
attachments=undefined.UNDEFINED,
component=undefined.UNDEFINED,
components=undefined.UNDEFINED,
mentions_everyone=undefined.UNDEFINED,
Expand Down

0 comments on commit f0c8167

Please sign in to comment.