com.avairebot.commands.CommandMessage

Here are the examples of the java api com.avairebot.commands.CommandMessage taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

362 Examples 7

19 Source : MentionableUtil.java
with GNU General Public License v3.0
from avaire

/**
 * Gets the <code>N</code>th index user object matching in the given context and arguments,
 * the method will try the following to get a user object out the other end.
 * <ul>
 * <li>Discord mentions (@Someone)</li>
 * <li>Full name mentions (Senither#000)</li>
 * <li>Name mentions (Senither)</li>
 * <li>User ID (88739639380172800)</li>
 * </ul>
 * <p>
 * If none of the checks finds a valid user object, <code>null</code> will be returned instead.
 *
 * @param context The command message context.
 * @param args    The arguments parsed to the command.
 * @param index   The index of the argument that should be checked.
 * @return Possibly-null, or the user matching the given index.
 */
@Nullable
public static User getUser(@Nonnull CommandMessage context, @Nonnull String[] args, int index) {
    if (args.length <= index) {
        return null;
    }
    String part = args[index].trim();
    if (!context.getMentionedUsers().isEmpty() && userRegEX.matcher(args[index]).matches()) {
        String userId = part.substring(2, part.length() - 1);
        if (userId.charAt(0) == '!') {
            userId = userId.substring(1, userId.length());
        }
        try {
            Member member = context.getGuild().getMemberById(userId);
            return member == null ? null : member.getUser();
        } catch (NumberFormatException e) {
            return null;
        }
    }
    if (NumberUtil.isNumeric(part)) {
        try {
            Member member = context.getGuild().getMemberById(part);
            return member == null ? null : member.getUser();
        } catch (NumberFormatException e) {
            return null;
        }
    }
    String[] parts = part.split("#");
    if (parts.length != 2) {
        if (parts.length == 0 || parts[0].trim().length() == 0) {
            return null;
        }
        List<Member> effectiveName = context.getGuild().getMembersByEffectiveName(parts[0], true);
        if (effectiveName.isEmpty()) {
            return null;
        }
        return effectiveName.get(0).getUser();
    }
    if (parts[0].length() == 0) {
        return null;
    }
    List<Member> members = context.getGuild().getMembersByName(parts[0], true);
    for (Member member : members) {
        if (member.getUser().getDiscriminator().equals(parts[1])) {
            return member.getUser();
        }
    }
    return null;
}

19 Source : MentionableUtil.java
with GNU General Public License v3.0
from avaire

/**
 * Gets the first user object matching in the given context and arguments, the
 * method will try the following to get a user object out the other end.
 * <p>
 * <ul>
 * <li>Discord mentions (@Someone)</li>
 * <li>Full name mentions (Senither#000)</li>
 * <li>Name mentions (Senither)</li>
 * <li>User ID (88739639380172800)</li>
 * </ul>
 * <p>
 * If none of the checks finds a valid user object, <code>null</code> will be returned instead.
 *
 * @param context The command message context.
 * @param args    The arguments parsed to the command.
 * @return Possibly-null, or the user matching the first index.
 */
@Nullable
public static User getUser(@Nonnull CommandMessage context, @Nonnull String[] args) {
    return getUser(context, args, 0);
}

19 Source : ThrottleMiddleware.java
with GNU General Public License v3.0
from avaire

@Override
public String buildHelpDescription(@Nonnull CommandMessage context, @Nonnull String[] arguments) {
    return String.format("**This command can only be used `%s` time(s) every `%s` seconds per %s**", arguments[1], arguments[2], arguments[0].equalsIgnoreCase("guild") ? "server" : arguments[0]);
}

19 Source : RequirePermissionMiddleware.java
with GNU General Public License v3.0
from avaire

@Override
public String buildHelpDescription(@Nonnull CommandMessage context, @Nonnull String[] arguments) {
    PermissionType type = PermissionType.fromName(arguments[0]);
    arguments = Arrays.copyOfRange(arguments, 1, arguments.length);
    if (arguments.length == 1) {
        return PermissionCommon.formatWithOneArgument(type, arguments[0]);
    }
    return String.format(PermissionCommon.getPermissionTypeMessage(type, true), Arrays.stream(arguments).map(Permissions::fromNode).map(Permissions::getPermission).map(Permission::getName).collect(Collectors.joining("`, `")));
}

19 Source : RequireOnePermissionMiddleware.java
with GNU General Public License v3.0
from avaire

@Override
public String buildHelpDescription(@Nonnull CommandMessage context, @Nonnull String[] arguments) {
    PermissionType type = PermissionType.fromName(arguments[0]);
    arguments = Arrays.copyOfRange(arguments, 1, arguments.length);
    if (arguments.length == 1) {
        return PermissionCommon.formatWithOneArgument(type, arguments[0]);
    }
    return String.format("**One of the following permissions is required to use this command:\n `%s`**", Arrays.stream(arguments).map(Permissions::fromNode).map(Permissions::getPermission).map(Permission::getName).collect(Collectors.joining("`, `")));
}

19 Source : IsDMMessageMiddleware.java
with GNU General Public License v3.0
from avaire

@Override
public String buildHelpDescription(@Nonnull CommandMessage context, @Nonnull String[] arguments) {
    return "**This command can only be used in DMs.**";
}

19 Source : IsBotAdminMiddleware.java
with GNU General Public License v3.0
from avaire

@Override
public String buildHelpDescription(@Nonnull CommandMessage context, @Nonnull String[] arguments) {
    return "**You must be a Bot Administrator to use this command!**";
}

19 Source : HasVotedTodayMiddleware.java
with GNU General Public License v3.0
from avaire

@Override
public String buildHelpDescription(@Nonnull CommandMessage context, @Nonnull String[] arguments) {
    if (!avaire.getConfig().getBoolean("vote-lock.enabled", true)) {
        return null;
    }
    return "**You must [vote for Ava](https://discordbots.org/bot/avaire) to use this command**";
}

19 Source : HasRoleMiddleware.java
with GNU General Public License v3.0
from avaire

