Encountering HTTP 403 error when my Discord bot attempts to send DM

I’m developing a Discord bot using Go with the discordgo library. My setup seems alright, and the bot responds to slash commands. However, I’m facing an HTTP 403 error when it tries to send direct messages to users.

Here’s the code I’m using:

package main

import (
    "fmt"
    "log"
    "github.com/bwmarrin/discordgo"
)

var token = "your_bot_token_here"

func main() {
    session, err := discordgo.New("Bot " + token)
    if err != nil {
        fmt.Println("Failed to create session:", err)
        return
    }

    session.AddHandler(handleCommand)

    err = session.Open()
    if err != nil {
        fmt.Println("Failed to open connection:", err)
        return
    }
    defer session.Close()

    _, err = session.ApplicationCommandCreate(session.State.User.ID, "", &discordgo.ApplicationCommand{
        Name:        "hello",
        Description: "Send a greeting",
    })
    if err != nil {
        fmt.Println("Failed to create command:", err)
        return
    }

    fmt.Println("Bot is online!")
    select {}
}

func handleCommand(s *discordgo.Session, interaction *discordgo.InteractionCreate) {
    if interaction.Type != discordgo.InteractionApplicationCommand {
        return
    }

    err := s.InteractionRespond(interaction.Interaction, &discordgo.InteractionResponse{
        Type: discordgo.InteractionResponseChannelMessageWithSource,
        Data: &discordgo.InteractionResponseData{
            Content: "I'll send you a private message now!",
            Flags:   1 << 6,
        },
    })
    if err != nil {
        log.Println("Failed to respond to interaction:", err)
        return
    }

    dmChannel, err := s.UserChannelCreate(interaction.Member.User.ID)
    if err != nil {
        log.Println("Failed to create DM channel:", err)
        return
    }

    _, err = s.ChannelMessageSend(dmChannel.ID, "This is your private message!")
    if err != nil {
        log.Println("Failed to send private message:", err)
    }
}

The specific error I’m encountering is:

2025/05/02 11:55:57 Failed to send private message: HTTP 403 Forbidden, {"message": "Cannot send messages to this user", "code": 50007}

My bot and I are members of the same server, and I’ve ensured that my DM settings are all enabled. The slash command works perfectly, but the direct messages are not being sent. Can anyone suggest what the issue might be?

That 403 error is super common with Discord bot DMs. Discord got really strict about this to stop spam.

Users can block DMs from server members or have privacy settings that prevent bot messages. Even if your settings allow DMs, others might not.

Your code’s fine - it’s Discord’s restrictions, not your implementation.

Instead of fighting Discord’s DM limits, set up a workflow with fallbacks. When someone uses your slash command, try the DM first. If you get a 403, automatically fall back to an ephemeral message in the channel, post in a bot channel, or send an email if you’ve got their email.

I’ve built similar systems for work notification bots. Having multiple channels ready when one fails is key.

The logic’s pretty straightforward: try DM, catch the 403, then trigger alternative methods automatically. Way more reliable than hoping DMs work.

Check out automated fallback systems like this: https://latenode.com

Discord’s privacy settings are weird - users think they’re open but they’re not. Server permissions can also block bot DMs no matter what the user’s settings are. I’d throw in some error logging to catch which user IDs are breaking - interaction.Member.User.ID sometimes grabs the wrong data depending on the guild context. Just add a permission check before you try sending the DM. Saves you from burning through rate limits on failed sends.

Had this same problem across several bot projects. That 403 isn’t a bug - it’s Discord’s anti-spam doing its job.

First, make sure you’ve got message content intent turned on in the Developer Portal. Discord requires it now, even for DMs. Check your privileged gateway intents.

But honestly? Don’t waste time fighting Discord’s DM restrictions. I gave up on forcing DMs and built something much better.

Create an automated system that handles the whole communication flow. User hits your slash command, system tries DM first. Gets a 403? Instantly switches to webhooks, email, or posts in a dedicated channel.

Built this for our internal stuff and it’s rock solid. Users get notifications no matter what Discord decides. The system remembers which method worked for each user and adapts.

Way more reliable than crossing your fingers every time. You can add SMS, Slack, whatever people actually use.

Discord’s gotten way more aggressive with DM blocking since 2023, especially for bots. Error 50007 means the user’s privacy settings are blocking your bot - even if they allow DMs from server members.

I noticed you’re not handling guild vs DM interactions properly. When you test slash commands in servers, the interaction object acts weird. Log the actual user ID you’re pulling to make sure it’s right.

Hit this exact problem last year with a reminder bot I built. Fixed it by checking permissions before trying to DM. Use s.UserChannelCreate() as a test - if it fails, you know the DM won’t work either. Way better than failing silently and leaving users confused.

Discord also throws false positives on this error when their API’s getting hammered. Added a simple retry with exponential backoff and it cut down failed DM attempts big time.

This happens because Discord handles bot-to-user DMs differently than regular messages. Even with the right privacy settings, Discord can still block your bot based on account age, server relationship, or recent activity.

I noticed something in your code - you’re not checking if the interaction comes from a guild member versus a DM. Sometimes interaction.Member can be nil, which breaks the user ID extraction. Add a null check there.

Discord also caches DM permissions weirdly. I’ve seen users change their settings but Discord doesn’t update the bot’s access right away. The 50007 error can stick around for hours even after they fix their privacy settings.

