Skip to content

Instantly share code, notes, and snippets.

@jerzabek
Created December 16, 2018 14:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jerzabek/3b5b4a259a33c276bd88e7ad823b66b8 to your computer and use it in GitHub Desktop.
Save jerzabek/3b5b4a259a33c276bd88e7ad823b66b8 to your computer and use it in GitHub Desktop.
package ga.jarza.dreamworldboye.chat.commands;
import ga.jarza.dreamworldboye.chat.ChatEvents;
import ga.jarza.dreamworldboye.chat.Command;
import ga.jarza.dreamworldboye.database.Database;
import ga.jarza.dreamworldboye.database.LogItem;
import ga.jarza.dreamworldboye.database.buffer.BanBuffer;
import ga.jarza.dreamworldboye.main.AccessLevel;
import ga.jarza.dreamworldboye.main.MainBot;
import ga.jarza.dreamworldboye.util.Utility;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map.Entry;
import sx.blah.discord.handle.impl.obj.Guild;
import sx.blah.discord.handle.obj.*;
import sx.blah.discord.util.EmbedBuilder;
import sx.blah.discord.util.MessageTokenizer;
import sx.blah.discord.util.PermissionUtils;
import sx.blah.discord.util.RequestBuffer;
import javax.rmi.CORBA.Util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collector;
import java.util.stream.Collectors;
public class BanCommand implements Command {
@Override
public void execute(IMessage message, String alias, String[] args) {
ArrayList<IUser> victims = new ArrayList<>();
EmbedBuilder e = new EmbedBuilder();
if(args.length < 1){
e.withDesc(":x: Incorrect usage. Here's the correct usage: " + Database.PREFIX + alias + " " + getUsage());
e.withColor(255, 0, 0);
Utility.sendMessage(message.getChannel(), e.build());
return;
}
Utility.deleteMessage(message);
StringBuilder reason = new StringBuilder();
HashMap<String, String> status = new HashMap<>();
if(alias.equalsIgnoreCase("ban")){
boolean reasonMode = false;
for(String arg : args){
if(reasonMode){
reason.append(arg).append(" ");
continue;
}
IUser tempVictim;
long victimID;
try {
victimID = Long.parseLong(arg);
tempVictim = MainBot.cli.fetchUser(victimID);
}catch (NumberFormatException ex){
if(!arg.endsWith(">")) {
// probably not an ID - meaning its a reason
reasonMode = true;
reason.append(arg).append(" ");
continue;
}
int beginIndex;
if(arg.startsWith("<@!")){
beginIndex = 3;
} else if(arg.startsWith("<@")){
beginIndex = 2;
} else {
// probably not an ID - meaning its a reason
reasonMode = true;
reason.append(arg).append(" ");
continue;
}
try {
victimID = Long.parseLong(arg.substring(beginIndex, arg.length()-1));
tempVictim = MainBot.cli.fetchUser(victimID);
}catch (NumberFormatException ex2){
// probably not an ID - meaning its a reason
reasonMode = true;
reason.append(arg).append(" ");
continue;
}
}
if(tempVictim == null){
status.put("User with ID: " + arg, "User could not be found");
}else {
// user has been found
victims.add(tempVictim);
}
}
} else {
for(String arg : args){
IUser tempVictim;
long victimID;
try {
victimID = Long.parseLong(arg);
tempVictim = MainBot.cli.fetchUser(victimID);
}catch (NumberFormatException ex){
if(!arg.endsWith(">")) {
// probably not an ID
continue;
}
int beginIndex;
if(arg.startsWith("<@!")){
beginIndex = 3;
} else if(arg.startsWith("<@")){
beginIndex = 2;
} else {
// probably not an ID
continue;
}
try {
victimID = Long.parseLong(arg.substring(beginIndex, arg.length()-1));
tempVictim = MainBot.cli.fetchUser(victimID);
}catch (NumberFormatException ex2){
// probably not an ID
continue;
}
}
if(tempVictim == null){
status.put("User with ID: " + arg, "User could not be found");
}else {
// user has been found
victims.add(tempVictim);
}
}
}
if(victims.isEmpty()){
e.withDesc(":x: User(s) invalid");
e.withColor(255, 0 , 0);
Utility.deleteMessage(message);
Utility.sendMessage(message.getChannel(), e.build());
return;
}
// filters guild list from non-whitelisted guilds
List<IGuild> guilds = MainBot.cli.getGuilds();
guilds.removeIf(g -> !ChatEvents.database.getWhitelist().contains(g.getLongID()));
boolean removedMod = false;
int numberOfMods = 0;
if (!AccessLevel.get(message.getAuthor(), message.getGuild()).hasAccessTo(AccessLevel.developer)) {
// removes moderators from ban list
int initialVictimsSize = victims.size();
for (IGuild g : guilds) {
victims.removeIf(vic -> AccessLevel.get(vic, g).hasAccessTo(AccessLevel.moderator));
numberOfMods += (initialVictimsSize - victims.size());
initialVictimsSize = victims.size();
}
}
if (numberOfMods > 0) removedMod = true;
// Only someone who is OP, has the developer AL can ban someone who is a mod
if(removedMod){
status.put(numberOfMods + " user" + (numberOfMods > 1 ? "s" : ""), "User" + (numberOfMods > 1 ? "s were" : " was") + " not banned because they are moderators.");
}
for(IUser user : victims){
if(BanBuffer.hasUser(user.getLongID())){
status.put(user.getName() + "#" + user.getDiscriminator() + " (" + user.getLongID() + ")", "User was already being banned.");
if(victims.size() == 1){
e.withColor(0, 255,0);
e.withDesc(
Utility.TICK
+ " User **"
+ victims.get(0).getName()
+ "#"
+ victims.get(0).getDiscriminator()
+ "** *("
+ victims.get(0).getLongID()
+ ")* is already being banned!");
Utility.deleteMessage(
Utility.sendMessage(message.getChannel(), e.build()),
5
);
return;
}
}else {
BanBuffer.queue(user.getLongID());
}
}
if(alias.equalsIgnoreCase("ban")){
// reason is already constructed
}else {
if(alias.equalsIgnoreCase("ad"))
reason.append("Advertisement");
else if(alias.equalsIgnoreCase("racism"))
reason.append("Racism/racist slur");
else if(alias.equalsIgnoreCase("raid"))
reason.append("Raid");
else if(alias.equalsIgnoreCase("hp"))
reason.append("Homophobia/homophobic slur");
else
reason.append("No reason provided");
}
IMessage confirmation;
EmbedBuilder ce = new EmbedBuilder();
if (victims.size() == 1) {
ce.withDesc("Proccessing the ban for **" + victims.get(0).getName() + "#" + victims.get(0).getDiscriminator() + "**...");
}else {
ce.withDesc("Proccessing the ban for **" + victims.size() + " users**...");
}
// ce.appendField("Reason:", reason, true);
ce.withColor(255,165,0);
ce.withTimestamp(message.getTimestamp());
confirmation = Utility.sendMessage(message.getChannel(), ce.build());
if(reason.toString().equals("")){
reason.append("No reason given");
}
if(reason.toString().trim().equals(""))
reason.append("No reason given");
final String finalReason = reason.toString();
int success = 0;
int fails = 0;
int alreadySuccessfull = 0;
List<Long> whitelist = ChatEvents.database.getWhitelist();
ArrayList<LogItem> logs = new ArrayList<>();
Collections.swap(whitelist, whitelist.indexOf(message.getGuild().getLongID()), 0);
for (IUser victim : victims) {
String username = victim.getName() + "#" + victim.getDiscriminator();
LogItem log =
new LogItem(
420,
victim.getLongID(),
username,
message.getAuthor().getLongID(),
message.getAuthor().getName() + "#" + message.getAuthor().getDiscriminator(),
message.getGuild().getLongID(),
finalReason,
message.getTimestamp().toString(),
0);
List<IGuild> failedGuilds = new ArrayList<>();
List<IGuild> bannedGuilds = new ArrayList<>();
int alreadyBanned = 0;
int numOfGuilds = 0;
Long firstBan = 0L;
for (Long id : whitelist) {
IGuild guild = MainBot.cli.getGuildByID(id);
if (bannedGuilds.contains(guild) || failedGuilds.contains(guild)) continue;
if (guild == null) continue;
if (!MainBot.cli.getOurUser().getPermissionsForGuild(guild).contains(Permissions.BAN)) {
failedGuilds.add(guild);
continue;
}
numOfGuilds++;
if (guild.getBannedUsers().contains(victim)) {
alreadyBanned++;
continue;
}
if (PermissionUtils.isUserHigher(guild, MainBot.cli.getOurUser(), victim)) {
bannedGuilds.add(guild);
if (guild.getLongID() == message.getGuild().getLongID()) {
// sends ban dm to the victim - since there is no way of knowing we will be able to send it later
StringBuilder msg =
new StringBuilder(
"You have been banned from the Dream world network, due to the following reason: `"
+ finalReason
+ "`. The network includes the following servers:");
// so it doesn't mention the 2 dream world log servers and cuko bot
for (Long lg : whitelist) {
IGuild wgg = MainBot.cli.getGuildByID(lg);
if (wgg != null
&& wgg.getLongID() != 465940832248397825L
&& wgg.getLongID() != 451928530461130775L
&& wgg.getLongID() != 334657301862547456L)
msg.append("*").append(wgg.getName()).append("*, ");
}
msg.delete(msg.length() - 2, msg.length());
// don't attempt to DM bots
if (!victim.isBot()) Utility.sendMessage(victim.getOrCreatePMChannel(), msg.toString());
firstBan = victim.getLongID();
RequestBuffer.request(() -> guild.banUser(victim, finalReason, 1));
}
} else {
failedGuilds.add(guild);
}
}
StringBuilder msg =
new StringBuilder(
"You have been banned from the Dream world network, due to the following reason: `"
+ finalReason
+ "`. The network includes the following servers:");
// so it doesn't mention the 2 dream world log servers and cuko bot
for (IGuild g : bannedGuilds) {
if (g != null
&& g.getLongID() != 465940832248397825L
&& g.getLongID() != 451928530461130775L
&& g.getLongID() != 334657301862547456L)
msg.append("*").append(g.getName()).append("*, ");
}
msg.delete(msg.length() - 2, msg.length());
// don't attempt to DM bots or the already banned person
if (!victim.isBot() && firstBan != 0L && firstBan != victim.getLongID()) Utility.sendMessage(victim.getOrCreatePMChannel(), msg.toString());
if (failedGuilds.size() > 0) {
StringBuilder text = new StringBuilder("Wasn't banned in: ");
failedGuilds.forEach(fg -> text.append(fg.getName()).append(", "));
text.delete(text.toString().length() - 2, text.toString().length());
String key = username // username
+ " (" + victim.getLongID() + ")"; // ID
status.put(key, text.toString()); // logs the guilds this user wasn't banned in
}
int gIndex = 0;
for(IGuild bg : bannedGuilds){
if(message.getGuild().getLongID() == bg.getLongID()){
gIndex = bannedGuilds.indexOf(message.getGuild());
break;
}
}
// firstly bans the user in the current guild
if(bannedGuilds.indexOf(message.getGuild()) != -1)
Collections.swap(bannedGuilds, gIndex, 0);
for (IGuild guild : bannedGuilds) {
RequestBuffer.request(() -> guild.banUser(victim, finalReason, 1));
}
BanBuffer.remove(victim.getLongID());
if (alreadyBanned == numOfGuilds) {
// user already banned - no logging necessary
alreadySuccessfull++;
} else if (bannedGuilds.size() == whitelist.size() || bannedGuilds.size() > 0) {
// successfully banned
ChatEvents.database.addLog(log);
logs.add(log);
success++;
// Utility.sendLog(log, bannedGuilds, message.getChannel());
} else {
fails++;
// fail
}
}
LogItem[] logArr = new LogItem[logs.size()];
for(int i = 0; i < logs.size(); i++){
logArr[i] = logs.get(i);
}
if(victims.size() == 1){
if (success == 1) {
e.appendField("Reason:", finalReason, true);
e.withColor(0, 255,0);
e.withDesc(
Utility.TICK
+ " Successfully banned **"
+ victims.get(0).getName()
+ "#"
+ victims.get(0).getDiscriminator()
+ "**! *("
+ victims.get(0).getLongID()
+ ")*");
} else if (alreadySuccessfull == 1) {
e.withColor(0, 255,0);
e.withDesc(
Utility.TICK
+ " User **"
+ victims.get(0).getName()
+ "#"
+ victims.get(0).getDiscriminator()
+ "** *("
+ victims.get(0).getLongID()
+ ")* is already banned!");
} else if (fails == 1) {
e.appendField("Reason:", finalReason, true);
e.withColor(255, 0,0);
e.withDesc(
Utility.X
+ " Failed to ban **"
+ victims.get(0).getName()
+ "#"
+ victims.get(0).getDiscriminator()
+ "** *("
+ victims.get(0).getLongID()
+ ")*!");
}
}else {
e.withColor(message.getAuthor().getColorForGuild(message.getGuild()));
e.withDesc("Successfully banned **" + success + "** people - failed to ban **" + fails + "** people - **" + alreadySuccessfull + "** were already banned");
}
e.appendField("Moderator: ", message.getAuthor().getName() + "#" + message.getAuthor().getDiscriminator(), true);
StringBuilder description = new StringBuilder("Details for the ban in " + message.getGuild().getName() + ":");
if(!status.isEmpty()){
for (Entry<String, String> entry : status.entrySet()) {
description.append("\n\t*").append(entry.getKey()).append("* - ").append(entry.getValue());
}
Utility.sendMessage(message.getAuthor().getOrCreatePMChannel(), description.toString());
}
Utility.editMessage(confirmation, e.build());
if(success > 0)
Utility.sendLog(message.getChannel(), logArr);
}
@Override
public String getName() {
return "ban";
}
@Override
public String getDesc() {
return "Bans a user across all dream world network:tm: guilds.";
}
@Override
public String getUsage() {
return "[one or more userIDs] [optional: reason]";
}
@Override
public AccessLevel getLevel() {
return AccessLevel.moderator;
}
@Override
public String[] getAliases() {
return new String[]{"ad", "racism", "raid", "hp"};
}
}
package com.jarza.peepocop.events.commands;
import com.jarza.peepocop.database.LogItem;
import com.jarza.peepocop.database.UserStatusObject;
import com.jarza.peepocop.events.Authority;
import com.jarza.peepocop.events.BanBuffer;
import com.jarza.peepocop.events.Command;
import com.jarza.peepocop.events.CommandManager;
import com.jarza.peepocop.main.PeepoCop;
import com.jarza.peepocop.main.Utility;
import discord4j.core.event.domain.message.MessageCreateEvent;
import discord4j.core.object.entity.Guild;
import discord4j.core.object.entity.Member;
import discord4j.core.object.entity.Message;
import discord4j.core.object.entity.TextChannel;
import discord4j.core.object.entity.User;
import discord4j.core.object.util.Snowflake;
import discord4j.core.spec.EmbedCreateSpec;
import java.awt.Color;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.TimeoutException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public class BanCommand implements Command {
// any id
private static String ID_REGEX = "\\d+";
private static Pattern ID_PATTERN = Pattern.compile(ID_REGEX, Pattern.MULTILINE);
@Override
public void execute(Member user, Guild guild, TextChannel channel, String alias, Message message) {
if (!message.getContent().isPresent()) {
return;
}
String messageText = message.getContent().get();
if (messageText.isEmpty()) {
message.addReaction(Utility.X).subscribe();
return;
}
String context = messageText.replaceFirst(CommandManager.prefix.concat(alias).concat(" "), "");
if (context.isEmpty()) {
message.addReaction(Utility.X).subscribe();
return;
}
ArrayList<String> arguments = new ArrayList<>();
Collections.addAll(arguments, context.split(" "));
arguments.removeIf(str -> str.trim().equalsIgnoreCase(""));
if (arguments.isEmpty()) {
message.addReaction(Utility.X).subscribe();
return;
}
ArrayList<Snowflake> snowflakes = new ArrayList<>();
int end = 0;
for (String arg : arguments) {
Matcher m = ID_PATTERN.matcher(arg);
if (m.find()) {
snowflakes.add(Snowflake.of(m.group()));
end += arg.length();
} else {
end += snowflakes.size(); // whitespace adjustment
break;
}
}
Utility.deleteMessage(message).subscribe();
// if no valid IDs are supplied we return
if (snowflakes.isEmpty()) {
// message.addReaction(Utility.X).subscribe();
channel.createMessage(spec ->
spec.setEmbed(embed ->
embed
.setColor(new Color(175, 0, 0))
.setDescription(Utility.X_EMOTE + " user(s) are invalid!")))
.subscribe();
return;
}
StringBuilder reason;
switch (alias.toLowerCase()) {
case "ad":
reason = new StringBuilder("Advertisement");
break;
case "hp":
reason = new StringBuilder("Homophobic slur");
break;
case "racism":
reason = new StringBuilder("Racist slur");
break;
case "raid":
reason = new StringBuilder("Raid");
break;
case "ban":
if (context.substring(end).trim().equalsIgnoreCase("")) {
reason = new StringBuilder("No reason provided");
} else {
reason = new StringBuilder(context.substring(end));
}
break;
default:
reason = new StringBuilder("No reason provided");
break;
}
Snowflake[] snowflakeArray = new Snowflake[snowflakes.size()];
snowflakes.toArray(snowflakeArray);
StringBuilder bannedUsername = new StringBuilder();
EmbedCreateSpec confirmationEmbed = new EmbedCreateSpec()
.setColor(new Color(167, 175, 7))
.setDescription("Ban pending for " + snowflakeArray.length + " member" + (snowflakeArray.length == 1 ? "" : "s") + "...")
.addField("Moderator:", user.getDisplayName() + "#" + user.getDiscriminator(), false)
.addField("Reason:", reason.toString(), false);
Message confirmation = channel.createMessage(spec ->
spec.setEmbed(confirmationEmbed))
.block();
int sessionID = BanBuffer.getID();
Flux<User> banFlux = Flux.just(snowflakeArray)
// filter ids that are not users
.flatMap(sf -> PeepoCop.client.getUserById(sf).onErrorResume(t -> {
String description = "Could not ban that user - invalid ID";
BanBuffer.remove(sf);
BanBuffer.addData(sessionID, sf, description);
return Mono.empty();
}))
// you cant ban yourselfTM filter
.filter(usr -> {
if (usr.getId().equals(user.getId())) {
String description = usr.getId().toString() + ": you can not ban yourself";
BanBuffer.remove(usr.getId());
BanBuffer.addData(sessionID, usr.getId(), description);
return false;
}
return true;
})
// staff filter
.filterWhen(usr ->
PeepoCop.client
.getGuilds()
.filter(g -> PeepoCop.database.getWhitelist().contains(g.getId()))
.flatMap(g -> g.getMemberById(usr.getId()).onErrorResume(t -> Mono.empty()))
.flatMap(Member::getRoles)
.filter(role -> PeepoCop.database.getModRolesForGuild(role.getGuildId().asLong()).contains(role.getId()))
.hasElements()
.doOnError(er -> CommandManager.log.error("oof2", er))
.doOnNext(isStaff -> {
if (isStaff) {
String description = "(" + usr.getUsername() + "#" + usr.getDiscriminator()
+ ") is staff so they were not be banned.";
BanBuffer.remove(usr.getId());
BanBuffer.addData(sessionID, usr.getId(), description);
}
})
.flatMap(bool -> Mono.just(!bool))
)
// error failsafe
.doOnError((err) -> {
EmbedCreateSpec embed = new EmbedCreateSpec()
.setColor(new Color(175, 0, 0))
.setDescription(Utility.X_EMOTE + " an error ocurred!")
.addField("Error:", err.getMessage(), false);
confirmation.edit(spec -> spec.setEmbed(embed)).subscribe();
})
// adds usernames
.doOnNext(usr ->
bannedUsername.append(usr.getUsername()).append("#").append(usr.getDiscriminator()))
.doOnNext(usr ->
PeepoCop.client
.getGuilds()
.filter(g -> PeepoCop.database.getWhitelist().contains(g.getId()))
// is member higher filter
.filterWhen(g ->
PeepoCop.client
.getSelf()
.flatMap(self -> self.asMember(g.getId())
.zipWith(usr.asMember(g.getId()).onErrorResume(t -> Mono.empty()))
// .switchIfEmpty(self.asMember(g.getId()).zipWith(self.asMember(g.getId())))
.flatMap(members ->
Utility.isMemberHigher(members.getT1(), members.getT2())
.doOnNext(bool ->
CommandManager.log.info("isMemberHigher(" + members.getT1().getUsername() +
", " + members.getT2().getUsername() + "): " + bool)))
.switchIfEmpty(Mono.just(true))
.doOnError(er -> CommandManager.log.error("oof3", er))
.doOnNext(bool -> {
if (!bool) {
String description = "(" + usr.getUsername() + "#" + usr.getDiscriminator()
+ ") could not be banned.";
CommandManager.log.info("Adding data to session " + sessionID + " in the isMemberHigher section");
BanBuffer.remove(usr.getId());
BanBuffer.addData(sessionID, usr.getId(), description);
}
})))
.doOnError(er -> CommandManager.log.error("Error from the ban chain", er))
.subscribe(g -> {
PeepoCop.client.getGuilds().filter(g1 ->
PeepoCop.database.getWhitelist().contains(g1.getId()))
.map(Guild::getName)
.reduce((a, b) -> a.concat(", ").concat(b)).subscribe(guildNames -> {
try {
usr.getPrivateChannel().block().createMessage(spec ->
spec.setContent("You have been banned from the Dream World Network. This includes the following servers: *" +
guildNames + "*\nHere is the reason: " + reason.toString())).subscribe(msg ->
g.ban(usr.getId(), spec ->
spec.setDeleteMessageDays(1).setReason(reason.toString()))
.doOnError(err -> {
String description = "(" + usr.getUsername() + "#" + usr.getDiscriminator()
+ ") could not be banned.";
BanBuffer.remove(usr.getId());
BanBuffer.addData(sessionID, usr.getId(), description);
CommandManager.log.error("error happened whilst banning, " + usr.toString(), err);
}).doOnSuccess(avoid -> {
LogItem log = new LogItem(420,
usr.getId(),
usr.getUsername() + "#" + usr.getDiscriminator(),
user.getId(),
user.getUsername() + "#" + user.getDiscriminator(),
guild.getId(),
reason.toString(),
message.getTimestamp().toString(),
0);
PeepoCop.database.addLog(log);
}).subscribe());
} catch (Throwable e) {
// silently ignore uwu
}
});
})).doAfterTerminate(() -> {
int size = snowflakeArray.length - BanBuffer.getData(sessionID).size();
if (size == 0) {
EmbedCreateSpec embed = new EmbedCreateSpec()
.setColor(new Color(175, 0, 0))
.setDescription("No one has been banned!");
confirmation.edit(spec -> spec.setEmbed(embed)).subscribe();
} else if (size == 1) {
EmbedCreateSpec embed = new EmbedCreateSpec()
.setColor(new Color(12, 213, 0))
.setDescription(bannedUsername.toString().concat(" has been banned in " + guild.getName() + "."))
.addField("Reason:", reason.toString(), true)
.addField("Moderator: ", user.getUsername() + "#" + user.getDiscriminator(), true);
confirmation.edit(spec -> spec.setEmbed(embed)).subscribe();
} else {
EmbedCreateSpec embed = new EmbedCreateSpec()
.setColor(new Color(12, 213, 0))
.setDescription((size > 1 ? size + " people have been banned" : size + " person has been banned").concat(" in " + guild.getName() + "."))
.addField("Reason:", reason.toString(), true)
.addField("Moderator: ", user.getUsername() + "#" + user.getDiscriminator(), true);
confirmation.edit(spec -> spec.setEmbed(embed)).subscribe();
}
sendSessionFeedback(sessionID, user);
});
final int BAN_TIMEOUT = 30;
PeepoCop.client.getEventDispatcher().on(MessageCreateEvent.class)
.filter(msg -> msg.getMember().isPresent() && !msg.getMember().get().isBot())
.filter(msg -> msg.getMessage().getContent().orElse("").trim().equalsIgnoreCase(CommandManager.prefix.concat("c")) ||
msg.getMessage().getContent().orElse("").trim().equalsIgnoreCase(CommandManager.prefix.concat("cancel")) ||
msg.getMessage().getContent().orElse("").trim().equalsIgnoreCase(CommandManager.prefix.concat("proceed")) ||
msg.getMessage().getContent().orElse("").trim().equalsIgnoreCase(CommandManager.prefix.concat("p")))
.filter(msg -> msg.getMember().get().getId().equals(user.getId()))
.map(mce -> mce.getMessage().getContent().orElse("").trim().equalsIgnoreCase(CommandManager.prefix.concat("proceed")) ||
mce.getMessage().getContent().orElse("").trim().equalsIgnoreCase(CommandManager.prefix.concat("p")))
.timeout(Duration.ofSeconds(BAN_TIMEOUT))
.flatMap(doProceed -> {
if(doProceed) {
confirmation.edit(spec ->
spec.setEmbed(confirmationEmbed
.setDescription("Processing...")
.setColor(Utility.RED))).subscribe((thing) -> banFlux.subscribe());
return Mono.empty();
}else {
PeepoCop.logger.debug("else");
return Mono.just(doProceed);
}
})
.onErrorResume(TimeoutException.class, (err) -> {
PeepoCop.logger.debug("RuntimeExceptionlol");
confirmation.edit(spec ->
spec.setEmbed(confirmationEmbed
.setDescription("Processing...")
.setColor(Utility.RED))).subscribe((thing) -> banFlux.subscribe());
return Mono.empty();
})
.next()
.subscribe(m ->
confirmation.edit(spec ->
spec.setEmbed(confirmationEmbed
.setDescription("Canceled!")
.setColor(Utility.DARK_RED))).subscribe());
}
private void sendSessionFeedback(int sessionID, User user) {
ArrayList<UserStatusObject> data = BanBuffer.getData(sessionID);
if (data.isEmpty()) {
return;
}
StringBuilder text = new StringBuilder();
for (UserStatusObject uso : data) {
text.append(uso.userID.asString()).append(": ").append(uso.status).append("\n");
}
CommandManager.log.info("session id: " + sessionID + " has " + data.size() + " objects.");
user.getPrivateChannel().subscribe(chnl ->
chnl.createMessage(messageCreateSpec ->
messageCreateSpec.setContent(text.toString())).subscribe());
}
@Override
public String getName() {
return "ban";
}
@Override
public String getUsage() {
return "[userid] [optional: reason]";
}
@Override
public String[] getAliases() {
return new String[]{"ad", "hp", "racism", "raid"};
}
@Override
public String getDescription() {
return "Bans the user in all Dream world guilds. If an error occurs the bot will DM you the details.";
}
@Override
public Authority getAuthority() {
return Authority.moderator;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment