use of net.dv8tion.jda.api.MessageBuilder in project MantaroBot by Mantaro.
the class PlayerCmds method badges.
@Subscribe
public void badges(CommandRegistry cr) {
final Random r = new Random();
ITreeCommand badgeCommand = cr.register("badges", new TreeCommand(CommandCategory.CURRENCY) {
@Override
public Command defaultTrigger(Context ctx, String mainCommand, String commandName) {
return new SubCommand() {
@Override
protected void call(Context ctx, I18nContext languageContext, String content) {
var optionalArguments = ctx.getOptionalArguments();
content = Utils.replaceArguments(optionalArguments, content, "brief");
// Lambdas strike again.
var contentFinal = content;
ctx.findMember(content, members -> {
var member = CustomFinderUtil.findMemberDefault(contentFinal, members, ctx, ctx.getMember());
if (member == null) {
return;
}
var toLookup = member.getUser();
Player player = ctx.getPlayer(toLookup);
PlayerData playerData = player.getData();
DBUser dbUser = ctx.getDBUser();
if (!optionalArguments.isEmpty() && optionalArguments.containsKey("brief")) {
ctx.sendLocalized("commands.badges.brief_success", member.getEffectiveName(), playerData.getBadges().stream().sorted().map(Badge::getDisplay).collect(Collectors.joining(", ")));
return;
}
var badges = playerData.getBadges();
Collections.sort(badges);
var embed = new EmbedBuilder().setAuthor(String.format(languageContext.get("commands.badges.header"), toLookup.getName())).setColor(ctx.getMemberColor()).setThumbnail(toLookup.getEffectiveAvatarUrl());
List<MessageEmbed.Field> fields = new LinkedList<>();
for (var b : badges) {
// God DAMNIT discord, I want it to look cute, stop trimming my spaces.
fields.add(new MessageEmbed.Field(b.toString(), "**\u2009\u2009\u2009\u2009- " + b.description + "**", false));
}
if (badges.isEmpty()) {
embed.setDescription(languageContext.get("commands.badges.no_badges"));
ctx.send(embed.build());
return;
}
var common = languageContext.get("commands.badges.profile_notice") + languageContext.get("commands.badges.info_notice") + ((r.nextInt(2) == 0 && !dbUser.isPremium() ? languageContext.get("commands.badges.donate_notice") : "\n") + String.format(languageContext.get("commands.badges.total_badges"), badges.size()));
DiscordUtils.sendPaginatedEmbed(ctx, embed, DiscordUtils.divideFields(6, fields), common);
});
}
};
}
@Override
public HelpContent help() {
return new HelpContent.Builder().setDescription("Shows your (or another person)'s badges.").setUsage("If you want to check out the badges of another person just mention them.\n" + "You can use `~>badges -brief` to get a brief versions of the badge showcase.").build();
}
});
badgeCommand.addSubCommand("info", new SubCommand() {
@Override
public String description() {
return "Shows info about a badge.";
}
@Override
protected void call(Context ctx, I18nContext languageContext, String content) {
if (content.isEmpty()) {
ctx.sendLocalized("commands.badges.info.not_specified", EmoteReference.ERROR);
return;
}
var badge = Badge.lookupFromString(content);
if (badge == null || badge == Badge.DJ) {
ctx.sendLocalized("commands.badges.info.not_found", EmoteReference.ERROR);
return;
}
var player = ctx.getPlayer();
var message = new MessageBuilder().setEmbeds(new EmbedBuilder().setAuthor(String.format(languageContext.get("commands.badges.info.header"), badge.display)).setDescription(String.join("\n", EmoteReference.BLUE_SMALL_MARKER + "**" + languageContext.get("general.name") + ":** " + badge.display, EmoteReference.BLUE_SMALL_MARKER + "**" + languageContext.get("general.description") + ":** " + badge.description, EmoteReference.BLUE_SMALL_MARKER + "**" + languageContext.get("commands.badges.info.achieved") + ":** " + player.getData().getBadges().stream().anyMatch(b -> b == badge))).setThumbnail("attachment://icon.png").setColor(Color.CYAN).build()).build();
ctx.getChannel().sendMessage(message).addFile(badge.icon, "icon.png").queue();
}
});
badgeCommand.addSubCommand("list", new SubCommand() {
@Override
public String description() {
return "Lists all the obtainable badges.";
}
@Override
protected void call(Context ctx, I18nContext languageContext, String content) {
var badges = Badge.values();
var builder = new EmbedBuilder().setAuthor(languageContext.get("commands.badges.ls.header"), null, ctx.getAuthor().getEffectiveAvatarUrl()).setColor(Color.PINK).setFooter(languageContext.get("general.requested_by").formatted(ctx.getMember().getEffectiveName()), null);
var player = ctx.getPlayer();
List<MessageEmbed.Field> fields = new LinkedList<>();
for (Badge badge : badges) {
if (!badge.isObtainable()) {
continue;
}
fields.add(new MessageEmbed.Field("%s\u2009\u2009\u2009%s".formatted(badge.unicode, badge.display), badge.getDescription() + "\n" + String.format(languageContext.get("commands.badges.ls.obtained"), player.getData().hasBadge(badge)), false));
}
DiscordUtils.sendPaginatedEmbed(ctx, builder, DiscordUtils.divideFields(7, fields), languageContext.get("commands.badges.ls.desc"));
}
});
badgeCommand.createSubCommandAlias("list", "ls");
badgeCommand.createSubCommandAlias("list", "1ist");
badgeCommand.createSubCommandAlias("list", "Is");
badgeCommand.createSubCommandAlias("list", "is");
badgeCommand.createSubCommandAlias("list", "1s");
cr.registerAlias("badges", "badge");
}
use of net.dv8tion.jda.api.MessageBuilder in project Saber-Bot by notem.
the class ListCommand method action.
@Override
public void action(String prefix, String[] args, MessageReceivedEvent event) {
int index = 0;
Integer entryId = ParsingUtilities.encodeIDToInt(args[index++]);
ScheduleEntry se = Main.getEntryManager().getEntryFromGuild(entryId, event.getGuild().getId());
String titleUrl = se.getTitleUrl() == null ? "https://nnmathe.ws/saber" : se.getTitleUrl();
String title = se.getTitle() + " [" + ParsingUtilities.intToEncodedID(entryId) + "]";
String content = "";
List<String> userFilters = new ArrayList<>();
List<String> roleFilters = new ArrayList<>();
boolean filterByType = false;
Set<String> typeFilters = new HashSet<>();
boolean mobileFlag = false;
boolean IdFlag = false;
for (; index < args.length; index++) {
if (args[index].equalsIgnoreCase("mobile") || args[index].equalsIgnoreCase("m")) {
mobileFlag = true;
continue;
}
if (args[index].equalsIgnoreCase("id") || args[index].equalsIgnoreCase("i")) {
IdFlag = true;
continue;
}
String filterType = args[index].split(":")[0].toLowerCase().trim();
String filterValue = args[index].split(":")[1].trim();
switch(filterType.toLowerCase()) {
case "r":
case "role":
roleFilters.add(filterValue.replace("<@&", "").replace(">", ""));
break;
case "u":
case "user":
userFilters.add(filterValue.replace("<@", "").replace(">", ""));
break;
case "t":
case "type":
filterByType = true;
typeFilters.add(filterValue);
break;
}
}
// maximum number of characters before creating a new message
int lengthCap = 1900;
// maximum number of lines until new message, in mobile mode
int mobileLineCap = 25;
Set<String> uniqueMembers = new HashSet<>();
Map<String, String> options = Main.getScheduleManager().getRSVPOptions(se.getChannelId());
for (String type : options.values()) {
if (!filterByType || typeFilters.contains(type)) {
content += "**\"" + type + "\"\n======================**\n";
Set<String> members = se.getRsvpMembersOfType(type);
for (String id : members) {
// if the message is nearing maximum length, or if in mobile mode and the max lines have been reached
if (content.length() > lengthCap || (mobileFlag && StringUtils.countMatches(content, "\n") > mobileLineCap)) {
// build and send the embedded message object
Message message = (new MessageBuilder()).setEmbed((new EmbedBuilder()).setDescription(content).setTitle(title, titleUrl).build()).build();
MessageUtilities.sendMsg(message, event.getChannel(), null);
// clear the content sting
content = "*continued. . .* \n";
}
if (id.matches("\\d+")) {
// cases in which the id is most likely a valid discord user's ID
Member member = event.getGuild().getMemberById(id);
if (checkMember(member, userFilters, roleFilters)) {
// if the user is still a member of the guild, add to the list
uniqueMembers.add(member.getUser().getId());
content += this.getNameDisplay(mobileFlag, IdFlag, member);
} else // otherwise, remove the member from the event and update
{
Set<String> tmp = se.getRsvpMembersOfType(type);
tmp.remove(id);
se.getRsvpMembersOfType(type).remove(id);
Main.getEntryManager().updateEntry(se, false);
}
} else {
// handles cases in which a non-discord user was added by an admin
uniqueMembers.add(id);
content += "*" + id + "*\n";
}
}
}
content += "\n";
}
if (!filterByType || typeFilters.contains("no-input")) {
// generate a list of all members of the guild who pass the filter and map to their ID
List<String> noInput = event.getGuild().getMembers().stream().filter(member -> checkMember(member, userFilters, roleFilters)).map(member -> member.getUser().getId()).collect(Collectors.toList());
for (String type : options.values()) {
noInput.removeAll(se.getRsvpMembersOfType(type));
}
content += "**No input\n======================\n**";
if (!filterByType & noInput.size() > 10) {
content += " Too many users to show: " + noInput.size() + " users with no rsvp\n";
} else
for (String id : noInput) {
if (content.length() > lengthCap || (mobileFlag && StringUtils.countMatches(content, "\n") > mobileLineCap)) {
// build and send the embedded message object
Message message = (new MessageBuilder()).setEmbed((new EmbedBuilder()).setDescription(content).setTitle(title, titleUrl).build()).build();
MessageUtilities.sendMsg(message, event.getChannel(), null);
// clear the content sting
content = "*continued. . .* \n";
}
Member member = event.getGuild().getMemberById(id);
content += this.getNameDisplay(mobileFlag, IdFlag, member);
}
}
String footer = uniqueMembers.size() + " unique member(s) appear in this search";
// build and send the embedded message object
Message message = (new MessageBuilder()).setEmbed((new EmbedBuilder()).setDescription(content).setTitle(title, titleUrl).setFooter(footer, null).build()).build();
MessageUtilities.sendMsg(message, event.getChannel(), null);
}
use of net.dv8tion.jda.api.MessageBuilder in project Saber-Bot by notem.
the class MessageGenerator method generate.
/**
* Primary method which generates a complete Discord message object for the event
* @param se (ScheduleEntry) to generate a message display
* @return the message to be used to display the event in it's associated Discord channel
*/
public static Message generate(ScheduleEntry se) {
if (se == null)
return new MessageBuilder().build();
// prepare title
String titleUrl = (se.getTitleUrl() != null && VerifyUtilities.verifyUrl(se.getTitleUrl())) ? se.getTitleUrl() : DEFAULT_URL;
String titleImage = ICON_URL;
// generate the footer
String footerStr = generateFooter(se);
// determine the embed color
Color embedColor = generateColor(se);
// generate the body of the embed
String bodyContent;
String style = Main.getScheduleManager().getStyle(se.getChannelId());
if (style.equalsIgnoreCase("narrow")) {
bodyContent = generateBodyNarrow(se);
} else {
bodyContent = generateBodyFull(se);
}
// prepare the embed
EmbedBuilder builder = new EmbedBuilder();
builder.setDescription(bodyContent.substring(0, Math.min(bodyContent.length(), 2048))).setColor(embedColor).setAuthor(se.getTitle(), // , titleImage)
titleUrl).setFooter(footerStr.substring(0, Math.min(footerStr.length(), 2048)), null);
// add the image and thumbnail url links (if valid)
if (se.getImageUrl() != null && VerifyUtilities.verifyUrl(se.getImageUrl())) {
builder.setImage(se.getImageUrl());
}
if (se.getThumbnailUrl() != null && VerifyUtilities.verifyUrl(se.getThumbnailUrl())) {
builder.setThumbnail(se.getThumbnailUrl());
}
MessageBuilder msgBuilder = new MessageBuilder().setEmbed(builder.build());
if (se.getNonEmbededText() != null) {
String fulltext = ParsingUtilities.processText(se.getNonEmbededText(), se, true);
msgBuilder.setContent(fulltext);
}
// return the fully constructed message
return msgBuilder.build();
}
use of net.dv8tion.jda.api.MessageBuilder in project MantaroBot by Mantaro.
the class TrackScheduler method onTrackStart.
private void onTrackStart() {
if (currentTrack == null) {
onStop();
return;
}
final var guild = MantaroBot.getInstance().getShardManager().getGuildById(guildId);
final var dbGuild = MantaroData.db().getGuild(guildId);
if (dbGuild.getData().isMusicAnnounce() && requestedChannel != 0 && getRequestedTextChannel() != null) {
var voiceState = getRequestedTextChannel().getGuild().getSelfMember().getVoiceState();
// What kind of massive meme is this? part 2
if (voiceState == null) {
this.getAudioPlayer().destroy();
return;
}
final var voiceChannel = voiceState.getChannel();
// It's called mantaro
if (voiceChannel == null) {
this.getAudioPlayer().destroy();
return;
}
if (getRequestedTextChannel().canTalk() && repeatMode != Repeat.SONG) {
var information = currentTrack.getInfo();
var title = information.title;
var trackLength = information.length;
Member user = null;
if (getCurrentTrack().getUserData() != null && guild != null) {
// Retrieve member instead of user, so it gets cached.
try {
user = guild.retrieveMemberById(String.valueOf(getCurrentTrack().getUserData()), false).complete();
} catch (Exception ignored) {
}
}
// Avoid massive spam of "now playing..." when repeating songs.
if (lastMessageSentAt == 0 || lastMessageSentAt + 10000 < System.currentTimeMillis()) {
getRequestedTextChannel().sendMessage(new MessageBuilder().append(String.format(language.get("commands.music_general.np_message"), "\uD83D\uDCE3", title, AudioCmdUtils.getDurationMinutes(trackLength), voiceChannel.getName(), user != null ? String.format(language.get("general.requested_by"), String.format("**%s**", user.getUser().getAsTag())) : "")).build()).queue(message -> {
if (getRequestedTextChannel() != null) {
lastMessageSentAt = System.currentTimeMillis();
message.delete().queueAfter(90, TimeUnit.SECONDS, scheduledExecutor);
}
});
}
}
}
}
use of net.dv8tion.jda.api.MessageBuilder in project Saber-Bot by notem.
the class SchedulesCommand method action.
@Override
public void action(String prefix, String[] args, MessageReceivedEvent event) {
Guild guild = event.getGuild();
List<String> scheduleIds = Main.getScheduleManager().getSchedulesForGuild(guild.getId());
// build output main body
StringBuilder content = new StringBuilder();
for (String sId : scheduleIds) {
content.append("<#").append(sId).append("> - has ").append(Main.getEntryManager().getEntriesFromChannel(sId).size()).append(" events\n");
}
// title for embed
String title = "Schedules on " + guild.getName();
// footer for embed
String footer = scheduleIds.size() + " schedule(s)";
// build embed
MessageEmbed embed = new EmbedBuilder().setDescription(content.toString()).setTitle(title).setFooter(footer, null).build();
// build message
Message message = new MessageBuilder().setEmbed(embed).build();
// send message
MessageUtilities.sendMsg(message, event.getTextChannel(), null);
}
Aggregations