Skip to content

Commit

Permalink
Add slash commands for music commands
Browse files Browse the repository at this point in the history
  • Loading branch information
duncte123 committed Aug 24, 2023
1 parent 2c92113 commit e88d8b1
Show file tree
Hide file tree
Showing 38 changed files with 698 additions and 95 deletions.
4 changes: 4 additions & 0 deletions .github/workflows/1-build-projects.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ jobs:

runs-on: ubuntu-latest

concurrency:
group: ${{ github.ref }}
cancel-in-progress: true

steps:
- uses: actions/checkout@v3
- name: Set up java
Expand Down
4 changes: 4 additions & 0 deletions .github/workflows/2-release-bot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ jobs:

runs-on: ubuntu-latest

concurrency:
group: ${{ github.ref }}
cancel-in-progress: true

steps:
- uses: actions/checkout@v3
with:
Expand Down
3 changes: 3 additions & 0 deletions .github/workflows/2-release-dashboard.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ on: workflow_dispatch
jobs:
build_docker:
runs-on: ubuntu-latest
concurrency:
group: ${{ github.ref }}
cancel-in-progress: true
steps:
- uses: actions/checkout@v3

Expand Down
10 changes: 7 additions & 3 deletions bot/src/main/java/ml/duncte123/skybot/CommandManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -759,10 +759,14 @@ public void executeSlashCommand(SlashCommandInteractionEvent event) {
return;
}

