Skip to content

Add purge command. - #218

Closed
RealYusufIsmail wants to merge 151 commits into
Together-Java:developfrom
BotCraftHub:feature/purge_command
Closed

RealYusufIsmail wants to merge 151 commits into
Together-Java:developfrom
BotCraftHub:feature/purge_command

Conversation

@RealYusufIsmail

Copy link
Copy Markdown
Contributor

This command works by doing /purge 1-200 and it will delete these messages. It would be best if we keep at 200 to avoid any lag. This pr also cover issue #17.

@Zabuzard

Copy link
Copy Markdown
Member

it just deletes the 100 last messages on the whole server

The last 100 messages in that specific channel

Oh okay, makes sense. Thats actually okay.

Still, you would have to "count" the messages. Would something like "delete from here to here" be possible? Like, "from message id to message id" (latter optional to delete all from the start point)

@RealYusufIsmail

Copy link
Copy Markdown
Contributor Author

it just deletes the 100 last messages on the whole server

The last 100 messages in that specific channel

Oh okay, makes sense. Thats actually okay.

Still, you would have to "count" the messages. Would something like "delete from here to here" be possible? Like, "from message id to message id" (latter optional to delete all from the start point)

Currently i believe that is not possible.

@RealYusufIsmail

Copy link
Copy Markdown
Contributor Author

Should i reduce the limit to 100 for the amount of messages you can delete

Comment on lines +1 to +130
package org.togetherjava.tjbot.commands.moderation;

import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import net.dv8tion.jda.api.interactions.commands.build.OptionData;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.togetherjava.tjbot.commands.SlashCommandAdapter;
import org.togetherjava.tjbot.commands.SlashCommandVisibility;

import java.util.Objects;

