Refactor ask command to improve message handling and add chunked response sending

This commit is contained in:
Joakim Hellsén 2025-09-23 05:00:14 +02:00
commit d3ee8903c6

87
main.py
View file

@ -20,6 +20,8 @@ from misc import add_message_to_memory, chat, get_allowed_users, get_raw_images_
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Callable from collections.abc import Callable
from discord.abc import Messageable as DiscordMessageable
sentry_sdk.init( sentry_sdk.init(
dsn="https://ebbd2cdfbd08dba008d628dad7941091@o4505228040339456.ingest.us.sentry.io/4507630719401984", dsn="https://ebbd2cdfbd08dba008d628dad7941091@o4505228040339456.ingest.us.sentry.io/4507630719401984",
send_default_pii=True, send_default_pii=True,
@ -35,6 +37,15 @@ load_dotenv(verbose=True)
discord_token: str = os.getenv("DISCORD_TOKEN", "") discord_token: str = os.getenv("DISCORD_TOKEN", "")
async def send_chunked_message(channel: DiscordMessageable, text: str, max_len: int = 2000) -> None:
"""Send a message to a channel, splitting into chunks if it exceeds Discord's limit."""
if len(text) <= max_len:
await channel.send(text)
return
for i in range(0, len(text), max_len):
await channel.send(text[i : i + max_len])
class LoviBotClient(discord.Client): class LoviBotClient(discord.Client):
"""The main bot client.""" """The main bot client."""
@ -76,52 +87,50 @@ class LoviBotClient(discord.Client):
# Add the message to memory # Add the message to memory
add_message_to_memory(str(message.channel.id), message.author.name, incoming_message) add_message_to_memory(str(message.channel.id), message.author.name, incoming_message)
lowercase_message: str = incoming_message.lower() if incoming_message else "" lowercase_message: str = incoming_message.lower()
trigger_keywords: list[str] = ["lovibot", "@lovibot", "<@345000831499894795>", "grok", "@grok"] trigger_keywords: list[str] = ["lovibot", "@lovibot", "<@345000831499894795>", "grok", "@grok"]
has_trigger_keyword: bool = any(trigger in lowercase_message for trigger in trigger_keywords) has_trigger_keyword: bool = any(trigger in lowercase_message for trigger in trigger_keywords)
should_respond: bool = has_trigger_keyword or should_respond_without_trigger(str(message.channel.id), message.author.name) should_respond_flag: bool = has_trigger_keyword or should_respond_without_trigger(str(message.channel.id), message.author.name)
if should_respond: if not should_respond_flag:
# Update trigger time if they used a trigger keyword return
if has_trigger_keyword:
update_trigger_time(str(message.channel.id), message.author.name)
logger.info( # Update trigger time if they used a trigger keyword
"Received message: %s from: %s (trigger: %s, recent: %s)", incoming_message, message.author.name, has_trigger_keyword, not has_trigger_keyword if has_trigger_keyword:
) update_trigger_time(str(message.channel.id), message.author.name)
async with message.channel.typing(): logger.info(
try: "Received message: %s from: %s (trigger: %s, recent: %s)", incoming_message, message.author.name, has_trigger_keyword, not has_trigger_keyword
response: str | None = await chat( )
user_message=incoming_message,
current_channel=message.channel,
user=message.author,
allowed_users=allowed_users,
all_channels_in_guild=message.guild.channels if message.guild else None,
)
except openai.OpenAIError as e:
logger.exception("An error occurred while chatting with the AI model.")
e.add_note(f"Message: {incoming_message}\nEvent: {message}\nWho: {message.author.name}")
await message.channel.send(f"An error occurred while chatting with the AI model. {e}")
return
if response: async with message.channel.typing():
logger.info("Responding to message: %s with: %s", incoming_message, response) try:
# Record the bot's reply in memory response: str | None = await chat(
try: user_message=incoming_message,
add_message_to_memory(str(message.channel.id), "LoviBot", response) current_channel=message.channel,
except Exception: user=message.author,
logger.exception("Failed to add bot reply to memory for on_message") allowed_users=allowed_users,
all_channels_in_guild=message.guild.channels if message.guild else None,
)
except openai.OpenAIError as e:
logger.exception("An error occurred while chatting with the AI model.")
e.add_note(f"Message: {incoming_message}\nEvent: {message}\nWho: {message.author.name}")
await message.channel.send(f"An error occurred while chatting with the AI model. {e}")
return
await message.channel.send(response) reply: str = response or "I forgor how to think 💀"
else: if response:
logger.warning("No response from the AI model. Message: %s", incoming_message) logger.info("Responding to message: %s with: %s", incoming_message, reply)
fallback = "I forgor how to think 💀" else:
try: logger.warning("No response from the AI model. Message: %s", incoming_message)
add_message_to_memory(str(message.channel.id), "LoviBot", fallback)
except Exception: # Record the bot's reply in memory
logger.exception("Failed to add fallback bot reply to memory for on_message") try:
await message.channel.send(fallback) add_message_to_memory(str(message.channel.id), "LoviBot", reply)
except Exception:
logger.exception("Failed to add bot reply to memory for on_message")
await send_chunked_message(message.channel, reply)
async def on_error(self, event_method: str, /, *args: Any, **kwargs: Any) -> None: # noqa: ANN401, PLR6301 async def on_error(self, event_method: str, /, *args: Any, **kwargs: Any) -> None: # noqa: ANN401, PLR6301
"""Log errors that occur in the bot.""" """Log errors that occur in the bot."""