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

JDA 5.0.0机器人如何处理带<@!ID>格式的Discord用户ID?

JDA 5.0.0处理用户提及格式ID的内置方案

JDA 5.0.0自带了专门处理用户提及格式的工具,不用手动去除符号。你可以用UserSnowflake.fromMention(String mention)方法解析<@!用户ID>或<@用户ID>这类格式的字符串,它会自动提取里面的纯数字Snowflake ID。

修改后的代码示例

private void sendBotMessageToUser(String textresult) {
    String resUser = model.getUserID();
    try {
        // 解析提及格式的用户ID
        UserSnowflake userSnowflake = UserSnowflake.fromMention(resUser);
        User sendMessageToUser = api.getUserById(userSnowflake.getIdLong());
        if (sendMessageToUser != null) {
            PrivateChannel privateChannel = sendMessageToUser.openPrivateChannel().complete();
            privateChannel.sendMessage(textresult).queue();
        }
    } catch (IllegalArgumentException e) {
        // 处理无效的提及格式或非法ID
        System.err.println("无效的用户提及格式:" + resUser);
        e.printStackTrace();
    }
}

注意事项

  • UserSnowflake.fromMention()能兼容两种用户提及格式:普通用户提及<@123456>和带昵称的用户提及<@!123456>。
  • 如果传入的字符串不是有效的用户提及格式,方法会抛出IllegalArgumentException,建议加上异常处理,避免程序因为非法输入崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 06:40:29