@Override
public String buildHelpDescription(@Nonnull CommandMessage context, @Nonnull String[] arguments) {
    if (arguments.length == 1) {
        return String.format("**The `%s` role is required to use this command!**", arguments[0]);
    }
    return String.format("**The `%s` roles is required to use this command!**", String.join("`, `", arguments));
}

19 Source : HasAnyRoleMiddleware.java
with GNU General Public License v3.0
from avaire

@Override
public String buildHelpDescription(@Nonnull CommandMessage context, @Nonnull String[] arguments) {
    if (arguments.length == 1) {
        return String.format("**The `%s` role is required to use this command!**", arguments[0]);
    }
    return String.format("**One of the `%s` roles is required to use this command!**", String.join("`, `", arguments));
}

19 Source : Middleware.java
with GNU General Public License v3.0
from avaire

/**
 * Builds the help description that should be displayed when the help command is used
 * for a command that uses the middleware, if null is returned the middleware will
 * be omitted from the help command.
 *
 * @param context   The command context from when the method was called.
 * @param arguments The arguments that was given to the middleware for the current command.
 * @return Possibly-null, the description of the middleware, or null if no description should be displayed.
 */
@Nullable
public String buildHelpDescription(@Nonnull CommandMessage context, @Nonnull String[] arguments) {
    return null;
}

19 Source : PlaylistSubCommand.java
with GNU General Public License v3.0
from avaire

/**
 * The main command handler for the sub playlist command, the method will invoke
 * another sub command depending on what the object type given is.
 *
 * @param context The command message context generated using the
 *                JDA message event that invoked the command.
 * @param args    The arguments parsed to the command.
 * @param guild   The guild transformer instance for the current guild.
 * @param object  The playlist transformer instance, or a collection
 *                of playlists loaded from the database.
 * @return {@code True} on success, {@code False} on failure.
 * @see #onCommand(CommandMessage, String[], GuildTransformer, Collection)
 * @see #onCommand(CommandMessage, String[], GuildTransformer, PlaylistTransformer)
 */
public final boolean onCommand(CommandMessage context, String[] args, GuildTransformer guild, Object object) {
    if (object instanceof PlaylistTransformer) {
        return onCommand(context, args, guild, (PlaylistTransformer) object);
    }
    return object instanceof Collection && onCommand(context, args, guild, (Collection) object);
}

19 Source : PlaylistSubCommand.java
with GNU General Public License v3.0
from avaire

/**
 * Handles the sub playlist command using the given command context,
 * command arguments, guild transformer for the current server,
 * and the collection of playlists.
 *
 * @param context   The command message context generated using the
 *                  JDA message event that invoked the command.
 * @param args      The arguments parsed to the command.
 * @param guild     The guild transformer instance for the current guild.
 * @param playlists The playlists that should be used for the command.
 * @return {@code True} on success, {@code False} on failure.
 */
public boolean onCommand(CommandMessage context, String[] args, GuildTransformer guild, Collection playlists) {
    return false;
}

19 Source : PlaylistSubCommand.java
with GNU General Public License v3.0
from avaire

/**
 * Handles the sub playlist command using the given command context,
 * command arguments, guild transformer for the current server,
 * and the playlist transformer for the selected playlist.
 *
 * @param context  The command message context generated using the
 *                 JDA message event that invoked the command.
 * @param args     The arguments parsed to the command.
 * @param guild    The guild transformer instance for the current guild.
 * @param playlist The selected playlist that should be used for the command.
 * @return {@code True} on success, {@code False} on failure.
 */
public boolean onCommand(CommandMessage context, String[] args, GuildTransformer guild, PlaylistTransformer playlist) {
    return false;
}

19 Source : Command.java
with GNU General Public License v3.0
from avaire

/**
 * Builds and sends the given error message to the
 * given channel for the JDA message object.
 *
 * @param context The command message context generated using the
 *                JDA message event that invoked the command.
 * @param error   The error message that should be sent.
 * @return false since the error message should only be used on failure.
 */
public final boolean sendErrorMessage(CommandMessage context, String error) {
    if (!isLanguageString(error)) {
        return sendErrorMessageAndDeleteMessage(context, error, 150, TimeUnit.SECONDS);
    }
    String i18nError = context.i18nRaw(error);
    return sendErrorMessageAndDeleteMessage(context, i18nError == null ? error : i18nError, 150, TimeUnit.SECONDS);
}

19 Source : Command.java
with GNU General Public License v3.0
from avaire

/**
 * Builds and sends the given error message to the given channel for the JDA
 * message object, then deletes the message again after the allotted time.
 *
 * @param context  The command message context generated using the
 *                 JDA message event that invoked the command.
 * @param error    The error message that should be sent.
 * @param deleteIn The amount of time the message should stay up before being deleted.
 * @param unit     The unit of time before the message should be deleted.
 * @return false since the error message should only be used on failure.
 */
public boolean sendErrorMessage(CommandMessage context, String error, long deleteIn, TimeUnit unit) {
    if (isLanguageString(error)) {
        String i18nError = context.i18nRaw(error);
        if (i18nError != null) {
            error = i18nError;
        }
    }
    if (unit == null) {
        unit = TimeUnit.SECONDS;
    }
    return sendErrorMessageAndDeleteMessage(context, error, deleteIn, unit);
}

19 Source : ChannelModuleCommand.java
with GNU General Public License v3.0
from avaire

/**
 * Sends the "Module has been enabled" message for the
 * given channel transformer, and the given type.
 *
 * @param context            The command message context.
 * @param channelTransformer The channel database transformer representing the current channel.
 * @param type               The of enabled message that should be sent.
 * @return Always returns {@code True}.
 */
protected boolean sendEnableMessage(CommandMessage context, ChannelTransformer channelTransformer, String type) {
    context.makeSuccess(context.i18nRaw("administration.channelModule.message")).set("type", type).set("message", getChannelModule(channelTransformer).getMessage()).set("command", generateCommandTrigger(context.getMessage())).queue();
    return true;
}

