net.dv8tion.jda.core.entities.TextChannel Java Examples

The following examples show how to use net.dv8tion.jda.core.entities.TextChannel. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SetPrefixCommand.java    From FlareBot with MIT License 6 votes vote down vote up
@Override
public void onCommand(User sender, GuildWrapper guild, TextChannel channel, Message message, String[] args, Member member) {
    if (args.length == 1) {
        if (args[0].equalsIgnoreCase("reset")) {
            guild.setPrefix('_');
            MessageUtils.sendInfoMessage("Reset the prefix back to `_`!", channel, sender);
        } else if (args[0].length() == 1) {
            guild.setPrefix(args[0].charAt(0));
            channel.sendMessage(MessageUtils.getEmbed(sender)
                    .setDescription(String.format("Set the prefix to `%s`", args[0])).build())
                    .queue();
        } else {
            MessageUtils.sendErrorMessage("Cannot set the prefix to be more that one character long!", channel, sender);
        }
    } else {
        channel.sendMessage(MessageUtils.getEmbed(sender)
                .setDescription(String.format("Current guild prefix is `%s`!", guild.getPrefix())).build()).queue();
    }
}
 
Example #2
Source File: MuteCommand.java    From FlareBot with MIT License 6 votes vote down vote up
@Override
public void onCommand(User sender, GuildWrapper guild, TextChannel channel, Message message, String[] args, Member member) {
    if (args.length == 0) {
        MessageUtils.sendUsage(this, channel, sender, args);
    } else {
        User user = GuildUtils.getUser(args[0], guild.getGuildId());
        if (user == null) {
            MessageUtils.sendErrorMessage("Invalid user!!", channel);
            return;
        }
        if (guild.getMutedRole() == null) {
            MessageUtils.sendErrorMessage("Error getting the \"Muted\" role! Check FlareBot has permissions to create it!", channel);
            return;
        }
        String reason = args.length > 1 ? MessageUtils.getMessage(args, 1) : null;
        ModlogHandler.getInstance().handleAction(guild, channel, sender, user, ModAction.MUTE, reason);
    }
}
 
Example #3
Source File: Autochannel.java    From DiscordBot with Apache License 2.0 6 votes vote down vote up
private void setChan(String id, Guild g, TextChannel tc) {
    VoiceChannel vc = getVchan(id, g);

    if (vc == null) {
        tc.sendMessage(new EmbedBuilder().setColor(Color.red).setDescription(
                String.format("Voice channel with the ID `%s` does not exist.", id)
        ).build()).queue();
    } else if (autochans.containsKey(vc)) {
        tc.sendMessage(new EmbedBuilder().setColor(Color.red).setDescription(
                "This channel is just set as auto channel."
        ).build()).queue();
    } else {
        autochans.put(vc, g);
        saveVchan(vc, g);
        tc.sendMessage(new EmbedBuilder().setColor(Color.green).setDescription(
                String.format("Successfully set voice channel `%s` as auto channel.", vc.getName())
        ).build()).queue();
    }
}
 
Example #4
Source File: CurrencyConversionUtil.java    From FlareBot with MIT License 6 votes vote down vote up
public static CurrencyComparison getCurrencyComparison(TextChannel channel, User sender, Command cmd,
                                                       String from, String to) {
    try {
        if (!isValidCurrency(from))
            throw new IllegalArgumentException("`" + from.toUpperCase() + "` is not a valid currency!");

        if (!isValidCurrency(to))
            throw new IllegalArgumentException("`" + to.toUpperCase() + "` is not a valid currency!");

        if (from.equalsIgnoreCase(to)) {
            if ((random.nextInt(100) + 1) == 100) {
                channel.sendMessage("I had hoped you didn't need me for that...").queue();
                Constants.logEG("Convert a currency to itself...", cmd, channel.getGuild(), sender);
            }
            return new CurrencyComparison(from, to, (double) 1);
        }

        CurrencyComparison normalCurrency = CurrencyConversionUtil.getNormalCurrency(from, to);
        if (normalCurrency != null) return normalCurrency;
        else return getCryptoCurrency(from, to);

    } catch (IOException e) {
        return null;
    }
}
 
