You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用on_message监听事件时无法向@提及用户发送私信的问题

Troubleshooting Your Discord Bot DM Issue

Hey Jake, let's break down why your bot isn't sending DMs when users are mentioned. I’ve gone through your code and spotted a few potential issues and fixes:

1. Missing Required Privileged Intent

First, make sure your bot has the message_content privileged intent enabled in the Discord Developer Portal, and that you’ve requested it in your bot setup. Starting with Discord.py v2.0+, bots need this intent to access message mentions, content, and attachments. Without it, message.mentions might return an empty list entirely—meaning your loop never runs at all.

2. Simplify DM Sending Logic

Your code manually checks for member.dm_channel and creates one if it doesn’t exist, but Discord.py handles this automatically when you use await member.send(). This removes unnecessary code and avoids edge cases where creating the DM channel might fail silently.

3. Verify Mentions Are Being Detected

Add a quick debug check to confirm the bot is actually picking up mentions. For example, log or print the length of message.mentions when the event triggers. If it’s empty, that confirms the permission/intent issue is the root cause.

4. Ensure Command Processing Isn’t Blocked

If your cog uses commands alongside this on_message listener, you need to call await self.bot.process_commands(message) at the end of your function. Otherwise, the bot might stop processing events early, preventing your DM logic from running as expected.

Modified Code with Fixes

Here’s an updated version of your code incorporating these changes:

@commands.Cog.listener()
async def on_message(self, message):
    """向用户发送私信回复。"""
    # Debug check: confirm mentions are detected
    print(f"Detected {len(message.mentions)} mentions in message: {message.content}")
    
    for member in message.mentions:
        try:
            time = datetime.utcnow()
            embed = discord.Embed(title=f"Reply", timestamp=time, colour=discord.Colour(0xff8100))
            embed.add_field(name="Message:", value="test message")
            # Let Discord.py handle DM channel creation automatically
            await member.send(embed=embed)
        except discord.Forbidden:
            await message.channel.send(f"Reply cannot be sent because {member.name}'s direct messages are set to private.")
        except discord.HTTPException as e:
            await message.channel.send(f'I failed to send the message: {str(e)}')
        except Exception as e:
            await message.channel.send(f'An unexpected error occurred: {str(e)}')
        else:
            await message.channel.send(f'Reply sent to {member.name}')
    
    # Don't forget to process commands if using them
    await self.bot.process_commands(message)

Additional Checks

  • Double-check that the bot is in the same server as the mentioned users (though message.mentions should only include server members, so this is less likely).
  • Test with a user who has DMs open to server members to rule out privacy settings as the only issue.

内容的提问来源于stack exchange,提问作者Jake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 20:42:50