Creating a Discord bot that echoes user messages in Python

I’m trying to make a Discord bot that can repeat what the user says. Here’s what I’ve got so far:

@bot.command()
async def echo(ctx):
    for server in bot.guilds:
        target_role = discord.utils.find(lambda r: r.name == 'echo_role', server.roles)
        for user in server.members:
            if target_role in user.roles:
                await user.send(message)
    message = ''

This code doesn’t work as intended. I want the bot to send the message that the command author types. Also, if possible, I’d like to know how to make the bot use a role specified by the user instead of a hardcoded one. Any help would be appreciated!

hey, i tried somethin similar. here’s a quick fix:

@bot.command()
async def echo(ctx, *, msg):
await ctx.send(msg)

this’ll repeat whatever u type after the command. for roles, u could do:

@bot.command()
async def echo_role(ctx, role: discord.Role, *, msg):
for m in role.members:
await m.send(msg)

hope this helps!

I’ve implemented something similar in my Discord server. Here’s a more efficient approach:

@bot.command()
async def echo(ctx, *, message):
await ctx.send(message)

This simple code will make the bot repeat the user’s message in the same channel. It’s straightforward and doesn’t require role checks.

If you want to add role-based functionality, you could modify it like this:

@bot.command()
async def echo_role(ctx, role: discord.Role, *, message):
for member in role.members:
try:
await member.send(message)
except discord.Forbidden:
pass

This sends the message to all members with the specified role, ignoring those who can’t receive DMs. Remember to implement proper error handling and permissions to prevent abuse.

I’ve worked on a similar bot before, and I can share some insights. Your approach is close, but there are a few adjustments needed.

First, to echo the user’s message, you need to capture it as an argument. Modify your command like this:

@bot.command()
async def echo(ctx, *, message):
await ctx.send(message)

This will repeat whatever the user types after the command.

For the role-specific feature, you can add an optional role argument:

@bot.command()
async def echo(ctx, role: discord.Role, *, message):
for member in ctx.guild.members:
if role in member.roles:
await member.send(message)

This allows users to specify a role and sends the message to all members with that role.

Remember to handle potential errors, like invalid roles or empty messages. Also, consider adding permissions to restrict who can use this command to prevent spam.