I am currently building a Discord bot using Python, and I want it to be able to send direct messages to users when they are mentioned. Specifically, when I enter a command like !DM @user
, the bot should directly message the user mentioned.
Here is my initial code, but it’s not functioning as expected:
@client.event
async def on_message(message):
if message.content.startswith('!DM'):
message_content = 'This is a direct message from the bot.'
await client.send_message(message.author, message_content)
The issue I’m facing is that this code sends the direct message back to myself instead of the mentioned user. What changes do I need to make to properly target the mentioned user and send them a direct message? Any guidance would be greatly appreciated!
yeah the message.author
thing gets everyone confused at first lol. basically you’re telling the bot to dm yourself instead of the person you mentioned. try checking if theres actually mentions in the msg before trying to send anything tho, otherwise it’ll crash when someone types !DM
without mentioning anyone.
Your problem stems from targeting message.author
, which always refers to whoever typed the command. You need to parse the mentioned user from the message content instead. The solution involves checking message.mentions
to get the actual user being mentioned.
@client.event
async def on_message(message):
if message.content.startswith('!DM'):
if len(message.mentions) > 0:
mentioned_user = message.mentions[0]
dm_content = 'This is a direct message from the bot.'
await mentioned_user.send(dm_content)
else:
await message.channel.send('No user mentioned!')
I encountered this exact issue when building my first bot last year. The key insight is that Discord automatically populates the mentions
list when users are tagged with the @ symbol. Also worth noting that client.send_message()
is deprecated in newer discord.py versions, so using user.send()
is the correct approach now.
The issue in your code arises from using message.author
, which targets the user sending the command instead of the mentioned user. To send a DM to the intended user, you’ll need to access the mentions from the message content. Here’s a modified version of your function:
@client.event
async def on_message(message):
if message.content.startswith('!DM'):
if message.mentions:
target_user = message.mentions[0]
message_content = 'This is a direct message from the bot.'
await target_user.send(message_content)
else:
await message.channel.send('Please mention a user to send a DM.')
This code uses message.mentions[0]
to specify the first mentioned user and utilizes target_user.send()
which is essential for sending direct messages. Additionally, ensure you check for mentions to prevent errors when none are provided.