Skip to content

Commit

Permalink
Merge pull request #78 from Ree6-Applications/feature/reddit-notifier
Browse files Browse the repository at this point in the history
Reddit post Notifier.
  • Loading branch information
DxsSucuk authored Jul 23, 2022
2 parents 72f8187 + edc4fb1 commit d7c2f80
Show file tree
Hide file tree
Showing 7 changed files with 423 additions and 12 deletions.
5 changes: 5 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@
</repositories>

<dependencies>
<dependency>
<groupId>com.github.masecla22</groupId>
<artifactId>Reddit4J</artifactId>
<version>master-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-vision</artifactId>
Expand Down
Original file line number Diff line number Diff line change
@@ -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 Subreddit " + 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 Subreddit " + 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" };
}
}
3 changes: 3 additions & 0 deletions src/main/java/de/presti/ree6/main/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
148 changes: 136 additions & 12 deletions src/main/java/de/presti/ree6/sql/SQLWorker.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

/**
Expand Down Expand Up @@ -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);
}

/**
Expand Down Expand Up @@ -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<WebhookReddit>} with all the needed data.
*/
public List<WebhookReddit> 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<String> getAllSubreddits() {

ArrayList<String> 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<String> getAllSubreddits(String guildId) {

ArrayList<String> 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

/**
Expand Down Expand Up @@ -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.
*/
Expand All @@ -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) {
Expand Down Expand Up @@ -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()) {
Expand Down Expand Up @@ -1556,7 +1680,7 @@ public void deleteAllData(String guildId) {

if (tableName == null) continue;

List<SQLParameter> sqlParameters = SQLUtil.getAllSQLParameter(aClass,false);
List<SQLParameter> sqlParameters = SQLUtil.getAllSQLParameter(aClass, false);

if (sqlParameters.isEmpty()) {
continue;
Expand Down Expand Up @@ -1584,7 +1708,7 @@ public boolean createTable(Class<? extends SQLEntity> entity) {
}

String tableName = SQLUtil.getTable(entity);
List<SQLParameter> sqlParameters = SQLUtil.getAllSQLParameter(entity,false);
List<SQLParameter> sqlParameters = SQLUtil.getAllSQLParameter(entity, false);

if (sqlParameters.isEmpty()) {
return false;
Expand Down Expand Up @@ -1638,7 +1762,7 @@ public void saveEntity(Object entity) {
}

String tableName = SQLUtil.getTable(entityClass);
List<SQLParameter> sqlParameters = SQLUtil.getAllSQLParameter(entity,false, false);
List<SQLParameter> sqlParameters = SQLUtil.getAllSQLParameter(entity, false, false);

if (sqlParameters.isEmpty()) {
return;
Expand Down Expand Up @@ -1680,8 +1804,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) {
Expand Down Expand Up @@ -1755,7 +1879,7 @@ public void deleteEntity(Object entity) {
}

String tableName = SQLUtil.getTable(entityClass);
List<SQLParameter> sqlParameters = SQLUtil.getAllSQLParameter(entity,false, true);
List<SQLParameter> sqlParameters = SQLUtil.getAllSQLParameter(entity, false, true);

if (sqlParameters.isEmpty()) {
return;
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
}
}
Loading

0 comments on commit d7c2f80

Please sign in to comment.