discord.py机器人读取私信转发报错求助:AttributeError与TypeError问题
Hey there! Let's break down what's going wrong with your code and get that DM forwarding working properly—you're already close, just a few small tweaks needed.
Let's go through your errors first:
AttributeErrorwithmessage.server:
Discord.py renamed theserverattribute toguildstarting in v1.0+, so usingmessage.serverwill throw an error. Your switch tomessage.guildwas the right call here.Bothas no attributesend_message:
Thesend_message()method was removed in newer Discord.py versions. Instead, you should callsend()directly on the channel object you want to send to.TypeErrorwithon_message(ctx, message):
Theon_messageevent callback only takes a single parameter:message. Thectx(context) parameter is used for command functions (like@bot.command()), not for event handlers. Adding it here causes Python to expect an extra argument that never gets passed.
Here's the corrected working code:
@bot.event async def on_message(message): # Replace with your actual channel ID (must be an integer, not a string!) target_channel_id = 123456789012345678 channel = bot.get_channel(target_channel_id) # Check if the message is a DM and not from the bot itself if message.guild is None and message.author != bot.user: # Forward the DM content to your target channel (includes sender info for clarity) await channel.send(f"Received DM from {message.author.name} ({message.author.id}):\n{message.content}") # Optional: Print the DM directly to your console too print(f"[DM] {message.author.name}: {message.content}") # Don't forget this line—otherwise your existing emoji/moderation commands won't work! await bot.process_commands(message)
Key notes about the fixed code:
- Channel ID must be an integer: Remove the quotes around your channel ID—
get_channel()expects a numeric ID, not a string. You can enable Discord's Developer Mode to copy channel IDs easily. - Clear DM detection:
message.guild is Nonecorrectly identifies direct messages, since DMs don't belong to any guild/server. - Proper message sending: Using
channel.send()is the current standard way to send messages in Discord.py. I added the sender's name and ID to the forwarded message to help you track who sent the DM—handy for moderation use cases. - Preserve existing commands: Always call
await bot.process_commands(message)at the end of youron_messageevent, otherwise your bot's existing commands will stop functioning.
If you ever run into a case where channel returns None, double-check that your bot has access to the target channel and that you're using the correct ID.
内容的提问来源于stack exchange,提问作者LeThiccBoi

