use of net.dv8tion.jda.core.entities.Member in project FredBoat by Frederikam.
the class KickCommand method onInvoke.
@Override
public void onInvoke(@Nonnull CommandContext context) {
Guild guild = context.guild;
// Ensure we have a search term
if (!context.hasArguments()) {
HelpCommand.sendFormattedCommandHelp(context);
return;
}
// was there a target provided?
Member target = ArgumentUtil.checkSingleFuzzyMemberSearchResult(context, context.args[0]);
if (target == null)
return;
// are we allowed to do that?
if (!checkKickAuthorization(context, target))
return;
// putting together a reason
String plainReason = DiscordUtil.getReasonForModAction(context);
String auditLogReason = DiscordUtil.formatReasonForAuditLog(plainReason, context.invoker);
// putting together the action
RestAction<Void> modAction = guild.getController().kick(target, auditLogReason);
// on success
String successOutput = context.i18nFormat("kickSuccess", TextUtils.escapeAndDefuse(target.getUser().getName()), target.getUser().getDiscriminator(), target.getUser().getId()) + "\n" + plainReason;
Consumer<Void> onSuccess = aVoid -> {
Metrics.successfulRestActions.labels("kick").inc();
context.replyWithName(successOutput);
};
// on fail
String failOutput = context.i18nFormat("kickFail", target.getUser());
Consumer<Throwable> onFail = t -> {
CentralMessaging.getJdaRestActionFailureHandler(String.format("Failed to kick user %s in guild %s", target.getUser().getId(), guild.getId())).accept(t);
context.replyWithName(failOutput);
};
// issue the mod action
modAction.queue(onSuccess, onFail);
}
use of net.dv8tion.jda.core.entities.Member 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()));
}
}
use of net.dv8tion.jda.core.entities.Member in project pokeraidbot by magnusmickelsson.
the class PokemonTrackingTarget method handle.
@Override
public void handle(Guild guild, LocaleService localeService, Config config, User user, Raid raid, String inputMessage) {
Validate.notNull(guild, "Guild is null");
Validate.notNull(config, "Config is null");
Validate.notNull(raid, "Raid is null");
Validate.notNull(user, "User is null");
Validate.notNull(localeService, "LocaleService is null");
final Member memberById = guild.getMemberById(Long.parseLong(userId));
if (memberById == null) {
LOGGER.warn("Member with ID " + userId + " doesn't exist for server " + guild.getName() + "!");
return;
}
final User userToMessage = memberById.getUser();
if (userToMessage == null) {
LOGGER.warn("User instance for member with ID " + userId + " doesn't exist for server " + guild.getName() + "!");
return;
}
final String commandInitiator = user.getName();
final Locale locale = localeService.getLocaleForUser(user);
final String message = localeService.getMessageFor(LocaleService.TRACKED_RAID, locale, guild.getName(), commandInitiator, raid.toString(locale));
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Sending DM to user with ID " + userId + " for tracked pokemon " + pokemon.getName());
}
try {
sendPrivateMessage(userToMessage, message);
} catch (Throwable t) {
LOGGER.warn("Could not send private message for tracking " + this + ": " + t.getMessage());
}
}
use of net.dv8tion.jda.core.entities.Member in project pokeraidbot by magnusmickelsson.
the class AdminCommands method execute.
@Override
protected void execute(CommandEvent event) {
final User user = event.getAuthor();
if (user == null || user.getId() == null || (!user.getId().equals(BotServerMain.BOT_CREATOR_USERID))) {
event.replyInDM("This command is reserved only for bot creator. Hands off! ;p Your user ID was: " + String.valueOf(user.getId()));
return;
} else {
final String eventArgs = event.getArgs();
if (eventArgs.startsWith("userconfig")) {
String userId = eventArgs.replaceAll("userconfig\\s{1,3}", "");
final UserConfig userConfig = userConfigRepository.findOne(userId);
if (userConfig == null) {
event.replyInDM("No user with ID " + userId);
return;
} else {
userConfigRepository.delete(userConfig);
event.replyInDM("Removed user configuration for user with ID " + userId);
return;
}
} else if (eventArgs.startsWith("permissions")) {
final JDA bot = botService.getBot();
final List<Guild> guilds = bot.getGuilds();
StringBuilder sb = new StringBuilder();
sb.append("**Permissions for bot across servers:**\n\n");
for (Guild guild : guilds) {
final Member member = guild.getMember(bot.getSelfUser());
if (member == null) {
event.replyInDM("Could not get bot as servermember!");
return;
}
sb.append("*").append(guild.getName()).append("*\n");
for (Permission p : member.getPermissions()) {
sb.append(p.getName()).append("(Guild: ").append(p.isGuild()).append(" Channel: ").append(p.isChannel()).append(")\n");
}
sb.append("\n\n");
}
event.replyInDM(sb.toString());
return;
} else if (eventArgs.startsWith("clear tracking")) {
trackingCommandListener.clearCache();
event.replyInDM("Cleared tracking cache.");
return;
} else if (eventArgs.startsWith("announce")) {
final JDA bot = botService.getBot();
final List<Guild> guilds = bot.getGuilds();
StringBuilder sb = new StringBuilder();
for (Guild guild : guilds) {
try {
guild.getDefaultChannel().sendMessage(eventArgs.replaceAll("announce\\s{1,3}", "")).queue();
sb.append("Sent message for guild ").append(guild.getName()).append("\n");
} catch (Throwable t) {
sb.append("Failed to send message for guild ").append(guild.getName()).append(": ").append(t.getMessage()).append("\n");
}
}
event.replyInDM(sb.toString());
return;
} else if (eventArgs.startsWith("ismember")) {
String userIdAndGuildName = eventArgs.replaceAll("ismember\\s{1,3}", "");
String[] args = userIdAndGuildName.split(" ");
if (args.length < 2) {
event.reply("Bad syntax, should be something like: !raid admin ismember {userid} {guildname}");
return;
} else {
final JDA bot = botService.getBot();
Guild guild = null;
final List<Guild> guilds = bot.getGuilds();
String guildName = StringUtils.join(ArrayUtils.remove(args, 0), " ");
for (Guild guildToCheck : guilds) {
if (guildToCheck.getName().equalsIgnoreCase(guildName)) {
guild = guildToCheck;
}
}
if (guild != null) {
final Member memberById = guild.getMemberById(args[0]);
if (memberById != null) {
event.reply("User is a member of server " + guild.getName());
} else {
event.reply("User is not a member of server " + guild.getName());
}
} else {
event.reply("There was no server the user is a member of.");
}
return;
}
} else if (eventArgs.startsWith("member")) {
String userIdAndGuildName = eventArgs.replaceAll("member\\s{1,3}", "");
String[] args = userIdAndGuildName.split(" ");
if (args.length < 1 || args.length > 2) {
event.reply("Bad syntax, should be something like: !raid admin member {userid}");
return;
} else {
StringBuilder sb = new StringBuilder();
final JDA bot = botService.getBot();
final List<Guild> guilds = bot.getGuilds();
sb.append("User with ID ").append(args[0]).append(" is a member of the following servers:\n\n");
if (guilds.size() == 0) {
sb.append("-");
}
for (Guild guild : guilds) {
final Member memberById = guild.getMemberById(args[0]);
if (memberById != null) {
sb.append(guild.getName()).append(" (Username ").append(memberById.getUser().getName()).append(")\n");
}
}
event.reply(sb.toString());
return;
}
} else if (eventArgs.startsWith("guilds")) {
final JDA bot = botService.getBot();
final List<Guild> guilds = bot.getGuilds();
StringBuilder sb = new StringBuilder();
for (Guild guildToCheck : guilds) {
sb.append(guildToCheck.getName().toLowerCase()).append("\n");
}
event.reply(sb.toString());
return;
} else if (eventArgs.startsWith("test")) {
final Config configForServer = serverConfigRepository.getConfigForServer(event.getGuild().getName().toLowerCase());
String[] args = eventArgs.replaceAll("test\\s{1,3}", "").trim().split(" ");
String pokemon = args[0];
LocalDateTime startsAt = LocalDateTime.of(LocalDate.now(), Utils.parseTime(user, args[1], localeService));
String gymName = StringUtils.join(ArrayUtils.removeElements(args, 0, 1), " ").trim();
final String region = configForServer.getRegion();
Raid raid = new Raid(pokemonRepository.search(pokemon, user), startsAt.plusMinutes(Utils.RAID_DURATION_IN_MINUTES), gymRepository.search(user, gymName, region), localeService, region);
final Raid createdRaid = raidRepository.newRaid(botService.getBot().getSelfUser(), raid, event.getGuild(), configForServer, event.getMessage().getRawContent());
event.reply("Bot created your test raid: " + createdRaid);
return;
} else if (eventArgs.startsWith("tier5")) {
String[] bosses = eventArgs.replaceAll("tier5\\s{1,3}", "").trim().split(";");
if (bosses == null || bosses.length < 1) {
event.reply("Bad syntax, should be: !raid admin tier5 Boss1;Boss2;Boss3");
return;
} else {
final CopyOnWriteArrayList<String> currentTier5Bosses = new CopyOnWriteArrayList<>();
currentTier5Bosses.addAll(Arrays.asList(bosses));
BotService.currentTier5Bosses = currentTier5Bosses;
event.reply("Set current tier5 boss list: " + StringUtils.join(bosses, ", "));
return;
}
}
}
event.reply("No such command. Existing ones are:\n- userconfig {userid}\n- permissions\n" + "- clear tracking\n- announce {message}\n- ismember {userid} {guild name}\n- guilds\n" + " - member {userid}\n - test {pokemon} {start time} {gym}\n- tier5 {list of bosses ;-separated}");
}
use of net.dv8tion.jda.core.entities.Member in project Saber-Bot by notem.
the class ListCommand method action.
@Override
public void action(String prefix, String[] args, MessageReceivedEvent event) {
int index = 0;
Integer entryId = ParsingUtilities.encodeIDToInt(args[index++]);
ScheduleEntry se = Main.getEntryManager().getEntryFromGuild(entryId, event.getGuild().getId());
String titleUrl = se.getTitleUrl() == null ? "https://nnmathe.ws/saber" : se.getTitleUrl();
String title = se.getTitle() + " [" + ParsingUtilities.intToEncodedID(entryId) + "]";
String content = "";
List<String> userFilters = new ArrayList<>();
List<String> roleFilters = new ArrayList<>();
boolean filterByType = false;
Set<String> typeFilters = new HashSet<>();
boolean mobileFlag = false;
boolean IdFlag = false;
for (; index < args.length; index++) {
if (args[index].equalsIgnoreCase("mobile") || args[index].equalsIgnoreCase("m")) {
mobileFlag = true;
continue;
}
if (args[index].equalsIgnoreCase("id") || args[index].equalsIgnoreCase("i")) {
IdFlag = true;
continue;
}
String filterType = args[index].split(":")[0].toLowerCase().trim();
String filterValue = args[index].split(":")[1].trim();
switch(filterType.toLowerCase()) {
case "r":
case "role":
roleFilters.add(filterValue.replace("<@&", "").replace(">", ""));
break;
case "u":
case "user":
userFilters.add(filterValue.replace("<@", "").replace(">", ""));
break;
case "t":
case "type":
filterByType = true;
typeFilters.add(filterValue);
break;
}
}
// maximum number of characters before creating a new message
int lengthCap = 1900;
// maximum number of lines until new message, in mobile mode
int mobileLineCap = 25;
Set<String> uniqueMembers = new HashSet<>();
Map<String, String> options = Main.getScheduleManager().getRSVPOptions(se.getChannelId());
for (String type : options.values()) {
if (!filterByType || typeFilters.contains(type)) {
content += "**\"" + type + "\"\n======================**\n";
List<String> members = se.getRsvpMembersOfType(type);
for (String id : members) {
// if the message is nearing maximum length, or if in mobile mode and the max lines have been reached
if (content.length() > lengthCap || (mobileFlag && StringUtils.countMatches(content, "\n") > mobileLineCap)) {
// build and send the embedded message object
Message message = (new MessageBuilder()).setEmbed((new EmbedBuilder()).setDescription(content).setTitle(title, titleUrl).build()).build();
MessageUtilities.sendMsg(message, event.getChannel(), null);
// clear the content sting
content = "*continued. . .* \n";
}
if (id.matches("\\d+")) {
// cases in which the id is most likely a valid discord user's ID
Member member = event.getGuild().getMemberById(id);
if (// if the user is still a member of the guild, add to the list
member != null) {
uniqueMembers.add(member.getUser().getId());
content += this.getNameDisplay(mobileFlag, IdFlag, member);
} else // otherwise, remove the member from the event and update
{
se.getRsvpMembersOfType(type).remove(id);
Main.getEntryManager().updateEntry(se, false);
}
} else {
// handles cases in which a non-discord user was added by an admin
uniqueMembers.add(id);
content += "*" + id + "*\n";
}
}
}
content += "\n";
}
if (!filterByType || typeFilters.contains("no-input")) {
// generate a list of all members of the guild who pass the filter and map to their ID
List<String> noInput = event.getGuild().getMembers().stream().filter(member -> checkMember(member, userFilters, roleFilters)).map(member -> member.getUser().getId()).collect(Collectors.toList());
for (String type : options.values()) {
noInput.removeAll(se.getRsvpMembersOfType(type));
}
content += "**No input\n======================\n**";
if (!filterByType & noInput.size() > 10) {
content += " Too many users to show: " + noInput.size() + " users with no rsvp\n";
} else
for (String id : noInput) {
if (content.length() > lengthCap || (mobileFlag && StringUtils.countMatches(content, "\n") > mobileLineCap)) {
// build and send the embedded message object
Message message = (new MessageBuilder()).setEmbed((new EmbedBuilder()).setDescription(content).setTitle(title, titleUrl).build()).build();
MessageUtilities.sendMsg(message, event.getChannel(), null);
// clear the content sting
content = "*continued. . .* \n";
}
Member member = event.getGuild().getMemberById(id);
content += this.getNameDisplay(mobileFlag, IdFlag, member);
}
}
String footer = uniqueMembers.size() + " unique member(s) appear in this search";
// build and send the embedded message object
Message message = (new MessageBuilder()).setEmbed((new EmbedBuilder()).setDescription(content).setTitle(title, titleUrl).setFooter(footer, null).build()).build();
MessageUtilities.sendMsg(message, event.getChannel(), null);
}
Aggregations