From 7cb304d22a4856815f74ae296517a99f37b936c8 Mon Sep 17 00:00:00 2001 From: Presti Date: Fri, 22 Jul 2022 16:22:32 +0200 Subject: [PATCH 1/5] * Added Reddit4J Library --- pom.xml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/pom.xml b/pom.xml index f0eb607df..96415cd16 100644 --- a/pom.xml +++ b/pom.xml @@ -48,6 +48,11 @@ + + com.github.masecla22 + Reddit4J + master-SNAPSHOT + com.google.cloud google-cloud-vision From 9bd7ac479ea6d644a943150349c59ec4d07f55ec Mon Sep 17 00:00:00 2001 From: DxsSucuk Date: Sat, 23 Jul 2022 21:28:40 +0200 Subject: [PATCH 2/5] * Implementation of Reddit-Notifier. --- .../impl/community/RedditNotifier.java | 102 ++++++++++++ .../java/de/presti/ree6/sql/SQLWorker.java | 148 ++++++++++++++++-- .../sql/entities/webhook/WebhookReddit.java | 45 ++++++ .../de/presti/ree6/utils/apis/Notifier.java | 119 ++++++++++++++ 4 files changed, 402 insertions(+), 12 deletions(-) create mode 100644 src/main/java/de/presti/ree6/commands/impl/community/RedditNotifier.java create mode 100644 src/main/java/de/presti/ree6/sql/entities/webhook/WebhookReddit.java diff --git a/src/main/java/de/presti/ree6/commands/impl/community/RedditNotifier.java b/src/main/java/de/presti/ree6/commands/impl/community/RedditNotifier.java new file mode 100644 index 000000000..73ebadd4c --- /dev/null +++ b/src/main/java/de/presti/ree6/commands/impl/community/RedditNotifier.java @@ -0,0 +1,102 @@ +package de.presti.ree6.commands.impl.community; + +import de.presti.ree6.commands.Category; +import de.presti.ree6.commands.CommandEvent; +import de.presti.ree6.commands.interfaces.Command; +import de.presti.ree6.commands.interfaces.ICommand; +import de.presti.ree6.main.Main; +import net.dv8tion.jda.api.Permission; +import net.dv8tion.jda.api.entities.TextChannel; +import net.dv8tion.jda.api.interactions.commands.build.CommandData; + +/** + * A Command to activate Reddit Notifications. + */ +@Command(name = "redditnotifier", description = "Manage your Reddit-Notifier!", category = Category.COMMUNITY) +public class RedditNotifier implements ICommand { + + /** + * @inheritDoc + */ + @Override + public void onPerform(CommandEvent commandEvent) { + if (!commandEvent.getGuild().getSelfMember().hasPermission(Permission.MANAGE_WEBHOOKS)) { + Main.getInstance().getCommandManager().sendMessage("I need the permission `Manage Webhooks` to use this command!", commandEvent.getChannel(), commandEvent.getInteractionHook()); + } + + if (commandEvent.isSlashCommand()) { + Main.getInstance().getCommandManager().sendMessage("This Command doesn't support slash commands yet.", commandEvent.getChannel(), commandEvent.getInteractionHook()); + return; + } + + if(commandEvent.getArguments().length == 1) { + if(commandEvent.getArguments()[0].equalsIgnoreCase("list")) { + StringBuilder end = new StringBuilder("```\n"); + + for(String users : Main.getInstance().getSqlConnector().getSqlWorker().getAllSubreddits(commandEvent.getGuild().getId())) { + end.append(users).append("\n"); + } + + end.append("```"); + + Main.getInstance().getCommandManager().sendMessage(end.toString(), 10, commandEvent.getChannel(), commandEvent.getInteractionHook()); + + } else { + Main.getInstance().getCommandManager().sendMessage("Please use " + Main.getInstance().getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getId(), "chatprefix").getStringValue() + "redditnotifier list/add/remove", 5, commandEvent.getChannel(), commandEvent.getInteractionHook()); + } + } else if(commandEvent.getArguments().length == 3) { + + if (commandEvent.getMessage().getMentions().getChannels(TextChannel.class).isEmpty()) { + Main.getInstance().getCommandManager().sendMessage("Please use " + Main.getInstance().getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getId(), "chatprefix").getStringValue() + "redditnotifier add/remove Subreddit #Channel", 5, commandEvent.getChannel(), commandEvent.getInteractionHook()); + return; + } + + String name = commandEvent.getArguments()[1]; + if (commandEvent.getArguments()[0].equalsIgnoreCase("add")) { + commandEvent.getMessage().getMentions().getChannels(TextChannel.class).get(0).createWebhook("Ree6-RedditNotifier-" + name).queue(w -> Main.getInstance().getSqlConnector().getSqlWorker().addRedditWebhook(commandEvent.getGuild().getId(), w.getId(), w.getToken(), name)); + Main.getInstance().getCommandManager().sendMessage("A Reddit Notifier has been created for the User " + name + "!", 5, commandEvent.getChannel(), commandEvent.getInteractionHook()); + + if (!Main.getInstance().getNotifier().isSubredditRegistered(name)) { + Main.getInstance().getNotifier().registerSubreddit(name); + } + } else if (commandEvent.getArguments()[0].equalsIgnoreCase("remove")) { + Main.getInstance().getCommandManager().sendMessage("Please use " + Main.getInstance().getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getId(), "chatprefix").getStringValue() + "redditnotifier remove Subreddit", 5, commandEvent.getChannel(), commandEvent.getInteractionHook()); + } else { + Main.getInstance().getCommandManager().sendMessage("Please use " + Main.getInstance().getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getId(), "chatprefix").getStringValue() + "redditnotifier add Subreddit #Channel", 5, commandEvent.getChannel(), commandEvent.getInteractionHook()); + } + } else if(commandEvent.getArguments().length == 2) { + String name = commandEvent.getArguments()[1]; + if(commandEvent.getArguments()[0].equalsIgnoreCase("remove")) { + Main.getInstance().getSqlConnector().getSqlWorker().removeRedditWebhook(commandEvent.getGuild().getId(), name); + Main.getInstance().getCommandManager().sendMessage("A Reddit Notifier has been removed from the User " + name + "!", 5, commandEvent.getChannel(), commandEvent.getInteractionHook()); + + if (Main.getInstance().getNotifier().isSubredditRegistered(name)) { + Main.getInstance().getNotifier().unregisterSubreddit(name); + } + } else if (commandEvent.getArguments()[0].equalsIgnoreCase("add")) { + Main.getInstance().getCommandManager().sendMessage("Please use " + Main.getInstance().getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getId(), "chatprefix").getStringValue() + "redditnotifier add Subreddit #Channel", 5, commandEvent.getChannel(), commandEvent.getInteractionHook()); + } else { + Main.getInstance().getCommandManager().sendMessage("Please use " + Main.getInstance().getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getId(), "chatprefix").getStringValue() + "redditnotifier remove Subreddit", 5, commandEvent.getChannel(), commandEvent.getInteractionHook()); + } + } else { + Main.getInstance().getCommandManager().sendMessage("Please use " + Main.getInstance().getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getId(), "chatprefix").getStringValue() + "redditnotifier list/add/remove", 5, commandEvent.getChannel(), commandEvent.getInteractionHook()); + } + Main.getInstance().getCommandManager().deleteMessage(commandEvent.getMessage(), commandEvent.getInteractionHook()); + } + + /** + * @inheritDoc + */ + @Override + public CommandData getCommandData() { + return null; + } + + /** + * @inheritDoc + */ + @Override + public String[] getAlias() { + return new String[] { "yt", "ytnotifier" }; + } +} diff --git a/src/main/java/de/presti/ree6/sql/SQLWorker.java b/src/main/java/de/presti/ree6/sql/SQLWorker.java index f2aa27e5c..a3fe7d465 100644 --- a/src/main/java/de/presti/ree6/sql/SQLWorker.java +++ b/src/main/java/de/presti/ree6/sql/SQLWorker.java @@ -56,7 +56,7 @@ public ChatUserLevel getChatLevelData(String guildId, String userId) { // Return a new UserLevel if there was an error OR if the user isn't in the database. return (ChatUserLevel) Objects.requireNonNull(getEntity(ChatUserLevel.class, "SELECT * FROM Level WHERE GID=? AND UID=?", guildId, userId)).getEntity(); } - return new ChatUserLevel(guildId, userId,0); + return new ChatUserLevel(guildId, userId, 0); } /** @@ -141,7 +141,7 @@ public VoiceUserLevel getVoiceLevelData(String guildId, String userId) { return (VoiceUserLevel) Objects.requireNonNull(getEntity(VoiceUserLevel.class, "SELECT * FROM VCLevel WHERE GID=? AND UID=?", guildId, userId)).getEntity(); } - return new VoiceUserLevel(guildId, userId,0); + return new VoiceUserLevel(guildId, userId, 0); } /** @@ -521,6 +521,127 @@ public boolean isTwitchSetup(String guildId, String twitchName) { //endregion + //region Reddit Notifier + + /** + * Get the RedditNotify data. + * + * @param guildId the ID of the Guild. + * @param subreddit the Name of the Subreddit. + * @return {@link WebhookReddit} with all the needed data. + */ + public WebhookReddit getRedditWebhook(String guildId, String subreddit) { + return (WebhookReddit) getEntity(WebhookReddit.class, "SELECT * FROM RedditNotify WHERE GID=? AND SUBREDDIT=?", guildId, subreddit).getEntity(); + } + + /** + * Get the RedditNotify data. + * + * @param subreddit the Name of the Subreddit. + * @return {@link List} with all the needed data. + */ + public List getRedditWebhookBySub(String subreddit) { + return getEntity(WebhookReddit.class, "SELECT * FROM RedditNotify WHERE SUBREDDIT=?", subreddit).getEntities().stream().map(WebhookReddit.class::cast).toList(); + } + + /** + * Get the all Reddit-Notifier. + * + * @return {@link List<>} in the first index is the Webhook ID and in the second the Auth-Token. + */ + public List getAllSubreddits() { + + ArrayList subreddits = new ArrayList<>(); + + // Creating a SQL Statement to get the Entry from the RedditNotify Table by the GuildID. + sqlConnector.querySQL("SELECT * FROM RedditNotify").getValues("SUBREDDIT") + .stream().map(String.class::cast).forEach(subreddits::add); + + return subreddits; + } + + /** + * Get every Reddit-Notifier that has been set up for the given Guild. + * + * @param guildId the ID of the Guild. + * @return {@link List<>} in the first index is the Webhook ID and in the second the Auth-Token. + */ + public List getAllSubreddits(String guildId) { + + ArrayList subreddits = new ArrayList<>(); + + // Creating a SQL Statement to get the Entry from the RedditNotify Table by the GuildID. + sqlConnector.querySQL("SELECT * FROM RedditNotify WHERE GID=?", guildId).getValues("SUBREDDIT") + .stream().map(String.class::cast).forEach(subreddits::add); + + return subreddits; + } + + /** + * Set the RedditNotify in our Database. + * + * @param guildId the ID of the Guild. + * @param webhookId the ID of the Webhook. + * @param authToken the Auth-token to verify the access. + * @param subreddit the Name of the Subreddit. + */ + public void addRedditWebhook(String guildId, String webhookId, String authToken, String subreddit) { + + // Check if there is already a Webhook set. + removeRedditWebhook(guildId, subreddit); + + // Add a new entry into the Database. + saveEntity(new WebhookReddit(guildId, subreddit, webhookId, authToken)); + } + + /** + * Remove a Reddit Notifier entry from our Database. + * + * @param guildId the ID of the Guild. + * @param subreddit the Name of the Subreddit. + */ + public void removeRedditWebhook(String guildId, String subreddit) { + + // Check if there is a Webhook set. + if (isRedditSetup(guildId, subreddit)) { + + // Get the Guild from the ID. + Guild guild = BotWorker.getShardManager().getGuildById(guildId); + + if (guild != null) { + Webhook webhookEntity = getRedditWebhook(guildId, subreddit); + // Delete the existing Webhook. + guild.retrieveWebhooks().queue(webhooks -> webhooks.stream().filter(webhook -> webhook.getToken() != null).filter(webhook -> webhook.getId().equalsIgnoreCase(webhookEntity.getChannelId()) && webhook.getToken().equalsIgnoreCase(webhookEntity.getToken())).forEach(webhook -> webhook.delete().queue())); + } + + // Delete the entry. + sqlConnector.querySQL("DELETE FROM RedditNotify WHERE GID=? AND SUBREDDIT=?", guildId, subreddit); + } + } + + /** + * Check if the Reddit Webhook has been set in our Database for this Server. + * + * @param guildId the ID of the Guild. + * @return {@link Boolean} if true, it has been set | if false, it hasn't been set. + */ + public boolean isRedditSetup(String guildId) { + return getEntity(WebhookReddit.class, "SELECT * FROM RedditNotify WHERE GID=?", guildId).isSuccess(); + } + + /** + * Check if the Reddit Webhook has been set for the given User in our Database for this Server. + * + * @param guildId the ID of the Guild. + * @param subreddit the Name of the Subreddit. + * @return {@link Boolean} if true, it has been set | if false, it hasn't been set. + */ + public boolean isRedditSetup(String guildId, String subreddit) { + return getEntity(WebhookReddit.class, "SELECT * FROM RedditNotify WHERE GID=? AND SUBREDDIT=?", guildId, subreddit).isSuccess(); + } + + //endregion + //region YouTube Notifier /** @@ -1061,7 +1182,8 @@ public void setInvite(String guildId, String inviteCreator, String inviteCode, l /** * Get the Invite from our Database. - * @param guildId the ID of the Guild. + * + * @param guildId the ID of the Guild. * @param inviteCode the Code of the Invite. * @return {@link Invite} as result if true, then it's saved in our Database | may be null. */ @@ -1071,9 +1193,10 @@ public Invite getInvite(String guildId, String inviteCode) { /** * Get the Invite from our Database. - * @param guildId the ID of the Guild. + * + * @param guildId the ID of the Guild. * @param inviteCreator the ID of the Invite Creator. - * @param inviteCode the Code of the Invite. + * @param inviteCode the Code of the Invite. * @return {@link Invite} as result if true, then it's saved in our Database | may be null. */ public Invite getInvite(String guildId, String inviteCreator, String inviteCode) { @@ -1358,7 +1481,8 @@ public void createSettings(String guildId) { if (!hasSetting(guildId, "level_message")) setSetting(new Setting(guildId, "level_message", false)); // Create the Join Message Setting - if (!hasSetting(guildId, "message_join")) setSetting(new Setting(guildId, "message_join", "Welcome %user_mention%!\nWe wish you a great stay on %guild_name%")); + if (!hasSetting(guildId, "message_join")) + setSetting(new Setting(guildId, "message_join", "Welcome %user_mention%!\nWe wish you a great stay on %guild_name%")); // Create Command Settings. for (ICommand command : Main.getInstance().getCommandManager().getCommands()) { @@ -1553,7 +1677,7 @@ public void deleteAllData(String guildId) { for (Class aClass : classes) { String tableName = SQLUtil.getTable(aClass); - List sqlParameters = SQLUtil.getAllSQLParameter(aClass,false); + List sqlParameters = SQLUtil.getAllSQLParameter(aClass, false); if (sqlParameters.isEmpty()) { return; @@ -1581,7 +1705,7 @@ public boolean createTable(Class entity) { } String tableName = SQLUtil.getTable(entity); - List sqlParameters = SQLUtil.getAllSQLParameter(entity,false); + List sqlParameters = SQLUtil.getAllSQLParameter(entity, false); if (sqlParameters.isEmpty()) { return false; @@ -1635,7 +1759,7 @@ public void saveEntity(Object entity) { } String tableName = SQLUtil.getTable(entityClass); - List sqlParameters = SQLUtil.getAllSQLParameter(entity,false, false); + List sqlParameters = SQLUtil.getAllSQLParameter(entity, false, false); if (sqlParameters.isEmpty()) { return; @@ -1677,8 +1801,8 @@ public void saveEntity(Object entity) { /** * Update an Entity in the Database. * - * @param oldEntity the old Entity. - * @param newEntity the new Entity. + * @param oldEntity the old Entity. + * @param newEntity the new Entity. * @param onlyUpdateField the only update the given Field. */ public void updateEntity(Object oldEntity, Object newEntity, boolean onlyUpdateField) { @@ -1752,7 +1876,7 @@ public void deleteEntity(Object entity) { } String tableName = SQLUtil.getTable(entityClass); - List sqlParameters = SQLUtil.getAllSQLParameter(entity,false, true); + List sqlParameters = SQLUtil.getAllSQLParameter(entity, false, true); if (sqlParameters.isEmpty()) { return; diff --git a/src/main/java/de/presti/ree6/sql/entities/webhook/WebhookReddit.java b/src/main/java/de/presti/ree6/sql/entities/webhook/WebhookReddit.java new file mode 100644 index 000000000..82045104f --- /dev/null +++ b/src/main/java/de/presti/ree6/sql/entities/webhook/WebhookReddit.java @@ -0,0 +1,45 @@ +package de.presti.ree6.sql.entities.webhook; + +import de.presti.ree6.sql.base.annotations.Property; +import de.presti.ree6.sql.base.annotations.Table; + +/** + * SQL Entity for the Reddit-Webhooks. + */ +@Table(name = "RedditNotify") +public class WebhookReddit extends Webhook { + + /** + * Name of the Channel. + */ + @Property(name = "subreddit") + private String subreddit; + + /** + * Constructor. + */ + public WebhookReddit() { + } + + + /** + * Constructor. + * + * @param guildId The guild ID. + * @param subreddit The name of the Subreddit. + * @param channelId The channel ID. + * @param token The token. + */ + public WebhookReddit(String guildId, String subreddit, String channelId, String token) { + super(guildId, channelId, token); + this.subreddit = subreddit; + } + + /** + * Get the name of the Subreddit. + * @return the subreddit name. + */ + public String getSubreddit() { + return subreddit; + } +} diff --git a/src/main/java/de/presti/ree6/utils/apis/Notifier.java b/src/main/java/de/presti/ree6/utils/apis/Notifier.java index ea1dce860..8a70acd4f 100644 --- a/src/main/java/de/presti/ree6/utils/apis/Notifier.java +++ b/src/main/java/de/presti/ree6/utils/apis/Notifier.java @@ -18,10 +18,14 @@ import de.presti.ree6.main.Main; import de.presti.ree6.utils.data.Data; import de.presti.ree6.utils.others.ThreadUtil; +import masecla.reddit4j.client.Reddit4J; +import masecla.reddit4j.exceptions.AuthenticationException; +import masecla.reddit4j.objects.Sorting; import twitter4j.*; import twitter4j.conf.ConfigurationBuilder; import java.awt.*; +import java.io.IOException; import java.time.Duration; import java.time.Instant; import java.util.List; @@ -38,6 +42,9 @@ public class Notifier { // Instance of the Twitter API Client. private final Twitter twitterClient; + // Instance of the Reddit API Client. + private final Reddit4J redditClient; + // Local list of registered Twitch Channels. private final ArrayList registeredTwitchChannels = new ArrayList<>(); @@ -47,6 +54,9 @@ public class Notifier { // Local list of registered Twitter Users. private final Map registeredTwitterUsers = new HashMap<>(); + // Local list of registered Subreddits. + private final ArrayList registeredSubreddits = new ArrayList<>(); + /** * Constructor used to created instance of the API Clients. */ @@ -68,6 +78,11 @@ public Notifier() { twitterClient = new TwitterFactory(configurationBuilder.build()).getInstance(); + Main.getInstance().getAnalyticsLogger().info("Initializing Reddit Client..."); + + redditClient = Reddit4J.rateLimited(); + createRedditPostStream(); + Main.getInstance().getAnalyticsLogger().info("Initializing YouTube Streams..."); createUploadStream(); } @@ -440,8 +455,102 @@ public boolean isYouTubeRegistered(String youtubeChannel) { //endregion + //region Reddit + + /** + * Used to register a Reddit-Post Event for all Subreddits. + */ + public void createRedditPostStream() { + ThreadUtil.createNewThread(x -> { + try { + for (String subreddit : registeredSubreddits) { + redditClient.getSubredditPosts(subreddit, Sorting.NEW).submit().stream().filter(redditPost -> redditPost.getCreated() > System.currentTimeMillis() - Duration.ofMinutes(5).toMillis()).forEach(redditPost -> { + // Create Webhook Message. + WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); + + webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl()); + webhookMessageBuilder.setUsername("Ree6"); + + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + + webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(redditPost.getTitle(), redditPost.getUrl())); + webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("Reddit Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl(), null)); + + webhookEmbedBuilder.setImageUrl(redditPost.getThumbnail()); + + // Set rest of the Information. + webhookEmbedBuilder.setDescription(redditPost.getSelftext()); + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Author**", redditPost.getAuthor())); + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Subreddit**", redditPost.getSubreddit())); + webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(Data.ADVERTISEMENT, BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl())); + + webhookEmbedBuilder.setColor(Color.ORANGE.getRGB()); + + webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); + + Main.getInstance().getSqlConnector().getSqlWorker().getRedditWebhookBySub(subreddit).forEach(webhook -> + WebhookUtil.sendWebhook(null, webhookMessageBuilder.build(), webhook, false)); + }); + } + } catch (IOException | AuthenticationException | InterruptedException e) { + Main.getInstance().getAnalyticsLogger().error("Could not get Reddit Posts!", e); + } + }, x -> Main.getInstance().getLogger().error("Couldn't start Reddit Stream!"), Duration.ofMinutes(5), true, true); + } + + /** + * Used to register a Reddit-Post Event for the given Subreddit + * + * @param subreddit the Names of the Subreddit. + */ + public void registerSubreddit(String subreddit) { + if (getRedditClient() == null) return; + + if (!isSubredditRegistered(subreddit)) registeredSubreddits.add(subreddit); + } + + /** + * Used to register a Reddit-Post Event for the Subreddit. + * + * @param subreddits the Names of the Subreddits. + */ + public void registerSubreddit(List subreddits) { + if (getRedditClient() == null) return; + + subreddits.forEach(s -> { + if (!isSubredditRegistered(s)) registeredSubreddits.add(s); + }); + } + + /** + * Used to unregister a Reddit-Post Event for the given Subreddit. + * + * @param subreddit the Names of the Subreddit. + */ + public void unregisterSubreddit(String subreddit) { + if (getRedditClient() == null) return; + + if (!Main.getInstance().getSqlConnector().getSqlWorker().getRedditWebhookBySub(subreddit).isEmpty()) + return; + + if (isSubredditRegistered(subreddit)) registeredSubreddits.remove(subreddit); + } + + /** + * Check if a Subreddit is already being checked. + * + * @param subreddit the Names of the Subreddit. + * @return true, if there is an Event for the Channel | false, if there isn't an Event for the Channel. + */ + public boolean isSubredditRegistered(String subreddit) { + return registeredSubreddits.contains(subreddit); + } + + //endregion + /** * Get an instance of the TwitchClient. + * * @return instance of the TwitchClient. */ public TwitchClient getTwitchClient() { @@ -450,9 +559,19 @@ public TwitchClient getTwitchClient() { /** * Get an instance of the TwitterClient. + * * @return instance of the TwitterClient. */ public Twitter getTwitterClient() { return twitterClient; } + + /** + * Get an instance of the RedditClient. + * + * @return instance of the RedditClient. + */ + public Reddit4J getRedditClient() { + return redditClient; + } } From 4538f75f89ab004095db84ab1e56d25eaaed2f3f Mon Sep 17 00:00:00 2001 From: DxsSucuk Date: Sat, 23 Jul 2022 21:42:19 +0200 Subject: [PATCH 3/5] * Fixed bug. --- src/main/java/de/presti/ree6/utils/apis/Notifier.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/de/presti/ree6/utils/apis/Notifier.java b/src/main/java/de/presti/ree6/utils/apis/Notifier.java index 8a70acd4f..ad21b12ff 100644 --- a/src/main/java/de/presti/ree6/utils/apis/Notifier.java +++ b/src/main/java/de/presti/ree6/utils/apis/Notifier.java @@ -492,8 +492,8 @@ public void createRedditPostStream() { WebhookUtil.sendWebhook(null, webhookMessageBuilder.build(), webhook, false)); }); } - } catch (IOException | AuthenticationException | InterruptedException e) { - Main.getInstance().getAnalyticsLogger().error("Could not get Reddit Posts!", e); + } catch (Exception exception) { + Main.getInstance().getAnalyticsLogger().error("Could not get Reddit Posts!", exception); } }, x -> Main.getInstance().getLogger().error("Couldn't start Reddit Stream!"), Duration.ofMinutes(5), true, true); } From 142d5dc96db233d7698094ba3c38ae7bf170472d Mon Sep 17 00:00:00 2001 From: DxsSucuk Date: Sat, 23 Jul 2022 23:01:37 +0200 Subject: [PATCH 4/5] * Fully functional Reddit Notifier. --- .../impl/community/RedditNotifier.java | 4 ++-- src/main/java/de/presti/ree6/main/Main.java | 3 +++ .../de/presti/ree6/utils/apis/Notifier.java | 24 +++++++++++++++---- .../de/presti/ree6/utils/data/Config.java | 2 ++ 4 files changed, 26 insertions(+), 7 deletions(-) diff --git a/src/main/java/de/presti/ree6/commands/impl/community/RedditNotifier.java b/src/main/java/de/presti/ree6/commands/impl/community/RedditNotifier.java index 73ebadd4c..79173bc44 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/RedditNotifier.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/RedditNotifier.java @@ -54,7 +54,7 @@ public void onPerform(CommandEvent commandEvent) { String name = commandEvent.getArguments()[1]; if (commandEvent.getArguments()[0].equalsIgnoreCase("add")) { commandEvent.getMessage().getMentions().getChannels(TextChannel.class).get(0).createWebhook("Ree6-RedditNotifier-" + name).queue(w -> Main.getInstance().getSqlConnector().getSqlWorker().addRedditWebhook(commandEvent.getGuild().getId(), w.getId(), w.getToken(), name)); - Main.getInstance().getCommandManager().sendMessage("A Reddit Notifier has been created for the User " + name + "!", 5, commandEvent.getChannel(), commandEvent.getInteractionHook()); + Main.getInstance().getCommandManager().sendMessage("A Reddit Notifier has been created for the Subreddit " + name + "!", 5, commandEvent.getChannel(), commandEvent.getInteractionHook()); if (!Main.getInstance().getNotifier().isSubredditRegistered(name)) { Main.getInstance().getNotifier().registerSubreddit(name); @@ -68,7 +68,7 @@ public void onPerform(CommandEvent commandEvent) { String name = commandEvent.getArguments()[1]; if(commandEvent.getArguments()[0].equalsIgnoreCase("remove")) { Main.getInstance().getSqlConnector().getSqlWorker().removeRedditWebhook(commandEvent.getGuild().getId(), name); - Main.getInstance().getCommandManager().sendMessage("A Reddit Notifier has been removed from the User " + name + "!", 5, commandEvent.getChannel(), commandEvent.getInteractionHook()); + Main.getInstance().getCommandManager().sendMessage("A Reddit Notifier has been removed from the Subreddit " + name + "!", 5, commandEvent.getChannel(), commandEvent.getInteractionHook()); if (Main.getInstance().getNotifier().isSubredditRegistered(name)) { Main.getInstance().getNotifier().unregisterSubreddit(name); diff --git a/src/main/java/de/presti/ree6/main/Main.java b/src/main/java/de/presti/ree6/main/Main.java index 568614bed..8c877c80c 100644 --- a/src/main/java/de/presti/ree6/main/Main.java +++ b/src/main/java/de/presti/ree6/main/Main.java @@ -163,6 +163,9 @@ public static void main(String[] args) { // Register all YouTube channels. instance.notifier.registerYouTubeChannel(instance.sqlConnector.getSqlWorker().getAllYouTubeChannels()); + // Register all Reddit Subreddits. + instance.notifier.registerSubreddit(instance.sqlConnector.getSqlWorker().getAllSubreddits()); + instance.logger.info("Creating JDA Instance."); // Create a new Instance of the Bot, as well as add the Events. diff --git a/src/main/java/de/presti/ree6/utils/apis/Notifier.java b/src/main/java/de/presti/ree6/utils/apis/Notifier.java index ad21b12ff..13f8ccdae 100644 --- a/src/main/java/de/presti/ree6/utils/apis/Notifier.java +++ b/src/main/java/de/presti/ree6/utils/apis/Notifier.java @@ -19,6 +19,7 @@ import de.presti.ree6.utils.data.Data; import de.presti.ree6.utils.others.ThreadUtil; import masecla.reddit4j.client.Reddit4J; +import masecla.reddit4j.client.UserAgentBuilder; import masecla.reddit4j.exceptions.AuthenticationException; import masecla.reddit4j.objects.Sorting; import twitter4j.*; @@ -26,6 +27,8 @@ import java.awt.*; import java.io.IOException; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; import java.time.Duration; import java.time.Instant; import java.util.List; @@ -80,8 +83,17 @@ public Notifier() { Main.getInstance().getAnalyticsLogger().info("Initializing Reddit Client..."); - redditClient = Reddit4J.rateLimited(); - createRedditPostStream(); + redditClient = Reddit4J.rateLimited() + .setClientId(Main.getInstance().getConfig().getConfiguration().getString("reddit.client.id")) + .setClientSecret(Main.getInstance().getConfig().getConfiguration().getString("reddit.client.secret")) + .setUserAgent("Ree6Bot/" + BotWorker.getBuild() + " (by /u/PrestiSchmesti)"); + + try { + redditClient.userlessConnect(); + createRedditPostStream(); + } catch (Exception exception) { + Main.getInstance().getLogger().error("Failed to connect to Reddit API.", exception); + } Main.getInstance().getAnalyticsLogger().info("Initializing YouTube Streams..."); createUploadStream(); @@ -464,7 +476,7 @@ public void createRedditPostStream() { ThreadUtil.createNewThread(x -> { try { for (String subreddit : registeredSubreddits) { - redditClient.getSubredditPosts(subreddit, Sorting.NEW).submit().stream().filter(redditPost -> redditPost.getCreated() > System.currentTimeMillis() - Duration.ofMinutes(5).toMillis()).forEach(redditPost -> { + redditClient.getSubredditPosts(subreddit, Sorting.NEW).submit().stream().filter(redditPost -> redditPost.getCreated() > (Duration.ofMillis(System.currentTimeMillis()).toSeconds() - Duration.ofMinutes(5).toSeconds())).forEach(redditPost -> { // Create Webhook Message. WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); @@ -476,10 +488,12 @@ public void createRedditPostStream() { webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(redditPost.getTitle(), redditPost.getUrl())); webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("Reddit Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl(), null)); - webhookEmbedBuilder.setImageUrl(redditPost.getThumbnail()); + + if (!redditPost.getThumbnail().equalsIgnoreCase("self")) + webhookEmbedBuilder.setImageUrl(redditPost.getThumbnail()); // Set rest of the Information. - webhookEmbedBuilder.setDescription(redditPost.getSelftext()); + webhookEmbedBuilder.setDescription(URLDecoder.decode(redditPost.getSelftext(), StandardCharsets.UTF_8)); webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Author**", redditPost.getAuthor())); webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Subreddit**", redditPost.getSubreddit())); webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(Data.ADVERTISEMENT, BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl())); diff --git a/src/main/java/de/presti/ree6/utils/data/Config.java b/src/main/java/de/presti/ree6/utils/data/Config.java index d6f6df2a2..127cc7b05 100644 --- a/src/main/java/de/presti/ree6/utils/data/Config.java +++ b/src/main/java/de/presti/ree6/utils/data/Config.java @@ -49,6 +49,8 @@ public void init() { yamlFile.addDefault("twitter.consumer.secret", "yourTwitterConsumerSecret"); yamlFile.addDefault("twitter.access.key", "yourTwitterAccessKey"); yamlFile.addDefault("twitter.access.secret", "yourTwitterAccessSecret"); + yamlFile.addDefault("reddit.client.id", "yourredditclientid"); + yamlFile.addDefault("reddit.client.secret", "yourredditclientsecret"); yamlFile.addDefault("youtube.api.key", "youryoutubeapikey"); yamlFile.addDefault("bot.tokens.rel", "ReleaseTokenhere"); yamlFile.addDefault("bot.tokens.dev", "DevTokenhere"); From edc4fb1eb389a5c9c5281d49bc53c66892818781 Mon Sep 17 00:00:00 2001 From: DxsSucuk Date: Sat, 23 Jul 2022 23:04:55 +0200 Subject: [PATCH 5/5] * Code cleanup. --- src/main/java/de/presti/ree6/utils/apis/Notifier.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/main/java/de/presti/ree6/utils/apis/Notifier.java b/src/main/java/de/presti/ree6/utils/apis/Notifier.java index 13f8ccdae..75a5dc603 100644 --- a/src/main/java/de/presti/ree6/utils/apis/Notifier.java +++ b/src/main/java/de/presti/ree6/utils/apis/Notifier.java @@ -19,14 +19,11 @@ import de.presti.ree6.utils.data.Data; import de.presti.ree6.utils.others.ThreadUtil; import masecla.reddit4j.client.Reddit4J; -import masecla.reddit4j.client.UserAgentBuilder; -import masecla.reddit4j.exceptions.AuthenticationException; import masecla.reddit4j.objects.Sorting; import twitter4j.*; import twitter4j.conf.ConfigurationBuilder; import java.awt.*; -import java.io.IOException; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.time.Duration;