For debugging, try creating the DM channel first without sending a message. If UserChannelCreate works but ChannelMessageSend fails, you’ll know it’s a message restriction rather than a channel problem. This helps figure out if it’s permissions or content filtering blocking you.

Had this exact problem building a moderation bot last month. Your code’s probably fine - Discord blocks DMs based on shared server history and user activity, not just privacy settings.

Newer accounts or users with limited server interaction get blocked more often. If you’re testing with a fresh account that hasn’t been active in your bot’s server, Discord flags it as spam.

Test with an account that’s been active in the server and sent recent messages. Also check if the user muted the server or left/rejoined recently - both trigger stricter DM filtering.

Best workaround I found: add a database check tracking which users successfully received DMs before. Skip DM attempts for users who previously failed. Saves API calls and prevents your bot from looking broken to users who can’t get messages anyway.

The Problem: Your Discord bot is encountering a 403 Forbidden error (code 50007: “Cannot send messages to this user”) when attempting to send direct messages (DMs) to users, even though slash commands work correctly. This usually indicates issues with Discord’s DM restrictions, user privacy settings, or bot permissions. The goal is to understand why DMs fail and implement strategies to handle these restrictions reliably.

TL;DR: The Quick Fix: The HTTP 403 Forbidden error when sending DMs is often due to Discord’s limitations, not a coding error. You must accept that DMs might fail and implement fallbacks. Don’t rely solely on DMs; create an automated system that tries DMs first and then switches to alternative notification methods (ephemeral messages, channel posts, emails, etc.) if a 403 error occurs.

:thinking: Understanding the “Why” (The Root Cause):

Discord has significantly tightened its restrictions on bot-to-user DMs to combat spam. The error code 50007 (“Cannot send messages to this user”) doesn’t always reflect a coding mistake; it frequently indicates that Discord is blocking the DM due to factors beyond your control:

  • User Privacy Settings: The user might have disabled DMs from server members. Even if they allow DMs from everyone, Discord’s algorithms might still block your bot.
  • Account Age and Activity: Newer Discord accounts or those with limited interaction within the server are more likely to have DMs blocked by Discord’s anti-spam measures.
  • Server Relationship: Discord’s algorithms assess the relationship between your bot and the user. If the user hasn’t interacted with your bot or the server recently, DMs are more likely to be blocked.
  • Rate Limits and API Issues: Excessive failed DM attempts can trigger rate limits. Discord’s API itself can also experience issues that temporarily prevent DM delivery.
  • Incorrect User ID: In guild contexts, the interaction.Member object can sometimes return null, leading to issues when extracting the user ID.

:gear: Step-by-Step Guide:

Step 1: Implement DM Fallback Mechanisms: Your core strategy should be to handle the 403 error gracefully and provide alternative notification methods.

// ... existing code ...

try {
    dmChannel, err := s.UserChannelCreate(interaction.Member.User.ID)
    if err != nil {
        // DM failed; handle the error
        if err.Error() == "HTTP 403 Forbidden" {
            // Try alternative notification method (ephemeral message, etc)
            if interaction.ChannelID != "" { // Ensure interaction happened in a channel, not in a DM
                err = s.InteractionRespond(interaction.Interaction, &discordgo.InteractionResponse{
                    Type: discordgo.InteractionResponseChannelMessageWithSource,
                    Data: &discordgo.InteractionResponseData{
                        Content: "I couldn't send you a DM! Check your settings. Here's your message:",
                        Flags: discordgo.MessageFlagsEphemeral, //Important: Ephemeral message
                        Embeds: []*discordgo.MessageEmbed{ //Consider using embeds for better formatting
                            {
                                Description: "This is your private message!",
                            },
                        },
                    },
                })
                if err != nil {
                    log.Println("Failed to respond with ephemeral message:", err)
                }
            } else {
                log.Println("DM failed and cannot send ephemeral message (original message was a DM).")
            }
            return
        }
        //other error, log it
        log.Println("Failed to create DM channel:", err)
        return
    }

    // DM succeeded; send the message
    _, err = s.ChannelMessageSend(dmChannel.ID, "This is your private message!")
    if err != nil {
        log.Println("Failed to send private message:", err)
    }
} catch (error) {
    log.Println("An unexpected error occurred while handling the DM:", error)
}


// ... rest of your code ...

Step 2: Implement Robust Error Handling and Logging: Catch the 403 error specifically and implement alternative communication strategies. Log all errors to a file for debugging and monitoring. This includes both failed DMs and any errors from the fallback methods.

Step 3: Check User IDs Carefully: Before attempting to send a DM, ensure interaction.Member is not null, especially when dealing with slash commands within a server. If interaction.Member is null, you might need to adjust how you fetch the user’s ID based on context.

Step 4: Consider a Retry Mechanism: Implement a retry mechanism with exponential backoff to handle temporary API issues that might cause a 403 error.

:mag: Common Pitfalls & What to Check Next:

  • Discord’s Rate Limits: Monitor your bot’s activity on the Discord Developer Portal for rate limit information. Excessive failed DM attempts can temporarily disable your bot.
  • User Privacy Settings: Educate users on how to configure their Discord privacy settings to allow DMs from server members.
  • Bot Permissions: Verify that your bot has the necessary permissions within the server.
  • Content Filtering: Discord might flag your message content as spam if it contains certain words or phrases. Review your message content.

:speech_balloon: Still running into issues? Share your (sanitized) config files, the exact command you ran, and any other relevant details. The community is here to help!

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