How to Send Direct Messages to Mentioned Users with Python Discord Bot

I need help creating a Discord bot feature where the bot can send private messages to users that get tagged. When someone with the right permissions writes !pm @username, I want the bot to automatically send a direct message to that mentioned user.

Here’s what I have so far but it’s not working correctly:

@bot.event
async def on_message(msg):
    if msg.content.startswith('!pm'):
        dm_text = 'You received a private message from the bot'
        await bot.send_message(msg.author, dm_text)

The problem is that this code sends the DM back to the person who typed the command instead of sending it to the user they mentioned. How can I modify this to detect the mentioned user and send the message to them instead? I’m pretty new to Discord bot development so any help would be appreciated.

Adding to lucask’s point - check permissions first before the dm command. Use if msg.author.guild_permissions.manage_messages: and wrap it in try/except since some users block bot DMs and it’ll error out.

You should validate the command format first. I’ve seen users type !pm without mentioning anyone, which crashes the bot when it tries to access msg.mentions[0] on an empty list. Just add a length check like if len(msg.mentions) > 0: before you do anything else. And don’t forget await bot.process_commands(msg) at the end of your on_message event - without it, your other commands won’t work since on_message overrides the default processing.

Your code isn’t extracting the mentioned user from the message. You need to parse the mentions from the message object. Here’s the fix:

@bot.event
async def on_message(msg):
    if msg.content.startswith('!pm') and msg.mentions:
        mentioned_user = msg.mentions[0]
        dm_text = 'You received a private message from the bot'
        await mentioned_user.send(dm_text)

The main change: use msg.mentions[0] to grab the first mentioned user, then call mentioned_user.send() instead of sending to msg.author. Also, bot.send_message() is deprecated in newer discord.py versions - user.send() is the way to go now. Don’t forget error handling for when users have DMs disabled or no one gets mentioned.

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.