import discord from discord import app_commands from discord.ext import commands from utils.attachments import save_attachments from src.utils.db import get_db from models import Message from config import BOT_COLOR class Archive(commands.Cog): def __init__(self, bot): self.bot = bot @app_commands.command() async def archive( self, interaction: discord.Interaction, channel: discord.TextChannel, amount: int, ): """Archive a channel's messages.""" # Ensure valid channel permissions if not channel.permissions_for( interaction.guild.me ).read_message_history: return await interaction.response.send_message( "I do not have permission to read message history in that" " channel.", ephemeral=True, ) # Ensure valid amount if amount < 1: return await interaction.response.send_message( "You must provide a number greater than 0.", ephemeral=True, ) embed = discord.Embed( title="Archive Beginning", description=( f"Archiving {amount} messages from {channel.mention}. I will" " DM you a message once complete, make sure to allow messages" " from me." ), color=BOT_COLOR, ) await interaction.response.send_message(embed=embed, ephemeral=True) # get database session and begin archiving db = next(get_db()) count = 0 messages = channel.history(limit=amount) async for message in messages: count += 1 paths = await save_attachments(message) db_message = Message( timestamp=message.created_at.isoformat(), message_id=message.id, author_id=message.author.id, channel_id=channel.id, stickers=[sticker.name for sticker in message.stickers], role_mentions=[role.id for role in message.role_mentions], mention_everyone=message.mention_everyone, mentions=[mention.id for mention in message.mentions], attachments=paths, content=message.content, ) db.add(db_message) if count > 500: db.commit() count = 0 # commit any remaining messages db.commit() embed = discord.Embed( title="Archive Complete", description=f"Archived {amount} messages from {channel.mention}.", color=BOT_COLOR, ) try: await interaction.user.send(embed=embed) except discord.Forbidden: await channel.send( f"{interaction.user.mention} I have completed the archive, but" " was unable to DM you the final message. Please check your" " DM settings to receive future messages." ) async def setup(bot): await bot.add_cog(Archive(bot))