Creating a Python Discord bot to store DM messages

Hey everyone! I’m trying to build a Discord bot using Python that can save all direct messages it receives. I’ve got some code that counts messages and logs timestamps, but I can’t figure out how to save the actual content of the DMs. Here’s what I’ve tried so far:

import asyncio
import time

async def log_message_stats():
    await client.wait_until_ready()
    global message_count

    while client.is_running():
        try:
            with open('message_log.txt', 'a') as log_file:
                log_file.write(f'Timestamp: {int(time.time())}, Messages: {message_count}\n')
            
            message_count = 0
            await asyncio.sleep(60)
        except Exception as error:
            print(f'Error occurred: {error}')
            await asyncio.sleep(60)

@client.event
async def on_message(message):
    global message_count
    message_count += 1
    
client.loop.create_task(log_message_stats())

This code tracks the number of messages and when they were sent, but it doesn’t save the actual message content. How can I modify it to store the full text of DMs sent to the bot? Any help would be appreciated!

I’ve dealt with similar challenges in my Discord bot projects. One approach that worked well for me was using a database instead of text files for storing messages. SQLite is lightweight and easy to integrate with Python.

Here’s a basic setup I used:

import sqlite3

conn = sqlite3.connect('messages.db')
c = conn.cursor()

c.execute('''CREATE TABLE IF NOT EXISTS messages
             (timestamp INTEGER, author TEXT, content TEXT)''')

@client.event
async def on_message(message):
    if isinstance(message.channel, discord.DMChannel):
        c.execute("INSERT INTO messages VALUES (?, ?, ?)",
                  (int(time.time()), str(message.author), message.content))
        conn.commit()

This stores each DM with a timestamp, author, and content. You can easily query the database later to retrieve messages. Remember to close the connection when your bot shuts down.

I’ve implemented a similar feature in one of my Discord bots. Instead of using text files, I found it more efficient to use a JSON-based approach. Here’s a snippet that might help:

import json
from datetime import datetime

@client.event
async def on_message(message):
    if isinstance(message.channel, discord.DMChannel):
        with open('dm_messages.json', 'a+') as f:
            f.seek(0)
            try:
                data = json.load(f)
            except json.JSONDecodeError:
                data = []
            
            data.append({
                'timestamp': datetime.now().isoformat(),
                'author': str(message.author),
                'content': message.content
            })
            
            f.seek(0)
            f.truncate()
            json.dump(data, f, indent=4)

This approach stores each DM as a JSON object, making it easier to process and analyze the data later. It’s also more flexible if you need to add more fields in the future.

hey there! i’ve worked on similar projects before. to save dm content, you’ll wanna modify your on_message function. try something like this:

if isinstance(message.channel, discord.DMChannel):
with open(‘dm_log.txt’, ‘a’) as f:
f.write(f’{message.author}: {message.content}\n’)

this should log the sender and content of each dm. hope it helps!