Search code examples
pythondiscorddiscord.py

How to make a Python Discord bot that logs the last n messages


I'm very new to discord.py and this seems like something very simple but I just can't get it to work. I'm trying to make a simple bot that will find and record the last n amount of messages in a channel.

The following is my code:

import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.messages = True

bot = commands.Bot(command_prefix='!', intents=intents)

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name}')

@bot.command()
async def record_last_messages(ctx, n: int):
    channel = ctx.channel
    messages = await channel.history(limit=n+1).flatten()
    messages.reverse()  # Reverse the list to get the messages in chronological order
    with open('recorded_messages.txt', 'w', encoding='utf-8') as file:
        for message in messages:
            file.write(f'{message.author.name}: {message.content}\n')
    await ctx.send(f'{n} last messages recorded!')

bot.run('QWERTYUIOPASDFGHJKLZXCVBNM')

I get the error message [WARNING ] discord.ext.commands.bot: Privileged message content intent is missing, commands may not work as expected. and when I try the command !record_last_messages 10, nothing happens.

Presence intent, server members intent and message content intent are all switched on on the discord developers website.


Solution

  • The only issue might be related to the intents you've provided. Please ensure that you've correctly enabled the necessary intents on both your code and your bot's configuration on the Discord Developer Portal.

    In order to fetch message history, you need the Guilds ( discord.Intents.guilds ), Messages ( discord.Intents.messages ), and Message Content ( discord.Intents.message_content ) intents. Here's how you can define them:

    intents = discord.Intents.default()
    intents.guilds = True
    intents.messages = True
    intents.message_content = True