@bot.event
async def on_message(message):
"""Event that is run when a message is sent in a channel or DM that the bot has access to"""
global last_message_id
if message.author == bot.user:
# ensure the bot does not reply to itself
return
is_dm = isinstance(message.channel, discord.DMChannel)
is_reply_to_bot = (
message.reference and message.reference.resolved.author == bot.user
)
is_mention = bot.user.mentioned_in(message)
if is_dm or is_reply_to_bot or is_mention:
# Remove the bot's mention from the message content if present
input = message.content.replace(f"<@{bot.user.id}>", "").strip()
# If the message is empty after removing the mention, ignore it
if not input:
return
# Get a user object for the message author
user_id = f"discord_{str(message.author.id)}"
user = honcho.apps.users.get_or_create(name=user_id, app_id=app.id)
# Use the channel ID as the location_id (for DMs, this will be unique to the user)
location_id = str(message.channel.id)
# Get or create a session for this user and location
session, _ = get_session(user.id, location_id, create=True)
# Get messages
history_iter = honcho.apps.users.sessions.messages.list(
app_id=app.id, session_id=session.id, user_id=user.id
)
history = list(msg for msg in history_iter)
# Add user message to session
user_msg = honcho.apps.users.sessions.messages.create(
app_id=app.id,
user_id=user.id,
session_id=session.id,
content=input,
is_user=True,
)
last_message_id = user_msg.id
async with message.channel.typing():
response = llm(input, history)
if len(response) > 1500:
# Split response into chunks at newlines, keeping under 1500 chars
chunks = []
current_chunk = ""
for line in response.splitlines(keepends=True):
if len(current_chunk) + len(line) > 1500:
chunks.append(current_chunk)
current_chunk = line
else:
current_chunk += line
if current_chunk:
chunks.append(current_chunk)
for chunk in chunks:
await message.channel.send(chunk)
else:
await message.channel.send(response)
# Add bot message to session
honcho.apps.users.sessions.messages.create(
app_id=app.id,
user_id=user.id,
session_id=session.id,
content=response,
is_user=False,
)