feat: Add MessageScraperCog to scrape and export messages from a channel

This commit is contained in:
Slipstream 2025-05-28 13:11:17 -06:00
parent 8f27e33bb0
commit 4b6632973d
Signed by: slipstream
GPG Key ID: 13E498CE010AC6FD

View File

@ -0,0 +1,55 @@
import discord
from discord.ext import commands
import io
class MessageScraperCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name="scrape_messages")
@commands.is_owner()
async def scrape_messages(self, ctx, limit: int = 100):
"""
Scrapes the last N messages from the current channel, excluding bots,
and includes reply information. Uploads the results as a .txt file.
"""
if limit > 500:
return await ctx.send("Please keep the limit under 500 messages to avoid rate limits.")
messages_data = []
async for message in ctx.channel.history(limit=limit):
if message.author.bot:
continue
reply_info = ""
if message.reference and message.reference.message_id:
try:
replied_message = await ctx.channel.fetch_message(message.reference.message_id)
reply_info = f" (In reply to: '{replied_message.author.display_name}: {replied_message.content[:50]}...')"
except discord.NotFound:
reply_info = " (In reply to: [Original message not found])"
except discord.HTTPException:
reply_info = " (In reply to: [Could not fetch original message])"
messages_data.append(
f"[{message.created_at.strftime('%Y-%m-%d %H:%M:%S')}] "
f"{message.author.display_name} ({message.author.id}): "
f"{message.content}{reply_info}"
)
if not messages_data:
return await ctx.send("No messages found matching the criteria.")
output_content = "\n".join(messages_data)
# Create a file-like object from the string content
file_data = io.BytesIO(output_content.encode('utf-8'))
# Send the file
await ctx.send(
f"Here are the last {len(messages_data)} messages from this channel (excluding bots):",
file=discord.File(file_data, filename="scraped_messages.txt")
)
async def setup(bot):
await bot.add_cog(MessageScraperCog(bot))