19 Source : ChannelModuleCommand.java
with GNU General Public License v3.0
from avaire

/**
 * Sends the example message of the command module by using
 * the provided command context, channel transformer,
 * and default value, sending it to the given user.
 *
 * @param context      The command message context.
 * @param user         The user that should be used for the user placeholders.
 * @param transformer  The channel database transformer representing the current channel.
 * @param defaultValue The default value that should be displayed if the
 *                     guild doesn't have one set for the module.
 * @return Always returns {@code True}.
 */
protected boolean sendExampleMessage(CommandMessage context, User user, ChannelTransformer transformer, String defaultValue) {
    String message = StringReplacementUtil.parse(context.getGuild(), context.getChannel(), user, getChannelModule(transformer).getMessage() == null ? defaultValue : getChannelModule(transformer).getMessage());
    String embedColor = getChannelModule(transformer).getEmbedColor();
    if (embedColor == null) {
        context.getMessageChannel().sendMessage(message).queue();
        return true;
    }
    context.getMessageChannel().sendMessage(MessageFactory.createEmbeddedBuilder().setDescription(message).setColor(Color.decode(embedColor)).build()).queue();
    return true;
}

19 Source : ChannelModuleCommand.java
with GNU General Public License v3.0
from avaire

/**
 * Updates the database for the current guild, and
 * then calls the callback supplier on success.
 *
 * @param context          The command message context.
 * @param guildTransformer The guild database transformer representing the current guild.
 * @param callback         The callback that should be invoked when the database record is updated.
 * @return The result of the {@code callback} if the database record was
 * updated successfully, or {@code False} if an error occurred.
 */
protected boolean updateDatabase(CommandMessage context, GuildTransformer guildTransformer, Supplier<Boolean> callback) {
    try {
        avaire.getDatabase().newQueryBuilder(Constants.GUILD_TABLE_NAME).andWhere("id", context.getGuild().getId()).update(statement -> statement.set("channels", guildTransformer.channelsToJson(), true));
        return callback.get();
    } catch (SQLException ex) {
        AvaIre.getLogger().error(ex.getMessage(), ex);
        context.makeError("Failed to save the guild settings: " + ex.getMessage()).queue();
        return false;
    }
}

19 Source : ChannelModuleCommand.java
with GNU General Public License v3.0
from avaire

/**
 * Handles the embed option for the channel module, this method is called
 * when the command specifies that it should use or disable embed
 * messages, by either parsing a colour code in a HEX format to
 * set the embed colour, or when using it with no additional
 * arguments to disable the feature.
 *
 * @param context            The command message context.
 * @param args               The arguments preplaceded to the original command.
 * @param guildTransformer   The guild database transformer representing the current guild.
 * @param channelTransformer The channel database transformer representing the current channel.
 * @param callback           The callback that should be invoked when the database record is updated.
 * @return {@code True} if everything ran successfully, or {@code False} if an error occurred, or invalid arguments was given.
 */
protected boolean handleEmbedOption(CommandMessage context, String[] args, GuildTransformer guildTransformer, ChannelTransformer channelTransformer, Supplier<Boolean> callback) {
    getChannelModule(channelTransformer).setEmbedColor(null);
    if (args.length > 1) {
        String color = args[1].toUpperCase();
        if (color.startsWith("#")) {
            color = color.substring(1);
        }
        if (!colorRegEx.matcher(color).matches()) {
            return sendErrorMessage(context, context.i18nRaw("administration.channelModule.invalidColorGiven"));
        }
        getChannelModule(channelTransformer).setEmbedColor("#" + color);
    }
    return updateDatabase(context, guildTransformer, callback);
}

19 Source : BanableCommand.java
with GNU General Public License v3.0
from avaire

private boolean banMemberOfServer(AvaIre avaire, Command command, CommandMessage context, User user, String[] args, boolean soft) {
    if (userHasHigherRole(user, context.getMember())) {
        return command.sendErrorMessage(context, context.i18n("higherRole"));
    }
    if (!context.getGuild().getSelfMember().canInteract(context.getGuild().getMember(user))) {
        return sendErrorMessage(context, context.i18n("userHaveHigherRole", user.getAsMention()));
    }
    String reason = generateReason(args);
    ModlogAction modlogAction = new ModlogAction(soft ? ModlogType.SOFT_BAN : ModlogType.BAN, context.getAuthor(), user, reason);
    String caseId = Modlog.log(avaire, context, modlogAction);
    Modlog.notifyUser(user, context.getGuild(), modlogAction, caseId);
    context.getGuild().ban(user, soft ? 0 : 7, String.format("%s - %s#%s (%s)", reason, context.getAuthor().getName(), context.getAuthor().getDiscriminator(), context.getAuthor().getId())).queue(aVoid -> {
        context.makeSuccess(context.i18n("success")).set("target", user.getName() + "#" + user.getDiscriminator()).set("reason", reason).queue();
    }, throwable -> context.makeWarning(context.i18n("failedToBan")).set("target", user.getName() + "#" + user.getDiscriminator()).set("error", throwable.getMessage()).queue());
    return true;
}

19 Source : BanableCommand.java
with GNU General Public License v3.0
from avaire

/**
 * Bans the mentioned user from the current server is a valid user was given.
 *
 * @param command The command that was used in banning the user.
 * @param context The message context object for the current message.
 * @param args    The arguments given by the user who ran the command.
 * @param soft    Determines if the user should be softbanned or not.
 * @return True if the user was banned successfully, false otherwise.
 */
protected boolean ban(AvaIre avaire, Command command, CommandMessage context, String[] args, boolean soft) {
    User user = MentionableUtil.getUser(context, args);
    if (user != null) {
        return banMemberOfServer(avaire, command, context, user, args, soft);
    }
    if (args.length > 0 && NumberUtil.isNumeric(args[0]) && args[0].length() > 16) {
        try {
            long userId = Long.parseLong(args[0], 10);
            Member member = context.getGuild().getMemberById(userId);
            if (member != null) {
                return banMemberOfServer(avaire, command, context, member.getUser(), args, soft);
            }
            return breplacederById(avaire, command, context, userId, args, soft);
        } catch (NumberFormatException ignored) {
        // This should never really be called since we check if
        // the argument is a number in the if-statement above.
        }
    }
    return command.sendErrorMessage(context, context.i18n("mustMentionUser"));
}

