|
1 | | -import contextlib |
2 | | -from typing import Optional, Sequence |
| 1 | +from typing import Literal, Optional, Sequence |
3 | 2 |
|
4 | | -from discord import ButtonStyle, Interaction, Message, NotFound, ui |
| 3 | +from discord import ButtonStyle, HTTPException, Interaction, Message, NotFound, ui |
5 | 4 |
|
6 | 5 | from pydis_core.utils.logging import get_logger |
7 | 6 |
|
8 | 7 | log = get_logger(__name__) |
9 | 8 |
|
10 | 9 |
|
| 10 | +async def _handle_modify_message(message: Message, action: Literal["edit", "delete"]) -> None: |
| 11 | + """Remove the view from, or delete the given message depending on the specified action.""" |
| 12 | + try: |
| 13 | + if action == "edit": |
| 14 | + await message.edit(view=None) |
| 15 | + elif action == "delete": |
| 16 | + await message.delete() |
| 17 | + except HTTPException as e: |
| 18 | + # Cover the case where this message has been deleted by external means, |
| 19 | + # or the message is now in an archived/locked thread. |
| 20 | + if e.code == 50083: |
| 21 | + log.debug(f"Could not {action} message {message.id} due to it being in an archived thread.") |
| 22 | + elif isinstance(e, NotFound): |
| 23 | + log.info(f"Could not find message {message.id} when attempting to {action} it.") |
| 24 | + else: |
| 25 | + log.error(f"Could not {action} message {message.id} due to Discord HTTP error:\n{str(e)}") |
| 26 | + |
| 27 | + |
11 | 28 | class ViewWithUserAndRoleCheck(ui.View): |
12 | 29 | """ |
13 | 30 | A view that allows the original invoker and moderators to interact with it. |
@@ -65,9 +82,7 @@ async def interaction_check(self, interaction: Interaction) -> bool: |
65 | 82 | async def on_timeout(self) -> None: |
66 | 83 | """Remove the view from ``self.message`` if set.""" |
67 | 84 | if self.message: |
68 | | - with contextlib.suppress(NotFound): |
69 | | - # Cover the case where this message has already been deleted by external means |
70 | | - await self.message.edit(view=None) |
| 85 | + await _handle_modify_message(self.message, "edit") |
71 | 86 |
|
72 | 87 |
|
73 | 88 | class DeleteMessageButton(ui.Button): |
@@ -95,4 +110,4 @@ def __init__( |
95 | 110 |
|
96 | 111 | async def callback(self, interaction: Interaction) -> None: |
97 | 112 | """Delete the original message on button click.""" |
98 | | - await interaction.message.delete() |
| 113 | + await _handle_modify_message(interaction.message, "delete") |
0 commit comments