Example #5
Source File: VolumeCommand.java    From DiscordBot with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(TextChannel textChannel, Member member, Message message, List<String> arguments) {
	EmbedBuilder embedBuilder = new EmbedBuilder();
	embedBuilder.setAuthor(textChannel.getJDA().getSelfUser().getName(), null, textChannel.getJDA().getSelfUser().getEffectiveAvatarUrl());
	embedBuilder.setColor(DiscordUtil.DEFAULT);
	
	if (arguments != null && !arguments.isEmpty()) {
		try {
			int volume = Integer.parseInt(arguments.get(0));
			if (volume > 100 || volume < 0) {
				volume = DiscordBot.getInstance().getDiscord().getAudioPlayer().getVolume();
			}
			
			DiscordBot.getInstance().getDiscord().getAudioPlayer().setVolume(volume);
			embedBuilder.setColor(DiscordUtil.SUCCESS);
		} catch (NumberFormatException ex) {
			embedBuilder.setColor(DiscordUtil.ERROR);
			embedBuilder.setTitle("Invalid volume!", null);
			DiscordBot.getInstance().getDiscord().getMessageSender().sendMessage(textChannel, embedBuilder.build(), true);
			return;
		}
	}
	
	embedBuilder.setTitle("Volume - " + DiscordBot.getInstance().getDiscord().getAudioPlayer().getVolume(), null);
	DiscordBot.getInstance().getDiscord().getMessageSender().sendMessage(textChannel, embedBuilder.build(), true);
}
 
Example #6
Source File: WarnCommand.java    From FlareBot with MIT License 6 votes vote down vote up
@Override
public void onCommand(User sender, GuildWrapper guild, TextChannel channel, Message message, String[] args, Member member) {
    if (args.length == 0) {
        MessageUtils.sendUsage(this, channel, sender, args);
    } else {
        User user = GuildUtils.getUser(args[0]);
        if (user == null) {
            MessageUtils.sendErrorMessage("We couldn't find that user!!", channel);
            return;
        }
        String reason = null;
        if (args.length >= 2) reason = MessageUtils.getMessage(args, 1);

        ModlogHandler.getInstance().handleAction(guild, channel, sender, user, ModAction.WARN, reason);
    }
}
 
Example #7
Source File: UnmuteCommand.java    From FlareBot with MIT License 6 votes vote down vote up
@Override
public void onCommand(User sender, GuildWrapper guild, TextChannel channel, Message message, String[] args, Member member) {
    if (args.length >= 1) {
        User target = GuildUtils.getUser(args[0]);
        if (target == null) {
            MessageUtils.sendErrorMessage("We cannot find that user! Try their ID if you didn't already.", channel, sender);
            return;
        }
        String reason = null;
        if (args.length >= 2)
            reason = MessageUtils.getMessage(args, 1);

        ModlogHandler.getInstance().handleAction(guild, channel, sender, target, ModAction.UNMUTE, reason);
    } else {
        MessageUtils.sendUsage(this, channel, sender, args);
    }
}
 
Example #8
Source File: UnbanCommand.java    From FlareBot with MIT License 6 votes vote down vote up
@Override
public void onCommand(User sender, GuildWrapper guild, TextChannel channel, Message message, String[] args, Member member) {
    if (args.length >= 1) {
        User target = GuildUtils.getUser(MessageUtils.getMessage(args, 0), null, true);
        if (target == null) {
            MessageUtils.sendErrorMessage("We cannot find that user! Try their ID if you didn't already.\n"
                            + "To get a User ID simply enable developer mode by going to User Settings > Appearance " +
                            "> Developer Mode then just right click the user and click Copy ID",
                    channel, sender);
            return;
        }
        ModlogHandler.getInstance().handleAction(guild, channel, sender, target, ModAction.UNBAN, null);
    } else {
        MessageUtils.sendUsage(this, channel, sender, args);
    }
}
 