19 Source : BanableCommand.java
with GNU General Public License v3.0
from avaire

private boolean breplacederById(AvaIre avaire, Command command, CommandMessage context, long userId, String[] args, boolean soft) {
    String reason = generateReason(args);
    context.getGuild().ban(String.valueOf(userId), soft ? 0 : 7, String.format("%s - %s#%s (%s)", reason, context.getAuthor().getName(), context.getAuthor().getDiscriminator(), context.getAuthor().getId())).queue(aVoid -> {
        User user = avaire.getShardManager().getUserById(userId);
        if (user != null) {
            Modlog.log(avaire, context, new ModlogAction(soft ? ModlogType.SOFT_BAN : ModlogType.BAN, context.getAuthor(), user, reason));
        } else {
            Modlog.log(avaire, context, new ModlogAction(soft ? ModlogType.SOFT_BAN : ModlogType.BAN, context.getAuthor(), userId, reason));
        }
        context.makeSuccess(context.i18n("success")).set("target", userId).set("reason", reason).queue(ignoreMessage -> context.delete().queue(null, RestActionUtil.ignore));
    }, throwable -> context.makeWarning(context.i18n("failedToBan")).set("target", userId).set("error", throwable.getMessage()).queue());
    return true;
}

19 Source : ApplicationShutdownCommand.java
with GNU General Public License v3.0
from avaire

/**
 * The command executor, this method is invoked by the command handler
 * and the middleware stack when a user sends a message matching the
 * commands prefix and one of its command triggers.
 *
 * @param context The JDA message object from the message received event.
 * @param args    The arguments given to the command, if no arguments was given the array will just be empty.
 * @return true on success, false on failure.
 */
@Override
public boolean onCommand(CommandMessage context, String[] args) {
    if (context.isMentionableCommand()) {
        return sendErrorMessage(context, "This command can not be used via mentions!");
    }
    if (args.length == 0) {
        return sendErrorMessage(context, "You must include the time you want the bot to shutdown.");
    }
    if (args[0].equalsIgnoreCase("now")) {
        context.makeInfo(shutdownNow()).queue(shutdownMessage -> avaire.shutdown(exitCode()), throwable -> avaire.shutdown(exitCode()));
        return true;
    }
    if (args[0].equalsIgnoreCase("cancel")) {
        context.makeInfo(scheduleCancel()).queue(shutdownMessage -> avaire.scheduleShutdown(null, exitCode()), throwable -> avaire.scheduleShutdown(null, exitCode()));
        return true;
    }
    Carbon time = formatInput(String.join(" ", args));
    if (time == null) {
        return sendErrorMessage(context, "Invalid time format given, `%s` is not a valid supported time format.", String.join(" ", args));
    }
    if (time.isPast()) {
        return sendErrorMessage(context, "The time given is in the past, that doesn't really work... Use a time set in the future, or use `now`.");
    }
    context.makeSuccess(scheduleShutdown()).set("fromNow", time.diffForHumans(true)).set("date", time.format("EEEEEEEE, dd MMMMMMM yyyy - HH:mm:ss z")).queue(shutdownMessage -> avaire.scheduleShutdown(time, exitCode()), throwable -> avaire.scheduleShutdown(time, exitCode()));
    return true;
}

19 Source : WeatherCommand.java
with GNU General Public License v3.0
from avaire

@Override
public boolean onCommand(CommandMessage context, String[] args) {
    if (!hasApiKey()) {
        return false;
    }
    if (args.length == 0) {
        return sendErrorMessage(context, "errors.missingArgument", "city");
    }
    DrainWeatherQueueTask.queueWeather(new DrainWeatherQueueTask.WeatherEnreplacedy(context.getAuthor().getIdLong(), context.getMessageChannel().getIdLong(), String.join(" ", args)));
    context.getMessageChannel().sendTyping().queue();
    return true;
}

19 Source : VoteCommand.java
with GNU General Public License v3.0
from avaire

@Override
public boolean onCommand(CommandMessage context, String[] args) {
    VoteCacheEnreplacedy voteEnreplacedy = avaire.getVoteManager().getVoteEnreplacedy(context.getAuthor());
    if (args.length > 0 && args[0].equalsIgnoreCase("check")) {
        return checkUser(context, voteEnreplacedy);
    }
    String utilityPrefix = generateCommandPrefix(context.getMessage());
    // noinspection ConstantConditions
    String note = I18n.format(String.join("\n", Arrays.asList("You'll gain access to the `{0}volume` and `{0}default-volume` commands for the", "next 12 hours, as well as getting a vote point, you can spend your vote points", "to unlock special rank backgrounds using the `{1}backgrounds` command.", "", "Have you already voted and didn't get your vote rewards?", "Try run `{1}vote check`")), CommandHandler.getCommand(PlayCommand.clreplaced).getCategory().getPrefix(context.getMessage()), utilityPrefix);
    Carbon expire = avaire.getVoteManager().getExpireTime(context.getAuthor());
    if (expire != null && expire.isFuture()) {
        note = "You have already voted today, thanks for that btw!\nYou can vote again in " + expire.diffForHumans() + ".";
    }
    context.makeSuccess(String.join("\n", Arrays.asList("Enjoy using the bot? Consider voting for the bot to help it grow, it's free but means a lot to the team behind Ava ❤", "", "https://discordbots.org/bot/avaire", "", ":note"))).set("note", note).setreplacedle("Vote for AvaIre on DBL", "https://discordbots.org/bot/avaire").setFooter("You have " + (voteEnreplacedy == null ? 0 : voteEnreplacedy.getVotePoints()) + " vote points").queue();
    return true;
}

19 Source : VoteCommand.java
with GNU General Public License v3.0
from avaire

