Discord机器人无法向用户发送私信(DM)的问题求助
Discord机器人无法向用户发送私信(DM)的问题求助
我最近开发了一个Discord机器人,已经把它加到了我自己的服务器里,运行了一段简单的代码,但遇到了一个问题:机器人能在频道里给我回复临时消息,却没法给我发私信,报错信息是:
2025/05/02 11:55:57 Error sending DM: HTTP 403 Forbidden, {"message": "Cannot send messages to this user", "code": 50007}
我和机器人在同一个服务器,而且我已经打开了所有私信相关的设置,有没有大佬能帮我分析下原因?
我的代码如下:
package main import ( "fmt" "log" "github.com/bwmarrin/discordgo" ) var botToken = "xxxx" func main() { // Create a new bot session dg, err := discordgo.New("Bot " + botToken) if err != nil { fmt.Println("Error creating session:", err) return } // Register the command handler dg.AddHandler(commandHandler) // Open the WebSocket connection err = dg.Open() if err != nil { fmt.Println("Error connecting to Discord:", err) return } defer dg.Close() // Register the slash command _, err = dg.ApplicationCommandCreate(dg.State.User.ID, "", &discordgo.ApplicationCommand{ Name: "start", Description: "Greeting message", }) if err != nil { fmt.Println("Error registering command:", err) return } // Bot is ready, waiting for commands fmt.Println("Bot is running!") select {} } // commandHandler handles the slash command func commandHandler(s *discordgo.Session, i *discordgo.InteractionCreate) { // Check that it's an application command if i.Type != discordgo.InteractionApplicationCommand { return } // Respond to the command with an ephemeral message (visible only to the user) err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ Type: discordgo.InteractionResponseChannelMessageWithSource, Data: &discordgo.InteractionResponseData{ Content: "Hello! I can send you a private message.", Flags: 1 << 6, // Ephemeral message (only visible to the user) }, }) if err != nil { log.Println("Error sending command response:", err) return } // Now the bot can send a DM to the user, // since the user has interacted with the bot channel, err := s.UserChannelCreate(i.Member.User.ID) if err != nil { log.Println("Error creating DM channel:", err) return } // Send a direct message to the user _, err = s.ChannelMessageSend(channel.ID, "Here is your private message from the bot!") if err != nil { log.Println("Error sending DM:", err) } }
可能的排查方向:
- 检查用户隐私设置:
再仔细确认Discord的隐私设置:进入「设置」→「隐私与安全」→「服务器隐私默认设置」,确保开启了「允许来自服务器成员的直接消息」;另外右键当前服务器→「隐私设置」,确认没有限制该服务器的成员(包括机器人)向你发送私信。 - 检查机器人是否被屏蔽:
查看你的Discord屏蔽列表,确认有没有不小心把这个机器人加入屏蔽名单,导致它无法给你发消息。 - 验证用户ID正确性:
在commandHandler函数里添加一行log.Println("Target User ID:", i.Member.User.ID),运行后查看输出的ID是否和你自己的Discord用户ID一致,避免因ID错误导致无法创建DM通道。 - 好友权限限制:
如果你的账号设置了「仅好友可以发送直接消息」,即使机器人和你在同一个服务器,也无法给你发私信,这种情况需要你先将机器人添加为好友。 - Discord临时限制:
极少数情况下,新创建的机器人可能会被Discord临时限制发送私信,你可以尝试稍等一段时间再测试,或者检查机器人的账号状态是否正常。
内容来源于stack exchange
相关产品推荐
相关产品推荐