Example #9
Source File: DiscordCommand.java    From DiscordBot with Apache License 2.0 6 votes vote down vote up
public void execute(TextChannel channel, Member member, String command) {
	if (command.equalsIgnoreCase("botinfo")) {
		channel.sendMessage("DiscordBot - Bungeecord Edition, Version " + DiscordBotCore.getInstance().getConfiguration().getDiscordBotVersion() + ", Created by LX_Gaming\nJDA - " + DiscordBotCore.getInstance().getConfiguration().getJDAVersion()).queue();
		return;
	}
	
	if (command.equalsIgnoreCase("website")) {
		channel.sendMessage("``Website:`` **https://lxgaming.github.io/**\n``Source:`` **https://github.com/LXGaming/DiscordBot/**").queue();
		return;
	}
	
	DiscordBotCore.getInstance().getEventManager().onCommandReceived(new Message()
			.setChannel(channel.getId())
			.setFormat(DiscordBotCore.getInstance().getConfiguration().getCommandFormat().get(command.split(" ")[0]))
			.setName(member.getEffectiveName())
			.setNick(member.getNickname())
			.setMessage(command));
}
 
Example #10
Source File: HelpCommand.java    From FlareBot with MIT License 6 votes vote down vote up
@Override
public void onCommand(User sender, GuildWrapper guild, TextChannel channel, Message message, String[] args, Member member) {
    if (args.length == 1) {
        CommandType type;
        try {
            type = CommandType.valueOf(args[0].toUpperCase());
        } catch (IllegalArgumentException ignored) {
            channel.sendMessage(MessageUtils.getEmbed(sender).setDescription("No such category!").build()).queue();
            return;
        }
        if (type.isInternal() && !GeneralUtils.canRunInternalCommand(type, sender)) {
            channel.sendMessage(MessageUtils.getEmbed(sender).setDescription("No such category!").build()).queue();
            return;
        }

        sendCommands(guild, channel, member, type);
    } else
        sendCommands(channel.getGuild(), channel, sender);
}
 
Example #11
Source File: ForceBanCommand.java    From FlareBot with MIT License 6 votes vote down vote up
@Override
public void onCommand(User sender, GuildWrapper guild, TextChannel channel, Message message, String[] args, Member member) {
    if (args.length >= 1) {
        User user = GuildUtils.getUser(args[0], true);
        if (user == null) {
            MessageUtils.sendErrorMessage("We cannot find that user!", channel, sender);
            return;
        }
        String reason = null;
        if (args.length >= 2)
            reason = MessageUtils.getMessage(args, 1);
        ModlogHandler.getInstance().handleAction(guild, channel, sender, user, ModAction.FORCE_BAN, reason);
    } else {
        MessageUtils.sendUsage(this, channel, sender, args);
    }
}
 
Example #12
Source File: HelpCommand.java    From FlareBot with MIT License 6 votes vote down vote up
public void sendCommands(GuildWrapper guild, TextChannel channel, Member member, CommandType type) {
    List<String> pages = new ArrayList<>();
    List<String> help = type.getCommands()
            .stream().filter(cmd -> getPermissions(channel)
                    .hasPermission(member, cmd.getPermission()))
            .map(command -> guild.getPrefix() + command.getCommand() + " - " + command
                    .getDescription() + '\n')
            .collect(Collectors.toList());
    StringBuilder sb = new StringBuilder();
    for (String s : help) {
        if (sb.length() + s.length() > 1024) {
            pages.add(sb.toString());
            sb.setLength(0);
        }
        sb.append(s);
    }
    pages.add(sb.toString());
    PagedEmbedBuilder<String> builder = new PagedEmbedBuilder<>(new PaginationList<>(pages));
    builder.setTitle("***FlareBot " + type + " commands!***")
            .setColor(Color.CYAN);
    PaginationUtil.sendEmbedPagedMessage(builder.build(), 0, channel, member.getUser(), ButtonGroupConstants.HELP);
}
 