private boolean checkUser(CommandMessage context, VoteCacheEnreplacedy voteEnreplacedy) {
    Carbon expire = avaire.getVoteManager().getExpireTime(context.getAuthor());
    if (expire != null && expire.isFuture()) {
        context.makeInfo("You have already voted today, thanks for that btw!\nYou can vote again in :time.").setFooter("You have " + (voteEnreplacedy == null ? 0 : voteEnreplacedy.getVotePoints()) + " vote points").set("time", expire.diffForHumans()).queue();
        return true;
    }
    boolean wasAdded = avaire.getVoteManager().queueEnreplacedy(new VoteEnreplacedy(context.getAuthor().getIdLong(), context.getMessageChannel().getIdLong()));
    if (!wasAdded) {
        return false;
    }
    context.makeInfo(":user, You've been put on a queue to get your vote rewards. Make sure you've voted or nothing will happen!").queue();
    return true;
}

19 Source : VersionCommand.java
with GNU General Public License v3.0
from avaire

@SuppressWarnings("unchecked")
private PlaceholderMessage addAndFormatLatestCommits(CommandMessage context, PlaceholderMessage message) {
    if (avaire.getCache().getAdapter(CacheType.FILE).has("github.commits")) {
        List<LinkedTreeMap<String, Object>> items = (List<LinkedTreeMap<String, Object>>) avaire.getCache().getAdapter(CacheType.FILE).get("github.commits");
        StringBuilder commitChanges = new StringBuilder();
        for (int i = 0; i < 5; i++) {
            LinkedTreeMap<String, Object> item = items.get(i);
            LinkedTreeMap<String, Object> commit = (LinkedTreeMap<String, Object>) item.get("commit");
            commitChanges.append(String.format("[`%s`](%s) %s\n", item.get("sha").toString().substring(0, 7), item.get("html_url"), commit.get("message").toString().split("\n")[0].trim()));
        }
        message.addField(context.i18n("latestChanges"), commitChanges.toString(), false);
    }
    return message;
}

19 Source : VersionCommand.java
with GNU General Public License v3.0
from avaire

@Override
public boolean onCommand(CommandMessage context, String[] args) {
    SemanticVersion latestVersion = getLatestVersion();
    if (latestVersion == null) {
        return sendErrorMessage(context, "Failed to fetch the latest version of AvaIre, try again later.");
    }
    String template = String.join("\n", context.i18n("current"), "", ":message", "", context.i18n("getLatest"));
    PlaceholderMessage versionMessage = null;
    SemanticVersion currentVersion = new SemanticVersion(AppInfo.getAppInfo().version);
    if (latestVersion.major > currentVersion.major) {
        versionMessage = context.makeError(template).set("message", context.i18n("versions.major")).set("difference", latestVersion.major - currentVersion.major).set("type", context.i18n("versions.majorName"));
    } else if (latestVersion.minor > currentVersion.minor) {
        versionMessage = context.makeWarning(template).set("message", context.i18n("versions.minor")).set("difference", latestVersion.minor - currentVersion.minor).set("type", context.i18n("versions.minorName"));
    } else if (latestVersion.patch > currentVersion.patch) {
        versionMessage = context.makeInfo(template).set("message", context.i18n("versions.patch")).set("difference", latestVersion.patch - currentVersion.patch).set("type", context.i18n("versions.patchName"));
    }
    if (versionMessage == null) {
        versionMessage = context.makeSuccess(context.i18n("usingLatest"));
    }
    addAndFormatLatestCommits(context, versionMessage).setreplacedle("v" + AppInfo.getAppInfo().version).setFooter(context.i18n("latestVersion", latestVersion)).queue();
    return true;
}

19 Source : UserInfoCommand.java
with GNU General Public License v3.0
from avaire

@Override
public boolean onCommand(CommandMessage context, String[] args) {
    Member member = context.getMember();
    if (args.length > 0) {
        User user = MentionableUtil.getUser(context, new String[] { String.join(" ", args) });
        if (user == null) {
            return sendErrorMessage(context, "errors.noUsersWithNameOrId", args[0]);
        }
        member = context.getGuild().getMember(user);
    }
    Carbon joinedDate = Carbon.createFromOffsetDateTime(member.getTimeJoined());
    Carbon createdDate = Carbon.createFromOffsetDateTime(member.getUser().getTimeCreated());
    PlaceholderMessage placeholderMessage = context.makeEmbeddedMessage(getRoleColor(member.getRoles()), new MessageEmbed.Field(context.i18n("fields.username"), member.getUser().getName(), true), new MessageEmbed.Field(context.i18n("fields.userId"), member.getUser().getId(), true), new MessageEmbed.Field(context.i18n("fields.joinedServer"), joinedDate.format(context.i18n("timeFormat")) + "\n*About " + shortenDiffForHumans(joinedDate) + "*", true), new MessageEmbed.Field(context.i18n("fields.joinedDiscord"), createdDate.format(context.i18n("timeFormat")) + "\n*About " + shortenDiffForHumans(createdDate) + "*", true)).setThumbnail(member.getUser().getEffectiveAvatarUrl());
    String memberRoles = context.i18n("noRoles");
    if (!member.getRoles().isEmpty()) {
        memberRoles = member.getRoles().stream().map(role -> role.getName()).collect(Collectors.joining("\n"));
    }
    placeholderMessage.addField(new MessageEmbed.Field(context.i18n("fields.roles", member.getRoles().size()), memberRoles, true));
    placeholderMessage.addField(new MessageEmbed.Field(context.i18n("fields.servers"), context.i18n("inServers", NumberUtil.formatNicely(avaire.getShardManager().getMutualGuilds(member.getUser()).size())), true));
    placeholderMessage.requestedBy(context.getMember()).queue();
    return true;
}

19 Source : UserIdCommand.java
with GNU General Public License v3.0
from avaire

