feat: Add MessageScraperCog to scrape and export messages from a channel
This commit is contained in:
parent
8f27e33bb0
commit
4b6632973d
55
cogs/message_scraper_cog.py
Normal file
55
cogs/message_scraper_cog.py
Normal 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))
|
Loading…
x
Reference in New Issue
Block a user