Example #13
Source File: Command.java    From DiscordBot with Apache License 2.0 6 votes vote down vote up
public void execute(TextChannel textChannel, Member member, Message message) {
	List<String> arguments;
	if (message.getContent().startsWith(DiscordBot.getInstance().getConfig().getCommandPrefix())) {
		arguments = getValidArguments(DiscordUtil.filter(message.getContent().substring(DiscordBot.getInstance().getConfig().getCommandPrefix().length())).split(" "));
	} else {
		arguments = getValidArguments(DiscordUtil.filter(message.getContent().substring(1)).split(" "));
	}
	
	if (arguments == null || arguments.size() < 1) {
		return;
	}
	
	for (Iterator<ICommand> iterator = getRegisteredCommands().iterator(); iterator.hasNext();) {
		ICommand command = iterator.next();
		if (checkCommandName(arguments.get(0), command.getName()) || checkCommandAliases(arguments.get(0), command.getAliases())) {
			LogHelper.debug("Processing Command '" + message.getContent() + "' For '" + member.getEffectiveName() + "'.");
			arguments.remove(0);
			command.execute(textChannel, member, message, arguments);
			DiscordBot.getInstance().getDiscord().getMessageSender().addMessage(message);
			return;
		}
	}
}
 
Example #14
Source File: MusicAnnounceCommand.java    From FlareBot with MIT License 6 votes vote down vote up
@Override
public void onCommand(User sender, GuildWrapper guild, TextChannel channel, Message message, String[] args, Member member) {
    if (args.length == 1 && ARGS_PATTERN.matcher(args[0]).matches()) {
        if (args[0].equalsIgnoreCase("here")) {
            guild.setMusicAnnounceChannelId(channel.getId());
            channel.sendMessage(MessageUtils.getEmbed(sender)
                    .setDescription("Set music announcements to appear in " + channel
                            .getAsMention()).build()).queue();
        } else {
            guild.setMusicAnnounceChannelId(null);
            channel.sendMessage(MessageUtils.getEmbed(sender)
                    .setDescription(String
                            .format("Disabled announcements for `%s`", channel.getGuild()
                                    .getName()))
                    .build()).queue();
        }
    } else {
        MessageUtils.sendUsage(this, channel, sender, args);
    }
}
 
Example #15
Source File: StopCommand.java    From DiscordBot with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(TextChannel textChannel, Member member, Message message, List<String> arguments) {
	EmbedBuilder embedBuilder = new EmbedBuilder();
	embedBuilder.setAuthor(textChannel.getJDA().getSelfUser().getName(), null, textChannel.getJDA().getSelfUser().getEffectiveAvatarUrl());
	embedBuilder.setColor(DiscordUtil.DEFAULT);
	
	if (DiscordBot.getInstance().getDiscord().getAudioPlayer().getPlayingTrack() == null) {
		embedBuilder.setColor(DiscordUtil.ERROR);
		embedBuilder.setTitle("Player is not playing anything!", null);
		DiscordBot.getInstance().getDiscord().getMessageSender().sendMessage(textChannel, embedBuilder.build(), true);
		return;
	}
	
	DiscordBot.getInstance().getDiscord().getAudioPlayer().stopTrack();
	embedBuilder.setColor(DiscordUtil.SUCCESS);
	embedBuilder.setTitle("Track stopped.", null);
	DiscordBot.getInstance().getDiscord().getMessageSender().sendMessage(textChannel, embedBuilder.build(), true);
}
 
Example #16
Source File: FlareBotManager.java    From FlareBot with MIT License 6 votes vote down vote up
public ArrayList<String> loadPlaylist(TextChannel channel, User sender, String name) {
    final ArrayList<String> list = new ArrayList<>();
    CassandraController.runTask(session -> {
        if (loadPlaylistStatement == null) loadPlaylistStatement = session.prepare("SELECT songs FROM " +
                "flarebot.playlist WHERE playlist_name = ? AND guild_id = ?");

        ResultSet set =
                session.execute(loadPlaylistStatement.bind().setString(0, name).setString(1, channel.getGuild().getId()));
        Row row = set.one();
        if (row != null) {
            list.addAll(row.getList("songs", String.class));
        } else
            channel.sendMessage(MessageUtils.getEmbed(sender)
                    .setDescription("That playlist does not exist!").build()).queue();
    });
    return list;
}
 
