use of net.dv8tion.jda.core.entities.Member in project TheLighterBot by PhotonBursted.
the class AccesslistModificationCommand method execute.
@Override
protected void execute() {
// Check if the input actually had enough arguments
if (input.size() < 1) {
handleError(String.format("You didn't supply the ID of the entity to %s!\nPlease use `+%s <idTo%s>`.", getActionDescription("%s", "remove from the %s"), primaryCommandName, StringUtils.capitalize(targetAccesslist)));
return;
}
// Get the input after the arguments as one string representation
String target = Utils.drainQueueToString(input);
String[] targetParts = target.split(":", 2);
String targetType = targetParts[0];
String targetName = targetParts.length > 1 ? targetParts[1] : null;
// Identify what the input was targeting
switch(targetType) {
case "user":
{
// Retrieve a list of users which could be targeted by the search
List<Member> candidates = ev.getGuild().getMembersByEffectiveName(targetName, true);
// See if there were any search results
if (candidates.size() <= 0) {
handleError(String.format("No user was found in this server having name **%s**!", targetName));
return;
}
// Otherwise, generate a selector and let the user decide what the target was
if (candidates.size() == 1) {
performAccesslistModification(new BannableUser(candidates.get(0).getUser()));
} else {
LinkedHashMap<String, BannableEntity> candidateMap = new LinkedHashMap<>();
candidates.forEach(c -> candidateMap.put(Utils.userAsString(c.getUser()), new BannableUser(c.getUser())));
new SelectorBuilder<>(this).setOptionMap(candidateMap).build();
}
break;
}
case "role":
{
// Retrieve a list of roles which could be targeted by the search
List<Role> candidates = ev.getGuild().getRolesByName(targetName, true);
// See if there were any search results
if (candidates.size() <= 0) {
handleError(String.format("No role was found in this server having name **%s**!", targetName));
return;
}
// Otherwise, generate a selector and let the user decide what the target was
if (candidates.size() == 1) {
performAccesslistModification(new BannableRole(candidates.get(0)));
} else {
LinkedHashMap<String, BannableEntity> candidateMap = new LinkedHashMap<>();
candidates.forEach(c -> candidateMap.put(c.getName(), new BannableRole(c)));
new SelectorBuilder<>(this).setOptionMap(candidateMap).build();
}
break;
}
default:
BannableEntity targetEntity = null;
// Test if the id was targeting a role or user. If not, throw an error, otherwise whitelist the target
if (ev.getGuild().getRoles().stream().anyMatch(role -> role.getId().equals(target))) {
targetEntity = new BannableRole(target);
}
if (ev.getGuild().getMembers().stream().anyMatch(member -> member.getUser().getId().equals(target))) {
targetEntity = new BannableUser(target);
}
if (targetEntity == null) {
handleError(String.format("The ID you supplied (`%s`) was neither a role or user in this server!", target));
return;
}
// Detect if the id specified is already blacklisted
if (performActionCheck(ev.getGuild(), targetEntity)) {
handleError(String.format("The entity you tried to %s is already %sed for this server!", getActionDescription("%s", "remove from the %s"), targetAccesslist));
return;
}
performAccesslistModification(targetEntity);
break;
}
}
use of net.dv8tion.jda.core.entities.Member in project FlareBot by FlareBot.
the class VariableUtils method parseVariables.
/**
* This method is used to parse variables in a message, this means that we can allow users to pass things into
* their command messages, things like usernames, mentions and channel names to name a few.
*
* Variable list:
* <h2>User Variables</h2>
* `{user}` - User's name.
* `{username}` - User's name.
* `{nickname}` - User's nickname for a guild or their username if the guild is not passed or they're not a member.
* `{tag}` - User's name and discrim in tag format - Username#discrim.
* `{mention}` - User mention.
* `{user_id}` - User's ID.
*
* <hr />
*
* <h2>Guild Variables</h2>
* `{guild}` - Guild name.
* `{region}` - Guild region (Pretty name - Amsterdam, Amsterdam (VIP)).
* `{members}` - Total guild members.
* `{owner}` - Guild owner's name.
* `{owner_id}` - Guild owner's ID.
* `{owner_mention}` - Guild owner mention.
*
* <hr />
*
* <h2>Channel Variables</h2>
* `{channel}` - Channel name.
* `{channel_mention}` - Channel mention.
* `{topic}` - Channel topic.
* `{category}` - Category name or 'no category'.
*
* <hr />
*
* <h2>Utility Variables</h2>
* `{random}` - Random value from 1-10.
* `{random:y}` - Random value from 1 to Y.
* `{random:x,y}` - Random value from X to Y.
*
* @return The parsed message
*/
public static String parseVariables(@Nonnull String message, @Nullable GuildWrapper wrapper, @Nullable TextChannel channel, @Nullable User user, @Nullable String[] args) {
@Nullable Guild guild = null;
@Nullable Member member = null;
if (wrapper != null) {
guild = wrapper.getGuild();
if (user != null)
member = guild.getMember(user);
}
String parsed = message;
// User variables
if (user != null) {
parsed = parsed.replace("{user}", user.getName()).replace("{username}", user.getName()).replace("{nickname}", member == null ? user.getName() : member.getEffectiveName()).replace("{tag}", user.getName() + "#" + user.getDiscriminator()).replace("{mention}", user.getAsMention()).replace("{user_id}", user.getId());
}
// Guild variables
if (guild != null) {
parsed = parsed.replace("{guild}", guild.getName()).replace("{region}", guild.getRegion().getName()).replace("{members}", String.valueOf(guild.getMemberCache().size())).replace("{owner}", guild.getOwner().getEffectiveName()).replace("{owner_id}", guild.getOwner().getUser().getId()).replace("{owner_mention}", guild.getOwner().getUser().getAsMention());
}
// Channel variables
if (channel != null) {
parsed = parsed.replace("{channel}", channel.getName()).replace("{channel_mention}", channel.getAsMention()).replace("{topic}", channel.getTopic()).replace("{category}", (channel.getParent() != null ? channel.getParent().getName() : "no category"));
}
// Utility variables
Matcher matcher = random.matcher(parsed);
if (matcher.find()) {
int min = 1;
int max = 100;
if (matcher.groupCount() >= 2) {
min = (matcher.group(3) != null ? GeneralUtils.getInt(matcher.group(2), min) : min);
max = (matcher.group(3) != null ? GeneralUtils.getInt(matcher.group(3), max) : max);
}
parsed = matcher.replaceAll(String.valueOf(RandomUtils.getInt(min, max)));
}
String[] variableArgs = args;
if (args == null || args.length == 0)
variableArgs = new String[] {};
matcher = arguments.matcher(parsed);
while (matcher.find()) {
int argIndex = GeneralUtils.getPositiveInt(matcher.group(1), 0);
String arg = matcher.groupCount() == 2 && matcher.group(2) != null ? matcher.group(2) : "William";
if (variableArgs.length >= argIndex)
arg = variableArgs[argIndex - 1];
parsed = matcher.replaceAll(arg);
}
return parsed;
}
use of net.dv8tion.jda.core.entities.Member in project FlareBot by FlareBot.
the class EvalCommand method onCommand.
@Override
public void onCommand(User sender, GuildWrapper guild, TextChannel channel, Message message, String[] args, Member member) {
if (args.length == 0) {
channel.sendMessage("Eval something at least smh!").queue();
return;
}
String imports = IMPORTS.stream().map(s -> "import " + s + ".*;").collect(Collectors.joining("\n"));
ScriptEngine engine = manager.getEngineByName("groovy");
engine.put("channel", channel);
engine.put("guild", guild);
engine.put("message", message);
engine.put("jda", sender.getJDA());
engine.put("sender", sender);
String msg = MessageUtils.getMessage(args);
final String[] code = { getCode(args) };
boolean silent = hasOption(Options.SILENT, msg);
if (hasOption(Options.SNIPPET, msg)) {
String snippetName = MessageUtils.getNextArgument(msg, Options.SNIPPET.getAsArgument());
if (snippetName == null) {
MessageUtils.sendErrorMessage("Please specify the snippet you wish to run! Do `-snippet (name)`", channel);
return;
}
CassandraController.runTask(session -> {
ResultSet set = session.execute("SELECT encoded_code FROM flarebot.eval_snippets WHERE snippet_name = '" + snippetName + "'");
Row row = set.one();
if (row != null) {
code[0] = StringUtils.newStringUtf8(Base64.getDecoder().decode(row.getString("encoded_code").getBytes()));
} else {
MessageUtils.sendErrorMessage("That eval snippet does not exist!", channel);
code[0] = null;
}
});
}
if (hasOption(Options.SAVE, msg)) {
String base64 = Base64.getEncoder().encodeToString(code[0].getBytes());
CassandraController.runTask(session -> {
String snippetName = MessageUtils.getNextArgument(msg, Options.SAVE.getAsArgument());
if (snippetName == null) {
MessageUtils.sendErrorMessage("Please specify the name of the snippet to save! Do `-save (name)`", channel);
return;
}
if (insertSnippet == null)
insertSnippet = session.prepare("UPDATE flarebot.eval_snippets SET encoded_code = ? WHERE snippet_name = ?");
session.execute(insertSnippet.bind().setString(0, base64).setString(1, snippetName));
MessageUtils.sendSuccessMessage("Saved the snippet `" + snippetName + "`!", channel);
});
return;
}
if (hasOption(Options.LIST, msg)) {
ResultSet set = CassandraController.execute("SELECT snippet_name FROM flarebot.eval_snippets");
if (set == null)
return;
MessageUtils.sendInfoMessage("**Available eval snippets**\n" + set.all().stream().map(row -> "`" + row.getString("snippet_name") + "`").collect(Collectors.joining(", ")), channel);
return;
}
if (code[0] == null)
return;
final String finalCode = code[0];
POOL.submit(() -> {
try {
String eResult = String.valueOf(engine.eval(imports + '\n' + finalCode));
if (eResult.length() > 2000) {
eResult = String.format("Eval too large, result pasted: %s", MessageUtils.paste(eResult));
}
if (!silent)
channel.sendMessage(eResult).queue();
} catch (Exception e) {
// FlareBot.LOGGER.error("Error occurred in the evaluator thread pool! " + e.getMessage(), e, Markers.NO_ANNOUNCE);
channel.sendMessage(MessageUtils.getEmbed(sender).addField("Result: ", "```bf\n" + e.getMessage() + "```", false).build()).queue();
}
});
}
use of net.dv8tion.jda.core.entities.Member in project FlareBot by FlareBot.
the class SkipCommand method onCommand.
@Override
public void onCommand(User sender, GuildWrapper guild, TextChannel channel, Message message, String[] args, Member member) {
boolean songMessage = message.getAuthor().getIdLong() == Getters.getSelfUser().getIdLong();
PlayerManager musicManager = FlareBot.instance().getMusicManager();
if (!channel.getGuild().getAudioManager().isConnected() || musicManager.getPlayer(channel.getGuild().getId()).getPlayingTrack() == null) {
channel.sendMessage("I am not playing anything!").queue();
return;
}
if (member.getVoiceState().inVoiceChannel() && !channel.getGuild().getSelfMember().getVoiceState().getChannel().getId().equals(member.getVoiceState().getChannel().getId()) && !getPermissions(channel).hasPermission(member, Permission.SKIP_FORCE)) {
channel.sendMessage("You must be in the channel in order to skip songs!").queue();
return;
}
Track currentTrack = musicManager.getPlayer(guild.getGuildId()).getPlayingTrack();
if (args.length == 0 && currentTrack.getMeta().get("requester").equals(sender.getId())) {
channel.sendMessage("Skipped your own song!").queue();
musicManager.getPlayer(guild.getGuildId()).skip();
if (songMessage)
SongCommand.updateSongMessage(sender, message, channel);
return;
}
if (args.length != 1) {
if (!channel.getGuild().getMember(sender).getVoiceState().inVoiceChannel() || channel.getGuild().getMember(sender).getVoiceState().getChannel().getIdLong() != channel.getGuild().getSelfMember().getVoiceState().getChannel().getIdLong()) {
MessageUtils.sendErrorMessage("You cannot skip if you aren't listening to it!", channel);
return;
}
if (VoteUtil.contains(skipUUID, guild.getGuild()))
MessageUtils.sendWarningMessage("There is already a vote to skip current song! Vote with `{%}skip yes | no`", channel, sender);
else {
VoteGroup group = new VoteGroup("Skip current song", skipUUID);
List<User> users = new ArrayList<>();
for (Member inChannelMember : channel.getGuild().getSelfMember().getVoiceState().getChannel().getMembers()) {
if (channel.getGuild().getSelfMember().getUser().getIdLong() != inChannelMember.getUser().getIdLong()) {
users.add(inChannelMember.getUser());
}
}
group.limitUsers(users);
VoteUtil.sendVoteMessage(skipUUID, (vote) -> {
if (vote.equals(VoteGroup.Vote.NONE) || vote.equals(VoteGroup.Vote.NO)) {
MessageUtils.sendMessage("Results are in: Keep!", channel);
} else {
MessageUtils.sendMessage("Skipping!", channel);
if (songMessage)
SongCommand.updateSongMessage(sender, message, channel);
musicManager.getPlayer(guild.getGuildId()).skip();
}
}, group, TimeUnit.MINUTES.toMillis(1), channel, sender, ButtonGroupConstants.VOTE_SKIP, new ButtonGroup.Button("\u23ED", (owner, user, message1) -> {
if (getPermissions(channel).hasPermission(channel.getGuild().getMember(user), Permission.SKIP_FORCE)) {
musicManager.getPlayer(channel.getGuild().getId()).skip();
if (songMessage) {
SongCommand.updateSongMessage(user, message1, channel);
}
musicManager.getPlayer(guild.getGuildId()).skip();
VoteUtil.remove(skipUUID, guild.getGuild());
} else {
channel.sendMessage("You are missing the permission `" + Permission.SKIP_FORCE + "` which is required for use of this button!").queue();
}
}));
}
} else {
if (args[0].equalsIgnoreCase("force")) {
if (getPermissions(channel).hasPermission(member, Permission.SKIP_FORCE)) {
if (songMessage)
SongCommand.updateSongMessage(sender, message, channel);
VoteUtil.remove(skipUUID, guild.getGuild());
musicManager.getPlayer(guild.getGuildId()).skip();
} else {
channel.sendMessage("You are missing the permission `" + Permission.SKIP_FORCE + "` which is required for use of this command!").queue();
}
return;
} else if (args[0].equalsIgnoreCase("cancel")) {
if (getPermissions(channel).hasPermission(member, Permission.SKIP_CANCEL)) {
VoteUtil.remove(skipUUID, channel.getGuild());
} else
channel.sendMessage("You are missing the permission `" + Permission.SKIP_CANCEL + "` which is required for use of this command!").queue();
return;
}
if (!channel.getGuild().getMember(sender).getVoiceState().inVoiceChannel() || channel.getGuild().getMember(sender).getVoiceState().getChannel().getIdLong() != channel.getGuild().getSelfMember().getVoiceState().getChannel().getIdLong()) {
MessageUtils.sendWarningMessage("You cannot vote to skip if you aren't listening to it!", channel);
return;
}
VoteGroup.Vote vote = VoteGroup.Vote.parseVote(args[0]);
if (vote != null) {
if (!VoteUtil.contains(skipUUID, guild.getGuild()))
MessageUtils.sendWarningMessage("Their is no vote currently running!", channel, sender);
else
VoteUtil.getVoteGroup(skipUUID, guild.getGuild()).addVote(vote, sender);
} else
MessageUtils.sendUsage(this, channel, sender, args);
}
}
use of net.dv8tion.jda.core.entities.Member in project FlareBot by FlareBot.
the class SongCommand method onCommand.
@Override
public void onCommand(User sender, GuildWrapper guild, TextChannel channel, Message message, String[] args, Member member) {
PlayerManager manager = FlareBot.instance().getMusicManager();
if (manager.getPlayer(channel.getGuild().getId()).getPlayingTrack() != null) {
Track track = manager.getPlayer(channel.getGuild().getId()).getPlayingTrack();
EmbedBuilder eb = MessageUtils.getEmbed(sender).addField("Current Song", getLink(track), false).setThumbnail("https://img.youtube.com/vi/" + track.getTrack().getIdentifier() + "/hqdefault.jpg");
if (track.getTrack().getInfo().isStream)
eb.addField("Amount Played", "Issa livestream ;)", false);
else
eb.addField("Amount Played", GeneralUtils.getProgressBar(track), true).addField("Time", String.format("%s / %s", FormatUtils.formatDuration(track.getTrack().getPosition()), FormatUtils.formatDuration(track.getTrack().getDuration())), false);
ButtonGroup buttonGroup = new ButtonGroup(sender.getIdLong(), ButtonGroupConstants.SONG);
buttonGroup.addButton(new ButtonGroup.Button("\u23EF", (owner, user, message1) -> {
if (manager.hasPlayer(guild.getGuildId())) {
if (manager.getPlayer(guild.getGuild().getId()).getPaused()) {
if (getPermissions(channel).hasPermission(guild.getGuild().getMember(user), Permission.RESUME_COMMAND)) {
manager.getPlayer(guild.getGuild().getId()).play();
}
} else {
if (getPermissions(channel).hasPermission(guild.getGuild().getMember(user), Permission.PAUSE_COMMAND)) {
manager.getPlayer(guild.getGuild().getId()).setPaused(true);
}
}
}
}));
buttonGroup.addButton(new ButtonGroup.Button("\u23F9", (owner, user, message1) -> {
if (manager.hasPlayer(guild.getGuildId()) && getPermissions(channel).hasPermission(guild.getGuild().getMember(user), Permission.STOP_COMMAND)) {
manager.getPlayer(guild.getGuildId()).stop();
}
}));
buttonGroup.addButton(new ButtonGroup.Button("\u23ED", (owner, user, message1) -> {
if (getPermissions(channel).hasPermission(guild.getGuild().getMember(user), Permission.SKIP_COMMAND)) {
Command cmd = FlareBot.getCommandManager().getCommand("skip", user);
if (cmd != null)
cmd.onCommand(user, guild, channel, message1, new String[0], guild.getGuild().getMember(user));
}
}));
buttonGroup.addButton(new ButtonGroup.Button("\uD83D\uDD01", (ownerID, user, message1) -> {
updateSongMessage(user, message1, message1.getTextChannel());
}));
ButtonUtil.sendButtonedMessage(channel, eb.build(), buttonGroup);
} else {
channel.sendMessage(MessageUtils.getEmbed(sender).addField("Current song", "**No song playing right now!**", false).build()).queue();
}
}
Aggregations