Sure! Below is a Jupyter Notebook that sets up a Discord bot capable of handling the /scrape command. This command allows you to specify a Discord user, fetches their last 100 messages, and saves them to a text file.
Please Note:
- Bot Token Security: Never share your Discord bot token publicly. Ensure it's kept secure. For this notebook, you'll need to input your bot token securely.
- Intents: The bot requires specific intents to read message history. Make sure to enable the necessary intents in your Discord Developer Portal for the bot.
- Running the Bot: Hosting a Discord bot within a Jupyter Notebook is not typical for production environments. This setup is primarily for educational or testing purposes.
1. Install Required Libraries
First, install the necessary libraries. We'll use discord.py for interacting with Discord's API and nest_asyncio to allow the asyncio event loop to run within the Jupyter Notebook.
!pip install discord.py
!pip install nest_asyncio
2. Import Libraries and Setup
Import the required libraries and apply nest_asyncio to allow nested event loops, which is necessary within Jupyter Notebooks.
import discord
from discord.ext import commands
import asyncio
import nest_asyncio
import os
from discord import app_commands
# Apply nest_asyncio to allow the event loop to run in the notebook
nest_asyncio.apply()
3. Configure Intents
Discord bots require specific intents to access certain data. Enable the following intents:
messages: To read message content.
guilds: To interact with guild (server) information.
Ensure these intents are also enabled in your Discord Developer Portal for the bot.
intents = discord.Intents.default()
intents.message_content = True # Enable access to message content
intents.guilds = True
intents.messages = True
4. Initialize the Bot
Create an instance of the bot with a command tree for handling application (slash) commands.
# Replace 'YOUR_BOT_TOKEN_HERE' with your actual Discord bot token
BOT_TOKEN = 'YOUR_BOT_TOKEN_HERE'
# Initialize the bot
bot = commands.Bot(command_prefix='!', intents=intents)
5. Define the /scrape Command
This command takes a Discord user as input, fetches their last 100 messages across all accessible text channels, and writes them to a text file.
@bot.event
async def on_ready():
print(f'Logged in as {bot.user}')
try:
synced = await bot.tree.sync()
print(f'Synced {len(synced)} command(s)')
except Exception as e:
print(e)
@bot.tree.command(name="scrape", description="Scrape the last 100 messages of a user")
@app_commands.describe(user="The Discord user to scrape messages from")
async def scrape(interaction: discord.Interaction, user: discord.User):
await interaction.response.defer() # Defer the response as fetching might take time
messages = []
try:
# Iterate through all guilds the bot is in
for guild in bot.guilds:
# Iterate through all text channels in the guild
for channel in guild.text_channels:
# Check if the bot has permissions to read message history in the channel
if channel.permissions_for(guild.me).read_message_history:
try:
# Fetch messages from the channel
async for message in channel.history(limit=100, oldest_first=False):
if message.author.id == user.id:
messages.append(f'[{message.created_at}] {message.content}\n')
if len(messages) >= 100:
break
if len(messages) >= 100:
break
except Exception as e:
print(f"Failed to fetch messages from {channel.name}: {e}")
if len(messages) >= 100:
break
if not messages:
await interaction.followup.send("No messages found for this user.")
return
# Trim to last 100 messages if more were collected
messages = messages[:100]
# Create a filename
filename = f"{user.name}_{user.id}_messages.txt"
# Write messages to the file
with open(filename, 'w', encoding='utf-8') as f:
f.writelines(messages)
# Send the file back to the user
await interaction.followup.send(file=discord.File(filename))
# Optionally, remove the file after sending
os.remove(filename)
except Exception as e:
await interaction.followup.send(f"An error occurred: {e}")
6. Run the Bot
Finally, run the bot. Ensure that you replace 'YOUR_BOT_TOKEN_HERE' with your actual Discord bot token.
# Start the bot
bot.run(BOT_TOKEN)
Complete Notebook Code
For convenience, here's the entire notebook content combined. You can copy this into a .ipynb file or directly into Jupyter Notebook cells.
# Discord Bot - Scrape User Messages
This notebook sets up a Discord bot that can scrape the last 100 messages from a specified user when the `/scrape` command is used.
## 1. Install Required Libraries
```python
!pip install discord.py
!pip install nest_asyncio
2. Import Libraries and Setup
import discord
from discord.ext import commands
import asyncio
import nest_asyncio
import os
from discord import app_commands
# Apply nest_asyncio to allow the event loop to run in the notebook
nest_asyncio.apply()
3. Configure Intents
intents = discord.Intents.default()
intents.message_content = True # Enable access to message content
intents.guilds = True
intents.messages = True
4. Initialize the Bot
# Replace 'YOUR_BOT_TOKEN_HERE' with your actual Discord bot token
BOT_TOKEN = 'YOUR_BOT_TOKEN_HERE'
# Initialize the bot
bot = commands.Bot(command_prefix='!', intents=intents)
5. Define the /scrape Command
@bot.event
async def on_ready():
print(f'Logged in as {bot.user}')
try:
synced = await bot.tree.sync()
print(f'Synced {len(synced)} command(s)')
except Exception as e:
print(e)
@bot.tree.command(name="scrape", description="Scrape the last 100 messages of a user")
@app_commands.describe(user="The Discord user to scrape messages from")
async def scrape(interaction: discord.Interaction, user: discord.User):
await interaction.response.defer() # Defer the response as fetching might take time
messages = []
try:
# Iterate through all guilds the bot is in
for guild in bot.guilds:
# Iterate through all text channels in the guild
for channel in guild.text_channels:
# Check if the bot has permissions to read message history in the channel
if channel.permissions_for(guild.me).read_message_history:
try:
# Fetch messages from the channel
async for message in channel.history(limit=100, oldest_first=False):
if message.author.id == user.id:
messages.append(f'[{message.created_at}] {message.content}\n')
if len(messages) >= 100:
break
if len(messages) >= 100:
break
except Exception as e:
print(f"Failed to fetch messages from {channel.name}: {e}")
if len(messages) >= 100:
break
if not messages:
await interaction.followup.send("No messages found for this user.")
return
# Trim to last 100 messages if more were collected
messages = messages[:100]
# Create a filename
filename = f"{user.name}_{user.id}_messages.txt"
# Write messages to the file
with open(filename, 'w', encoding='utf-8') as f:
f.writelines(messages)
# Send the file back to the user
await interaction.followup.send(file=discord.File(filename))
# Optionally, remove the file after sending
os.remove(filename)
except Exception as e:
await interaction.followup.send(f"An error occurred: {e}")
6. Run the Bot
# Start the bot
bot.run(BOT_TOKEN)
---
### Additional Steps:
1. **Enable Privileged Intents:**
- Go to the [Discord Developer Portal](https://discord.com/developers/applications) and select your application.
- Navigate to the "Bot" section.
- Under "Privileged Gateway Intents," enable **Message Content Intent**.
- Save the changes.
2. **Invite the Bot to Your Server:**
- Still in the Developer Portal, navigate to the "OAuth2" section.
- Under "URL Generator," select the `bot` and `applications.commands` scopes.
- Assign the necessary permissions, especially the ones related to reading message history.
- Use the generated URL to invite the bot to your Discord server.
3. **Use the `/scrape` Command:**
- In your Discord server, type `/scrape` and start typing the user's name to see the auto-complete feature.
- Select the desired user and execute the command.
- The bot will respond with a text file containing the last 100 messages from that user.
---
### Important Considerations:
- **Permissions:** Ensure the bot has the necessary permissions in all channels where it needs to read message history.
- **Rate Limits:** Discord imposes rate limits on API calls. Fetching messages from many channels or large servers may hit these limits.
- **Privacy:** Scraping user messages can have privacy implications. Ensure you have the necessary permissions and are compliant with Discord’s Terms of Service and relevant laws.
If you encounter any issues or have further questions, feel free to ask!