@Override
public boolean onCommand(CommandMessage context, String[] args) {
    User user = context.getAuthor();
    if (args.length > 0) {
        user = MentionableUtil.getUser(context, new String[] { String.join(" ", args) });
    }
    if (user == null) {
        return sendErrorMessage(context, "errors.noUsersWithNameOrId", args[0]);
    }
    context.makeSuccess(context.i18n("message")).set("target", user.getAsMention()).set("targetid", user.getId()).queue();
    return true;
}

19 Source : UserAvatarCommand.java
with GNU General Public License v3.0
from avaire

@Override
public boolean onCommand(CommandMessage context, String[] args) {
    User user = context.getAuthor();
    if (args.length > 0) {
        user = MentionableUtil.getUser(context, new String[] { String.join(" ", args) });
    }
    if (user == null) {
        return sendErrorMessage(context, context.i18n("noUserFound", args[0]));
    }
    String avatarUrl = generateAvatarUrl(user);
    MessageFactory.makeEmbeddedMessage(context.getChannel()).setreplacedle(context.i18n("replacedle", user.getName(), user.getDiscriminator()), avatarUrl).requestedBy(context.getMember()).setImage(avatarUrl).queue();
    return true;
}

19 Source : UptimeCommand.java
with GNU General Public License v3.0
from avaire

@Override
public boolean onCommand(CommandMessage context, String[] args) {
    RuntimeMXBean rb = ManagementFactory.getRuntimeMXBean();
    int uptimeInSeconds = (int) rb.getUptime() / 1000;
    Carbon time = Carbon.now().subSeconds(uptimeInSeconds);
    context.makeInfo(context.i18n("message")).set("time", formatUptimeNicely(uptimeInSeconds)).setFooter(context.i18n("footer", time.format("EEEEEEEE, dd MMM yyyy"), time.format("HH:mm:ss z"))).queue();
    return true;
}

19 Source : TemperatureConvertCommand.java
with GNU General Public License v3.0
from avaire

@Override
public boolean onCommand(CommandMessage context, String[] args) {
    if (args.length == 0 || args[0].length() == 1) {
        return sendErrorMessage(context, "errors.missingArgument", "temperature");
    }
    final String message = String.join(" ", args).trim();
    try {
        char temperatureConversion = message.toUpperCase().charAt(message.length() - 1);
        double temperature = Double.parseDouble(message.substring(0, message.length() - 1));
        switch(temperatureConversion) {
            case 'C':
                context.makeInfo(context.i18n("message")).set("input", NumberUtil.formatNicelyWithDecimals(temperature) + "° C").set("one", NumberUtil.formatNicelyWithDecimals(celsiusToFahrenheit(temperature)) + "° F").set("two", NumberUtil.formatNicelyWithDecimals(celsiusToKelvin(temperature)) + "° K").queue();
                break;
            case 'F':
                double fahrenheitToCelsius = fahrenheitToCelsius(temperature);
                context.makeInfo(context.i18n("message")).set("input", NumberUtil.formatNicelyWithDecimals(temperature) + "° F").set("one", NumberUtil.formatNicelyWithDecimals(fahrenheitToCelsius) + "° C").set("two", NumberUtil.formatNicelyWithDecimals(celsiusToKelvin(fahrenheitToCelsius)) + "° K").queue();
                break;
            case 'K':
                double kelvinToCelsius = kelvinToCelsius(temperature);
                context.makeInfo(context.i18n("message")).set("input", NumberUtil.formatNicelyWithDecimals(temperature) + "° K").set("one", NumberUtil.formatNicelyWithDecimals(kelvinToCelsius) + "° C").set("two", NumberUtil.formatNicelyWithDecimals(celsiusToFahrenheit(kelvinToCelsius)) + "° F").queue();
                break;
            default:
                return sendErrorMessage(context, context.i18n("invalidConvertFormat", temperatureConversion, String.join("\n", getValidConvertModes())));
        }
    } catch (NumberFormatException ex) {
        return sendErrorMessage(context, context.i18n("invalidNumberFormat", message.substring(0, message.length() - 1)));
    }
    return true;
}

19 Source : StatsCommand.java
with GNU General Public License v3.0
from avaire

private String formatDynamicValue(CommandMessage context, int rawValue) {
    double value = rawValue / ((double) ManagementFactory.getRuntimeMXBean().getUptime() / 1000D);
    return I18n.format(context.i18n(value < 1.5D ? "formats.perMinute" : "formats.perSecond"), NumberUtil.formatNicely(rawValue), NumberUtil.formatNicelyWithDecimals(value < 1.5D ? value * 60D : value));
}

19 Source : StatsCommand.java
with GNU General Public License v3.0
from avaire

