Skip to content

Commit

Permalink
Merge branch 'master' of /~https://github.com/xdnw/locutus
Browse files Browse the repository at this point in the history
  • Loading branch information
xdnw committed Feb 22, 2025
2 parents d4bfbf8 + b81aa9e commit 849d0ac
Show file tree
Hide file tree
Showing 43 changed files with 599 additions and 485 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,7 @@
String descMethod() default "";
String[] groups() default {};
String[] groupDescs() default {};
boolean viewable() default false;

Kw[] keywords() default {};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package link.locutus.discord.commands.manager.v2.binding.annotation;

public enum Kw {
// "war", "room", "sync", "channel", "update", "warcat", "category"
WAR,
ROOM,
SYNC,
CHANNEL,
UPDATE,
WARCAT,
CATEGORY,
//
ACTIVITY,
SHEET,
SPREADSHEET(SHEET),
LOGIN,
TIMES,
USER,
SESSION,
ACCESS,
HISTORY,
TRACK,
RECORD,
TIMESTAMP,
NATION,

;

private final Kw[] aliases;

Kw(Kw... aliases) {
this.aliases = aliases;
}
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
package link.locutus.discord.commands.manager.v2.binding.annotation;


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER, ElementType.METHOD})
public @interface Viewable {
}
@Target({ElementType.METHOD})
public @interface Similar {
Class<?>[] value();
/**
* If true, then this command will be added to other command's similar list
*/
boolean reciprical() default true;
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ public interface CommandCallable {

String simpleHelp();

boolean isViewable();

List<String> aliases();

Map<String, Object> toJson(PermissionHandler permHandler, boolean includeReturnType);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import link.locutus.discord.util.StringMan;
import link.locutus.discord.util.math.ArrayUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.checkerframework.checker.units.qual.C;
import org.json.JSONObject;

import java.lang.reflect.Field;
Expand All @@ -39,6 +40,34 @@ public CommandGroup(CommandCallable parent, String[] aliases, ValueStore store,
this.aliases = Arrays.asList(aliases);
}

public Map.Entry<CommandCallable, String> getCallableAndPath(List<String> args) {
CommandCallable root = this;
List<String> path = new ArrayList<>();

Queue<String> stack = new ArrayDeque<>(args);
while (!stack.isEmpty()) {
String arg = stack.poll();
path.add(arg);
if (root instanceof CommandGroup cg && cg.get(arg) != null) {
root = cg.get(arg);
} else {
String primary = root.getPrimaryCommandId();
if (primary.isEmpty()) primary = "/";
String msg = "Command: `" + primary + "` of type " + root.getClass().getSimpleName() + " has no subcommand: `" + arg + "`";
if (root instanceof CommandGroup group) {
msg += "\nValid subcommands: `" + StringMan.join(group.primarySubCommandIds(), ", ") + "`";
}
throw new IllegalArgumentException(msg);
}
}
return new AbstractMap.SimpleEntry<>(root, StringMan.join(path, " "));
}

@Override
public boolean isViewable() {
return false;
}

@Override
public Map<String, Object> toJson(PermissionHandler permHandler, boolean includeReturnType) {
Map<String, Object> root = new LinkedHashMap<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ public class ParametricCallable implements ICommand {
private final boolean isStatic;
private final String[] groups;
private final String[] groupDescs;
private final boolean isViewable;
private Supplier<String> descMethod;

public ParametricCallable(CommandCallable parent, ParametricCallable clone, List<String> aliases) {
Expand All @@ -75,6 +76,7 @@ public ParametricCallable(CommandCallable parent, ParametricCallable clone, List
this.returnType = clone.returnType;
this.groups = clone.groups;
this.groupDescs = clone.groupDescs;
this.isViewable = clone.isViewable;
}

public ParametricCallable(CommandCallable parent, ValueStore store, Object object, Method method, Command definition) {
Expand Down Expand Up @@ -179,6 +181,7 @@ public ParametricCallable(CommandCallable parent, ValueStore store, Object objec
}
}

this.isViewable = definition.viewable() || getAnnotation(NoForm.class) != null;
this.aliases = new ArrayList<>(Arrays.asList(definition.aliases()));
if (aliases.isEmpty()) aliases.add(method.getName());

Expand Down Expand Up @@ -258,6 +261,11 @@ private static String[] lookupParameterNames(Method method) {
return names;
}

@Override
public boolean isViewable() {
return this.isViewable;
}

public Type getReturnType() {
return returnType;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -752,7 +752,7 @@ public OptionType createType(Type type) {

@Override
public void onCommandAutoCompleteInteraction(@Nonnull CommandAutoCompleteInteractionEvent event) {
CommandManager2 commands = getCommands();
CommandManager2 manager = getCommands();
long startNanos = System.nanoTime();
User user = event.getUser();
userIdToAutoCompleteTimeNs.put(user.getIdLong(), startNanos);
Expand All @@ -762,7 +762,7 @@ public void onCommandAutoCompleteInteraction(@Nonnull CommandAutoCompleteInterac
String optionName = option.getName();

List<String> pathArgs = StringMan.split(path, ' ');
Map.Entry<CommandCallable, String> cmdAndPath = commands.getCallableAndPath(pathArgs);
Map.Entry<CommandCallable, String> cmdAndPath = manager.getCommands().getCallableAndPath(pathArgs);
CommandCallable cmd = cmdAndPath.getKey();

if (cmd == null) {
Expand Down Expand Up @@ -795,20 +795,20 @@ public void run() {
Parser binding = param.getBinding();
Key key = binding.getKey();
Key parserKey = key.append(Autoparse.class);
Parser parser = commands.getStore().get(parserKey);
Parser parser = manager.getStore().get(parserKey);

if (parser == null) {
autoParse = false;
Key completerKey = key.append(Autocomplete.class);
parser = commands.getStore().get(completerKey);
parser = manager.getStore().get(completerKey);
}

if (parser == null) {
Logg.text("[Autocomplete]" + user + " | No parser or completer found for `" + key + "` at `" + path + "`");
return;
}

LocalValueStore<Object> locals = new LocalValueStore<>(commands.getStore());
LocalValueStore<Object> locals = new LocalValueStore<>(manager.getStore());
locals.addProvider(Key.of(User.class, Me.class), event.getUser());
if (event.isFromGuild()) {
locals.addProvider(Key.of(Guild.class, Me.class), event.getGuild());
Expand All @@ -819,7 +819,7 @@ public void run() {

// Option with current value
List<String> args = new ArrayList<>(List.of(option.getValue()));
ArgumentStack stack = new ArgumentStack(args, locals, commands.getValidators(), commands.getPermisser());
ArgumentStack stack = new ArgumentStack(args, locals, manager.getValidators(), manager.getPermisser());
locals.addProvider(stack);

List<Choice> choices = new ArrayList<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -732,23 +732,6 @@ public CommandCallable getCallable(List<String> args) {
return commands.getCallable(args);
}

public Map.Entry<CommandCallable, String> getCallableAndPath(List<String> args) {
CommandCallable root = commands;
List<String> path = new ArrayList<>();

Queue<String> stack = new ArrayDeque<>(args);
while (!stack.isEmpty()) {
String arg = stack.poll();
path.add(arg);
if (root instanceof CommandGroup) {
root = ((CommandGroup) root).get(arg);
} else {
throw new IllegalArgumentException("Command: " + root.getPrimaryCommandId() + " of type " + root.getClass().getSimpleName() + " has no subcommand: " + arg);
}
}
return new AbstractMap.SimpleEntry<>(root, StringMan.join(path, " "));
}

public void run(Guild guild, IMessageIO io, User author, String command, boolean async, boolean returnNotFound) {
String fullCmdStr = DiscordUtil.trimContent(command).trim();
if (!fullCmdStr.isEmpty() && Locutus.cmd().isModernPrefix(fullCmdStr.charAt(0))) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,10 +109,12 @@
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import static link.locutus.discord.commands.manager.v2.binding.annotation.Kw.*;

public class AdminCommands {

@Command(desc = "Sync and debug war rooms")
@Command(desc = "Sync and debug war rooms",
keywords = {WAR, ROOM, SYNC, CHANNEL, UPDATE, WARCAT, CATEGORY})
@RolePermission(Roles.ADMIN)
public String syncWarrooms(@Me IMessageIO io, @Me JSONObject command, @Me GuildDB db, @Switch("f") boolean force) throws IOException {
long start = System.currentTimeMillis();
Expand Down Expand Up @@ -575,10 +577,9 @@ public String unsetKeys(@Me IMessageIO io, @Me JSONObject command,
return null;
}

@Command(desc = "Generate a google spreadsheet for a guild setting value for a set of discord servers")
@Command(desc = "Generate a google spreadsheet for a guild setting value for a set of discord servers", viewable = true)
@RolePermission(value = Roles.ADMIN, root = true)
@Ephemeral
@Viewable
public String infoBulk(@Me GuildDB db, @Me IMessageIO io, GuildSetting setting, Set<GuildDB> guilds, @Switch("s") SpreadSheet sheet) throws GeneralSecurityException, IOException {
if (sheet == null) {
sheet = SpreadSheet.create(db, SheetKey.SETTINGS_SERVERS);
Expand Down Expand Up @@ -805,7 +806,8 @@ public String syncTreasures() {
return "Done!";
}

@Command(desc = "Generate a sheet of recorded login times for a set of nations within a time range")
@Command(desc = "Generate a sheet of recorded login times for a set of nations within a time range", viewable = true,
keywords = {LOGIN, TIMES, USER, ACTIVITY, SESSION, HISTORY, TRACK, RECORD, TIMESTAMP, SPREADSHEET})
public String loginTimes(@Me GuildDB db, @Me IMessageIO io, Set<DBNation> nations, @Timestamp long cutoff, @Switch("s") SpreadSheet sheet) throws IOException, GeneralSecurityException {
if (sheet == null) {
sheet = SpreadSheet.create(db, SheetKey.NATION_SHEET);
Expand Down Expand Up @@ -964,7 +966,7 @@ public String archiveAnnouncement(@Me GuildDB db, int announcementId, @Default B
return (archive ? "Archived" : "Unarchived") + " announcement with id: #" + announcementId;
}

@Command(desc = "Find the announcement for the closest matching invite")
@Command(desc = "Find the announcement for the closest matching invite", viewable = true)
@RolePermission(Roles.ADMIN)
@NoFormat
public String find_invite(@Me GuildDB db, String invite) throws IOException {
Expand All @@ -977,7 +979,7 @@ public String find_invite(@Me GuildDB db, String invite) throws IOException {
}
}

@Command(desc = "Find the announcement closest matching a message")
@Command(desc = "Find the announcement closest matching a message", viewable = true)
@RolePermission(Roles.ADMIN)
@NoFormat
public String find_announcement(@Me GuildDB db, int announcementId, String message) throws IOException {
Expand Down Expand Up @@ -1840,7 +1842,7 @@ public String debugPurgeChannels(Category category, @Range(min=60) @Timestamp lo
}

@Command(desc = "List guilds which have not sent a recent message\n" +
"Note: Deprecated. Not reliable if message content intent is disabled")
"Note: Deprecated. Not reliable if message content intent is disabled", viewable = true)
@Ephemeral
@RolePermission(value = Roles.ADMIN, root = true)
public String listExpiredGuilds(boolean checkMessages) {
Expand Down Expand Up @@ -1931,7 +1933,7 @@ public String leaveServer(long guildId) {
return "Leaving " + guild.getName();
}

@Command(desc = "List accounts with the offshore which are inactive, as well as details about last owner/alliance activity and last transfer info")
@Command(desc = "List accounts with the offshore which are inactive, as well as details about last owner/alliance activity and last transfer info", viewable = true)
@Ephemeral
@RolePermission(value = Roles.ADMIN, root = true)
public String listExpiredOffshores() {
Expand Down Expand Up @@ -2048,7 +2050,7 @@ public String listExpiredOffshores() {
return response.toString();
}

@Command(desc = "List the owners of the guilds Locutus is connected to")
@Command(desc = "List the owners of the guilds Locutus is connected to", viewable = true)
@RolePermission(value = Roles.ADMIN, root = true)
public String listGuildOwners() {
ArrayList<GuildDB> guilds = new ArrayList<>(Locutus.imp().getGuildDatabases().values());
Expand Down Expand Up @@ -2239,7 +2241,7 @@ public String listAuthenticated(@Me GuildDB db) {
return result.toString().trim();
}

@Command
@Command(desc = "Generate a sheet of nation customization (or lack thereof), and mark specific nation ids in the sheet with the ids provided", viewable = true)
public String multiInfoSheet(@Me IMessageIO io, @Me GuildDB db, Set<DBNation> nations, @Switch("s") SpreadSheet sheet, @Switch("m") Set<DBNation> mark) throws IOException, ParseException, GeneralSecurityException {
Set<Integer> nationIds = new IntOpenHashSet(nations.stream().map(DBNation::getId).collect(Collectors.toSet()));
Map<Integer, String> discords = new Int2ObjectOpenHashMap<>();
Expand Down Expand Up @@ -2388,7 +2390,7 @@ public synchronized String importLinkedBans() throws IOException {
return "Done";
}

@Command(desc = "List players currently sharing a network or an active ban")
@Command(desc = "List players currently sharing a network or an active ban", viewable = true)
@RolePermission(Roles.INTERNAL_AFFAIRS)
public synchronized String hasSameNetworkAsBan(@Me IMessageIO io, @Me User author, Set<DBNation> nations, @Switch("e") boolean listExpired,
@Switch("a") boolean onlySameAlliance,
Expand Down Expand Up @@ -2878,7 +2880,7 @@ public String syncOffshore(DBAlliance alliance) throws IOException {
return "Done!";
}

@Command(desc = "View info about trades with a given id")
@Command(desc = "View info about trades with a given id", viewable = true)
@RolePermission(value = Roles.ADMIN, root = true)
public String tradeId(Set<Integer> ids) {
List<DBTrade> offers = new ArrayList<>();
Expand All @@ -2889,15 +2891,15 @@ public String tradeId(Set<Integer> ids) {
return "- " + StringMan.join(offers, "\n- ");
}

@Command(desc = "View info about a guild with a given id")
@Command(desc = "View info about a guild with a given id", viewable = true)
@RolePermission(value = Roles.ADMIN, root = true)
public String guildInfo(Guild guild) {
return guild.getName() + "/" + guild.getIdLong() + "\n" +
"Owner: " + guild.getOwner() + "\n" +
"Members: " + StringMan.getString(guild.getMembers());
}

@Command(desc = "View meta information about a nation in the bot's database")
@Command(desc = "View meta information about a nation in the bot's database", viewable = true)
@RolePermission(value = Roles.ADMIN, root = true)
public String nationMeta(DBNation nation, NationMeta meta) {
ByteBuffer buf = nation.getMeta(meta);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,7 @@ public String saveMetrics(Set<AllianceMetric> metrics, @Default @Timestamp Long
}

@Command(desc = "Get alliance attributes by day\n" +
"If your metric does not relate to cities, set `skipCityData` to true to speed up the process.")
"If your metric does not relate to cities, set `skipCityData` to true to speed up the process.", viewable = true)
@RolePermission(value = Roles.ADMIN, root = true)
@NoFormat
public String AlliancesDataByDay(@Me GuildDB db, @Me IMessageIO io, @Me JSONObject command,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ public boolean onCommand(IMessageIO io, GuildDB db, User user, MessageChannel ch
return false;
}

@Command(desc = "Open a custom saved menu for the discord guild")
@Command(desc = "Open a custom saved menu for the discord guild", viewable = true)
@NoFormat
@Ephemeral
public void openMenu(@Me IMessageIO io, @Me GuildDB db, @Me User user, AppMenu menu) {
Expand Down Expand Up @@ -149,7 +149,7 @@ public void describeMenu(@Me IMessageIO io, @Me GuildDB db, @Me User user, AppMe
}

@Command(desc = "Set and display the temporary menu context for yourself\n" +
"This determines the buttons and their actions, for editing the menu, such as removing, renaming or swapping buttons")
"This determines the buttons and their actions, for editing the menu, such as removing, renaming or swapping buttons", viewable = true)
@NoFormat
@Ephemeral
public void setMenuState(@Me IMessageIO io, @Me GuildDB db, @Me User user, AppMenu menu, MenuState state) {
Expand Down Expand Up @@ -372,7 +372,7 @@ public void cancel(@Me IMessageIO io, @Me GuildDB db, @Me User user, AppMenu men
}
}

@Command(desc = "List all custom discord menus set in the guild")
@Command(desc = "List all custom discord menus set in the guild", viewable = true)
@NoFormat
@Ephemeral
public String list(@Me GuildDB db) {
Expand All @@ -388,7 +388,7 @@ public String list(@Me GuildDB db) {
return sb.toString();
}

@Command(desc = "Display the information for a custom discord menu set in the guild")
@Command(desc = "Display the information for a custom discord menu set in the guild", viewable = true)
@NoFormat
@Ephemeral
public void info(@Me IMessageIO io, AppMenu menu) {
Expand Down
Loading

0 comments on commit 849d0ac

Please sign in to comment.