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

Discord4J getContent()方法返回空字符串问题求助

问题分析与解决建议

你的核心问题是Discord4J无法获取用户发送的消息内容(返回空字符串),但能正常读取机器人自身的消息,这是Discord API的Intent权限限制导致的——Discord v10及以后的API要求明确声明MESSAGE_CONTENT Intent才能获取用户消息的内容,默认不会授予该权限。

解决步骤

1. 在Discord开发者平台开启Message Content Intent

  • 登录Discord开发者门户,进入你的Bot应用页面
  • 切换到「Bot」标签页,找到「Privileged Gateway Intents」区域
  • 开启「Message Content Intent」开关并保存设置

2. 在Discord4J客户端配置中添加对应Intent

在Spring环境下配置DiscordClient Bean时,必须显式指定需要启用的Intent,包括MESSAGE_CONTENT以及你需要的消息事件Intent(如服务器消息GUILD_MESSAGES或私信DIRECT_MESSAGES):

import discord4j.core.DiscordClient;
import discord4j.core.GatewayDiscordClient;
import discord4j.core.intent.Intent;
import discord4j.core.intent.Intents;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DiscordBotConfig {

    @Bean
    public GatewayDiscordClient gatewayDiscordClient(@Value("${discord.bot.token}") String botToken) {
        return DiscordClient.create(botToken)
                .gateway()
                // 启用非特权Intent + 消息内容Intent
                .setEnabledIntents(Intents.nonPrivileged().plus(Intent.MESSAGE_CONTENT))
                .login()
                .block();
    }
}

3. 验证消息监听逻辑

确保你的MessageListener是监听MessageCreateEvent事件,并且正确处理消息对象:

import discord4j.core.event.domain.message.MessageCreateEvent;
import discord4j.core.object.entity.Message;
import reactor.core.publisher.Mono;

@Component
public class MessageListener {

    public Mono<Void> processCommand(MessageCreateEvent event) {
        Message eventMessage = event.getMessage();
        
        System.out.println("Message: " + eventMessage.getContent());
        System.out.println("User: " + eventMessage.getAuthor().map(user -> user.getUsername()).orElse("Unknown"));

        return Mono.just(eventMessage)
                .filter(message -> message.getAuthor().map(user -> !user.isBot()).orElse(false))
                .filter(message -> message.getContent().equalsIgnoreCase("!todo"))
                .flatMap(Message::getChannel)
                .flatMap(channel -> channel.createMessage("Things to do today:\n" +
                                                          " - write a bot\n" +
                                                          " - eat lunch\n" +
                                                          " - play a game"))
                .then();
    }
}

4. 重启机器人测试

完成上述配置后,重启你的Spring Boot应用,再次发送!todo指令,检查控制台输出的消息内容是否正常显示,机器人是否能正确响应。

额外注意事项

  • 如果你的Bot需要处理私信消息,需要额外添加Intent.DIRECT_MESSAGES到启用的Intent列表中
  • 确保你的Bot邀请链接中包含了messages.read权限(生成邀请链接时勾选「Send Messages」等必要权限)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 09:52:40