能否统计服务器上所有用户发送的消息(含机器人添加前的消息)及实现方法?
Great question! I’ve tackled similar requests before, so let’s break this down clearly—this is absolutely feasible, but the exact steps depend on the chat platform you’re using (I’ll focus on Discord since it’s the most common for bot-based message tracking).
Feasibility Breakdown
The core requirement hinges on two key factors:
- You have administrative access to the server (to grant the bot necessary permissions).
- The platform retains historical message data (most major platforms like Discord, Slack, or Teams do this by default, unless the server explicitly purged messages).
Step-by-Step Implementation (Discord Example)
Let’s walk through how to build this with a Python bot using discord.py:
1. Configure Bot Permissions & Intents
First, you need to enable critical intents and assign server permissions:
- Head to your bot's page in the Discord Developer Portal and enable the Message Content Intent and Server Members Intent under the "Privileged Gateway Intents" section.
- In your server, assign the bot the Read Message History and View Channels permissions (add channel-specific access if you need to pull data from private channels).
2. Batch Fetch Historical Messages
Discord’s API limits you to 100 messages per request, so you’ll need to paginate through the history using the before parameter to keep pulling older messages until you hit the server’s earliest message.
Here’s a simplified code snippet to handle this:
import discord from discord.ext import commands # Enable required intents intents = discord.Intents.default() intents.message_content = True intents.members = True bot = commands.Bot(command_prefix="!", intents=intents) @bot.command() async def count_all_messages(ctx, channel_id: int): target_channel = bot.get_channel(channel_id) if not target_channel: await ctx.send("Oops, couldn't find that channel!") return all_messages = [] last_msg_id = None # Paginate through message history while True: # Fetch up to 100 messages before the last one we pulled message_batch = await target_channel.history(limit=100, before=last_msg_id).flatten() if not message_batch: break # No more messages to fetch all_messages.extend(message_batch) last_msg_id = message_batch[-1].id # Set the last message ID for next batch # Count messages per user (skip bots if needed) user_message_counts = {} for msg in all_messages: if msg.author.bot: continue user_key = f"{msg.author.name}#{msg.author.discriminator}" user_message_counts[user_key] = user_message_counts.get(user_key, 0) + 1 # Send sorted results await ctx.send("### Message Count Results:") for user, count in sorted(user_message_counts.items(), key=lambda x: x[1], reverse=True): await ctx.send(f"- {user}: {count} messages") # Replace with your bot token bot.run("YOUR_BOT_TOKEN_HERE")
3. Handle Large Datasets
If your server has tens of thousands of messages, avoid storing everything in memory. Instead:
- Write batches of messages directly to a database (like SQLite or PostgreSQL) as you fetch them.
- Run your count queries directly against the database to avoid memory overload.
Key Notes
- Rate Limits: Discord’s API has rate limits—don’t spam requests, or your bot will get temporarily restricted. The
discord.pylibrary handles this automatically for the most part, but keep batch sizes reasonable. - Purged Messages: If the server deleted old messages manually or via auto-purge bots, those messages can’t be recovered.
- Platform Differences: For other platforms like Slack, the process is similar—you’ll need to use their API’s history endpoints and ensure your app has the right scopes (e.g.,
channels:historyfor Slack).
内容的提问来源于stack exchange,提问作者MegaMix_Craft

