Skip to content

Commit

Permalink
support file attachments
Browse files Browse the repository at this point in the history
  • Loading branch information
fredsmith committed Dec 4, 2024
1 parent e05f07a commit 82002b1
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,18 @@ async def get_or_create_conversation(channel_id):
}
return channel_conversations[channel_id]

async def get_text_file_contents(attachment):
"""Download and read the contents of a text file attachment"""
if not attachment.filename.endswith(('.txt', '.md', '.py', '.js', '.html', '.css', '.json', '.yaml', '.yml')):
return None

try:
file_content = await attachment.read()
return f"\nContents of {attachment.filename}:\n```\n{file_content.decode('utf-8')}\n```"
except Exception as e:
print(f"Error reading attachment {attachment.filename}: {e}")
return None

@bot.event
async def on_ready():
print(f'{bot.user} has connected to Discord!')
Expand All @@ -69,10 +81,20 @@ async def on_message(message):
# Get or create conversation for this channel
conversation = await get_or_create_conversation(message.channel.id)

# Process message content and any text file attachments
full_message = message.content

# Handle text file attachments
if message.attachments:
for attachment in message.attachments:
file_content = await get_text_file_contents(attachment)
if file_content:
full_message += file_content

# Always add message to conversation history
conversation['messages'].append({
'role': 'user',
'content': message.content
'content': full_message
})

# Keep conversation history manageable (last 20 messages)
Expand Down

0 comments on commit 82002b1

Please sign in to comment.