use of net.dv8tion.jda.core.exceptions.PermissionException 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.exceptions.PermissionException in project MantaroBot by Mantaro.
the class ModerationCmds method tempban.
@Command
public static void tempban(CommandRegistry cr) {
cr.register("tempban", new SimpleCommand(Category.MODERATION) {
@Override
protected void call(GuildMessageReceivedEvent event, String content, String[] args) {
String reason = content;
Guild guild = event.getGuild();
User author = event.getAuthor();
TextChannel channel = event.getChannel();
Message receivedMessage = event.getMessage();
if (!guild.getMember(author).hasPermission(net.dv8tion.jda.core.Permission.BAN_MEMBERS)) {
channel.sendMessage(EmoteReference.ERROR + "Cannot ban: You have no Ban Members permission.").queue();
return;
}
if (event.getMessage().getMentionedUsers().isEmpty()) {
event.getChannel().sendMessage(EmoteReference.ERROR + "You need to mention an user!").queue();
return;
}
for (User user : event.getMessage().getMentionedUsers()) {
reason = reason.replaceAll("(\\s+)?<@!?" + user.getId() + ">(\\s+)?", "");
}
int index = reason.indexOf("time:");
if (index < 0) {
event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot temp ban an user without giving me the time!").queue();
return;
}
String time = reason.substring(index);
reason = reason.replace(time, "").trim();
time = time.replaceAll("time:(\\s+)?", "");
if (reason.isEmpty()) {
event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot temp ban someone without a reason.!").queue();
return;
}
if (time.isEmpty()) {
event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot temp ban someone without giving me the time!").queue();
return;
}
final DBGuild db = MantaroData.db().getGuild(event.getGuild());
long l = AudioCmdUtils.parseTime(time);
String finalReason = reason;
String sTime = StringUtils.parseTime(l);
receivedMessage.getMentionedUsers().forEach(user -> guild.getController().ban(user, 7).queue(success -> {
user.openPrivateChannel().complete().sendMessage(EmoteReference.MEGA + "You were **temporarly banned** by " + event.getAuthor().getName() + "#" + event.getAuthor().getDiscriminator() + " with reason: " + finalReason + ".").queue();
db.getData().setCases(db.getData().getCases() + 1);
db.saveAsync();
channel.sendMessage(EmoteReference.ZAP + "You will be missed... or not " + user.getName()).queue();
ModLog.log(event.getMember(), user, finalReason, ModLog.ModAction.TEMP_BAN, db.getData().getCases(), sTime);
MantaroBot.getTempBanManager().addTempban(guild.getId() + ":" + user.getId(), l + System.currentTimeMillis());
TextChannelGround.of(event).dropItemWithChance(1, 2);
}, error -> {
if (error instanceof PermissionException) {
channel.sendMessage(EmoteReference.ERROR + "Error banning " + user.getName() + ": " + "(I need the permission " + ((PermissionException) error).getPermission() + ")").queue();
} else {
channel.sendMessage(EmoteReference.ERROR + "I encountered an unknown error while banning " + user.getName() + ": " + "<" + error.getClass().getSimpleName() + ">: " + error.getMessage()).queue();
log.warn("Encountered an unexpected error while trying to ban someone.", error);
}
}));
}
@Override
public MessageEmbed help(GuildMessageReceivedEvent event) {
return helpEmbed(event, "Tempban Command").setDescription("**Temporarily bans an user**").addField("Usage", "`~>tempban <user> <reason> time:<time>`", false).addField("Example", "`~>tempban @Kodehawa example time:1d`", false).addField("Extended usage", "`time` - can be used with the following parameters: " + "d (days), s (second), m (minutes), h (hour). **For example time:1d1h will give a day and an hour.**", false).build();
}
});
}
use of net.dv8tion.jda.core.exceptions.PermissionException in project MantaroBot by Mantaro.
the class MantaroListener method onMessage.
private void onMessage(GuildMessageReceivedEvent event) {
//Moderation features
DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
GuildData guildData = dbGuild.getData();
//This is a pretty lazy check.
if (!guildData.getMutedTimelyUsers().isEmpty()) {
guildData.getMutedTimelyUsers().forEach((id, maxTime) -> {
System.out.println(System.currentTimeMillis() > maxTime);
if (System.currentTimeMillis() > maxTime) {
try {
guildData.getMutedTimelyUsers().remove(id);
dbGuild.saveAsync();
event.getGuild().getController().removeRolesFromMember(event.getGuild().getMemberById(id), event.getGuild().getRoleById(guildData.getMutedRole())).queue();
guildData.setCases(guildData.getCases() + 1);
dbGuild.save();
ModLog.log(event.getMember(), MantaroBot.getInstance().getUserById(id), "Mute timeout expired", ModLog.ModAction.UNMUTE, guildData.getCases());
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//link protection
if (guildData.isLinkProtection() && !guildData.getLinkProtectionAllowedChannels().contains(event.getChannel().getId())) {
if (DISCORD_INVITE.matcher(event.getMessage().getContent()).find() && !event.getMember().hasPermission(Permission.ADMINISTRATOR) && !event.getMember().hasPermission(Permission.MANAGE_SERVER)) {
Member bot = event.getGuild().getSelfMember();
if (bot.hasPermission(Permission.MESSAGE_MANAGE) || bot.hasPermission(Permission.ADMINISTRATOR)) {
User author = event.getAuthor();
//Ignore myself.
if (event.getAuthor().getId().equals(event.getJDA().getSelfUser().getId())) {
return;
}
//Ignore log channel.
if (guildData.getGuildLogChannel() != null && event.getChannel().getId().equals(guildData.getGuildLogChannel())) {
return;
}
//Yes, I know the check previously done is redundant, but in case someone decides to change the law of nature, it should do .
event.getMessage().delete().queue();
event.getChannel().sendMessage(EmoteReference.ERROR + "**You cannot advertise here.** Deleted invite link sent by **" + author.getName() + "#" + author.getDiscriminator() + "**.").queue();
} else {
event.getChannel().sendMessage(EmoteReference.ERROR + "I cannot remove the invite link because I don't have permission to delete messages!").queue();
}
}
}
//Slow mode
if (guildData.isSlowMode()) {
if (!slowModeLimiter.process(event.getAuthor().getId())) {
Member bot = event.getGuild().getSelfMember();
if (bot.hasPermission(Permission.MESSAGE_MANAGE) || bot.hasPermission(Permission.ADMINISTRATOR) && !event.getMember().hasPermission(Permission.ADMINISTRATOR) && !event.getMember().hasPermission(Permission.MANAGE_SERVER)) {
event.getMessage().delete().queue();
} else {
event.getChannel().sendMessage(EmoteReference.ERROR + "I cannot engage slow mode because I don't have permission to delete messages!").queue();
guildData.setSlowMode(false);
dbGuild.save();
event.getChannel().sendMessage(EmoteReference.WARNING + "**Disabled slowmode due to a lack of permissions.**").queue();
}
}
}
//Anti-spam. Allows 2 messages every 3 seconds.
if (guildData.isAntiSpam()) {
if (!spamModeLimiter.process(event.getAuthor().getId())) {
Member bot = event.getGuild().getSelfMember();
if (bot.hasPermission(Permission.MESSAGE_MANAGE) || bot.hasPermission(Permission.ADMINISTRATOR) && !event.getMember().hasPermission(Permission.ADMINISTRATOR) && !event.getMember().hasPermission(Permission.MANAGE_SERVER)) {
event.getMessage().delete().queue();
} else {
event.getChannel().sendMessage(EmoteReference.ERROR + "I cannot engage anti-spam mode because I don't have permission to delete messages!").queue();
guildData.setAntiSpam(false);
dbGuild.save();
event.getChannel().sendMessage(EmoteReference.WARNING + "**Disabled anti-spam mode due to a lack of permissions.**").queue();
}
}
}
//Birthday role checker.
try {
Role birthdayRole = event.getGuild().getRoleById(MantaroData.db().getGuild(event.getGuild()).getData().getBirthdayRole());
UserData user = MantaroData.db().getUser(event.getMember()).getData();
if (birthdayRole != null && user.getBirthday() != null) {
TextChannel channel = event.getGuild().getTextChannelById(MantaroData.db().getGuild(event.getGuild()).getData().getBirthdayChannel());
Calendar cal = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
if (user.getBirthday().substring(0, 5).equals(dateFormat.format(cal.getTime()).substring(0, 5))) {
if (!event.getMember().getRoles().contains(birthdayRole)) {
event.getGuild().getController().addRolesToMember(event.getMember(), birthdayRole).queue(s -> channel.sendMessage(String.format(EmoteReference.POPPER + "**%s is a year older now! Wish them a happy birthday.** :tada:", event.getMember().getEffectiveName())).queue());
}
} else {
if (event.getGuild().getRoles().contains(birthdayRole)) {
event.getGuild().getController().removeRolesFromMember(event.getMember(), birthdayRole).queue();
}
}
}
} catch (Exception e) {
if (e instanceof PermissionException) {
resetBirthdays(event.getGuild());
event.getChannel().sendMessage(EmoteReference.ERROR + "Error while applying birthday role, so the role assigner will be resetted. **Remember that the bot MUST have permissions to apply roles to that person, always**").queue();
}
//else ignore
}
}
use of net.dv8tion.jda.core.exceptions.PermissionException in project Ardent by adamint.
the class CommandFactory method pass.
/**
* Handles generic message events, parses message content
* and creates a new AsyncCommandExecutor that will execute the command
*
* @param event the MessageReceivedEvent to be handled
*/
public void pass(MessageReceivedEvent event, String prefix) {
try {
Guild guild = event.getGuild();
User ardent = guild.getSelfMember().getUser();
User user = event.getAuthor();
if (user.isBot())
return;
Message message = event.getMessage();
MessageChannel channel = event.getChannel();
String[] args = message.getContent().split(" ");
String rawContent = message.getRawContent();
if (rawContent.startsWith(guild.getSelfMember().getUser().getAsMention())) {
rawContent = rawContent.replaceFirst(ardent.getAsMention(), "");
if (rawContent.length() == 0)
channel.sendMessage("Type @Ardent [msg] to talk to me or /help to see a list of commands").queue();
else {
if (!Ardent.disabledCommands.contains("cleverbot")) {
channel.sendMessage(Unirest.post("https://cleverbot.io/1.0/ask").field("user", Ardent.cleverbotUser).field("key", Ardent.cleverbotKey).field("nick", "ardent").field("text", rawContent).asJson().getBody().getObject().getString("response")).queue();
} else
channel.sendMessage("Cleverbot is currently disabled, sorry.").queue();
}
return;
}
if (!args[0].startsWith(prefix))
return;
String cmd = args[0].replaceFirst(prefix, "");
final boolean[] ranCommand = { false };
String pre = StringEscapeUtils.escapeJava(prefix);
if (args[0].startsWith(pre)) {
args[0] = args[0].replaceFirst(pre, "");
baseCommands.forEach(command -> {
if (command.getBotCommand().containsAlias(args[0])) {
command.botCommand.usages++;
if (!Ardent.disabledCommands.contains(command.getName())) {
EntityGuild entityGuild = EntityGuild.get(guild);
for (RestrictedUser u : entityGuild.getRestrictedUsers()) {
if (u.getUserId().equalsIgnoreCase(user.getId())) {
command.sendRestricted(user);
return;
}
}
GuildModel guildModel = BaseCommand.asPojo(r.table("guilds").get(guild.getId()).run(connection), GuildModel.class);
if (guildModel == null) {
guildModel = new GuildModel(guild.getId(), "english", "/");
r.table("guilds").insert(r.json(shard.gson.toJson(guildModel))).runNoReply(connection);
}
if (guildModel.role_permissions != null) {
for (RolePermission rolePermission : guildModel.role_permissions) {
Member member = guild.getMember(user);
Role r = guild.getRoleById(rolePermission.getId());
if (r != null && member.getRoles().contains(r) && !member.hasPermission(Permission.MANAGE_SERVER)) {
if (!rolePermission.getCanUseArdentCommands()) {
user.openPrivateChannel().queue(privateChannel -> privateChannel.sendMessage("One of " + "your roles, **" + r.getName() + "**, cannot send Ardent commands!").queue());
return;
}
if (!message.getRawContent().toLowerCase().contains("discord.gg") && !rolePermission.getCanSendDiscordInvites()) {
message.delete().queue();
user.openPrivateChannel().queue(privateChannel -> privateChannel.sendMessage("One of " + "your roles, **" + r.getName() + "**, cannot send Discord server invite " + "links!").queue());
return;
}
if (!rolePermission.getCanSendLinks()) {
if (message.getContent().toLowerCase().contains("http://") || message.getContent().toLowerCase().contains("https://")) {
message.delete().queue();
user.openPrivateChannel().queue(privateChannel -> privateChannel.sendMessage("One" + " of " + "your roles, **" + r.getName() + "**, cannot send websiet links!").queue());
return;
}
}
}
}
}
new AsyncCommandExecutor(command.botCommand, guild, channel, event.getAuthor(), message, args, user).run();
commandsReceived++;
ranCommand[0] = true;
UserUtils.addMoney(user, 1);
} else {
command.sendTranslatedMessage("Sorry, this command is currently disabled and will be re-enabled soon.", channel, user);
ranCommand[0] = true;
}
}
});
}
if (!ranCommand[0]) {
if (!prefix.equalsIgnoreCase("/")) {
pass(event, "/");
}
}
} catch (Throwable ex) {
if (ex instanceof PermissionException) {
event.getAuthor().openPrivateChannel().queue(privateChannel -> privateChannel.sendMessage("I don't have permission to " + "send a message in this channel, please tell a server administrator").queue());
} else {
new BotException(ex);
}
}
}
use of net.dv8tion.jda.core.exceptions.PermissionException in project Ardent by adamint.
the class Join method onJoinUser.
@SubscribeEvent
public void onJoinUser(GuildMemberJoinEvent event) throws SQLException {
userJoinEvents.add(Instant.now());
Member joined = event.getMember();
User joinedUser = joined.getUser();
Guild guild = event.getGuild();
Role role = DefaultRole.getDefaultRole(guild);
if (role != null) {
try {
guild.getController().addRolesToMember(event.getMember(), role).queue();
} catch (PermissionException ex) {
}
}
Triplet<String, String, String> automessageSettings = Automessage.getMessagesAndChannel(guild);
String channelId = automessageSettings.getA();
String welcome = automessageSettings.getB();
if (channelId != null && welcome != null) {
TextChannel channel = guild.getTextChannelById(channelId);
if (channel != null) {
try {
welcome = welcome.replace("{user}", joinedUser.getAsMention()).replace("{servername}", guild.getName()).replace("{amtusers}", String.valueOf(guild.getMembers().size()));
channel.sendMessage(welcome).queue();
} catch (PermissionException ex) {
}
}
}
GuildModel guildModel = BaseCommand.asPojo(r.table("guilds").get(guild.getId()).run(connection), GuildModel.class);
guildModel.role_permissions.forEach(rolePermission -> {
Rankable rankable = rolePermission.getRankable();
if (rankable != null && rankable.getStartsOnServerJoin()) {
rankable.getQueued().put(joinedUser.getId(), Instant.now().getEpochSecond());
}
});
}
Aggregations