/**
* This command can ban users and optionally remove their messages from the past days. Banning can
* also be paired with a ban reason. The command will also try to DM the user to inform him about
* the action and the reason.
* <p>
* The command fails if the user triggering it is lacking permissions to either ban other users or
* to ban the specific given user (for example a moderator attempting to ban an admin).
*
*/
public final class BanCommand extends SlashCommandAdapter {
private static final String USER_OPTION = "user";
private static final String DELETE_HISTORY_OPTION = "delete-history";
private static final String REASON_OPTION = "reason";
/**
* As stated in {@link Guild#ban(User, int, String)} The reason can be only 512 characters.
*/
private static final Integer REASON_MAX_LENGTH = 512;
private static final Logger logger = LoggerFactory.getLogger(BanCommand.class);

/**
* Creates an instance of the ban command.
*/
public BanCommand() {
super("ban", "Bans a given user", SlashCommandVisibility.GUILD);

getData().addOption(OptionType.USER, USER_OPTION, "The user who you want to ban", true)
.addOption(OptionType.STRING, REASON_OPTION, "why the user should be banned", true)
.addOptions(new OptionData(OptionType.INTEGER, DELETE_HISTORY_OPTION,
"the amount of days of the message history to delete, none means no messages are deleted.",
true).addChoice("none", 0).addChoice("recent", 1).addChoice("all", 7));
}

@Override
public void onSlashCommand(@NotNull SlashCommandEvent event) {
Member user = Objects.requireNonNull(event.getOption(USER_OPTION)).getAsMember();
Member author = Objects.requireNonNull(event.getMember());
String reason = Objects.requireNonNull(event.getOption(REASON_OPTION)).getAsString();
Member bot = Objects.requireNonNull(event.getGuild()).getSelfMember();

if (!author.hasPermission(Permission.BAN_MEMBERS)) {
event.reply(
"You do not have the BAN_MEMBERS permission which means you can't unable to ban users in this server.")
.setEphemeral(true)
.queue();
return;
}

if (!author.canInteract(Objects.requireNonNull(user))) {
event.reply("The user" + user + " is too powerful for you to ban.")
.setEphemeral(true)
.queue();
return;
}

if (!bot.hasPermission(Permission.BAN_MEMBERS)) {
event.reply(
"I don't have the BAN_MEMBERS permission which means I am unable to ban users in this server.")
.setEphemeral(true)
.queue();

logger.error("The bot does not have BAN_MEMBERS permissions on the server '{}' ",
event.getGuild().getId());
return;
}
if (!bot.canInteract(Objects.requireNonNull(user))) {
event.reply("The user" + user.getUser().getIdLong() + "is too powerful for me to ban.")
.setEphemeral(true)
.queue();

logger.error("The bot does not have enough permissions to ban '{}'",
user.getUser().getIdLong());
return;
}

int days = Math
.toIntExact(Objects.requireNonNull(event.getOption(DELETE_HISTORY_OPTION)).getAsLong());

if (reason.length() > BanCommand.REASON_MAX_LENGTH) {
event.reply("The reason can not be over 512 characters").setEphemeral(true).queue();
return;
}

banUser(user, reason, days, user.getUser().getIdLong(), author.getIdLong(), event);
}

private static void banUser(@NotNull Member user, @NotNull String reason, int days, long userId,
long authorId, @NotNull SlashCommandEvent event) {

event.getJDA()
.openPrivateChannelById(userId)
.flatMap(channel -> channel.sendMessage(
"""
Hey there, sorry to tell you but unfortunately you have been banned from the guild 'Together Java'.\040
If you think this was a mistake, please contact a moderator or admin of the guild.
The ban reason is: %s
"""
.formatted(reason)))
.queue(null, throwable -> {
logger.error("I could not dm the user '{}' to inform them they were banned.",
userId);
});

event.getGuild()
.ban(user, days, reason)
.flatMap(v -> event.reply(user.getUser().getAsTag() + " was banned by "
+ user.getUser().getAsTag() + " for: " + reason))
.queue();

logger.info(
" '{}' banned the user '{}' and deleted the message history of the last '{}' days. Reason was '{}'",
authorId, userId, days, reason);
}
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this file here? This is about the purge command. Not ban. Clean up this mess...

Comment on lines +1 to +108
package org.togetherjava.tjbot.commands.moderation;

import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.togetherjava.tjbot.commands.SlashCommandAdapter;
import org.togetherjava.tjbot.commands.SlashCommandVisibility;
import java.util.Objects;


/**
* <p>
* The implemented command is {@code /kick @user reason}, upon which the bot will kick the user.
*/
public final class KickCommand extends SlashCommandAdapter {
private static final Logger logger = LoggerFactory.getLogger(KickCommand.class);
private static final String USER_OPTION = "user";
private static final String REASON_OPTION = "reason";


/**
* Creates an instance of the kick command.
*/
public KickCommand() {
super("kick", "Kicks a given user", SlashCommandVisibility.GUILD);

getData().addOption(OptionType.USER, USER_OPTION, "The user which you want to kick", true)
.addOption(OptionType.STRING, REASON_OPTION, "why the user should be kicked", true);
}

/**
* When triggered with {@code /kick @user reason}, the bot will check if the user has perms.
* Then it will check if itself has perms to kick. If it does it will check if the user is too
* powerful or not. If the user is not then bot will kick the user and reply with
* {@code Kicked User!}.
*
* @param event the corresponding event
*/
@Override
public void onSlashCommand(@NotNull SlashCommandEvent event) {
Member user = Objects.requireNonNull(event.getOption(USER_OPTION)).getAsMember();
Member author = Objects.requireNonNull(event.getMember());
String reason = Objects.requireNonNull(event.getOption(REASON_OPTION)).getAsString();
Member bot = Objects.requireNonNull(event.getGuild()).getSelfMember();
long userId = Objects.requireNonNull(user).getUser().getIdLong();

if (!author.hasPermission(Permission.KICK_MEMBERS)) {
event.reply(
"You do not have the KICK_MEMBERS permission which means you can't unable to kick users in this server.")
.setEphemeral(true)
.queue();
return;
}

if (!author.canInteract(Objects.requireNonNull(user))) {
event.reply("The user" + user + "is too powerful for you to kick.")
.setEphemeral(true)
.queue();
return;
}

if (!bot.hasPermission(Permission.KICK_MEMBERS)) {
event.reply(
"I don't have the KICK_MEMBERS permission which means I am unable to kick users in this server.")
.setEphemeral(true)
.queue();

logger.error("The bot does not have KICK_MEMBERS permissions on the server '{}' ",
event.getGuild().getId());
return;
}

if (!bot.canInteract(Objects.requireNonNull(user))) {
event.reply("The user" + user.getUser().getIdLong() + "is too powerful for me to kick.")
.setEphemeral(true)
.queue();

logger.error("The bot does not have enough permissions to kick '{}'",
user.getUser().getIdLong());
return;
}

event.getJDA()
.openPrivateChannelById(userId)
.flatMap(channel -> channel.sendMessage(
"""
Hey there, sorry to tell you but unfortunately you have been kicked from the guild 'Together Java'.
If you think this was a mistake, please contact a moderator or admin of the guild.
The kick reason is:
"""
+ reason))
.queue();

event.getGuild()
.kick(user, reason)
.flatMap(v -> event.reply(user.getUser().getAsTag() + " was kicked by "
+ author.getUser().getAsTag() + " for: " + reason))
.queue();

logger.info(" '{} ({})' kicked the user '{} ({})' due to reason being '{}'",
author.getUser().getAsTag(), author.getIdLong(), author.getUser().getAsTag(),
userId, reason);
}
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this file here? This is about the purge command. Not kick. Clean up this mess...

Comment on lines +1 to +81
package org.togetherjava.tjbot.commands.moderation;

import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.exceptions.ErrorResponseException;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import net.dv8tion.jda.api.requests.ErrorResponse;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.togetherjava.tjbot.commands.SlashCommandAdapter;
import org.togetherjava.tjbot.commands.SlashCommandVisibility;

import java.util.Objects;

/**
* <p>
* The implemented command is {@code /unban user_id}, upon which the bot will unban the user.
*/
public final class UnbanCommand extends SlashCommandAdapter {
private static final Logger logger = LoggerFactory.getLogger(UnbanCommand.class);
private static final String USER_ID = "user_id";

/**
* Creates an instance of the ban command.
*/
public UnbanCommand() {
super("unban", "Unbans a given user", SlashCommandVisibility.GUILD);

getData().addOption(OptionType.STRING, USER_ID,
"The user id of the user which you want to unban", true);

}

/**
* When triggered with {@code /unban user_id}}, the bot will respond will check if the user has
* perms. Then it will check if itself has perms to unban. If it does it will check if the user
* is the user is too powerful or not. If the user is not then unban will ban the user.
*
* @param event the corresponding event
*/
@Override
public void onSlashCommand(@NotNull SlashCommandEvent event) {
final String userId = Objects.requireNonNull(event.getOption(USER_ID)).getAsString();

if (!Objects.requireNonNull(event.getMember()).hasPermission(Permission.BAN_MEMBERS)) {
event.reply(
"You do not have the BAN_MEMBERS permission to urban users from this server.")
.setEphemeral(true)
.queue();
return;
}

if (!(Objects.requireNonNull(event.getGuild())).getSelfMember()
.hasPermission(Permission.BAN_MEMBERS)) {
event.reply(
"I don't have the BAN_MEMBERS permission which means I am unable to unban users in this server.")
.setEphemeral(true)
.queue();

logger.error("The bot does not have enough permissions to unban '{}'", userId);
return;
}

event.getGuild().unban(userId).queue(v -> {
event.reply("Unbanned the user").queue();
logger.info(" '{}' unbanned user id '{}' ", event.getMember().getIdLong(), userId);
}, throwable -> {
if (throwable instanceof ErrorResponseException errorResponseException
&& errorResponseException.getErrorResponse() == ErrorResponse.UNKNOWN_USER) {

event.reply("the specified user doesn't exist").queue();
logger.debug("The user '{}' does not exist", userId);
} else {
event.reply("Something went wrong, check the logs or contact a helper/moderator")
.queue();
logger.error("Something went wrong in the unban command: " + throwable);
}
});
}
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this file here? This is about the purge command. Not unban. Clean up this mess...

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed

key TEXT NOT NULL PRIMARY KEY,
value TEXT NOT NULL
)
) No newline at end of file

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Whats this? Undo.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed

@Zabuzard

Zabuzard commented Oct 23, 2021 •

Copy link
Copy Markdown
Member

it just deletes the 100 last messages on the whole server

The last 100 messages in that specific channel

Oh okay, makes sense. Thats actually okay.
Still, you would have to "count" the messages. Would something like "delete from here to here" be possible? Like, "from message id to message id" (latter optional to delete all from the start point)

Currently i believe that is not possible.

Why do you think so? You just use the method you are using already to retrieve the history of the channel (as much as possible) and then you iterate them in chronological order. As soon as you found the requested message ID, you can start deleting. If not found, the message is too old and you say "no".

So it is like "from this message ID to that message ID" (if they are within the max history you can get from discord). Sounds easy to do (@Tais993 ) and is definitely better UX than what this is now, imo.

@Tais993

Tais993 commented Oct 23, 2021

Copy link
Copy Markdown
Member

You cant do minutes or seconds unless you ban a person

You can, when retrieving messages you just say till a specific date iirc

@Tais993

Tais993 commented Oct 23, 2021 •

Copy link
Copy Markdown
Member

https://ci.dv8tion.net/job/JDA/javadoc/net/dv8tion/jda/api/requests/restaction/pagination/PaginationAction.html#takeUntilAsync(int,java.util.function.Predicate%29

@Zabuzard and @RealYusufIsmail

Maybe this is what you need, I'll take a look tomorrow otherwise

@Zabuzard

Copy link
Copy Markdown
Member

https://ci.dv8tion.net/job/JDA/javadoc/net/dv8tion/jda/api/requests/restaction/pagination/PaginationAction.html#takeUntilAsync(int,java.util.function.Predicate%29

@Zabuzard and @RealYusufIsmail

Maybe this is what you need, I'll take a look tomorrow otherwise

I found this MessageChannel#getHistoryAfter​ which accepts a message ID. Sounds promising.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

new command Add a new command or group of commands to the bot

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants