use of net.dv8tion.jda.api.Permission in project MantaroBot by Mantaro.
the class MessageCmds method prune.
@Subscribe
public void prune(CommandRegistry cr) {
var pruneCmd = cr.register("prune", new TreeCommand(CommandCategory.MODERATION) {
@Override
public Command defaultTrigger(Context context, String mainCommand, String commandName) {
return new SubCommand() {
@Override
protected void call(Context ctx, I18nContext languageContext, String content) {
var args = ctx.getArguments();
if (content.isEmpty()) {
ctx.sendLocalized("commands.prune.no_messages_specified", EmoteReference.ERROR);
return;
}
var mentionedUsers = ctx.getMentionedUsers();
var amount = 5;
if (args.length > 0) {
try {
amount = Integer.parseInt(args[0]);
if (amount < 3) {
amount = 3;
}
} catch (Exception e) {
ctx.sendLocalized("commands.prune.not_valid", EmoteReference.ERROR);
return;
}
}
if (!mentionedUsers.isEmpty()) {
List<Long> users = mentionedUsers.stream().map(User::getIdLong).collect(Collectors.toList());
final var finalAmount = amount;
ctx.getChannel().getHistory().retrievePast(100).queue(messageHistory -> getMessageHistory(ctx, messageHistory, finalAmount, "commands.prune.mention_no_messages", message -> users.contains(message.getAuthor().getIdLong())), error -> ctx.sendLocalized("commands.prune.error_retrieving", EmoteReference.ERROR, error.getClass().getSimpleName(), error.getMessage()));
return;
}
ctx.getChannel().getHistory().retrievePast(Math.min(amount, 100)).queue(messageHistory -> prune(ctx, messageHistory), error -> {
ctx.sendLocalized("commands.prune.error_retrieving", EmoteReference.ERROR, error.getClass().getSimpleName(), error.getMessage());
error.printStackTrace();
});
}
};
}
@Override
public HelpContent help() {
return new HelpContent.Builder().setDescription("Prunes X amount of messages from a channel. Requires Message Manage permission.").setUsage("`~>prune <messages> [@user...]`").addParameter("messages", "Number of messages from 4 to 100.").addParameterOptional("@user...", "Prunes messages only from mentioned users.").build();
}
});
pruneCmd.setPredicate(ctx -> {
if (!ctx.getMember().hasPermission(Permission.MESSAGE_MANAGE)) {
ctx.sendLocalized("commands.prune.no_permissions_user", EmoteReference.ERROR);
return false;
}
if (!ctx.getSelfMember().hasPermission(Permission.MESSAGE_MANAGE)) {
ctx.sendLocalized("commands.prune.no_permissions", EmoteReference.ERROR);
return false;
}
return true;
});
pruneCmd.addSubCommand("bot", new SubCommand() {
@Override
public String description() {
return "Prune bot messages. It takes the number of messages as an argument.";
}
@Override
protected void call(Context ctx, I18nContext languageContext, String content) {
var args = ctx.getArguments();
var amount = 100;
if (args.length >= 1) {
try {
amount = Integer.parseInt(args[0]);
if (amount < 3) {
amount = 3;
}
} catch (Exception e) {
ctx.sendLocalized("commands.prune.not_valid", EmoteReference.ERROR);
return;
}
}
final var finalAmount = amount;
ctx.getChannel().getHistory().retrievePast(100).queue(messageHistory -> {
String prefix = MantaroData.db().getGuild(ctx.getGuild()).getData().getGuildCustomPrefix();
getMessageHistory(ctx, messageHistory, finalAmount, "commands.prune.bots_no_messages", message -> message.getAuthor().isBot() || message.getContentRaw().startsWith(prefix == null ? "~>" : prefix));
}, error -> {
ctx.sendLocalized("commands.prune.error_retrieving", EmoteReference.ERROR, error.getClass().getSimpleName(), error.getMessage());
error.printStackTrace();
});
}
});
pruneCmd.addSubCommand("nopins", new SubCommand() {
@Override
public String description() {
return "Prune messages that aren't pinned. It takes the number of messages as an argument.";
}
@Override
protected void call(Context ctx, I18nContext languageContext, String content) {
var args = ctx.getArguments();
var amount = 100;
if (args.length >= 1) {
try {
amount = Integer.parseInt(args[0]);
if (amount < 3) {
amount = 3;
}
} catch (Exception e) {
ctx.sendLocalized("commands.prune.not_valid", EmoteReference.ERROR);
return;
}
}
final var finalAmount = amount;
ctx.getChannel().getHistory().retrievePast(100).queue(messageHistory -> getMessageHistory(ctx, messageHistory, finalAmount, "commands.prune.no_pins_no_messages", message -> !message.isPinned()), error -> {
ctx.sendLocalized("commands.prune.error_retrieving", EmoteReference.ERROR, error.getClass().getSimpleName(), error.getMessage());
error.printStackTrace();
});
}
});
}
use of net.dv8tion.jda.api.Permission in project Saber-Bot by notem.
the class EventsCommand method action.
@Override
public void action(String prefix, String[] args, MessageReceivedEvent event) {
// process any optional channel arguments
List<String> channelIds = new ArrayList<>();
for (String arg : args) {
channelIds.add(arg.replaceAll("[^\\d]", ""));
}
Guild guild = event.getGuild();
List<String> scheduleIds = Main.getScheduleManager().getSchedulesForGuild(guild.getId());
if (!channelIds.isEmpty()) {
// filter the list of schedules
scheduleIds = scheduleIds.stream().filter(channelIds::contains).collect(Collectors.toList());
}
// build the embed body content
StringBuilder content = new StringBuilder();
String title = "Events on " + guild.getName(), footer = "(events list continued on next page)";
// total number of events
int count = 0;
// get the caller's guild member information
Member caller = event.getGuild().getMember(event.getAuthor());
if (// hide all events if null
caller != null) {
// list events by their schedule
for (String sId : scheduleIds) {
// only show users events that are on schedules they can view
TextChannel sChannel = event.getGuild().getTextChannelById(sId);
Collection<Permission> permissions = sChannel != null ? caller.getPermissions(sChannel) : new ArrayList();
if (true || (sChannel != null && permissions != null && permissions.contains(Permission.MESSAGE_READ))) {
if (content.length() > 1400) {
sendEventsMessage(footer, title, content, event.getTextChannel());
// adjust title and footer to reflect future messages are a continuation
title = "Events on " + guild.getName() + " (continued)";
footer = "(events list continued on next page)";
content = new StringBuilder();
}
// for each schedule, generate a list of events scheduled
Collection<ScheduleEntry> entries = Main.getEntryManager().getEntriesFromChannel(sId);
if (!entries.isEmpty()) {
// start a new schedule list
content.append("<#").append(sId).append("> ...\n");
while (!entries.isEmpty()) {
if (content.length() > 1800) {
sendEventsMessage(footer, title, content, event.getTextChannel());
// adjust title and footer to reflect future messages are a continuation
title = "Events on " + guild.getName() + " (continued)";
footer = "(events list continued on next page)";
content = new StringBuilder();
}
// find and remove the next earliest occurring event
ScheduleEntry top = entries.toArray(new ScheduleEntry[entries.size()])[0];
for (ScheduleEntry se : entries) {
if (se.getStart().isBefore(top.getStart()))
top = se;
}
entries.remove(top);
// determine time until the event begins/ends
long timeTil = ZonedDateTime.now().until(top.getStart(), ChronoUnit.MINUTES);
String status = "begins";
if (// adjust if event is ending
timeTil < 0) {
timeTil = ZonedDateTime.now().until(top.getEnd(), ChronoUnit.MINUTES);
status = "ends";
}
// add the event as a single line in the content
content.append(":id:``").append(ParsingUtilities.intToEncodedID(top.getId())).append("`` ~ **").append(top.getTitle()).append("** ").append(status).append(" in *");
ParsingUtilities.addTimeGap(content, timeTil, false, 3);
content.append("*\n");
// iterate event counter
count++;
}
// end a schedule list
content.append("\n");
}
}
}
}
// final footer shows count
footer = count + " event(s)";
sendEventsMessage(footer, title, content, event.getTextChannel());
}
use of net.dv8tion.jda.api.Permission in project Saber-Bot by notem.
the class ScheduleManager method createSchedule.
/**
* Create a new schedule and it's associated schedule channel, if the bot cannot create the
* new channel no schedule will be created
* @param gId (String) guild ID
* @param optional (String) optional name of schedule channel
*/
public void createSchedule(String gId, String optional) {
JDA jda = Main.getShardManager().getJDA(gId);
// bot self permissions
Collection<Permission> channelPerms = Stream.of(Permission.MESSAGE_ADD_REACTION, Permission.MESSAGE_EMBED_LINKS, Permission.MESSAGE_MANAGE, Permission.MESSAGE_HISTORY, Permission.MESSAGE_READ, Permission.MESSAGE_WRITE, Permission.MESSAGE_ATTACH_FILES).collect(Collectors.toList());
// create channel and get ID
String cId;
try {
Guild guild = jda.getGuildById(gId);
cId = guild.createTextChannel(optional != null ? optional : "new_schedule").addPermissionOverride(// allow self permissions
guild.getMember(jda.getSelfUser()), channelPerms, new ArrayList<>()).addPermissionOverride(// disable @everyone message write
guild.getPublicRole(), // disable @everyone message write
new ArrayList<>(), Collections.singletonList(Permission.MESSAGE_WRITE)).complete().getId();
} catch (PermissionException e) {
String m = e.getMessage() + ": Guild ID " + gId;
Logging.warn(this.getClass(), m);
return;
} catch (Exception e) {
Logging.exception(this.getClass(), e);
return;
}
// create the schedule database entry
createNewSchedule(cId, gId);
}
use of net.dv8tion.jda.api.Permission in project Saber-Bot by notem.
the class ScheduleManager method createSchedule.
/**
* Convert a pre-existing discord channel to a new saber schedule channel
* @param channel (TextChannel) a pre-existing channel to convert to a schedule
*/
public void createSchedule(TextChannel channel) {
JDA jda = Main.getShardManager().getJDA(channel.getGuild().getId());
// bot self permissions
Collection<Permission> channelPerms = Stream.of(Permission.MESSAGE_ADD_REACTION, Permission.MESSAGE_EMBED_LINKS, Permission.MESSAGE_MANAGE, Permission.MESSAGE_HISTORY, Permission.MESSAGE_READ, Permission.MESSAGE_WRITE, Permission.MESSAGE_ATTACH_FILES).collect(Collectors.toList());
// attempt to set the channel permissions
try {
// self perms
channel.createPermissionOverride(channel.getGuild().getMember(jda.getSelfUser())).setAllow(channelPerms).queue();
// @everyone perms
channel.createPermissionOverride(channel.getGuild().getPublicRole()).setDeny(Collections.singleton(Permission.MESSAGE_WRITE)).queue();
} catch (PermissionException e) {
String m = e.getMessage() + ": Guild ID " + channel.getGuild().getId();
Logging.warn(this.getClass(), m);
} catch (Exception e) {
Logging.exception(this.getClass(), e);
}
// create the schedule database entry
createNewSchedule(channel.getId(), channel.getGuild().getId());
}
Aggregations