iTranslated by AI
Building a Discord Bot to Export Messages to CSV
Introduction
Do you all love Discord? Since the beginning of this year, I've been joining various Discord servers and having a great time!
It's great because information tends to be more concentrated than on X, and it has a high level of psychological safety.
As a Discord user like that, I recently started managing a Discord server myself and have been looking into many things.
In this article, I will show you how to save messages within a Discord channel into a CSV file.
Specifically, we will be running Python code on a local PC.
Execution Environment
M2 Macbook
Python 3.5.0
pyenv
VS Code
How to Create a Bot to Save Discord Messages to CSV
Now, when I wanted to export messages from Discord and looked into it,
I found that there is no such built-in feature. So, I created a custom Bot and wrote/executed Python code to run that Bot.
ChatGPT wrote most of the code, so I was able to implement it easily without much effort!
However, since there is very little information about Discord in Japanese, I hope this will be helpful to someone.
The following are the steps to save messages in a channel to a CSV file.
1. Create a Discord Bot
First, access the Discord developer portal.

Click "New Application" to create a new application.
Application Settings
Enter a name for the application and click "Create". This name can be changed later.
Adding the Bot
On the application settings page, select the "Bot" tab and click "Add Bot" to add the application as a Bot.
Obtaining the Bot TOKEN
Click "Copy" in the "Token" section to copy the Bot's TOKEN. This TOKEN is extremely important and is required to control the Bot. Do not share it with others.
Inviting the Bot to a Server
Navigate to the "OAuth2" tab in the application settings and select the "URL Generator" sub-tab.
Selecting Permissions
In the "SCOPES" section, check "bot". In the "BOT PERMISSIONS" section below it, select the permissions necessary for the Bot (e.g., read messages, send messages, etc.).
Generating the Invitation URL
A URL will be generated based on the selected permissions. Copy this URL, paste it into your browser, and access it.
Adding the Bot to the Server
Ensure you are logged into Discord and select the server you want to add the Bot to. Click "Authorize" to add the Bot to the server. (Administrator privileges for the server are required.)
2. Write the program to run the Bot
Create a new directory and set up a Python virtual environment within that directory.
# Create directory
mkdir my_discord_bot
cd my_discord_bot
# Create virtual environment (Linux/macOS)
python3 -m venv botenv
# Create virtual environment (Windows)
python -m venv botenv
Activate the virtual environment.
# Linux/macOS
source botenv/bin/activate
# Windows
botenv\Scripts\activate
Create a Python file (e.g., app.py) and write the following code.
from dotenv import load_dotenv
import discord
import csv
import asyncio
import os
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
CHANNEL_ID_STR = os.getenv('DISCORD_CHANNEL_ID') # ID of the channel from which you want to retrieve messages (integer)
CHANNEL_ID = int(CHANNEL_ID_STR)
LAST_MESSAGE_ID_FILE = 'last_message_id.txt' # Filename to save the last retrieved message ID
# Enable privileged intents
intents = discord.Intents.default()
intents.members = True
intents.presences = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
# Replace CHANNEL_ID with the appropriate channel ID
channel = client.get_channel(CHANNEL_ID)
if channel is None:
print('Channel not found.')
return
# Load the last retrieved message ID
if os.path.exists(LAST_MESSAGE_ID_FILE):
with open(LAST_MESSAGE_ID_FILE, 'r') as file:
last_message_id = int(file.read().strip())
else:
last_message_id = None
after = discord.Object(id=last_message_id) if last_message_id else None
# Open CSV file to save messages
with open('output.csv', 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
# Add "Nickname" column
writer.writerow(["Username", "Nickname", "UserID", "MessageID", "Timestamp", "Content"])
messages = [message async for message in channel.history(limit=1000, after=after)]
for message in messages:
# Use nickname if the user is a server member, otherwise use the username
nickname = message.author.nick if message.author.nick else message.author.name
writer.writerow([message.author.name, nickname, message.author.id, message.id, message.created_at, message.content])
if messages:
# Record the latest message ID to a file
with open(LAST_MESSAGE_ID_FILE, 'w') as file:
file.write(str(messages[0].id))
print('CSV file has been saved.')
# Logout the Bot
await client.close()
# Replace TOKEN with the appropriate token
client.run(TOKEN)
Installing Necessary Packages
Since we are setting environment variables in a .env file this time, run the following commands in your directory:
pip install python-dotenv
Also, let's install the package for discord:
pip install discord.py
Then, create a .env file in the same directory as app.py and define the TOKEN and CHANNEL_ID_STR.
TOKEN = XXXXXXX
CHANNEL_ID_STR = XXXXXXXX
Obtain the TOKEN from the Discord developer portal.
The CHANNEL_ID_STR is displayed when you left-click on the server's channel name.
If it doesn't appear, you might not have Discord's Developer Mode enabled, so please make sure to turn it on.
The following article is helpful:
Run the Bot
Run the Bot with the following command.
python app.py
If successful, a CSV file will be saved in the same directory.
When Things Don't Work
If the Bot's permissions are not set correctly, you will encounter a 4XX error.
Review the permissions on the Discord developer portal!
*This is where I got stuck.
Summary
Discord allows you to add various features to a Bot using its API.
Regarding the code, I was able to implement it quite smoothly using ChatGPT, so I hope this helps!
Discussion