[英]What's the best way to handle not being able to send a private message to a user?
我正在开发一个 discord 机器人,该机器人使用私人消息通知用户是否已被版主警告。 在处理此问题时,我发现存在一种边缘情况,即机器人由于其隐私设置而无法向用户发送消息。 如何编写代码来打开私人频道、尝试发送消息并处理无法发送的问题?
这是发送消息的代码:
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());
}
您可以使用flatMap
和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)
}
或者,您也可以使用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")));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.