【问题标题】:What's the best way to handle not being able to send a private message to a user?处理无法向用户发送私人消息的最佳方法是什么?
【发布时间】:2020-08-01 05:11:12
【问题描述】:

我正在开发一个不和谐的机器人,它使用私人消息来通知用户是否已收到版主的警告。在处理此问题时,我发现存在一种边缘情况,即机器人由于其隐私设置而无法向用户发送消息。如何编写代码来打开私人频道、尝试发送消息并处理无法发送的问题?

这是发送消息的代码:

public static void sendNotification(Warning warning, TextChannel alt) {
    User target = jda.getUserById(warning.getuId());
    if(target == null)
        return;
    target.openPrivateChannel().queue(c -> c.sendMessage(WarningUtil.generateWarningMessage(warning)).queue());
}

【问题讨论】:

    标签: java discord-jda


    【解决方案1】:

    您可以使用flatMaponErrorFlatMap 的组合:

    public RestAction<Message> sendMessage(User user, TextChannel context, String content) {
        return user.openPrivateChannel() // RestAction<PrivateChannel>
            .flatMap((channel) -> channel.sendMessage(content)) // RestAction<Message>
            .onErrorFlatMap(CANNOT_SEND_TO_USER::test,
                (error) -> context.sendMessage("Cannot send direct message to " + user.getAsMention())
            ); // RestAction<Message> (must be the same as above)
    }
    

    或者,您也可以使用ErrorHandler

    public static void sendMessage(User user, String content) {
        user.openPrivateChannel()
            .flapMap(channel -> channel.sendMessage(content))
            .queue(null, new ErrorHandler()
                .handle(ErrorResponse.CANNOT_SEND_TO_USER,
                    (ex) -> System.out.println("Cannot send message to user")));
    }
    

    【讨论】:

    • 我最终使用了平面地图,您建议的功能显然已在我的版本中删除,但它为我指明了正确的方向
    • 我认为是相反的,你的版本太旧了,没有得到这个功能,但它是在 4.1.1_135 中添加的
    • 哦,我已经过时了!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2017-06-04
    • 2020-05-31
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    • 2010-10-13
    • 2021-07-22
    • 1970-01-01
    相关资源
    最近更新 更多