use of net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent in project Emolga by TecToast.
the class NominateCommand method process.
@Override
public void process(PrivateMessageReceivedEvent e) {
JSONObject nds = getEmolgaJSON().getJSONObject("drafts").getJSONObject("NDS");
JSONObject nom = nds.getJSONObject("nominations");
int currentDay = nom.getInt("currentDay");
if (!nom.has(currentDay))
nom.put(currentDay, new JSONObject());
if (nom.getJSONObject(String.valueOf(currentDay)).has(e.getAuthor().getId())) {
e.getChannel().sendMessage("Du hast für diesen Spieltag dein Team bereits nominiert!").queue();
return;
}
JSONArray arr = nds.getJSONObject("picks").getJSONArray(e.getAuthor().getId());
List<JSONObject> list = arr.toJSONList();
list.sort(tiercomparator);
List<String> b = list.stream().map(o -> o.getString("name")).collect(Collectors.toList());
Nominate n = new Nominate(list);
e.getChannel().sendMessageEmbeds(new EmbedBuilder().setTitle("Nominierungen").setColor(Color.CYAN).setDescription(n.generateDescription()).build()).setActionRows(addAndReturn(getActionRows(b, s -> Button.primary("nominate;" + s, s)), ActionRow.of(Button.success("nominate;FINISH", Emoji.fromUnicode("✅"))))).queue(m -> nominateButtons.put(m.getIdLong(), n));
}
use of net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent in project aiode by robinfriedli.
the class ConnectCommand method awaitPrivateMessage.
private void awaitPrivateMessage(ClientSession clientSession, long userId, Guild guild, User user, int attemptNumber) {
CompletableFuture<PrivateMessageReceivedEvent> futurePrivateMessage = getManager().getEventWaiter().awaitEvent(PrivateMessageReceivedEvent.class, event -> event.getAuthor().getIdLong() == userId).orTimeout(1, TimeUnit.MINUTES);
CompletableFutures.handleWhenComplete(futurePrivateMessage, (event, error) -> {
try {
MessageService messageService = getMessageService();
if (event != null) {
String token = event.getMessage().getContentRaw();
UUID sessionId;
try {
sessionId = UUID.fromString(token);
} catch (IllegalArgumentException e) {
String message = String.format("'%s' is not a valid token. ", token);
if (attemptNumber >= RETRY_COUNT) {
messageService.sendError(message + "Maximum retry count reached.", user);
} else {
messageService.sendError(message + String.format("Attempt %d / %d", attemptNumber, RETRY_COUNT), user);
awaitPrivateMessage(clientSession, userId, guild, user, attemptNumber + 1);
}
return;
}
QueryBuilderFactory queryBuilderFactory = getQueryBuilderFactory();
MutexSyncMode<UUID> mutexSyncMode = new MutexSyncMode<>(sessionId, TOKEN_SYNC);
HibernateInvoker.create().invokeConsumer(Mode.create().with(mutexSyncMode), session -> {
Optional<GeneratedToken> foundGeneratedToken = queryBuilderFactory.find(GeneratedToken.class).where((cb, root) -> cb.equal(root.get("token"), sessionId)).build(session).uniqueResultOptional();
if (foundGeneratedToken.isEmpty()) {
String message = "Token is invalid. Make sure it matches the token generated by your web client. Tokens may not be shared or reused. ";
if (attemptNumber >= RETRY_COUNT) {
messageService.sendError(message + "Maximum retry count reached.", user);
} else {
messageService.sendError(message + String.format("Attempt %d / %d", attemptNumber, RETRY_COUNT), user);
awaitPrivateMessage(clientSession, userId, guild, user, attemptNumber + 1);
}
return;
}
GeneratedToken generatedToken = foundGeneratedToken.get();
Long existingSessionCount = queryBuilderFactory.select(ClientSession.class, (from, cb) -> cb.count(from.get("pk")), Long.class).where((cb, root) -> cb.equal(root.get("sessionId"), sessionId)).build(session).uniqueResult();
if (existingSessionCount > 0) {
messageService.sendError("A session with this ID already exists. You are probably already signed in, try reloading your web client. If your client still can't sign in try generating a new token using the reload button and then try the connect command again.", user);
return;
}
clientSession.setLastRefresh(LocalDateTime.now());
clientSession.setSessionId(sessionId);
clientSession.setIpAddress(generatedToken.getIp());
session.persist(clientSession);
session.delete(generatedToken);
messageService.sendSuccess(String.format("Okay, a session connected to guild '%s' " + "has been prepared. You may return to the web client to complete the setup. The client should " + "connect automatically, else you can continue manually.", guild.getName()), user);
});
} else if (error != null) {
if (error instanceof TimeoutException) {
messageService.sendError("Your connection attempt timed out", user);
} else {
EmbedBuilder exceptionEmbed = ExceptionUtils.buildErrorEmbed(error);
exceptionEmbed.setTitle("Exception");
exceptionEmbed.setDescription("There has been an error awaiting private message to establish connection");
LoggerFactory.getLogger(getClass()).error("unexpected exception while awaiting private message", error);
sendMessage(exceptionEmbed.build());
}
setFailed(true);
}
} finally {
USERS_WITH_PENDING_CONNECTION.remove(userId);
}
}, e -> {
LoggerFactory.getLogger(getClass()).error("Unexpected error in whenComplete of event handler", e);
EmbedBuilder embedBuilder = ExceptionUtils.buildErrorEmbed(e).setTitle("Exception").setDescription("There has been an unexpected exception while trying to establish the connection");
getMessageService().send(embedBuilder.build(), user);
});
}
use of net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent in project ExciteBot by TheGameCommunity.
the class Commands method handleCommand.
public void handleCommand(PrivateMessageReceivedEvent e) {
MessageContext<PrivateMessageReceivedEvent> context = new MessageContext<PrivateMessageReceivedEvent>(e);
String message = e.getMessage().getContentRaw();
try {
DiscordUser sender = DiscordUser.getDiscordUser(ConsoleContext.INSTANCE, e.getAuthor().getIdLong());
if (!sender.isBanned()) {
if (!sender.isBanned()) {
CommandAudit.addCommandAudit(context, message);
this.dispatcher.execute(message, context);
}
}
} catch (CommandSyntaxException ex) {
context.sendMessage(ex.getMessage());
} catch (Throwable t) {
context.sendMessage(StacktraceUtil.getStackTrace(t));
if (!context.isConsoleMessage()) {
t.printStackTrace();
}
if (t instanceof Error) {
throw t;
}
}
}
use of net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent in project Robertify-Bot by bombies.
the class ReportsEvents method onPrivateMessageReceived.
@Override
public void onPrivateMessageReceived(@NotNull PrivateMessageReceivedEvent event) {
if (!ReportsCommand.activeReports.contains(event.getAuthor().getIdLong()))
return;
final var user = event.getAuthor();
final var channel = event.getChannel();
try {
final var response = event.getMessage().getContentRaw();
if (response.chars().count() > 1024) {
channel.sendMessageEmbeds(EmbedUtils.embedMessageWithTitle("Bug reports", "Your response cannot be more than 1024 characters!").build()).queue();
return;
}
final var nextPage = getNextPage(user.getIdLong());
var responseList = responses.get(user.getIdLong());
responseList.add(response);
responses.put(user.getIdLong(), responseList);
event.getChannel().sendMessageEmbeds(nextPage.getEmbed()).queue();
} catch (IllegalStateException e) {
var responseList = responses.get(user.getIdLong());
responseList.add(event.getMessage().getContentRaw());
responses.put(user.getIdLong(), responseList);
final var collectedResponses = responses.get(user.getIdLong());
responses.remove(user.getIdLong());
final var config = BotBDCache.getInstance();
final var openedReportsChannel = Robertify.shardManager.getTextChannelById(config.getReportsID(BotBDCache.ReportsConfigField.CHANNEL));
if (openedReportsChannel == null) {
channel.sendMessageEmbeds(EmbedUtils.embedMessage("Could not send your report!\n" + "Please contact a developer in our [support server](https://discord.gg/VbjmtfJDvU).").build()).queue();
return;
}
openedReportsChannel.sendMessageEmbeds(new EmbedBuilder().setTitle("Bug Report from " + user.getName()).setThumbnail(user.getEffectiveAvatarUrl()).addField("Reporter", user.getAsMention(), false).addField("Command/Feature Origin", collectedResponses.get(0), false).addField("Reproduction of Bug", collectedResponses.get(1), false).addField("Additional Comments", collectedResponses.get(2), false).setColor(new Color(255, 106, 0)).build()).queue(success -> {
ReportsCommand.activeReports.remove(user.getIdLong());
channel.sendMessageEmbeds(EmbedUtils.embedMessageWithTitle("Bug Reports", "You have submitted your bug report. \nThank you for answering all the questions!" + " Be on the lookout for a response from us!").build()).queue();
currentQuestionForUser.remove(user.getIdLong());
});
}
}
Aggregations