Skip to content

Commit

Permalink
Merge pull request #390 from Paillat-dev/feat-respond-retryal
Browse files Browse the repository at this point in the history
Fix for Unknown Interaction errors
  • Loading branch information
Kav-K authored Nov 11, 2023
2 parents 700c3ab + 24c57e8 commit 70bfe9c
Show file tree
Hide file tree
Showing 7 changed files with 66 additions and 11 deletions.
3 changes: 2 additions & 1 deletion cogs/code_interpreter_service_cog.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
from services.deletion_service import Deletion
from services.environment_service import EnvService
from services.moderations_service import Moderation
from utils.safe_ctx_respond import safe_ctx_respond


class CaptureStdout:
Expand Down Expand Up @@ -400,7 +401,7 @@ async def code_interpreter_chat_command(
name=ctx.user.name + "'s code interpreter conversation with GPT",
auto_archive_duration=60,
)
await ctx.respond("Conversation started.")
await safe_ctx_respond(ctx=ctx, content="Conversation started.")

self.sessions[thread.id] = self.SessionedCodeExecutor()

Expand Down
12 changes: 5 additions & 7 deletions cogs/image_service_cog.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from services.image_service import ImageService
from services.moderations_service import Moderation
from services.text_service import TextService
from utils.safe_ctx_respond import safe_ctx_respond

users_to_interactions = {}
ALLOWED_GUILDS = EnvService.get_allowed_guilds()
Expand Down Expand Up @@ -85,9 +86,7 @@ async def draw_command(
except Exception as e:
print(e)
traceback.print_exc()
await ctx.respond(
"Something went wrong. Please try again later.", ephemeral=from_action
)
await safe_ctx_respond(ctx=ctx, content="Something went wrong. Please try again later.", ephemeral=from_action)
await ctx.send_followup(e, ephemeral=from_action)

async def draw_old_command(
Expand Down Expand Up @@ -124,9 +123,8 @@ async def draw_old_command(
except Exception as e:
print(e)
traceback.print_exc()
await ctx.respond(
"Something went wrong. Please try again later.", ephemeral=from_action
)
await safe_ctx_respond(ctx=ctx, content="Something went wrong. Please try again later.", ephemeral=from_action)

await ctx.send_followup(e, ephemeral=from_action)

async def draw_action(self, ctx, message):
Expand All @@ -153,7 +151,7 @@ async def local_size_command(self, ctx: discord.ApplicationContext):

# Format the size to be in MB and send.
total_size = total_size / 1000000
await ctx.respond(f"The size of the local images folder is {total_size} MB.")
await safe_ctx_respond(ctx=ctx, content=f"The size of the local images folder is {total_size} MB.")

async def clear_local_command(self, ctx):
"""Delete all local images"""
Expand Down
3 changes: 2 additions & 1 deletion cogs/search_service_cog.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
from services.moderations_service import Moderation
from services.text_service import TextService
from models.openai_model import Models
from utils.safe_ctx_respond import safe_ctx_respond

from contextlib import redirect_stdout

Expand Down Expand Up @@ -435,7 +436,7 @@ async def search_chat_command(
name=ctx.user.name + "'s internet-connected conversation with GPT",
auto_archive_duration=60,
)
await ctx.respond("Conversation started.")
await safe_ctx_respond(ctx=ctx, content="Conversation started.")

# Make a new agent for this user to chat.
search = GoogleSearchAPIWrapper(
Expand Down
3 changes: 2 additions & 1 deletion cogs/text_service_cog.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
from services.pickle_service import Pickler
from services.sharegpt_service import ShareGPTService
from services.text_service import SetupModal, TextService
from utils.safe_ctx_respond import safe_ctx_respond

original_message = {}
ALLOWED_GUILDS = EnvService.get_allowed_guilds()
Expand Down Expand Up @@ -1208,7 +1209,7 @@ async def converse_command(
name=user.name + "'s conversation with GPT",
auto_archive_duration=60,
)
await ctx.respond("Conversation started.")
await safe_ctx_respond(ctx=ctx, content="Conversation started.")
target = thread
else:
# Check if this current channel is already in a conversation
Expand Down
3 changes: 2 additions & 1 deletion models/index_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@
from models.openai_model import Models
from models.check_model import UrlCheck
from services.environment_service import EnvService
from utils.safe_ctx_respond import safe_ctx_respond

SHORT_TO_LONG_CACHE = {}
MAX_DEEP_COMPOSE_PRICE = EnvService.get_max_deep_compose_price()
Expand Down Expand Up @@ -572,7 +573,7 @@ async def start_index_chat(self, ctx, model):
name=ctx.user.name + "'s data-connected conversation with GPT",
auto_archive_duration=60,
)
await ctx.respond("Conversation started.")
await safe_ctx_respond(ctx=ctx, content="Conversation started.")

try:
await preparation_message.delete()
Expand Down
1 change: 1 addition & 0 deletions utils/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .safe_ctx_respond import safe_ctx_respond
52 changes: 52 additions & 0 deletions utils/safe_ctx_respond.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import discord

async def safe_ctx_respond(*args, **kwargs) -> None:
"""
Safely responds to a Discord interaction.
Args:
*args: Positional arguments to be passed to the `respond` or `reply` method of the context.
**kwargs: Keyword arguments to be passed to the `respond` or `reply` method of the context.
`ctx` is a required keyword argument.
Raises:
ValueError: If `ctx` is not provided in the `kwargs`.
Examples:
```py
# Respond to an interaction
await safe_ctx_respond(ctx=ctx, content="Hello World!")
```
"""
# Get the context from the kwargs
ctx: discord.ApplicationContext = kwargs.get("ctx", None)
kwargs.pop("ctx", None)

# Raise an error if context is not provided
if ctx is None:
raise ValueError("ctx is a required keyword argument")

try:
# Try to respond to the interaction
await ctx.respond(*args, **kwargs)
except discord.NotFound: # NotFound is raised when the interaction is not found
try:
# If the interaction is not found, try to reply to the message
if kwargs.get("ephemeral", False):
kwargs.pop("ephemeral")
kwargs["delete_after"] = 5
await ctx.message.reply(*args, **kwargs)
except (
discord.NotFound,
AttributeError,
): # AttributeError is raised when ctx.message is None, NotFound is raised when the message is not found
# If the message is not found, send a new message to the channel
if len(args) > 0:
content = args[0] or ""
args = args[1:]
else:
content = kwargs.get("content", "")
kwargs["content"] = f"**{ctx.author.mention}** \n{content}".strip(
"\n"
).strip()
await ctx.channel.send(*args, **kwargs)

0 comments on commit 70bfe9c

Please sign in to comment.