final SlashSupport command = (SlashSupport) this.getCommand(event.getName());
try {
final SlashSupport command = (SlashSupport) this.getCommand(event.getName());

if (command != null) {
command.handleEvent(event, variables);
if (command != null) {
command.handleEvent(event, variables);
}
} catch (Exception e) {
e.printStackTrace();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import me.duncte123.botcommons.messaging.EmbedUtils;
import me.duncte123.botcommons.messaging.MessageConfig;
import me.duncte123.botcommons.messaging.MessageUtils;
import ml.duncte123.skybot.Variables;
import ml.duncte123.skybot.objects.command.Command;
import ml.duncte123.skybot.objects.command.CommandCategory;
import ml.duncte123.skybot.objects.command.CommandContext;
Expand Down Expand Up @@ -61,7 +62,7 @@ public WolframAlphaCommand() {
this.usage = "<query>";
}

private MessageEmbed generateEmbed(CommandContext ctx, WAQueryResult result, String googleKey, ObjectMapper mapper) {
private MessageEmbed generateEmbed(CommandContext ctx, WAQueryResult result, Variables variables) {
final Member member = ctx.getMember();
final EmbedBuilder embed = EmbedUtils.getDefaultEmbed();
embed.setAuthor(member.getEffectiveName(), PATREON, member.getUser().getAvatarUrl());
Expand All @@ -86,7 +87,7 @@ private MessageEmbed generateEmbed(CommandContext ctx, WAQueryResult result, Str
for (final Visitable variable : sp.getContents()) {
if (variable instanceof final WAImage image) {
builder.append("[Image by text](")
.append(shortenUrl(image.getURL(), googleKey, mapper).execute())
.append(shortenUrl(image.getURL(), variables, false).execute())
.append(')');
} else if (variable instanceof final WAInfo info) {
builder.append(parseString(info.getText()));
Expand All @@ -97,12 +98,12 @@ private MessageEmbed generateEmbed(CommandContext ctx, WAQueryResult result, Str
builder.append('[')
.append(parseString(link.getText()))
.append("](")
.append(shortenUrl(link.getURL(), googleKey, mapper).execute())
.append(shortenUrl(link.getURL(), variables, false).execute())
.append(')');
} else if (variable instanceof final WAPlainText plainText) {
builder.append(parseString(plainText.getText()));
} else if (variable instanceof final WASound sound) {
builder.append(shortenUrl(sound.getURL(), googleKey, mapper).execute());
builder.append(shortenUrl(sound.getURL(), variables, false).execute());
}

builder.append("\n\n");
Expand Down Expand Up @@ -159,7 +160,7 @@ public void execute(@Nonnull CommandContext ctx) {

editMsg(message, ctx.getChannel(), new MessageEditBuilder().setContent("Result:")
.setEmbeds(
generateEmbed(ctx, result, ctx.getConfig().apis.googl, ctx.getVariables().getJackson())
generateEmbed(ctx, result, ctx.getVariables())
).build());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,13 @@

package ml.duncte123.skybot.commands.guild.owner;

import ml.duncte123.skybot.Variables;
import ml.duncte123.skybot.objects.command.CommandContext;
import ml.duncte123.skybot.objects.command.MusicCommand;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import org.jetbrains.annotations.NotNull;

import javax.annotation.Nonnull;

Expand Down Expand Up @@ -53,6 +56,10 @@ public void run(@Nonnull CommandContext ctx) {
getLavalinkManager().closeConnection(guild);

sendMsg(ctx, "Successfully sent the disconnect signal to the server");
}

@Override
public void handleEvent(@NotNull SlashCommandInteractionEvent event, @NotNull Variables variables) {
event.reply("Slash command not supported yet, sorry. Please report this issue.").queue();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,10 @@

import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import lavalink.client.player.LavalinkPlayer;
import ml.duncte123.skybot.Variables;
import ml.duncte123.skybot.objects.command.CommandContext;
import ml.duncte123.skybot.objects.command.MusicCommand;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.internal.utils.Helpers;
import org.jetbrains.annotations.NotNull;

Expand Down Expand Up @@ -124,6 +126,11 @@ public void run0(@Nonnull CommandContext ctx) throws NumberFormatException {

}

@Override
public void handleEvent(@NotNull SlashCommandInteractionEvent event, @NotNull Variables variables) {
event.reply("Slash command not supported yet, sorry. Please report this issue.").queue();
}

private void handleOverSkip(@NotNull CommandContext ctx, LavalinkPlayer player, String arg0, Supplier<Long> trackDuration) {
if (arg0.charAt(0) == '-') {
sendMsg(ctx, "You're trying to skip more than the length of the track into the negatives?");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,11 +128,7 @@ protected SubcommandData getSubData() {
return new SubcommandData(getName(), getHelp(getName(), "/"));
}

// TODO: implement in all
@SuppressWarnings({"PMD.EmptyMethodInAbstractClassShouldBeAbstract"})
public void handleEvent(@Nonnull SlashCommandInteractionEvent event, @Nonnull Variables variables) {
//
}
public abstract void handleEvent(@Nonnull SlashCommandInteractionEvent event, @Nonnull Variables variables);

public static SlashCommandData getMusicCommandData(CommandManager mngr) {
final var base = Commands.slash("music", "base command for music commands")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ public static class Apis {
public final String alexflipnote;
public final Cache youtubeCache;
public final String googl;
public final String shroten;
public final String weebSh;
public final String ksoft;
public final String genius;
Expand All @@ -69,12 +70,13 @@ public static class Apis {
public final String thecatapi;

public Apis(
String alexflipnote, Cache youtubeCache, String googl, String weebSh, String ksoft, String genius,
Spotify spotify, String blargbot, String wolframalpha, String thecatapi
String alexflipnote, Cache youtubeCache, String googl, String shorten, String weebSh, String ksoft,
String genius, Spotify spotify, String blargbot, String wolframalpha, String thecatapi
) {
this.alexflipnote = alexflipnote;
this.youtubeCache = youtubeCache;
this.googl = googl;
this.shroten = shorten;
this.weebSh = weebSh;
this.ksoft = ksoft;
this.genius = genius;
Expand Down Expand Up @@ -175,6 +177,7 @@ public static DunctebotConfig fromEnv() {
System.getenv("API_ALEXFLIPNOTE"),
youtubeCache,
System.getenv("API_GOOGLE"),
System.getenv("API_SHORTEN"),
System.getenv("API_WEEBSH"),
System.getenv("API_KSOFT"),
System.getenv("API_GENIUS"),
Expand Down
51 changes: 51 additions & 0 deletions bot/src/main/java/ml/duncte123/skybot/utils/AirUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.github.natanbc.reliqua.limiter.RateLimiter;
import com.github.natanbc.reliqua.request.PendingRequest;
Expand All @@ -34,6 +35,7 @@
import me.duncte123.botcommons.web.WebUtils;
import me.duncte123.botcommons.web.requests.JSONRequestBody;
import ml.duncte123.skybot.SkyBot;
import ml.duncte123.skybot.Variables;
import ml.duncte123.skybot.audio.GuildMusicManager;
import ml.duncte123.skybot.database.AbstractDatabase;
import ml.duncte123.skybot.entities.jda.FakeMember;
Expand Down Expand Up @@ -323,10 +325,59 @@ public static void setJDAContext(JDA jda) {
((JDAImpl) jda).setContext();
}

public static PendingRequest<String> shortenUrl(String url, Variables variables, boolean duncteBotDomain) {
final JsonMapper mapper = variables.getJackson();
final ObjectNode json = mapper.createObjectNode();

json.set("destinations",
mapper.createArrayNode()
.add(
mapper.createObjectNode()
.put("url", url)
.putNull("country")
.putNull("os")
)
);

final var domainNamePart = duncteBotDomain ? "&domainName=duncte.bot" : "";

try {
return WebUtils.ins.postRequest(
"https://api.shorten.rest/aliases?aliasName=@rnd" + domainNamePart,
JSONRequestBody.fromJackson(json),
(r) -> r.header("x-api-key", variables.getConfig().apis.shroten)
)
.setRateLimiter(RateLimiter.directLimiter())
.build(
(r) -> {
final ObjectNode response = toJSONObject(r, mapper);

System.out.println(response);

if (response == null) {
return "Shorten did a fucky wucky and send invalid json";
}

return response.get("shortUrl").asText();
},
WebParserUtils::handleError
);
}
catch (JsonProcessingException e) {
e.printStackTrace();

// Return a fake pending request to make sure that things don't break
return new FakePendingRequest<>("JSON PARSING FAILED: " + e.getMessage());
}
}

// TODO: find replacement for firebase
@Deprecated
public static PendingRequest<String> shortenUrl(String url, String googleKey, ObjectMapper mapper) {
return shortenUrl(url, googleKey, mapper, "duncte.bot");
}

@Deprecated
@Nonnull
public static PendingRequest<String> shortenUrl(String url, String googleKey, ObjectMapper mapper, String prefix) {
final ObjectNode json = mapper.createObjectNode();
Expand Down
60 changes: 40 additions & 20 deletions bot/src/main/java/ml/duncte123/skybot/utils/CommandUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import gnu.trove.map.TLongLongMap;
import gnu.trove.set.TLongSet;
import me.duncte123.botcommons.messaging.EmbedUtils;
import me.duncte123.botcommons.messaging.MessageConfig;
import ml.duncte123.skybot.Settings;
import ml.duncte123.skybot.objects.api.AllPatronsData;
import ml.duncte123.skybot.objects.command.CommandContext;
Expand All @@ -32,20 +33,19 @@
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.entities.channel.middleman.MessageChannel;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.sharding.ShardManager;
import net.dv8tion.jda.internal.utils.Checks;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Supplier;

import static me.duncte123.botcommons.messaging.MessageUtils.sendEmbed;
import static me.duncte123.botcommons.messaging.MessageUtils.sendMsg;
import static ml.duncte123.skybot.Settings.PATREON;

/**
Expand Down Expand Up @@ -145,7 +145,7 @@ public static String parseJagTag(CommandContext ctx, String content) {
return parsed;
}

private static boolean isPatron(@Nonnull User user, @Nullable CommandContext ctx) {
private static boolean isPatron(@Nonnull User user, @Nullable MessageChannel replyChannel) {
// Developers have access to paton features
if (isDev(user) || PATRONS.contains(user.getIdLong())) {
return true;
Expand All @@ -163,21 +163,29 @@ private static boolean isPatron(@Nonnull User user, @Nullable CommandContext ctx

// If the member is not in our guild we tell them to join it
if (member == null) {
if (ctx != null) {
sendEmbed(ctx, EmbedUtils.embedMessage("This command is a patron only command and is locked for you because you " +
"are not one of our patrons.\n" +
"For only $1 per month you can have access to this and many other commands [click here link to get started](" + PATREON + ").\n" +
"You will also need to join our discord server [here](https://duncte.bot/server)"), false);
if (replyChannel != null) {
sendMsg(
new MessageConfig.Builder()
.setChannel(replyChannel)
.setEmbeds(EmbedUtils.embedMessage("This command is a patron only command and is locked for you because you " +
"are not one of our patrons.\n" +
"For only $1 per month you can have access to this and many other commands [click here link to get started](" + PATREON + ").\n" +
"You will also need to join our discord server [here](https://duncte.bot/server)"))
);
}
return false;
}

// If the member is not a patron tell them to become one
if (!member.getRoles().contains(supportGuild.getRoleById(Settings.PATRONS_ROLE))) {
if (ctx != null) {
sendEmbed(ctx, EmbedUtils.embedMessage("This command is a patron only command and is locked for you because you " +
"are not one of our patrons.\n" +
"For only $1 per month you can have access to this and many other commands [click here link to get started](" + PATREON + ")."), false);
if (replyChannel != null) {
sendMsg(
new MessageConfig.Builder()
.setChannel(replyChannel)
.setEmbeds(EmbedUtils.embedMessage("This command is a patron only command and is locked for you because you " +
"are not one of our patrons.\n" +
"For only $1 per month you can have access to this and many other commands [click here link to get started](" + PATREON + ")."))
);
}
return false;
}
Expand All @@ -195,9 +203,9 @@ public static boolean isUserTagPatron(long userId) {
return TAG_PATRONS.contains(userId) || isDev(userId);
}

private static boolean isPatron(@Nonnull User user, @Nullable CommandContext ctx, boolean reply) {
final CommandContext context = reply ? ctx : null;
return isPatron(user, context) || isUserTagPatron(user);
private static boolean isPatron(@Nonnull User user, @Nullable MessageChannel replyChannel, boolean reply) {
final MessageChannel channel = reply ? replyChannel : null;
return isPatron(user, channel) || isUserTagPatron(user);
}

public static boolean isGuildPatron(@Nonnull Guild guild) {
Expand Down Expand Up @@ -235,8 +243,20 @@ private static boolean isGuildPatron(@Nonnull User user, @Nonnull Guild guild) {
}

public static boolean isUserOrGuildPatron(@Nonnull CommandContext ctx, boolean reply) {
final boolean isGuild = isGuildPatron(ctx.getAuthor(), ctx.getGuild());
return isGuild || isPatron(ctx.getAuthor(), ctx, reply);
return isUserOrGuildPatron(ctx.getAuthor(), ctx.getGuild(), ctx.getChannel(), reply);
}

public static boolean isUserOrGuildPatron(@Nonnull SlashCommandInteractionEvent event, boolean reply) {
return isUserOrGuildPatron(event.getUser(), Objects.requireNonNull(event.getGuild()), event.getChannel(), reply);
}

public static boolean isUserOrGuildPatron(@Nonnull SlashCommandInteractionEvent event) {
return isUserOrGuildPatron(event, true);
}

public static boolean isUserOrGuildPatron(@Nonnull User author, @Nonnull Guild guild, @Nonnull MessageChannel channel, boolean reply) {
final boolean isGuild = isGuildPatron(author, guild);
return isGuild || isPatron(author, channel, reply);
}

public static boolean isUserOrGuildPatron(@Nonnull CommandContext ctx) {
Expand Down
Loading

0 comments on commit e88d8b1

Please sign in to comment.