Skip to content

Commit

Permalink
Merge pull request #232 from beanbeanjuice/integration
Browse files Browse the repository at this point in the history
Ready for Release v2.4.1
  • Loading branch information
beanbeanjuice committed May 29, 2021
2 parents 11275ee + 724a3cd commit f5ed6d0
Show file tree
Hide file tree
Showing 10 changed files with 240 additions and 43 deletions.
1 change: 1 addition & 0 deletions README.md
Expand Up @@ -143,6 +143,7 @@ As you can see, this was shown using the command `!!help order`. It shows each p
* `order` - Order a menu item for someone!
* `balance` - Check your balance!
##### 3. **FUN**
* `coffee-meme` - Get a coffee meme!
* `meme` - Send a meme in the current channel. (SFW)
* `joke` - Send a joke in the current channel. (SFW)
* `add-poll` - Create a poll! Currently, you can only have 3 polls due to server costs. This will go up in the future!
Expand Down
4 changes: 2 additions & 2 deletions build.gradle
Expand Up @@ -63,8 +63,8 @@ dependencies {
// Spotify API
implementation group: 'se.michaelthelin.spotify', name: 'spotify-web-api-java', version: '6.5.2'

// Web Utils
implementation group: 'me.duncte123', name: 'botCommons', version: '2.0.122'
// JSOUP for Parsing
implementation group: 'org.jsoup', name: 'jsoup', version: '1.13.1'

// JSON
implementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.12.1'
Expand Down
72 changes: 72 additions & 0 deletions src/main/java/com/beanbeanjuice/command/fun/CoffeeMemeCommand.java
@@ -0,0 +1,72 @@
package com.beanbeanjuice.command.fun;

import com.beanbeanjuice.main.CafeBot;
import com.beanbeanjuice.utility.command.CommandContext;
import com.beanbeanjuice.utility.command.ICommand;
import com.beanbeanjuice.utility.command.usage.Usage;
import com.beanbeanjuice.utility.command.usage.categories.CategoryType;
import com.beanbeanjuice.utility.helper.RedditAPI;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;

/**
* An {@link ICommand} used to get coffee memes from the {@link com.beanbeanjuice.utility.helper.RedditAPI RedditAPI}.
*
* @author beanbeanjuice
*/
public class CoffeeMemeCommand implements ICommand {

@Override
public void handle(CommandContext ctx, ArrayList<String> args, User user, GuildMessageReceivedEvent event) {
event.getChannel().sendMessage(new RedditAPI().getRedditEmbed(getSubreddits().get(CafeBot.getGeneralHelper().getRandomNumber(0, getSubreddits().size())))).queue();
}

@NotNull
private ArrayList<String> getSubreddits() {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("CoffeePorn");
arrayList.add("coffeememes");
arrayList.add("coffeewithaview");
return arrayList;
}

@Override
public String getName() {
return "coffee-meme";
}

@Override
public ArrayList<String> getAliases() {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("coffeememe");
arrayList.add("coffee");
arrayList.add("coffee-memes");
arrayList.add("coffeememes");
arrayList.add("cafe-meme");
arrayList.add("cafememe");
return arrayList;
}

@Override
public String getDescription() {
return "Get a coffee meme!";
}

@Override
public String exampleUsage() {
return "`!!coffee-meme`";
}

@Override
public Usage getUsage() {
return new Usage();
}

@Override
public CategoryType getCategoryType() {
return CategoryType.FUN;
}
}
27 changes: 11 additions & 16 deletions src/main/java/com/beanbeanjuice/command/fun/JokeCommand.java
Expand Up @@ -5,9 +5,7 @@
import com.beanbeanjuice.utility.command.ICommand;
import com.beanbeanjuice.utility.command.usage.Usage;
import com.beanbeanjuice.utility.command.usage.categories.CategoryType;
import com.beanbeanjuice.utility.logger.LogLevel;
import com.fasterxml.jackson.databind.JsonNode;
import me.duncte123.botcommons.web.WebUtils;
import com.beanbeanjuice.utility.helper.RedditAPI;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.entities.User;
Expand All @@ -26,20 +24,17 @@ public class JokeCommand implements ICommand {

@Override
public void handle(CommandContext ctx, ArrayList<String> args, User user, GuildMessageReceivedEvent event) {
WebUtils.ins.getJSONObject("https://apis.duncte123.me/joke").async((json) -> {
if (!json.get("success").asBoolean()) {
event.getChannel().sendMessage(cannotGetJSONEmbed()).queue();
CafeBot.getLogManager().log(JokeCommand.class, LogLevel.ERROR, "Cannot get JSON.");
return;
}

final JsonNode data = json.get("data");
final String title = data.get("title").asText();
final String url = data.get("url").asText();
final String body = data.get("body").asText();
event.getChannel().sendMessage(new RedditAPI().getRedditEmbed(getSubreddits().get(CafeBot.getGeneralHelper().getRandomNumber(0, getSubreddits().size())))).queue();
}

event.getChannel().sendMessage(messageEmbed(title, url, body)).queue();
});
@NotNull
private ArrayList<String> getSubreddits() {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("oneliners");
arrayList.add("dadjokes");
arrayList.add("jokes");
arrayList.add("cleanjokes");
return arrayList;
}

@NotNull
Expand Down
28 changes: 12 additions & 16 deletions src/main/java/com/beanbeanjuice/command/fun/MemeCommand.java
Expand Up @@ -5,9 +5,7 @@
import com.beanbeanjuice.utility.command.ICommand;
import com.beanbeanjuice.utility.command.usage.Usage;
import com.beanbeanjuice.utility.command.usage.categories.CategoryType;
import com.beanbeanjuice.utility.logger.LogLevel;
import com.fasterxml.jackson.databind.JsonNode;
import me.duncte123.botcommons.web.WebUtils;
import com.beanbeanjuice.utility.helper.RedditAPI;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.entities.User;
Expand All @@ -26,20 +24,18 @@ public class MemeCommand implements ICommand {

@Override
public void handle(CommandContext ctx, ArrayList<String> args, User user, GuildMessageReceivedEvent event) {
WebUtils.ins.getJSONObject("https://apis.duncte123.me/meme").async((json) -> {
if (!json.get("success").asBoolean()) {
event.getChannel().sendMessage(cannotGetJSONEmbed()).queue();
CafeBot.getLogManager().log(MemeCommand.class, LogLevel.ERROR, "Cannot get JSON.");
return;
}

final JsonNode data = json.get("data");
final String title = data.get("title").asText();
final String url = data.get("url").asText();
final String image = data.get("image").asText();
event.getChannel().sendMessage(new RedditAPI().getRedditEmbed(getSubreddits().get(CafeBot.getGeneralHelper().getRandomNumber(0, getSubreddits().size())))).queue();
}

event.getChannel().sendMessage(messageEmbed(title, url, image)).queue();
});
@NotNull
private ArrayList<String> getSubreddits() {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("memes");
arrayList.add("dankmemes");
arrayList.add("me_irl");
arrayList.add("PrequelMemes");
arrayList.add("thatHappened");
return arrayList;
}

@NotNull
Expand Down
Expand Up @@ -5,6 +5,7 @@
import com.beanbeanjuice.utility.command.ICommand;
import com.beanbeanjuice.utility.command.usage.Usage;
import com.beanbeanjuice.utility.command.usage.categories.CategoryType;
import com.beanbeanjuice.utility.helper.timestamp.TimestampDifference;
import com.beanbeanjuice.utility.sections.music.lavaplayer.GuildMusicManager;
import com.beanbeanjuice.utility.sections.music.lavaplayer.PlayerManager;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
Expand Down Expand Up @@ -41,7 +42,6 @@ public void handle(CommandContext ctx, ArrayList<String> args, User user, GuildM
}

if (selfVoiceState.inVoiceChannel()) {

GuildMusicManager musicManager = PlayerManager.getInstance().getMusicManager(ctx.getGuild());
AudioPlayer audioPlayer = musicManager.audioPlayer;
final AudioTrack audioTrack = audioPlayer.getPlayingTrack();
Expand All @@ -52,16 +52,31 @@ public void handle(CommandContext ctx, ArrayList<String> args, User user, GuildM
}

final AudioTrackInfo info = audioTrack.getInfo();
event.getChannel().sendMessage(nowPlaying(info.title, info.author, info.uri)).queue();

event.getChannel().sendMessage(nowPlaying(info.title, info.author, info.uri, audioTrack.getPosition(), audioTrack.getDuration())).queue();
}
}

@NotNull
private MessageEmbed nowPlaying(@NotNull String title, @NotNull String author, @NotNull String url) {
private MessageEmbed nowPlaying(@NotNull String title, @NotNull String author, @NotNull String url, @NotNull Long songTimestamp, @NotNull Long songDuration) {
EmbedBuilder embedBuilder = new EmbedBuilder();
embedBuilder.setTitle("Now Playing", url);
String message = String.format("`%s` by `%s`", title, author);
int songPositionSeconds = CafeBot.getGeneralHelper().roundTime(songTimestamp, TimestampDifference.SECONDS);
String songPositionSecondsString = String.valueOf(songPositionSeconds);

if (!CafeBot.getGeneralHelper().isDoubleDigit(songPositionSeconds)) {
songPositionSecondsString = "0" + songPositionSecondsString;
}
String songPosition = String.format("%s:%s", CafeBot.getGeneralHelper().roundTime(songTimestamp, TimestampDifference.MINUTES), songPositionSecondsString);

int songLengthSeconds = CafeBot.getGeneralHelper().roundTime(songDuration, TimestampDifference.SECONDS);
String songLengthSecondsString = String.valueOf(songLengthSeconds);

if (!CafeBot.getGeneralHelper().isDoubleDigit(songLengthSeconds)) {
songLengthSecondsString = "0" + songLengthSecondsString;
}

String songLength = String.format("%s:%s", CafeBot.getGeneralHelper().roundTime(songDuration, TimestampDifference.MINUTES), songLengthSecondsString);
String message = String.format("`%s` by `%s` - [`%s / %s`]", title, author, songPosition, songLength);
embedBuilder.setDescription(message);
embedBuilder.setColor(Color.cyan);
return embedBuilder.build();
Expand Down
22 changes: 18 additions & 4 deletions src/main/java/com/beanbeanjuice/command/music/SkipCommand.java
Expand Up @@ -5,9 +5,11 @@
import com.beanbeanjuice.utility.command.ICommand;
import com.beanbeanjuice.utility.command.usage.Usage;
import com.beanbeanjuice.utility.command.usage.categories.CategoryType;
import com.beanbeanjuice.utility.helper.timestamp.TimestampDifference;
import com.beanbeanjuice.utility.sections.music.lavaplayer.GuildMusicManager;
import com.beanbeanjuice.utility.sections.music.lavaplayer.PlayerManager;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.GuildVoiceState;
import net.dv8tion.jda.api.entities.Member;
Expand Down Expand Up @@ -57,7 +59,7 @@ public void handle(CommandContext ctx, ArrayList<String> args, User user, GuildM
}

musicManager.scheduler.nextTrack();
event.getChannel().sendMessage(successEmbed()).queue();
event.getChannel().sendMessage(successEmbed(musicManager.audioPlayer.getPlayingTrack(), musicManager.scheduler.queue.size())).queue();
}

@NotNull
Expand Down Expand Up @@ -95,11 +97,23 @@ private MessageEmbed mustBeInVoiceChannelEmbed() {
}

@NotNull
private MessageEmbed successEmbed() {
private MessageEmbed successEmbed(@NotNull AudioTrack audioTrack, @NotNull Integer songsLeftInQueue) {
EmbedBuilder embedBuilder = new EmbedBuilder();
embedBuilder.setDescription("Successfully skipped the track.");
embedBuilder.setColor(Color.green);
embedBuilder.setTitle("Skipped Song");

int songLength = CafeBot.getGeneralHelper().roundTime(audioTrack.getDuration(), TimestampDifference.SECONDS);
String songLengthString = String.valueOf(songLength);

if (!CafeBot.getGeneralHelper().isDoubleDigit(songLength)) {
songLengthString = "0" + songLengthString;
}
String songPosition = String.format("%s:%s", CafeBot.getGeneralHelper().roundTime(audioTrack.getDuration(), TimestampDifference.MINUTES), songLengthString);
StringBuilder descriptionBuilder = new StringBuilder();
descriptionBuilder.append("Now Playing - `" + audioTrack.getInfo().title + "` by `" + audioTrack.getInfo().author + "` [`" + songPosition + "]`");

embedBuilder.setDescription(descriptionBuilder.toString());
embedBuilder.setColor(Color.green);
embedBuilder.setFooter("Songs Left: " + songsLeftInQueue);
return embedBuilder.build();
}

Expand Down
1 change: 1 addition & 0 deletions src/main/java/com/beanbeanjuice/main/CafeBot.java
Expand Up @@ -202,6 +202,7 @@ public static void main(String[] args) throws LoginException, InterruptedExcepti

// Fun Commands
commandManager.addCommands(
new CoffeeMemeCommand(),
new MemeCommand(),
new JokeCommand(),
new AddPollCommand(),
Expand Down
25 changes: 25 additions & 0 deletions src/main/java/com/beanbeanjuice/utility/helper/GeneralHelper.java
Expand Up @@ -51,6 +51,31 @@ public Integer getRandomNumber(@NotNull Integer minimum, @NotNull Integer maximu
return (int) ((Math.random() * (maximum - minimum)) + minimum);
}

/**
* Checks if a specified {@link Integer} is a double digit.
* @param number The {@link Integer} specified.
* @return Whether or not the {@link Integer} is a double digit.
*/
@NotNull
public Boolean isDoubleDigit(@NotNull Integer number) {
return (number > 9 && number < 100) || (number < -9 && number > -100);
}

/**
* Round a time to minutes or seconds.
* @param time The time in milliseconds.
* @param timestampDifference The timestamp difference specified.
* @return The rounded time.
*/
@NotNull
public Integer roundTime(@NotNull Long time, @NotNull TimestampDifference timestampDifference) {

if (timestampDifference.equals(TimestampDifference.MINUTES)) {
return Math.round(((time/1000)/60));
}
return Math.round((time/1000)%60);
}

/**
* Compare the difference in time between two {@link Timestamp} objects.
* @param oldTime The old {@link Timestamp}.
Expand Down
78 changes: 78 additions & 0 deletions src/main/java/com/beanbeanjuice/utility/helper/RedditAPI.java
@@ -0,0 +1,78 @@
package com.beanbeanjuice.utility.helper;

import com.beanbeanjuice.main.CafeBot;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.MessageEmbed;
import org.jetbrains.annotations.NotNull;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class RedditAPI {

private String reddit_api_url = "https://www.reddit.com/r/{SUBREDDIT}/random/.json";
private String reddit_url;
private String reddit_image_url;
private String reddit_title;
private String reddit_username;
private String reddit_subreddit;
private String reddit_description;

/**
* Get the completed {@link MessageEmbed} for the subreddit.
* @param subreddit The subreddit specified.
* @return The new {@link MessageEmbed} to be sent.
*/
@NotNull
public MessageEmbed getRedditEmbed(@NotNull String subreddit) {
reddit_subreddit = subreddit;
reddit_api_url = reddit_api_url.replace("{SUBREDDIT}", reddit_subreddit);
contactRedditAPI();

// Making sure it's not a video
while (reddit_image_url.contains("v.red")) {
contactRedditAPI();
}

EmbedBuilder embedBuilder = new EmbedBuilder();
embedBuilder.setTitle(reddit_title, reddit_url);
embedBuilder.setImage(reddit_image_url);
embedBuilder.setFooter("By: " + reddit_username + " - r/" + reddit_subreddit);
embedBuilder.setColor(CafeBot.getGeneralHelper().getRandomColor());
embedBuilder.setDescription(reddit_description);
return embedBuilder.build();
}

/**
* A method used for contacting the guilds who have enabled the bot update notification.
*/
private void contactRedditAPI() {
HttpClient client = HttpClient.newBuilder().followRedirects(HttpClient.Redirect.ALWAYS).build();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(reddit_api_url)).build();
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenApply(this::parse)
.join();
}

private String parse(String responseBody) {
ObjectMapper defaultObjectMapper = new ObjectMapper();
try {
JsonNode node = defaultObjectMapper.readTree(responseBody).get(0).get("data").get("children").get(0).get("data");
reddit_url = "https://www.reddit.com" + node.get("permalink").textValue();
reddit_image_url = node.get("url").textValue();
reddit_title = node.get("title").textValue();
reddit_username = node.get("author").textValue();
reddit_description = node.get("selftext").textValue();
return node.toString();
} catch (JsonProcessingException e) {
return null;
}
}

}

0 comments on commit f5ed6d0

Please sign in to comment.