Reputation: 75
I'm working on a discord bot that uses private messages to inform a user if they've been warned by a moderator. While working on this, I discovered that there is an edge case where a bot can't send a message to a user because of their privacy settings. How can I write my code to open a private channel, attempt sending a message, and handle not being able to send it?
Here is the code that sends the message:
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());
}
Upvotes: 2
Views: 1105
Reputation: 6134
You can use a combination of flatMap
and onErrorFlatMap
:
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)
}
Alternatively, you can also use 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")));
}
Upvotes: 3