use of net.dv8tion.jda.core.entities.Message in project MantaroBot by Mantaro.
the class QuoteCmd method quote.
@Command
public static void quote(CommandRegistry cr) {
cr.register("quote", new SimpleCommand(Category.MISC) {
@Override
protected void call(GuildMessageReceivedEvent event, String content, String[] args) {
if (content.isEmpty()) {
onHelp(event);
return;
}
String action = args[0];
String phrase = content.replace(action + " ", "");
Guild guild = event.getGuild();
ManagedDatabase db = MantaroData.db();
EmbedBuilder builder = new EmbedBuilder();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
List<Message> messageHistory;
try {
messageHistory = event.getChannel().getHistory().retrievePast(100).complete();
} catch (Exception e) {
if (e instanceof PermissionException) {
event.getChannel().sendMessage(EmoteReference.CRYING + "I don't have permission to do this :<").queue();
return;
}
event.getChannel().sendMessage(EmoteReference.ERROR + "It seems like discord is on fire, as my" + " " + "request to retrieve message history was denied" + "with the error `" + e.getClass().getSimpleName() + "`").queue();
log.warn("Shit exploded on Discord's backend. <@155867458203287552>", e);
return;
}
if (action.equals("addfrom")) {
Message message = messageHistory.stream().filter(msg -> msg.getContent().toLowerCase().contains(phrase.toLowerCase()) && !msg.getContent().startsWith(db.getGuild(guild).getData().getGuildCustomPrefix() == null ? MantaroData.config().get().getPrefix() : db.getGuild(guild).getData().getGuildCustomPrefix()) && !msg.getContent().startsWith(MantaroData.config().get().getPrefix())).findFirst().orElse(null);
if (message == null) {
event.getChannel().sendMessage(EmoteReference.ERROR + "I couldn't find a message matching the specified search" + " criteria. Please try again with a more specific query.").queue();
return;
}
TextChannel channel = guild.getTextChannelById(message.getChannel().getId());
Quote quote = Quote.of(guild.getMember(message.getAuthor()), channel, message);
db.getQuotes(guild).add(quote);
event.getChannel().sendMessage(buildQuoteEmbed(dateFormat, builder, quote)).queue();
quote.saveAsync();
return;
}
if (action.equals("random")) {
try {
Quote quote = CollectionUtils.random(db.getQuotes(event.getGuild()));
event.getChannel().sendMessage(buildQuoteEmbed(dateFormat, builder, quote)).queue();
} catch (Exception e) {
event.getChannel().sendMessage(EmoteReference.ERROR + "This server has no set quotes!").queue();
}
return;
}
if (action.equals("readfrom")) {
try {
List<Quote> quotes = db.getQuotes(guild);
for (int i2 = 0; i2 < quotes.size(); i2++) {
if (quotes.get(i2).getContent().contains(phrase)) {
Quote quote = quotes.get(i2);
event.getChannel().sendMessage(buildQuoteEmbed(dateFormat, builder, quote)).queue();
break;
}
}
} catch (Exception e) {
event.getChannel().sendMessage(EmoteReference.ERROR + "I didn't find any quotes! (no quotes match the criteria).").queue();
}
return;
}
if (action.equals("removefrom")) {
try {
List<Quote> quotes = db.getQuotes(guild);
for (int i2 = 0; i2 < quotes.size(); i2++) {
if (quotes.get(i2).getContent().contains(phrase)) {
Quote quote = quotes.get(i2);
db.getQuotes(guild).remove(i2);
quote.saveAsync();
event.getChannel().sendMessage(EmoteReference.CORRECT + "Removed quote with content: " + quote.getContent()).queue();
break;
}
}
} catch (Exception e) {
event.getChannel().sendMessage(EmoteReference.ERROR + "No quotes match the criteria.").queue();
}
}
}
@Override
public MessageEmbed help(GuildMessageReceivedEvent event) {
return helpEmbed(event, "Quote command").setDescription("**Quotes a message by search term.**").addField("Usage", "`~>quote addfrom <phrase>`- **Add a quote with the content defined by the specified number. For example, providing 1 will quote " + "the last message.**\n" + "`~>quote removefrom <phrase>` - **Remove a quote based on your text query.**\n" + "`~>quote readfrom <phrase>` - **Search for the first quote which matches your search criteria and prints " + "it.**\n" + "`~>quote random` - **Get a random quote.** \n", false).addField("Parameters", "`phrase` - A part of the quote phrase.", false).setColor(Color.DARK_GRAY).build();
}
});
}
use of net.dv8tion.jda.core.entities.Message in project MantaroBot by Mantaro.
the class ReactionOperations method createOrGet.
public static Future<Void> createOrGet(Message message, long timeoutSeconds, ReactionOperation operation, String... defaultReactions) {
if (!message.getAuthor().equals(message.getJDA().getSelfUser()))
throw new IllegalArgumentException("Must provide a message sent by the bot");
Future<Void> f = createOrGet(message.getIdLong(), timeoutSeconds, operation);
if (defaultReactions.length > 0) {
AtomicInteger index = new AtomicInteger();
AtomicReference<Consumer<Void>> c = new AtomicReference<>();
Consumer<Throwable> ignore = (t) -> {
};
c.set(ignored -> {
int i = index.incrementAndGet();
if (i < defaultReactions.length) {
message.addReaction(defaultReactions[i]).queue(c.get(), ignore);
}
});
message.addReaction(defaultReactions[0]).queue(c.get(), ignore);
}
return f;
}
use of net.dv8tion.jda.core.entities.Message in project MantaroBot by Mantaro.
the class DiscordUtils method list.
public static Future<Void> list(GuildMessageReceivedEvent event, int timeoutSeconds, boolean canEveryoneUse, IntIntObjectFunction<EmbedBuilder> supplier, String... parts) {
if (parts.length == 0)
return null;
List<MessageEmbed> embeds = new ArrayList<>();
StringBuilder sb = new StringBuilder();
int total;
{
int t = 0;
int c = 0;
for (String s : parts) {
if (s.length() + c + 1 > MessageEmbed.TEXT_MAX_LENGTH) {
t++;
c = 0;
}
c += s.length() + 1;
}
if (c > 0)
t++;
total = t;
}
for (String s : parts) {
int l = s.length() + 1;
if (l > MessageEmbed.TEXT_MAX_LENGTH)
throw new IllegalArgumentException("Length for one of the pages is greater than the maximum");
if (sb.length() + l > MessageEmbed.TEXT_MAX_LENGTH) {
EmbedBuilder eb = supplier.apply(embeds.size() + 1, total);
eb.setDescription(sb.toString());
embeds.add(eb.build());
sb = new StringBuilder();
}
sb.append(s).append('\n');
}
if (sb.length() > 0) {
EmbedBuilder eb = supplier.apply(embeds.size() + 1, total);
eb.setDescription(sb.toString());
embeds.add(eb.build());
}
AtomicInteger index = new AtomicInteger();
Message m = event.getChannel().sendMessage(embeds.get(0)).complete();
return ReactionOperations.create(m, timeoutSeconds, (e) -> {
if (!canEveryoneUse && e.getUser().getIdLong() != event.getAuthor().getIdLong())
return false;
switch(e.getReactionEmote().getName()) {
case //left arrow
"⬅":
if (index.get() == 0)
break;
m.editMessage(embeds.get(index.decrementAndGet())).queue();
break;
case //right arrow
"➡":
if (index.get() + 1 >= embeds.size())
break;
m.editMessage(embeds.get(index.incrementAndGet())).queue();
break;
}
if (event.getGuild().getSelfMember().hasPermission(e.getTextChannel(), Permission.MESSAGE_MANAGE)) {
e.getReaction().removeReaction(e.getUser()).queue();
}
return false;
}, "⬅", "➡");
}
use of net.dv8tion.jda.core.entities.Message in project MantaroBot by Mantaro.
the class DiscordUtils method listUpdatable.
public static Future<Void> listUpdatable(GuildMessageReceivedEvent event, int timeoutSeconds, boolean canEveryoneUse, IntIntObjectFunction<EmbedBuilder> supplier, String... parts) {
if (parts.length == 0)
return null;
List<StringBuilder> embeds = new ArrayList<>();
AtomicInteger index = new AtomicInteger();
StringBuilder sb = new StringBuilder();
int total;
{
int t = 0;
int c = 0;
for (String s : parts) {
if (s.length() + c + 1 > MessageEmbed.TEXT_MAX_LENGTH) {
t++;
c = 0;
}
c += s.length() + 1;
}
if (c > 0)
t++;
total = t;
}
for (String s : parts) {
int l = s.length() + 1;
if (l > MessageEmbed.TEXT_MAX_LENGTH)
throw new IllegalArgumentException("Length for one of the pages is greater than the maximum");
if (sb.length() + l > MessageEmbed.TEXT_MAX_LENGTH) {
embeds.add(sb);
sb = new StringBuilder();
}
sb.append(s).append('\n');
}
if (sb.length() > 0) {
embeds.add(sb);
}
Message m = event.getChannel().sendMessage(supplier.apply(1, total).setDescription(embeds.get(0)).build()).complete();
return ReactionOperations.create(m, timeoutSeconds, (e) -> {
if (!canEveryoneUse && e.getUser().getIdLong() != event.getAuthor().getIdLong())
return false;
switch(e.getReactionEmote().getName()) {
case "⬅":
{
//left arrow
if (index.get() == 0)
break;
int i = index.decrementAndGet();
m.editMessage(supplier.apply(i + 1, total).setDescription(embeds.get(i)).build()).queue();
}
break;
case "➡":
{
//right arrow
if (index.get() + 1 >= embeds.size())
break;
int i = index.incrementAndGet();
m.editMessage(supplier.apply(i + 1, total).setDescription(embeds.get(i)).build()).queue();
}
break;
}
if (event.getGuild().getSelfMember().hasPermission(e.getTextChannel(), Permission.MESSAGE_MANAGE)) {
e.getReaction().removeReaction(e.getUser()).queue();
}
return false;
}, "⬅", "➡");
}
use of net.dv8tion.jda.core.entities.Message in project Ardent by adamint.
the class Tinder method setupSubcommands.
@Override
public void setupSubcommands() throws Exception {
subcommands.add(new Subcommand("Match yourself with someone in the server!", "matchme", "matchme") {
@Override
public void onCall(Guild guild, MessageChannel channel, User user, Message message, String[] args) throws Exception {
ArrayList<TinderMatch> matches = queryAsArrayList(TinderMatch.class, r.table("tinder_matches").filter(row -> row.g("user_id").eq(user.getId())).run(connection));
User potentialMatch = getPotentialMatch(user, guild, matches);
EmbedBuilder builder = MessageUtils.getDefaultEmbed(user);
String matchMe = "Match me | Tinder";
builder.setAuthor(matchMe, getShard().url, getShard().bot.getAvatarUrl());
builder.setThumbnail(potentialMatch.getAvatarUrl());
StringBuilder description = new StringBuilder();
description.append("**" + matchMe + "**");
description.append("\nTheir name: " + UserUtils.getNameWithDiscriminator(potentialMatch.getId()));
description.append("Swipe right (rightreaction) to connect with this person, or swipe left (left reaction) to pass them " + "by\nType /tinder connect to connect with the people you've swiped right on");
Message sent = sendEmbed(builder.setDescription(description.toString()), channel, user, ":arrow_left:", ":arrow_right:");
interactiveReaction(channel, sent, user, 15, messageReaction -> {
String name = messageReaction.getEmote().getName();
if (name != null) {
if (name.equals("➡")) {
r.table("tinder_matches").insert(r.json(gson.toJson(new TinderMatch(user.getId(), potentialMatch.getId(), true)))).run(connection);
sendEditedTranslation("You swiped right on {0}! Connect with them using /tinder connect", user, channel, potentialMatch.getName());
} else if (name.equals("⬅")) {
r.table("tinder_matches").insert(r.json(gson.toJson(new TinderMatch(user.getId(), potentialMatch.getId(), false)))).run(connection);
sendEditedTranslation("You swiped right on {0} - Don't worry, you can find better!", user, channel, potentialMatch.getName());
} else
sendTranslatedMessage("You reacted with an unexpected emoji :thinking:", channel, user);
}
});
}
});
subcommands.add(new Subcommand("Connect with the people you've swiped right on", "connect", "connect") {
@Override
public void onCall(Guild guild, MessageChannel channel, User user, Message message, String[] args) throws Exception {
String yourMatches = "Discord Tinder | Your Matches";
String swipedRightOnYou = "Swiped right on you";
EmbedBuilder builder = MessageUtils.getDefaultEmbed(user);
builder.setAuthor(yourMatches, getShard().url, getShard().bot.getAvatarUrl());
builder.setThumbnail(user.getAvatarUrl());
StringBuilder description = new StringBuilder();
description.append("**" + yourMatches + "**");
ArrayList<TinderMatch> matches = queryAsArrayList(TinderMatch.class, r.table("tinder_matches").filter(r.hashMap("user_id", user.getId()).with("swipedRight", true)).run(connection));
if (matches.size() == 0) {
description.append("\nYou don't have any connections :frowning:");
} else {
for (int i = 0; i < matches.size(); i++) {
String swipedRightWithId = matches.get(i).getPerson_id();
boolean mutual = swipedRightWith(user.getId(), swipedRightWithId);
String yesNo;
if (mutual)
yesNo = EmojiParser.parseToUnicode(":white_check_mark:");
else
yesNo = EmojiParser.parseToAliases(":x:");
description.append("\n#" + (i + 1) + ": " + UserUtils.getNameWithDiscriminator(swipedRightWithId) + " | " + swipedRightOnYou + ": " + yesNo);
}
}
description.append("\n\nUse /tinder message [number on connection list] to message that person. However, they must have " + "swiped right on you as well to be able to contact them");
sendEmbed(builder.setDescription(description), channel, user);
}
});
subcommands.add(new Subcommand("Message one of your mutual connections!", "message [number in connection list]", "message") {
@Override
public void onCall(Guild guild, MessageChannel channel, User user, Message message, String[] args) throws Exception {
if (args.length == 2) {
sendTranslatedMessage("Usage: /tinder message [person's number in /tinder connect] [message here]", channel, user);
return;
}
if (message.getRawContent().split(" ").length == 3) {
sendTranslatedMessage("You need to include a message to send that person!", channel, user);
return;
}
try {
int number = Integer.parseInt(args[2]) - 1;
if (number < 0)
sendTranslatedMessage("Usage: /tinder message [person's number in /tinder connect] [message here]", channel, user);
else {
ArrayList<TinderMatch> matches = queryAsArrayList(TinderMatch.class, r.table("tinder_matches").filter(r.hashMap("user_id", user.getId()).with("swipedRight", true)).run(connection));
if (number >= matches.size()) {
sendTranslatedMessage("Sorry, but you don't have this many matches!", channel, user);
return;
}
TinderMatch selected = matches.get(number);
if (!swipedRightWith(user.getId(), selected.getPerson_id())) {
sendTranslatedMessage("That person hasn't swiped right on you!", channel, user);
return;
}
User toMessage = UserUtils.getUserById(selected.getPerson_id());
try {
toMessage.openPrivateChannel().queue(privateChannel -> privateChannel.sendMessage("One of your Tinder " + "matches, **" + UserUtils.getNameWithDiscriminator(user.getId()) + "**, sent you " + "a message!\n\n**" + user.getName() + "**: " + replace(message.getRawContent(), 3)).queue());
if (!sentTo.contains(toMessage.getId())) {
toMessage.openPrivateChannel().queue(privateChannel -> {
privateChannel.sendMessage("To stop receiving messages from this person, remove them from your match " + "list with /tinder remove [number on the /tinder connect list]\n" + "\n" + "To send a message back to this person, type /tinder message [number on your /tinder connect " + "list] [message here] in a server - meet other tinder savvy people on the Ardent guild (where" + " we have a dedicated Tinder channel)! - https://discordapp.com/invite/rfGSxNA").queue();
sentTo.add(toMessage.getId());
});
}
sendTranslatedMessage("Ok! I sent that person your message :wink:", channel, user);
} catch (Exception e) {
sendTranslatedMessage("I was unable to message that person :frowning:", channel, user);
}
}
} catch (NumberFormatException e) {
sendTranslatedMessage("Usage: /tinder message [person's number in /tinder connect] [message here]", channel, user);
}
}
});
subcommands.add(new Subcommand("Remove one of your connections", "remove [number in connection list]", "remove") {
@Override
public void onCall(Guild guild, MessageChannel channel, User user, Message message, String[] args) throws Exception {
if (args.length == 2) {
sendTranslatedMessage("Usage: /tinder remove [person's number in /tinder connect]", channel, user);
return;
}
try {
int number = Integer.parseInt(args[2]) - 1;
if (number < 0)
sendTranslatedMessage("Usage: /tinder remove [person's number in /tinder connect]", channel, user);
else {
ArrayList<TinderMatch> matches = queryAsArrayList(TinderMatch.class, r.table("tinder_matches").filter(r.hashMap("user_id", user.getId()).with("swipedRight", true)).run(connection));
if (number >= matches.size()) {
sendTranslatedMessage("Sorry, but you don't have this many matches!", channel, user);
return;
}
TinderMatch selected = matches.get(number);
r.table("tinder_matches").filter(r.hashMap("user_id", user.getId()).with("person_id", selected.getPerson_id())).delete().run(connection);
sendTranslatedMessage(":ok_hand: Removed that person from your connection list", channel, user);
}
} catch (NumberFormatException e) {
sendTranslatedMessage("Usage: /tinder remove [person's number in /tinder connect]", channel, user);
}
}
});
}
Aggregations