Example #17
Source File: HelpCommand.java    From DiscordBot with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(TextChannel textChannel, Member member, Message message, List<String> arguments) {
	EmbedBuilder embedBuilder = new EmbedBuilder();
	embedBuilder.setAuthor(textChannel.getJDA().getSelfUser().getName(), null, textChannel.getJDA().getSelfUser().getEffectiveAvatarUrl());
	embedBuilder.setColor(DiscordUtil.DEFAULT);
	embedBuilder.setTitle("Commands", null);
	
	for (Iterator<ICommand> iterator = DiscordBot.getInstance().getDiscord().getCommand().getRegisteredCommands().iterator(); iterator.hasNext();) {
		ICommand command = iterator.next();
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append("Description - " + command.getDescription() + "\n");
		stringBuilder.append("Usage - " + command.getUsage() + "\n");
		
		if (command.getAliases() != null && !command.getAliases().isEmpty()) {
			stringBuilder.append("Aliases - " + String.join(", ", command.getAliases()));
		}
		embedBuilder.addField(command.getName(), stringBuilder.toString(), false);
	}
	
	embedBuilder.setFooter("<> = Required Argument, [] = Optional Argument", null);
	DiscordBot.getInstance().getDiscord().getMessageSender().sendMessage(textChannel, embedBuilder.build(), true);
}
 
Example #18
Source File: ModlogCommand.java    From FlareBot with MIT License 6 votes vote down vote up
private void listEvents(TextChannel channel, int page, User user) {
    StringBuilder sb = new StringBuilder();
    String groupKey = null;
    for (ModlogEvent modlogEvent : ModlogEvent.events) {
        String name = modlogEvent.getName();
        String[] split = name.split(" ");
        if (groupKey == null || groupKey.isEmpty())
            groupKey = split[0];

        if (!groupKey.equals(split[0])) {
            sb.append('\n');
            groupKey = split[0];
        }

        sb.append("`").append(modlogEvent.getTitle()).append("` - ").append(modlogEvent.getDescription()).append('\n');
    }
    sb.append("`Default` - Is for all the normal default events\n");
    sb.append("`All` - Is for targeting all events");
    PaginationUtil.sendEmbedPagedMessage(
            new PagedEmbedBuilder<>(PaginationUtil.splitStringToList(sb.toString(), PaginationUtil.SplitMethod.CHAR_COUNT, 1024))
                    .setTitle("Modlog Events")
                    .build(), page - 1, channel, user, ButtonGroupConstants.MODLOG_FEATURES);

}
 
Example #19
Source File: InfoCommand.java    From FlareBot with MIT License 5 votes vote down vote up
@Override
public void onCommand(User sender, GuildWrapper guild, TextChannel channel, Message message, String[] args, Member member) {
    if (args.length == 0) {
        EmbedBuilder bld = MessageUtils.getEmbed()
                .setThumbnail(MessageUtils.getAvatar(channel.getJDA().getSelfUser()))
                .setFooter("Made by Walshy#9060 and BinaryOverload#2382", channel.getJDA().getSelfUser().getEffectiveAvatarUrl());
        bld.setDescription("FlareBot v" + FlareBot.getVersion() + " info")
                .setColor(Color.CYAN);
        for (Content content : Content.values) {
            bld.addField(content.getName(), content.getReturn(), content.isAlign());
        }
        channel.sendMessage(bld.build()).queue();
    } else
        GeneralUtils.handleMultiSelectionCommand(sender, channel, args, Content.values);
}
 
Example #20
Source File: LoopCommand.java    From FlareBot with MIT License 5 votes vote down vote up
@Override
public void onCommand(User sender, GuildWrapper guild, TextChannel channel, Message message, String[] args, Member member) {
    Player player = FlareBot.instance().getMusicManager().getPlayer(channel.getGuild().getId());
    if (!player.getLooping()) {
        player.setLooping(true);
        channel.sendMessage("Looping: **ON**").queue();
    } else {
        player.setLooping(false);
        channel.sendMessage("Looping: **OFF**").queue();
    }
}
 
