2025-09-14 18:54:56 -04:00
import os
from datetime import datetime
import discord
from discord import app_commands
from discord . ext import commands
from discord . ext . commands import Context
2025-09-28 23:07:46 -04:00
def archive_command ( ) :
2025-09-14 18:54:56 -04:00
@commands.hybrid_command (
name = " archive " ,
description = " Archives in a text file the last messages with a chosen limit of messages. " ,
)
@commands.has_permissions ( manage_messages = True )
@app_commands.describe (
limit = " The limit of messages that should be archived. " ,
)
2025-09-28 23:07:46 -04:00
async def archive ( self , context , limit : int = 10 ) :
2025-09-14 18:54:56 -04:00
"""
Archives in a text file the last messages with a chosen limit of messages . This command requires the MESSAGE_CONTENT intent to work properly .
: param context : The hybrid command context .
: param limit : The limit of messages that should be archived . Default is 10.
"""
log_file = f " { context . channel . id } .log "
2025-11-02 23:32:52 -05:00
2025-09-15 14:45:00 -04:00
messages = [ ]
async for message in context . channel . history (
limit = limit , before = context . message
) :
attachments = [ ]
for attachment in message . attachments :
attachments . append ( attachment . url )
attachments_text = (
f " [Attached File { ' s ' if len ( attachments ) > = 2 else ' ' } : { ' , ' . join ( attachments ) } ] "
if len ( attachments ) > = 1
else " "
)
2025-11-02 23:32:52 -05:00
2025-09-15 14:50:53 -04:00
message_line = f " { message . created_at . strftime ( ' % m/ %d / % Y % H: % M: % S ' ) } { message . author } { message . id } : { message . clean_content } { attachments_text } \n "
2025-09-15 14:45:00 -04:00
messages . append ( message_line )
2025-11-02 23:32:52 -05:00
2025-09-14 18:54:56 -04:00
with open ( log_file , " w " , encoding = " UTF-8 " ) as f :
f . write (
2025-09-15 14:50:53 -04:00
f ' Archived messages from: # { context . channel } ( { context . channel . id } ) in the guild " { context . guild } " ( { context . guild . id } ) at { datetime . now ( ) . strftime ( " % m/ %d / % Y % H: % M: % S " ) } \n '
2025-09-14 18:54:56 -04:00
)
2025-09-15 14:45:00 -04:00
for message_line in reversed ( messages ) :
f . write ( message_line )
2025-11-02 23:32:52 -05:00
2025-09-14 18:54:56 -04:00
f = discord . File ( log_file )
await context . send ( file = f )
os . remove ( log_file )
2025-11-02 23:32:52 -05:00
return archive