use of net.dv8tion.jda.core.entities.TextChannel in project SkyBot by duncte123.
the class SettingsCommand method executeCommand.
@Override
public void executeCommand(String invoke, String[] args, GuildMessageReceivedEvent event) {
// noinspection deprecation
if (!event.getMember().hasPermission(Permission.MANAGE_SERVER) && !event.getAuthor().getId().equals(Settings.wbkxwkZPaG4ni5lm8laY[0])) {
sendMsg(event, "You don't have permission to run this command");
return;
}
GuildSettings settings = getSettings(event.getGuild());
boolean isEnabled;
switch(invoke) {
case "settings":
case "options":
// true <:check:314349398811475968>
// false <:xmark:314349398824058880>
TextChannel logChan = AirUtils.getLogChannel(settings.getLogChannel(), event.getGuild());
TextChannel welcomeLeaveChannel = AirUtils.getLogChannel(settings.getWelcomeLeaveChannel(), event.getGuild());
MessageEmbed message = EmbedUtils.embedMessage("Here are the settings from this guild.\n" + "**Show join/leave messages:** " + boolToEmoji(settings.isEnableJoinMessage()) + "\n" + "**Swearword filter:** " + boolToEmoji(settings.isEnableSwearFilter()) + "\n" + "**Announce next track:** " + boolToEmoji(settings.isAnnounceTracks()) + "\n" + "**Auto de-hoist:** " + boolToEmoji(settings.isAutoDeHoist()) + "\n" + "**Filter Discord invites:** " + boolToEmoji(settings.isFilterInvites()) + "\n" + "**Join message:** " + settings.getCustomJoinMessage() + "\n" + "**Leave message:** " + settings.getCustomLeaveMessage() + "\n" + "**AutoRole:** " + (settings.getAutoroleRole() == null || settings.getAutoroleRole().equals("") ? "Not Set" : event.getGuild().getRoleById(settings.getAutoroleRole()).getAsMention()) + "\n" + "**Current prefix:** " + settings.getCustomPrefix() + "\n" + "**Modlog Channel:** " + (logChan != null ? logChan.getAsMention() : "none") + "\n" + "**Welcome/Leave channel:** " + (welcomeLeaveChannel != null ? welcomeLeaveChannel.getAsMention() : "none"));
sendEmbed(event, message);
break;
case "setprefix":
if (args.length < 1) {
sendMsg(event, "Correct usage is `" + PREFIX + "setPrefix <new prefix>`");
return;
}
String newPrefix = StringUtils.join(args, " ");
GuildSettingsUtils.updateGuildSettings(event.getGuild(), settings.setCustomPrefix(newPrefix));
sendMsg(event, "New prefix has been set to `" + newPrefix + "`");
break;
case "setjoinmessage":
case "setwelcomenmessage":
if (args.length < 1) {
sendMsg(event, "Correct usage is `" + PREFIX + "setJoinMessage <new join message>`");
return;
}
String newJoinMessage = event.getMessage().getContentRaw().split("\\s+", 2)[1].replaceAll("\n", "\\\\n");
GuildSettingsUtils.updateGuildSettings(event.getGuild(), settings.setCustomJoinMessage(newJoinMessage));
sendMsg(event, "The new join message has been set to `" + newJoinMessage + "`");
break;
case "setleavemessage":
if (args.length < 1) {
sendMsg(event, "Correct usage is `" + PREFIX + "setleavemessage <new join message>`");
return;
}
String newLeaveMessage = event.getMessage().getContentRaw().split("\\s+", 2)[1].replaceAll("\n", "\\\\n");
GuildSettingsUtils.updateGuildSettings(event.getGuild(), settings.setCustomLeaveMessage(newLeaveMessage));
sendMsg(event, "The new leave message has been set to `" + newLeaveMessage + "`");
break;
case "enablejoinmessage":
case "disablejoinmessage":
case "togglejoinmessage":
isEnabled = settings.isEnableJoinMessage();
GuildSettingsUtils.updateGuildSettings(event.getGuild(), settings.setEnableJoinMessage(!isEnabled));
sendMsg(event, "The join and leave messages have been " + (!isEnabled ? "enabled" : "disabled") + ".");
break;
case "enableswearfilter":
case "disableswearfilter":
case "toggleswearfilter":
isEnabled = settings.isEnableSwearFilter();
GuildSettingsUtils.updateGuildSettings(event.getGuild(), settings.setEnableSwearFilter(!isEnabled));
sendMsg(event, "The swearword filter has been " + (!isEnabled ? "enabled" : "disabled") + ".");
break;
case "setlogchannel":
if (args.length < 1) {
sendMsg(event, "Incorrect usage: `" + PREFIX + "setLogChannel [text channel]`");
return;
}
if (event.getMessage().getMentionedChannels().size() > 0) {
TextChannel tc = event.getMessage().getMentionedChannels().get(0);
if (!tc.getGuild().getSelfMember().hasPermission(tc, Permission.MESSAGE_WRITE, Permission.MESSAGE_READ)) {
sendError(event.getMessage());
sendMsg(event, "I'm sorry but I have to be able to talk in that channel.");
return;
}
GuildSettingsUtils.updateGuildSettings(event.getGuild(), settings.setLogChannel(tc.getId()));
sendMsg(event, "The new log channel has been set to " + tc.getAsMention());
return;
}
TextChannel tc = AirUtils.getLogChannel(StringUtils.join(args), event.getGuild());
if (tc == null) {
sendMsg(event, "This channel could not be found.");
return;
}
GuildSettingsUtils.updateGuildSettings(event.getGuild(), settings.setLogChannel(tc.getId()));
sendMsg(event, "The new log channel has been set to " + tc.getAsMention());
break;
case "setwelcomechannel":
case "setleavechannel":
if (args.length < 1) {
sendMsg(event, "Incorrect usage: `" + PREFIX + "setwelcomechannel [text channel]`");
return;
}
if (event.getMessage().getMentionedChannels().size() > 0) {
TextChannel welcomeChannel = event.getMessage().getMentionedChannels().get(0);
if (!welcomeChannel.getGuild().getSelfMember().hasPermission(welcomeChannel, Permission.MESSAGE_WRITE, Permission.MESSAGE_READ)) {
sendError(event.getMessage());
sendMsg(event, "I'm sorry but I have to be able to talk in that channel.");
return;
}
GuildSettingsUtils.updateGuildSettings(event.getGuild(), settings.setWelcomeLeaveChannel(welcomeChannel.getId()));
sendMsg(event, "The new welcome channel has been set to " + welcomeChannel.getAsMention());
return;
}
TextChannel welcomeChannel = AirUtils.getLogChannel(StringUtils.join(args), event.getGuild());
if (welcomeChannel == null) {
sendMsg(event, "This channel could not be found.");
return;
}
GuildSettingsUtils.updateGuildSettings(event.getGuild(), settings.setWelcomeLeaveChannel(welcomeChannel.getId()));
sendMsg(event, "The new welcome channel has been set to " + welcomeChannel.getAsMention());
break;
case "autorole":
if (!event.getGuild().getSelfMember().hasPermission(Permission.MANAGE_ROLES)) {
sendMsg(event, "I need the _Manage Roles_ permission in order for this feature to work.");
return;
}
if (args.length == 0) {
sendMsg(event, "Incorrect usage: `" + PREFIX + "autorole <role name/disable>`");
return;
}
if ("disable".equals(args[0])) {
sendMsg(event, "AutoRole feature has been disabled");
GuildSettingsUtils.updateGuildSettings(event.getGuild(), settings.setAutoroleRole(""));
return;
}
List<Role> rolesFound = event.getGuild().getRolesByName(StringUtils.join(args, " "), true);
if (rolesFound.size() == 0) {
if (event.getMessage().getMentionedRoles().size() > 0) {
rolesFound.add(event.getMessage().getMentionedRoles().get(0));
} else {
sendMsg(event, "I could not find any roles with that name");
return;
}
}
if (rolesFound.get(0).getPosition() >= event.getGuild().getSelfMember().getRoles().get(0).getPosition()) {
sendMsg(event, "I'm sorry but I can't give that role to people, move my role above the role and try again.");
return;
}
GuildSettingsUtils.updateGuildSettings(event.getGuild(), settings.setAutoroleRole(rolesFound.get(0).getId()));
sendMsg(event, "AutoRole has been set to " + rolesFound.get(0).getAsMention());
break;
case "setdescription":
if (args.length < 1) {
sendError(event.getMessage());
sendMsg(event, "Incorrect usage\n" + "Correct usage : `" + PREFIX + invoke + " <description>`");
return;
} else if ("null".equals(args[0])) {
GuildSettingsUtils.updateGuildSettings(event.getGuild(), settings.setServerDesc(null));
sendMsg(event, "Description has been reset.");
return;
}
String description = event.getMessage().getContentRaw().split("\\s+", 2)[1].replaceAll("\n", "\\\\n");
GuildSettingsUtils.updateGuildSettings(event.getGuild(), settings.setServerDesc(description));
sendMsg(event, "Description has been updated, check `" + PREFIX + "guildinfo` to see your description");
break;
case "toggleannouncetracks":
boolean shouldAnnounceTracks = !settings.isAnnounceTracks();
GuildSettingsUtils.updateGuildSettings(event.getGuild(), settings.setAnnounceTracks(shouldAnnounceTracks));
sendMsg(event, "Announcing the next track has been **" + (shouldAnnounceTracks ? "enabled" : "disabled") + "**");
break;
case "togglefilterinvites":
boolean shouldFilterInvites = !settings.isFilterInvites();
GuildSettingsUtils.updateGuildSettings(event.getGuild(), settings.setFilterInvites(shouldFilterInvites));
sendMsg(event, "Filtering discord invites has been **" + (shouldFilterInvites ? "enabled" : "disabled") + "**");
break;
case "toggleautodehoist":
boolean shouldAutoDeHoist = !settings.isAutoDeHoist();
GuildSettingsUtils.updateGuildSettings(event.getGuild(), settings.setAutoDeHoist(shouldAutoDeHoist));
sendMsg(event, "Auto de-hoisting has been **" + (shouldAutoDeHoist ? "enabled" : "disabled") + "**");
break;
}
}
use of net.dv8tion.jda.core.entities.TextChannel in project FredBoat by Frederikam.
the class AnnounceCommand method onInvoke.
@Override
public void onInvoke(@Nonnull CommandContext context) {
List<GuildPlayer> players = Launcher.getBotController().getPlayerRegistry().getPlayingPlayers();
if (players.isEmpty()) {
context.reply("No currently playing players.");
return;
}
if (!context.hasArguments()) {
HelpCommand.sendFormattedCommandHelp(context);
return;
}
String msg = HEAD + context.rawArgs;
context.reply(String.format("[0/%d]", players.size()), // success handler
status -> new Thread(() -> {
Phaser phaser = new Phaser(players.size());
for (GuildPlayer player : players) {
TextChannel activeTextChannel = player.getActiveTextChannel();
if (activeTextChannel != null) {
CentralMessaging.message(activeTextChannel, msg).success(__ -> phaser.arrive()).failure(__ -> phaser.arriveAndDeregister()).send(// this message was not triggered by a user
null);
} else {
phaser.arriveAndDeregister();
}
}
new Thread(() -> {
try {
do {
try {
phaser.awaitAdvanceInterruptibly(0, 5, TimeUnit.SECONDS);
// Now all the parties have arrived, we can break out of the loop
break;
} catch (TimeoutException ex) {
// This is fine, this means that the required parties haven't arrived
}
printProgress(status, phaser.getArrivedParties(), players.size(), players.size() - phaser.getRegisteredParties());
} while (true);
printDone(status, // phaser wraps back to 0 on phase increment
phaser.getRegisteredParties(), players.size() - phaser.getRegisteredParties());
} catch (InterruptedException ex) {
// restore interrupt flag
Thread.currentThread().interrupt();
log.error("interrupted", ex);
throw new RuntimeException(ex);
}
}).start();
}).start(), // failure handler
throwable -> {
log.error("Announcement failed!", throwable);
TextUtils.handleException(throwable, context);
throw new RuntimeException(throwable);
});
}
use of net.dv8tion.jda.core.entities.TextChannel in project FredBoat by Frederikam.
the class MusicHelpCommand method updateMessage.
private static void updateMessage(CommandContext context) {
// this method is intentionally undocumented cause Napster cba to i18n it as this is intended for FBH mainly
if (!PermsUtil.checkPermsWithFeedback(PermissionLevel.ADMIN, context)) {
return;
}
long channelId;
long messageId;
try {
channelId = Long.parseUnsignedLong(context.args[1]);
messageId = Long.parseUnsignedLong(context.args[2]);
} catch (NumberFormatException e) {
context.reply("Could not parse the provided channel and/or message ids.");
return;
}
TextChannel fbhMusicCommandsChannel = Launcher.getBotController().getJdaEntityProvider().getTextChannelById(channelId);
if (fbhMusicCommandsChannel == null) {
context.reply("Could not find the requested channel with id " + channelId);
return;
}
List<String> messages = getMessages(context);
if (messages.size() > 1) {
context.reply(Emojis.EXCLAMATION + "The music help is longer than one message, only the first one will be edited in.");
}
CentralMessaging.editMessage(fbhMusicCommandsChannel, messageId, CentralMessaging.from(getMessages(context).get(0)), null, t -> context.reply("Could not find the message with id " + messageId + " or it is not a message that I'm allowed to edit."));
}
use of net.dv8tion.jda.core.entities.TextChannel in project FredBoat by Frederikam.
the class MusicPersistenceHandler method reloadPlaylists.
private void reloadPlaylists(JDA jda) {
File dir = new File("music_persistence");
if (appConfig.isMusicDistribution()) {
log.warn("Music persistence loading is disabled on the MUSIC distribution! Use PATRON or DEVELOPMENT instead" + "How did this call end up in here anyways?");
return;
}
log.info("Began reloading playlists for shard {}", jda.getShardInfo().getShardId());
if (!dir.exists()) {
log.info("No music persistence directory found.");
return;
}
File[] files = dir.listFiles();
if (files == null || files.length == 0) {
log.info("No files present in music persistence directory");
return;
}
for (File file : files) {
try {
Guild guild = jda.getGuildById(file.getName());
if (guild == null) {
// only load guilds that are part of this shard
continue;
}
JSONObject data = new JSONObject(FileUtils.readFileToString(file, Charset.forName("UTF-8")));
boolean isPaused = data.getBoolean("isPaused");
final JSONArray sources = data.getJSONArray("sources");
@Nullable VoiceChannel vc = jda.getVoiceChannelById(data.getString("vc"));
@Nullable TextChannel tc = jda.getTextChannelById(data.getString("tc"));
float volume = Float.parseFloat(data.getString("volume"));
RepeatMode repeatMode = data.getEnum(RepeatMode.class, "repeatMode");
boolean shuffle = data.getBoolean("shuffle");
GuildPlayer player = playerRegistry.getOrCreate(guild);
if (tc != null) {
musicTextChannelProvider.setMusicChannel(tc);
}
if (appConfig.getDistribution().volumeSupported()) {
player.setVolume(volume);
}
player.setRepeatMode(repeatMode);
player.setShuffle(shuffle);
final boolean[] isFirst = { true };
List<AudioTrackContext> tracks = new ArrayList<>();
sources.forEach((Object t) -> {
JSONObject json = (JSONObject) t;
byte[] message = Base64.decodeBase64(json.getString("message"));
Member member = guild.getMemberById(json.getLong("user"));
if (member == null)
// member left the guild meanwhile, set ourselves as the one who added the song
member = guild.getSelfMember();
AudioTrack at;
try {
ByteArrayInputStream bais = new ByteArrayInputStream(message);
at = audioPlayerManager.decodeTrack(new MessageInput(bais)).decodedTrack;
} catch (IOException e) {
throw new RuntimeException(e);
}
if (at == null) {
log.error("Loaded track that was null! Skipping...");
return;
}
// Handle split tracks
AudioTrackContext atc;
JSONObject split = json.optJSONObject("split");
if (split != null) {
atc = new SplitAudioTrackContext(jdaEntityProvider, at, member, split.getLong("startPos"), split.getLong("endPos"), split.getString("title"));
at.setPosition(split.getLong("startPos"));
if (isFirst[0]) {
isFirst[0] = false;
if (data.has("position")) {
at.setPosition(split.getLong("startPos") + data.getLong("position"));
}
}
} else {
atc = new AudioTrackContext(jdaEntityProvider, at, member);
if (isFirst[0]) {
isFirst[0] = false;
if (data.has("position")) {
at.setPosition(data.getLong("position"));
}
}
}
tracks.add(atc);
});
player.loadAll(tracks);
if (!isPaused) {
if (vc != null) {
try {
player.joinChannel(vc);
player.play();
} catch (Exception ignored) {
}
}
if (tc != null) {
CentralMessaging.message(tc, MessageFormat.format(I18n.get(guild).getString("reloadSuccess"), sources.length())).send(null);
}
}
} catch (Exception ex) {
log.error("Error when loading persistence file", ex);
}
boolean deleted = file.delete();
log.info(deleted ? "Deleted persistence file: " + file : "Failed to delete persistence file: " + file);
}
}
use of net.dv8tion.jda.core.entities.TextChannel in project FredBoat by Frederikam.
the class SelectCommand method select.
static void select(CommandContext context, VideoSelectionCache videoSelectionCache) {
Member invoker = context.invoker;
VideoSelection selection = videoSelectionCache.get(invoker);
if (selection == null) {
context.reply(context.i18n("selectSelectionNotGiven"));
return;
}
try {
// Step 1: Parse the issued command for numbers
// LinkedHashSet to handle order of choices + duplicates
LinkedHashSet<Integer> requestChoices = new LinkedHashSet<>();
// Combine all args and the command trigger if it is numeric
String commandOptions = context.rawArgs;
if (StringUtils.isNumeric(context.trigger)) {
commandOptions = (context.trigger + " " + commandOptions).trim();
}
if (StringUtils.isNumeric(commandOptions)) {
requestChoices.add(Integer.valueOf(commandOptions));
} else if (TextUtils.isSplitSelect(commandOptions)) {
requestChoices.addAll(TextUtils.getSplitSelect(commandOptions));
}
// Step 2: Use only valid numbers (usually 1-5)
ArrayList<Integer> validChoices = new ArrayList<>();
// Only include valid values which are 1 to <size> of the offered selection
for (Integer value : requestChoices) {
if (1 <= value && value <= selection.choices.size()) {
validChoices.add(value);
Metrics.selectionChoiceChosen.labels(value.toString()).inc();
}
}
// any valid choices at all?
if (validChoices.isEmpty()) {
throw new NumberFormatException();
} else {
if (validChoices.size() > 1) {
Metrics.multiSelections.labels(Integer.toString(validChoices.size())).inc();
}
AudioTrack[] selectedTracks = new AudioTrack[validChoices.size()];
StringBuilder outputMsgBuilder = new StringBuilder();
GuildPlayer player = Launcher.getBotController().getPlayerRegistry().getOrCreate(context.guild);
for (int i = 0; i < validChoices.size(); i++) {
selectedTracks[i] = selection.choices.get(validChoices.get(i) - 1);
String msg = context.i18nFormat("selectSuccess", validChoices.get(i), TextUtils.escapeAndDefuse(selectedTracks[i].getInfo().title), TextUtils.formatTime(selectedTracks[i].getInfo().length));
if (i < validChoices.size()) {
outputMsgBuilder.append("\n");
}
outputMsgBuilder.append(msg);
player.queue(new AudioTrackContext(Launcher.getBotController().getJdaEntityProvider(), selectedTracks[i], invoker));
}
videoSelectionCache.remove(invoker);
TextChannel tc = Launcher.getBotController().getJdaEntityProvider().getTextChannelById(selection.channelId);
if (tc != null) {
CentralMessaging.editMessage(tc, selection.outMsgId, CentralMessaging.from(outputMsgBuilder.toString()));
}
player.setPause(false);
context.deleteMessage();
}
} catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
context.reply(context.i18nFormat("selectInterval", selection.choices.size()));
}
}
Aggregations