Example #21
Source File: StatsCommand.java    From FlareBot with MIT License 5 votes vote down vote up
@Override
public void onCommand(User sender, GuildWrapper guild, TextChannel channel, Message message, String[] args, Member member) {
    if (args.length == 0) {
        EmbedBuilder bld = MessageUtils.getEmbed(sender).setColor(Color.CYAN)
                .setThumbnail(MessageUtils.getAvatar(channel.getJDA().getSelfUser()));
        bld.setDescription("FlareBot v" + FlareBot.instance().getVersion() + " stats");
        for (MultiSelectionContent<String, String, Boolean> content : Content.values) {
            bld.addField(content.getName(), content.getReturn(), content.isAlign());
        }
        channel.sendMessage(bld.build()).queue();
    } else
        GeneralUtils.handleMultiSelectionCommand(sender, channel, args, Content.values);
}
 
Example #22
Source File: URLChecker.java    From FlareBot with MIT License 5 votes vote down vote up
public void checkMessage(GuildWrapper wrapper, TextChannel channel, String message,
                         BiConsumer<URLCheckFlag, String> callback) {
    NINO nino = wrapper.getNINO();
    Matcher m = nino.getNINOMode() == NINOMode.AGGRESSIVE ? URLConstants.URL_PATTERN_NO_PROTOCOL.matcher(message)
            : URLConstants.URL_PATTERN.matcher(message);
    if (!m.find()) return;

    String url = normalizeUrl(m.group(0));

    EXECUTOR.submit(() -> {
        Set<URLCheckFlag> flags = wrapper.getNINO().getURLFlags();

        Pair<URLCheckFlag, String> pair = checkURL(url, flags, channel);

        if (pair != null) {
            // Returned if it's a whitelisted URL
            if (pair.getKey() == null && pair.getValue() != null) {
                callback.accept(null, null);
                return;
            }
            logger.debug("{} was found to be under the flag {} ({})", url, pair.getKey(), pair.getValue());
            callback.accept(pair.getKey(), pair.getValue());
            return;
        } else {
            if (nino.getNINOMode() == NINOMode.RELAXED) return; // Shouldn't follow.
            logger.debug("{} was not flagged, going to try and follow the URL.", url);
            if ((pair = followURL(url, channel, flags, null)) != null) {
                logger.debug("{} was found to be under the flag {} ({}) after following it", url, pair.getKey(), pair.getValue());
                callback.accept(pair.getKey(), pair.getValue());
                return;
            }
        }

        callback.accept(null, null);
    });
}
 
Example #23
Source File: InfoCommand.java    From DiscordBot with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(TextChannel textChannel, Member member, Message message, List<String> arguments) {
	EmbedBuilder embedBuilder = new EmbedBuilder();
	embedBuilder.setAuthor(Reference.APP_NAME + " v" + Reference.APP_VERSION, null, textChannel.getJDA().getSelfUser().getEffectiveAvatarUrl());
	embedBuilder.setColor(DiscordUtil.DEFAULT);
	embedBuilder.addField("Author", String.join(", ", Reference.AUTHORS), false);
	embedBuilder.addField("Source", Reference.SOURCE, false);
	embedBuilder.addField("Website", Reference.WEBSITE, false);
	embedBuilder.addField("Dependencies", ""
			+ "\n- " + Reference.JDA_NAME + " v" + Reference.JDA_VERSION
			+ "\n- " + Reference.LAVA_NAME + " v" + Reference.LAVA_VERSION, false);
	DiscordBot.getInstance().getDiscord().getMessageSender().sendMessage(textChannel, embedBuilder.build(), true);
}
 
Example #24
Source File: URLChecker.java    From FlareBot with MIT License 5 votes vote down vote up
public void runTests(String[] links, TextChannel channel) {
    GuildWrapper wrapper = FlareBotManager.instance().getGuild(channel.getGuild().getId());

    byte before = wrapper.getNINO().getMode();
    Set<URLCheckFlag> oldFlags = wrapper.getNINO().getURLFlags();
    wrapper.getNINO().setMode(NINOMode.AGGRESSIVE.getMode());
    wrapper.getNINO().setFlags(URLCheckFlag.getDebugFlags());

    StringBuilder sb = new StringBuilder();
    sb.append("Links:\n");
    CountDownLatch countDownLatch = new CountDownLatch(links.length);
    for (String link : links) {
        instance().checkMessage(wrapper, null, link.trim(), (flag, u) -> {
            if (flag != null)
                sb.append(link.trim()).append(" - ").append(flag).append("\n");
            logger.info("{} - {}", link.trim(), flag);
            countDownLatch.countDown();
        });
    }
    try {
        countDownLatch.await();

        channel.sendMessage(sb.toString()).queue();
    } catch (InterruptedException e) {
        logger.error("Failed to wait for checks", e);
        channel.sendMessage("Something went wrong: " + e.getMessage()).queue();
    }
    wrapper.getNINO().setMode(before);
    wrapper.getNINO().setFlags(oldFlags);
}
 
