private void createChannel(CommandManager.ParsedCommandInvocation parsedCommandInvocation) { String[] args = parsedCommandInvocation.getArgs(); Guild guild = parsedCommandInvocation.getMessage().getGuild(); StringBuilder names = new StringBuilder(); for (int i = 1; i < args.length; i++) { names.append(args[i]).append(" "); } String name = names.toString(); name = names.replace(name.lastIndexOf(" "), name.lastIndexOf(" ") + 1, "").toString(); Channel channel = guild.getController().createVoiceChannel(name).complete(); String oldEntry = RubiconBot.getMySQL().getGuildValue(guild, "autochannels"); String newEntry = oldEntry + ", " + channel.getId(); RubiconBot.getMySQL().updateGuildValue(guild, "autochannels", newEntry); Message mymsg = parsedCommandInvocation.getMessage().getTextChannel().sendMessage(EmbedUtil.success("Created Autochannel", "Successfully created autochannel -> " + channel.getName() + "").build()).complete(); new Timer().schedule(new TimerTask() { @Override public void run() { mymsg.delete().queue(); } }, 5000); }
private void handleMessages(MessageReceivedEvent event) { String channelName = event.getChannel().getName(); String username = event.getAuthor().getName(); String message = event.getMessage().getContent(); String messageId = event.getMessage().getId(); Channel channel = event.getTextChannel(); User sender = event.getAuthor(); Boolean isAdmin = PermissionUtil.checkPermission(channel, event.getMember(), Permission.ADMINISTRATOR); com.gmt2001.Console.out.println("[DISCORD] [#" + channelName + "] " + username.toLowerCase() + ": " + message); // Be sure that this is commented out before a release back into the master branch! /* if (message.equals("!testjoin") && isAdmin) { EventBus.instance().post(new DiscordJoinEvent(event.getMember())); } */ if (message.startsWith("!")) { commandEvent(sender, channel, message, isAdmin); } EventBus.instance().postAsync(new DiscordMessageEvent(sender, channel, message, messageId, isAdmin)); }
@Override protected RequestBody finalizeData() { final Member self = guild.getSelfMember(); if (!self.hasPermission(Permission.MANAGE_CHANNEL)) throw new InsufficientPermissionException(Permission.MANAGE_CHANNEL); JSONArray array = new JSONArray(); for (int i = 0; i < orderList.size(); i++) { Channel chan = orderList.get(i); array.put(new JSONObject() .put("id", chan.getId()) .put("position", i)); } return getRequestBody(array); }
@Nonnull private static Collection<? extends Channel> getChannelsOfType(Category category, ChannelType type) { Checks.notNull(type, "ChannelType"); Checks.notNull(category, "Category"); // In the event Discord allows a new channel type to be nested in categories, // supporting them via CategoryOrderAction is just a matter of adding a new case here. switch(type) { case TEXT: return category.getTextChannels(); case VOICE: return category.getVoiceChannels(); default: throw new IllegalArgumentException("Cannot order category with specified channel type " + type); } }
public static final boolean isPermissionGranted(PermissionFilter filter, Channel channel, boolean memberOnly) { if (filter == null) { return true; } if (channel == null || channel.getRolePermissionOverrides().isEmpty()) { return false; } if (channel.getMemberPermissionOverrides().stream().filter((po) -> !po.getDenied().contains(Permission.MESSAGE_READ) || !po.getDenied().contains(Permission.MESSAGE_HISTORY)).anyMatch((po) -> (!filter.isGuildPermissionGranted(GuildBotRole.getGuildBotRolesByMember(po.getMember())) && !filter.isGlobalPermissionGranted(GlobalBotRole.getGlobalBotRolesByUser(po.getMember().getUser()))))) { return false; } if (memberOnly) { return true; } return channel.getRolePermissionOverrides().stream().filter((po) -> !po.getDenied().contains(Permission.MESSAGE_READ) || !po.getDenied().contains(Permission.MESSAGE_HISTORY)).noneMatch((po) -> !filter.isGuildPermissionGranted(GuildBotRole.getGuildBotRolesByRole(po.getRole()))); }
public static final boolean isPermissionGranted(List<Command> commands, Channel channel) { if (channel == null) { return false; } if (commands == null || commands.isEmpty()) { return true; } return commands.stream().allMatch((command) -> isPermissionGranted(command.getPermissionFilter(), channel)); }
private boolean isAutoChannel(Guild g, Channel ch) { String oldEntry = RubiconBot.getMySQL().getGuildValue(g, "autochannels"); if (oldEntry != null) if(oldEntry.contains(ch.getId())) { return true; } return false; }
private void commandEvent(User sender, Channel channel, String message, Boolean isAdmin) { String command = message.substring(1); String arguments = ""; if (command.contains(" ")) { String commandString = command; command = commandString.substring(0, commandString.indexOf(" ")); arguments = commandString.substring(commandString.indexOf(" ") + 1); } ScriptEventManager.instance().onEvent(new DiscordCommandEvent(sender, channel, command, arguments, isAdmin)); }
public DiscordCommandEvent(User sender, Channel channel, String command, String arguments, Boolean isAdmin) { super(sender, channel); this.command = command; this.arguments = arguments; this.isAdmin = isAdmin; parse(); }
public DiscordMessageEvent(User sender, Channel channel, String message, String messageId, Boolean isAdmin) { super(sender, channel); this.message = message; this.messageId = messageId; this.channelId = channel.getId(); this.isAdmin = isAdmin; }
public DiscordEvent(User user, Channel channel) { this.user = user; this.channel = channel; this.username = user.getName(); this.discrim = user.getDiscriminator(); this.channelName = channel.getName(); this.senderId = user.getId(); this.sender = (username + "#" + discrim); this.mention = "<@" + senderId + ">"; }
public static String parseChannel(Channel channel, String string) { string = string.replaceAll("%channel%", "<#" + channel.getId() + ">"); string = string.replaceAll("%channelname%", channel.getName()); string = string.replaceAll("%channelid%", channel.getId()); return string; }
@Override public boolean hasPermission(Channel channel, Permission... permissions) { long effectivePerms = PermissionUtil.getEffectivePermission(channel, this); for (Permission perm : permissions) { final long rawValue = perm.getRawValue(); if ((effectivePerms & rawValue) != rawValue) return false; } return true; }
@Override public boolean hasPermission(Channel channel, Collection<Permission> permissions) { Checks.notNull(permissions, "Permission Collection"); return hasPermission(channel, permissions.toArray(new Permission[permissions.size()])); }
private static Collection<? extends Channel> getChannelsOfType(Guild guild, ChannelType type) { switch(type) { case TEXT: return guild.getTextChannels(); case VOICE: return guild.getVoiceChannels(); case CATEGORY: return guild.getCategories(); default: throw new IllegalArgumentException("Cannot order specified channel type " + type); } }
private String formatText(String text, Channel channel) { return formatText(text, channel, true); }
String getFormattedTextDiscord(Channel channel) { return formatText(getUnformattedText(), channel, true); }
@Override public boolean hasPermission(Channel channel, Permission... permissions) { return false; }
@Override public boolean hasPermission(Channel channel, Collection<Permission> collection) { return false; }
public static final boolean isPermissionGranted(PermissionFilter filter, Channel channel) { return isPermissionGranted(filter, channel, false); }
@Override public final EmbedBuilder getMessage(Channel channel) { return super.getMessage(channel).appendDescription(Standard.NEW_LINE_DISCORD + "Please check the help command for more information on how to use this command."); }
public EmbedBuilder getMessage(Channel channel) { return new EmbedBuilder().setColor(Color.RED).setDescription(getMessage()).setTitle(getClass().getSimpleName()); }
public final boolean hasAccess(Guild guild, User user, Channel channel) { return containsHolder(guild == null ? 0 : guild.getIdLong(), user == null ? 0 : user.getIdLong(), channel == null ? 0 : channel.getIdLong()); }
public static final MultiObjectHolder of(Guild guild, User user, Channel channel) { return of(guild == null ? 0 : guild.getIdLong(), user == null ? 0 : user.getIdLong(), channel == null ? 0 : channel.getIdLong()); }
@Override public void handle(RoutingContext ctx, Server server, DiscordBot bot, DSLContext database) { HttpServerRequest request = ctx.request(); HttpServerResponse response = ctx.response(); String guildId = request.getParam("guildId"); int shardId = DiscordUtils.getShardIdFromGuildId(Long.parseLong(guildId), bot.getConfig().jim.shard_count); JDA shard = bot.getShards().get(shardId).getShard(); Guild guild = shard.getGuildById(guildId); SettingsRecord record = database.selectFrom(Tables.SETTINGS) .where(Tables.SETTINGS.GUILDID.eq(guildId)) .fetchAny(); if (record == null || guild == null) { response.setStatusCode(404); response.end(); return; } Gson gson = new GsonBuilder().serializeNulls().create(); List<PartialChannel> channels = guild.getTextChannels() .stream() .map((channel) -> new PartialChannel(channel.getId(), channel.getName())) .collect(Collectors.toList()); List<PartialRole> roles = guild.getRoles() .stream() .map((role) -> new PartialRole(role.getId(), role.getName())) .collect(Collectors.toList()); Channel modLogChannel = shard.getTextChannelById(record.getModlogchannelid()); PartialChannel modLogChannelPartial = new PartialChannel(modLogChannel.getId(), modLogChannel.getName()); Channel welcomeMessageChannel = shard.getTextChannelById(record.getWelcomemessagechannelid()); PartialChannel welcomeMessageChannelPartial = new PartialChannel(welcomeMessageChannel.getId(), welcomeMessageChannel.getName()); Role holdingRoomRole = null; PartialRole holdingRoomRolePartial = null; if (record.getHoldingroomroleid() != null) { holdingRoomRole = shard.getRoleById(record.getHoldingroomroleid()); holdingRoomRolePartial = new PartialRole(holdingRoomRole.getId(), holdingRoomRole.getName()); } GuildSettings settings = new GuildSettings( guildId, record.getModlog(), modLogChannelPartial, record.getHoldingroom(), holdingRoomRolePartial, record.getHoldingroomminutes(), record.getInvitelinkremover(), record.getWelcomemessage(), record.getMessage(), welcomeMessageChannelPartial, record.getPrefix(), record.getSilentcommands(), record.getNospaceprefix(), record.getStatistics(), channels, roles ); String responseJson = gson.toJson(settings); response.putHeader("Content-Type", "application/json"); response.end(responseJson); }
public Channel getDiscordChannel() { return this.channel; }
@Override public boolean onCommand(Message message, String[] args) { Channel channel = message.getTextChannel(); if (args.length > 0) { channel = MentionableUtil.getChannel(message, args); if (channel == null) { return sendErrorMessage(message, "I found no channels with the name or ID of `%s`", args[0]); } } Carbon time = Carbon.createFromOffsetDateTime(channel.getCreationTime()); PlaceholderMessage placeholder = MessageFactory.makeEmbeddedMessage(message.getChannel()) .setColor(MessageType.INFO.getColor()) .setTitle("#" + channel.getName()) .addField("ID", channel.getId(), true) .addField("Position", "" + channel.getPosition(), true) .addField("Users", "" + channel.getMembers().size(), true) .addField("Category", getCategoryFor(channel), true); if (channel instanceof TextChannel) { TextChannel textChannel = (TextChannel) channel; String topic = "*No topic has been set for this channel*"; if (textChannel.getTopic() != null && textChannel.getTopic().trim().length() > 0) { topic = textChannel.getTopic(); } placeholder .setDescription(topic) .addField("NSFW", textChannel.isNSFW() ? "ON" : "OFF", true); } if (channel instanceof VoiceChannel) { VoiceChannel voiceChannel = (VoiceChannel) channel; int bitRate = voiceChannel.getBitrate() / 1000; placeholder .setDescription("*This voice channel has *") .addField("Bit Rate", bitRate + " kbps", true); } placeholder .addField("Created At", time.format("EEE, dd MMM yyyy HH:mm") + "\n*About " + shortenDiffForHumans(time) + "*", true) .queue(); return true; }
private String getCategoryFor(Channel channel) { if (channel.getParent() == null) { return "*No Category*"; } return channel.getParent().getName(); }
private SparkRedditBean(Channel ch, String subreddit) { this.channelId = ch.getId(); this.channelName = ch.getName(); this.subreddit = subreddit; }
private SparkChannelBean(Channel ch) { this.id = ch.getId(); this.name = ch.getName(); this.position = ch.getPosition(); }
private SparkTwitterBean(Channel ch, String twitterHandle) { this.channelId = ch.getId(); this.channelName = ch.getName(); this.twitterHandle = twitterHandle; }
@Override public void executeCommand(Message msg) { GuildObject g = GuildObject.guildMap.get(msg.getGuild().getId()); EmbedBuilder em = new EmbedBuilder(); if(g.getConfig().getMutedRoleId() != null && !g.getConfig().getMutedRoleId().isEmpty()) { if (msg.getGuild().getRoleById(g.getConfig().getMutedRoleId()) != null) { em.setTitle("Error", null) .setColor(Color.RED) .setDescription("Looks like I'm already setup here..."); msg.getChannel().sendMessage(em.build()).queue(); return; } } msg.getGuild().getController().createRole().queue(role -> { role.getManagerUpdatable() .getNameField().setValue("muted") .getMentionableField().setValue(false) .getColorField().setValue(new Color(217, 0, 90)) .getPermissionField().revokePermissions(Permission.MESSAGE_WRITE, Permission.VOICE_SPEAK, Permission.MESSAGE_ADD_REACTION) .update().queue(success -> { g.getConfig().setMutedRoleId(role.getId()); for (Channel channel : msg.getGuild().getTextChannels()) { channel.createPermissionOverride(role).queue(or -> { or.getManager().deny(Permission.MESSAGE_WRITE, Permission.VOICE_SPEAK, Permission.MESSAGE_ADD_REACTION).queue(); }, failure -> { em.setTitle("Error", null) .setColor(Color.RED) .setDescription(failure.getMessage()); msg.getChannel().sendMessage(em.build()).queue(); }); } }); }, failure -> { em.setTitle("Error", null) .setColor(Color.RED) .setDescription(failure.getMessage()); msg.getChannel().sendMessage(em.build()).queue(); }); em.setTitle("Success", null) .setColor(Color.GREEN) .setDescription("Setup your muted role and saved configuration"); msg.getChannel().sendMessage(em.build()).queue(); }
@Nonnull private static RestAction<?> setPermissionsInChannelForRoleOrMember(@Nonnull final Channel channel, @Nonnull final IPermissionHolder memberOrRole, @Nonnull final PermissionAction action, @Nonnull final Permission... permissions) { final PermissionOverride po; if (memberOrRole instanceof Role) { po = channel.getPermissionOverride((Role) memberOrRole); } else if (memberOrRole instanceof Member) { po = channel.getPermissionOverride((Member) memberOrRole); } else { log.warn("Unsupported class of IPermissionHolder detected: {}, returning an empty action", memberOrRole); return new RestAction.EmptyRestAction<>(channel.getJDA(), null); } final RestAction ra; if (po != null) { switch (action) { case GRANT: //do nothing if the permission override already grants the permission if (po.getAllowed().containsAll(Arrays.asList(permissions))) { ra = new RestAction.EmptyRestAction<>(channel.getJDA(), null); } else { ra = po.getManager().grant(permissions); } break; case DENY: //do nothing if the permission override already denies the permission if (po.getDenied().containsAll(Arrays.asList(permissions))) { ra = new RestAction.EmptyRestAction<>(channel.getJDA(), null); } else { ra = po.getManager().deny(permissions); } break; case CLEAR: //if the permission override becomes empty as a result of clearing these permissions, delete it final List<Permission> currentPerms = new ArrayList<>(); currentPerms.addAll(po.getDenied()); currentPerms.addAll(po.getAllowed()); currentPerms.removeAll(Arrays.asList(permissions)); if (currentPerms.isEmpty()) { ra = po.delete(); } else { ra = po.getManager().clear(permissions); } break; default: throw new IllegalArgumentException("Unknown PermissionAction passed: " + action.name()); } } else { final PermissionOverrideAction poa; if (memberOrRole instanceof Role) { poa = channel.createPermissionOverride((Role) memberOrRole); } else { poa = channel.createPermissionOverride((Member) memberOrRole); } switch (action) { case GRANT: ra = poa.setAllow(permissions); break; case DENY: ra = poa.setDeny(permissions); break; case CLEAR: //do nothing if we are trying to clear a nonexisting permission override ra = new RestAction.EmptyRestAction<>(channel.getJDA(), null); break; default: throw new IllegalArgumentException("Unknown PermissionAction passed: " + action.name()); } } return ra; }
public static RestAction<?> deny(@Nonnull final Channel channel, @Nonnull final IPermissionHolder memberOrRole, @Nonnull final Permission... permissions) { return setPermissionsInChannelForRoleOrMember(channel, memberOrRole, PermissionAction.DENY, permissions); }
public static RestAction<?> clear(@Nonnull final Channel channel, @Nonnull final IPermissionHolder memberOrRole, @Nonnull final Permission... permissions) { return setPermissionsInChannelForRoleOrMember(channel, memberOrRole, PermissionAction.CLEAR, permissions); }
/** * @param channel Channel where this role and permission should take effect * @param memberOrRole Member or Role that will be granted/denied the permission * @param permissions Permissions that shall be granted/denied to the member/role */ public static RestAction<?> grant(@Nonnull final Channel channel, @Nonnull final IPermissionHolder memberOrRole, @Nonnull final Permission... permissions) { return setPermissionsInChannelForRoleOrMember(channel, memberOrRole, PermissionAction.GRANT, permissions); }
/** * The {@link net.dv8tion.jda.core.entities.Channel Channel} this Manager's * {@link net.dv8tion.jda.core.entities.PermissionOverride PermissionOverride} is in. * <br>This is logically the same as calling {@code getPermissionOverride().getChannel()} * * @return The parent {@link net.dv8tion.jda.core.entities.Channel Channel} */ public Channel getChannel() { return override.getChannel(); }
/** * Creates a new ChannelManager instance * * @param channel * {@link net.dv8tion.jda.core.entities.Channel Channel} that should be modified * <br>Either {@link net.dv8tion.jda.core.entities.VoiceChannel Voice}- or {@link net.dv8tion.jda.core.entities.TextChannel TextChannel} */ public ChannelManager(Channel channel) { this.updatable = new ChannelManagerUpdatable(channel); }
/** * The {@link net.dv8tion.jda.core.entities.Channel Channel} that will * be modified by this Manager instance * * @return The {@link net.dv8tion.jda.core.entities.Channel Channel} * * @see ChannelManagerUpdatable#getChannel() */ public Channel getChannel() { return updatable.getChannel(); }
/** * The {@link net.dv8tion.jda.core.entities.Channel Channel} this Manager's * {@link net.dv8tion.jda.core.entities.PermissionOverride PermissionOverride} is in. * <br>This is logically the same as calling {@code getPermissionOverride().getChannel()} * * @return The parent {@link net.dv8tion.jda.core.entities.Channel Channel} */ public Channel getChannel() { return updatable.getChannel(); }