private String memoryUsage(CommandMessage context) {
    return context.i18n("formats.memory", (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / (1024 * 1024), Runtime.getRuntime().totalMemory() / (1024 * 1024));
}

19 Source : StatsCommand.java
with GNU General Public License v3.0
from avaire

private String getDatabaseQueriesStats(CommandMessage context) {
    return formatDynamicValue(context, getTotalsFrom(Metrics.databaseQueries.collect()));
}

19 Source : StatsCommand.java
with GNU General Public License v3.0
from avaire

@Override
public boolean onCommand(CommandMessage context, String[] args) {
    PlaceholderMessage message = context.makeEmbeddedMessage(MessageType.INFO, new MessageEmbed.Field(context.i18n("fields.author"), "[Senither#0001](https://senither.com/)", true), new MessageEmbed.Field(context.i18n("fields.website"), "[avairebot.com](https://avairebot.com/)", true), new MessageEmbed.Field(context.i18n("fields.library"), "[JDA](https://github.com/DV8FromTheWorld/JDA)", true), new MessageEmbed.Field(context.i18n("fields.database"), getDatabaseQueriesStats(context), true), new MessageEmbed.Field(context.i18n("fields.messages"), getMessagesReceivedStats(context), true), new MessageEmbed.Field(context.i18n("fields.commands"), getCommandExecutedStats(context), true), new MessageEmbed.Field(context.i18n("fields.shard"), "" + context.getJDA().getShardInfo().getShardId(), true), new MessageEmbed.Field(context.i18n("fields.memory"), memoryUsage(context), true), new MessageEmbed.Field(context.i18n("fields.uptime"), applicationUptime(), true), new MessageEmbed.Field(context.i18n("fields.members"), NumberUtil.formatNicely(avaire.getShardEnreplacedyCounter().getUsers()), true), new MessageEmbed.Field(context.i18n("fields.channels"), NumberUtil.formatNicely(avaire.getShardEnreplacedyCounter().getChannels()), true), new MessageEmbed.Field(context.i18n("fields.servers"), NumberUtil.formatNicely(avaire.getShardEnreplacedyCounter().getGuilds()), true));
    if (avaire.getConfig().getBoolean("use-music", true)) {
        message.setFooter(context.i18n("footer", NumberUtil.formatNicely(AudioHandler.getDefaultAudioHandler().getTotalListenersSize()), NumberUtil.formatNicely(AudioHandler.getDefaultAudioHandler().getTotalQueueSize())));
    }
    message.setreplacedle(context.i18n("replacedle"), "https://avairebot.com/support").setAuthor("AvaIre v" + AppInfo.getAppInfo().version, "https://avairebot.com/support", avaire.getSelfUser().getEffectiveAvatarUrl()).queue();
    return true;
}

19 Source : StatsCommand.java
with GNU General Public License v3.0
from avaire

private String getCommandExecutedStats(CommandMessage context) {
    return formatDynamicValue(context, getTotalsFrom(Metrics.commandsReceived.collect()));
}

19 Source : StatsCommand.java
with GNU General Public License v3.0
from avaire

private String getMessagesReceivedStats(CommandMessage context) {
    return formatDynamicValue(context, (int) Metrics.jdaEvents.labels(MessageReceivedEvent.clreplaced.getSimpleName()).get());
}

19 Source : SourceCommand.java
with GNU General Public License v3.0
from avaire

@Override
public boolean onCommand(CommandMessage context, String[] args) {
    if (args.length == 0) {
        context.makeInfo(context.i18n("noArgs") + "\n\n" + rootUrl).queue();
        return true;
    }
    CommandContainer command = getCommand(context.getMessage(), args[0]);
    if (command == null) {
        context.makeInfo(context.i18n("invalidCommand") + "\n\n" + rootUrl).queue();
        return true;
    }
    String sourceUri = command.getSourceUri();
    if (sourceUri == null) {
        context.makeInfo(context.i18n("externalCommand") + "\n\n" + rootUrl).queue();
        return true;
    }
    context.makeInfo(context.i18n("command") + "\n\n" + sourceUri).set("command", command.getCommand().getName()).queue();
    return true;
}

19 Source : ServerInfoCommand.java
with GNU General Public License v3.0
from avaire

@Override
public boolean onCommand(CommandMessage context, String[] args) {
    Guild guild = context.getGuild();
    Carbon time = Carbon.createFromOffsetDateTime(guild.getTimeCreated());
    long bots = guild.getMembers().stream().filter(member -> member.getUser().isBot()).count();
    PlaceholderMessage placeholderMessage = context.makeEmbeddedMessage(getRoleColor(guild.getSelfMember().getRoles()), new MessageEmbed.Field(context.i18n("fields.id"), guild.getId(), true), new MessageEmbed.Field(context.i18n("fields.owner"), guild.getOwner().getUser().getName() + "#" + guild.getOwner().getUser().getDiscriminator(), true), new MessageEmbed.Field(context.i18n("fields.textChannels"), NumberUtil.formatNicely(guild.getTextChannels().size()), true), new MessageEmbed.Field(context.i18n("fields.voiceChannels"), NumberUtil.formatNicely(guild.getVoiceChannels().size()), true), new MessageEmbed.Field(context.i18n("fields.members"), NumberUtil.formatNicely(guild.getMembers().size()), true), new MessageEmbed.Field(context.i18n("fields.roles"), NumberUtil.formatNicely(guild.getRoles().size()), true), new MessageEmbed.Field(context.i18n("fields.users"), NumberUtil.formatNicely(guild.getMembers().size() - bots), true), new MessageEmbed.Field(context.i18n("fields.bots"), NumberUtil.formatNicely(bots), true), new MessageEmbed.Field(context.i18n("fields.region"), guild.getRegion().getName(), true), new MessageEmbed.Field(context.i18n("fields.emotes"), NumberUtil.formatNicely(guild.getEmotes().size()), true), new MessageEmbed.Field(context.i18n("fields.createdAt"), time.format(context.i18n("timeFormat")) + "\n*About " + shortenDiffForHumans(time) + "*", true)).setreplacedle(guild.getName()).setThumbnail(guild.getIconUrl());
    placeholderMessage.requestedBy(context.getMember()).queue();
    return true;
}

19 Source : ServerIdCommand.java
with GNU General Public License v3.0
from avaire

@Override
public boolean onCommand(CommandMessage context, String[] args) {
    context.makeSuccess(context.i18n("message")).queue();
    return true;
}

19 Source : RemindCommand.java
with GNU General Public License v3.0
from avaire

private void handleReminderMessage(CommandMessage context, Message message, int time, boolean respondInDM) {
    if (respondInDM) {
        context.getAuthor().openPrivateChannel().queue(privateChannel -> {
            privateChannel.sendMessage(message).queueAfter(time, TimeUnit.SECONDS, null, RestActionUtil.ignore);
        }, throwable -> {
            context.getMessageChannel().sendMessage(message).queueAfter(time, TimeUnit.SECONDS, null, RestActionUtil.ignore);
        });
    } else {
        context.getMessageChannel().sendMessage(message).queueAfter(time, TimeUnit.SECONDS, null, throwable -> {
            context.getAuthor().openPrivateChannel().queue(privateChannel -> {
                privateChannel.sendMessage(message).queueAfter(time, TimeUnit.SECONDS, null, RestActionUtil.ignore);
            });
        });
    }
}

19 Source : RemindCommand.java
with GNU General Public License v3.0
from avaire

@Override
public boolean onCommand(CommandMessage context, String[] args) {
    if (args.length == 0) {
        return sendErrorMessage(context, "errors.missingArgument", "type");
    }
    if (!(args[0].equalsIgnoreCase("here") || args[0].equalsIgnoreCase("me"))) {
        return sendErrorMessage(context, context.i18n("errors.invalidMeHere"));
    }
    boolean respondInDM = args[0].equalsIgnoreCase("me");
    if (args.length == 1) {
        return sendErrorMessage(context, "errors.missingArgument", "time");
    }
    final int time = parse(args[1]);
    if (time == 0) {
        return sendErrorMessage(context, "errors.invalidProperty", "time", "time format");
    }
    // Time must be greater than 60 seconds and less than 3 days.
    if (time < 60 || time > 259200) {
        return sendErrorMessage(context, context.i18n("errors.invalidTime"));
    }
    if (args.length == 2) {
        return sendErrorMessage(context, "errors.missingArgument", "message");
    }
    handleReminderMessage(context, new MessageBuilder().setContent(String.format("%s, %s you asked to be reminded about:", context.getAuthor().getAsMention(), Carbon.now().subSeconds(time).diffForHumans())).setEmbed(new EmbedBuilder().setDescription(String.join(" ", Arrays.copyOfRange(args, 2, args.length))).build()).build(), time, respondInDM);
    context.makeInfo("Alright :user, in :time I'll remind you about :message").set("time", Carbon.now().subSeconds(time).diffForHumans(true)).set("message", String.join(" ", Arrays.copyOfRange(args, 2, args.length))).queue();
    return true;
}

19 Source : RankCommand.java
with GNU General Public License v3.0
from avaire

private void sendEmbeddedMessage(CommandMessage context, User author, String score, String levelBar, long level, long nextLevelXp, long experience, long zeroExperience, double percentage, DatabaseProperties properties) {
    MessageFactory.makeEmbeddedMessage(context.getChannel(), Color.decode("#E91E63")).setAuthor(author.getName(), "https://avairebot.com/leaderboard/" + context.getGuild().getId(), author.getEffectiveAvatarUrl()).setFooter("https://avairebot.com/leaderboard/" + context.getGuild().getId()).addField(context.i18n("fields.rank"), score, true).addField(context.i18n("fields.level"), NumberUtil.formatNicely(level), true).addField(context.i18n("fields.experience"), (experience - zeroExperience - 100 < 0 ? "0" : context.i18n("fields.total", NumberUtil.formatNicely(experience - zeroExperience - 100), NumberUtil.formatNicely(properties.getTotal()))), true).addField(context.i18n("fields.experienceToNext"), context.i18n("fields.youNeedMoreXpToLevelUp", levelBar, NumberUtil.formatNicelyWithDecimals(percentage), '%', NumberUtil.formatNicely(nextLevelXp - experience)), false).requestedBy(context.getMember()).queue();
}

19 Source : PingCommand.java
with GNU General Public License v3.0
from avaire

private String ratePing(CommandMessage context, long ping) {
    if (ping <= 10)
        return context.i18n("rating.10");
    if (ping <= 100)
        return context.i18n("rating.100");
    if (ping <= 200)
        return context.i18n("rating.200");
    if (ping <= 300)
        return context.i18n("rating.300");
    if (ping <= 400)
        return context.i18n("rating.400");
    if (ping <= 500)
        return context.i18n("rating.500");
    if (ping <= 600)
        return context.i18n("rating.600");
    if (ping <= 700)
        return context.i18n("rating.700");
    if (ping <= 800)
        return context.i18n("rating.800");
    if (ping <= 900)
        return context.i18n("rating.900");
    if (ping <= 1600)
        return context.i18n("rating.1600");
    if (ping <= 10000)
        return context.i18n("rating.10000");
    return context.i18n("rating.other");
}

19 Source : PingCommand.java
with GNU General Public License v3.0
from avaire

@Override
public boolean onCommand(CommandMessage context, String[] args) {
    long start = System.currentTimeMillis();
    context.getMessage().getChannel().sendTyping().queue(v -> {
        long ping = System.currentTimeMillis() - start;
        context.makeInfo(context.i18n("message")).set("heartbeat", context.getJDA().getGatewayPing()).set("rating", ratePing(context, ping)).set("ping", ping).queue();
    });
    return true;
}

19 Source : LeaderboardCommand.java
with GNU General Public License v3.0
from avaire

private Collection loadUserRank(CommandMessage context) {
    return (Collection) CacheUtil.getUncheckedUnwrapped(cache, asKey(context, true), () -> {
        try {
            return avaire.getDatabase().query(String.format("SELECT COUNT(*) AS rank FROM (" + "    SELECT `user_id` FROM `experiences` WHERE `guild_id` = '%s' AND `active` = 1 GROUP BY `user_id` HAVING SUM(`experience`) > (" + "        SELECT SUM(`experience`) FROM `experiences` WHERE `user_id` = '%s' AND `guild_id` = '%s' AND `active` = 1" + "    )" + ") t;", context.getGuild().getId(), context.getAuthor().getId(), context.getGuild().getId()));
        } catch (SQLException e) {
            log.error("Failed to fetch leaderboard data for user: " + context.getGuild().getId(), e);
            return Collection.EMPTY_COLLECTION;
        }
    });
}

19 Source : LeaderboardCommand.java
with GNU General Public License v3.0
from avaire

private Collection loadTop100From(CommandMessage context) {
    return (Collection) CacheUtil.getUncheckedUnwrapped(cache, asKey(context, false), () -> {
        try {
            return avaire.getDatabase().newQueryBuilder(Constants.PLAYER_EXPERIENCE_TABLE_NAME).where("guild_id", context.getGuild().getId()).where("active", 1).orderBy("experience", "desc").take(100).get();
        } catch (SQLException e) {
            log.error("Failed to fetch leaderboard data for server: " + context.getGuild().getId(), e);
            return Collection.EMPTY_COLLECTION;
        }
    });
}

See More Examples