Example #25
Source File: UpdateCommand.java    From FlareBot with MIT License 5 votes vote down vote up
/**
 * Update to the newest version of FlareBot!
 *
 * @param force   If the version number has not changed this will need to be true in order to update it.
 * @param channel Channel the command was sent in.
 */
public static void update(boolean force, TextChannel channel) {
    if (force) {
        doTheUpdate(channel, "latest", FlareBot.getVersion());
        return;
    }
    try {
        URL url = new URL("https://raw.githubusercontent.com/FlareBot/FlareBot/master/pom.xml");
        BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
        String line;
        while (true) {
            line = br.readLine();
            if (line != null && (line.contains("<version>") && line.contains("</version>"))) {
                String latestVersion = line.replace("<version>", "").replace("</version>", "").replaceAll(" ", "")
                        .replaceAll("\t", "");
                String currentVersion = FlareBot.getVersion();
                if (isHigher(latestVersion, currentVersion)) {
                    doTheUpdate(channel, latestVersion, currentVersion);
                } else {
                    if (channel != null)
                        channel.sendMessage("I am currently up to date! Current version: `" + currentVersion + "`")
                                .queue();
                }
                break;
            }
        }
    } catch (IOException e) {
        FlareBot.LOGGER.error("Could not update!", e);
    }
}
 
Example #26
Source File: SourcesCommand.java    From DiscordBot with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(TextChannel textChannel, Member member, Message message, List<String> arguments) {
	EmbedBuilder embedBuilder = new EmbedBuilder();
	embedBuilder.setAuthor(textChannel.getJDA().getSelfUser().getName(), null, textChannel.getJDA().getSelfUser().getEffectiveAvatarUrl());
	embedBuilder.setColor(DiscordUtil.DEFAULT);
	embedBuilder.addField("Sources", String.join(",\n", DiscordBot.getInstance().getConfig().getAllowedSources()), false);
	DiscordBot.getInstance().getDiscord().getMessageSender().sendMessage(textChannel, embedBuilder.build(), true);
}
 
Example #27
Source File: SongNickCommand.java    From FlareBot with MIT License 5 votes vote down vote up
@Override
public void onCommand(User sender, GuildWrapper guild, TextChannel channel, Message message, String[] args, Member member) {
    if (guild.isSongnickEnabled()) {
        guild.setSongnick(false);
        if (GuildUtils.canChangeNick(guild.getGuildId()))
            channel.getGuild().getController().setNickname(channel.getGuild().getSelfMember(), null).queue();
        MessageUtils.sendSuccessMessage("Disabled changing nickname with song!", channel, sender);
    } else {
        if (!GuildUtils.canChangeNick(guild.getGuildId())) {
            MessageUtils.sendErrorMessage("FlareBot can't change it's nickname so SongNick hasn't been enabled",
                    channel);
            return;
        }
        guild.setSongnick(true);
        if (FlareBot.instance().getMusicManager().getPlayer(guild.getGuildId()).getPlayingTrack() != null) {
            Track track = FlareBot.instance().getMusicManager().getPlayer(guild.getGuildId()).getPlayingTrack();
            String str = null;
            if (track != null) {
                str = track.getTrack().getInfo().title;
                if (str.length() > 32)
                    str = str.substring(0, 32);
                str = str.substring(0, str.lastIndexOf(' ') + 1);
            } // Even I couldn't make this a one-liner
            guild.getGuild().getController()
                    .setNickname(guild.getGuild().getSelfMember(), str)
                    .queue();
        }
        MessageUtils.sendSuccessMessage("Enabled changing nickname with song!", channel, sender);
    }
}
 
Example #28
Source File: KillCommand.java    From FlareBot with MIT License 5 votes vote down vote up
@Override
public void onCommand(User sender, GuildWrapper guild, TextChannel channel, Message message, String[] args, Member member) {
    if (guild.getGuild().getAudioManager().isAttemptingToConnect() || guild.getGuild().getAudioManager().isConnected()) {
        guild.getGuild().getAudioManager().closeAudioConnection();
        FlareBot.instance().getMusicManager().getPlayer(guild.getGuildId()).clean();
    }
    channel.sendMessage("Killed the voice connection, please change voice region and try to use the bot " +
            "again!").queue();
}
 
Example #29
Source File: FlareBotManager.java    From FlareBot with MIT License 5 votes vote down vote up
public void savePlaylist(Command command, TextChannel channel, String ownerId, boolean overwriteAllowed, String name, List<String> songs) {
    CassandraController.runTask(session -> {
        if (savePlaylistStatement == null)
            savePlaylistStatement = session.prepare("SELECT * FROM flarebot.playlist " +
                    "WHERE playlist_name = ? AND guild_id = ?");

        ResultSet set =
                session.execute(savePlaylistStatement.bind().setString(0, name).setString(1, channel.getGuild().getId()));
        if (set.one() != null) {
            if (ConfirmUtil.checkExists(ownerId, command.getClass())) {
                MessageUtils.sendWarningMessage("Overwriting playlist!", channel);
            } else if (!overwriteAllowed) {
                MessageUtils.sendErrorMessage("That name is already taken! You need the `flarebot.queue.save.overwrite` permission to overwrite", channel);
                return;
            } else {
                MessageUtils.sendErrorMessage("That name is already taken! Do this again within 1 minute to overwrite!", channel);
                ConfirmUtil.pushAction(ownerId, new RunnableWrapper(Runnables.doNothing(), command.getClass()));
                return;
            }
        }
        if (insertPlaylistStatement == null)
            insertPlaylistStatement = session.prepare("INSERT INTO flarebot.playlist" +
                    " (playlist_name, guild_id, owner, songs, scope, times_played) VALUES (?, ?, ?, ?, ?, ?)");

        session.execute(insertPlaylistStatement.bind().setString(0, name).setString(1, channel.getGuild().getId())
                .setString(2, ownerId).setList(3, songs).setString(4, "local").setInt(5, 0));
        channel.sendMessage(MessageUtils.getEmbed(Getters.getUserById(ownerId))
                .setDescription("Successfully saved the playlist: " + MessageUtils.escapeMarkdown(name)).build()).queue();
    });
}
 
Example #30
Source File: SeekCommand.java    From FlareBot with MIT License 5 votes vote down vote up
@Override
public void onCommand(User sender, GuildWrapper guild, TextChannel channel, Message message, String[] args, Member member) {
    if (args.length == 1) {
        Long millis = GeneralUtils.parseTime(args[0]);
        if (millis == null || millis > Integer.MAX_VALUE) {
            MessageUtils.sendErrorMessage("You have entered an invalid duration to skip to!\n" + getExtraInfo(), channel);
            return;
        }
        Track t = FlareBot.instance().getMusicManager().getPlayer(guild.getGuildId()).getPlayingTrack();
        if (t == null) {
            MessageUtils.sendErrorMessage("There is no song currently playing!", channel);
            return;
        } else {
            if (t.getTrack().getInfo().isStream) {
                MessageUtils.sendErrorMessage("Cannot seek on a livestream!", channel);
                return;
            } else if (!t.getTrack().isSeekable()) {
                MessageUtils.sendErrorMessage("Cannot seek on this track!", channel);
                return;
            } else {
                if (millis >= t.getTrack().getDuration()) {
                    MessageUtils.sendErrorMessage("The duration specified is bigger than the length of the video!", channel);
                    return;
                } else {
                    t.getTrack().setPosition(millis);
                    MessageUtils.sendSuccessMessage("The track has been skipped to: " + FormatUtils.formatJodaTime(new Duration(millis).toPeriod()), channel);
                    return;
                }
            }
        }
    }
    MessageUtils.sendUsage(this, channel, sender, args);
}