Skip to content

Commit

Permalink
Merge pull request #262 from KittyBot-Org/development
Browse files Browse the repository at this point in the history
voting rewards
  • Loading branch information
topi314 authored Feb 22, 2021
2 parents 1cea74a + e1b689a commit 5c8d2c9
Show file tree
Hide file tree
Showing 33 changed files with 688 additions and 137 deletions.
1 change: 1 addition & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ dependencies {
implementation 'net.dv8tion:JDA:4.2.0_228'
implementation 'com.jagrosh:jda-utilities:3.0.5'
implementation 'club.minnced:discord-webhooks:0.5.4'
implementation 'com.github.caneleex:BotListHandler:1.0.6'

// audio
implementation("com.github.KittyBot-Org:Lavalink-Client:94660b3") {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ public RemoveCommand(){
public void run(Options options, Interaction ia){
var environment = options.getInt("environment");
if(environment == 0){
if(Environment.getCurrentEnv() == Environment.PRODUCTION){
if(Environment.getCurrent() == Environment.PRODUCTION){
ia.reply(new InteractionResponse.Builder().ephemeral().setContent("Removing commands globally in production is not allowed sorry :3").build());
return;
}
Expand Down
28 changes: 28 additions & 0 deletions src/main/java/de/kittybot/kittybot/commands/info/VoteCommand.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package de.kittybot.kittybot.commands.info;

import de.kittybot.kittybot.objects.enums.BotList;
import de.kittybot.kittybot.slashcommands.application.Category;
import de.kittybot.kittybot.slashcommands.application.RunCommand;
import de.kittybot.kittybot.slashcommands.interaction.Interaction;
import de.kittybot.kittybot.slashcommands.interaction.Options;
import de.kittybot.kittybot.utils.MessageUtils;

import java.util.Arrays;
import java.util.stream.Collectors;

@SuppressWarnings("unused")
public class VoteCommand extends RunCommand{

public VoteCommand(){
super("vote", "Displays all info about voting for kitty", Category.INFORMATION);
}

@Override
public void run(Options options, Interaction ia){
ia.reply("You can vote on following sites for KittyBot:\n" + Arrays.stream(BotList.values()).
filter(BotList::canVote)
.map(botList -> MessageUtils.maskLink(botList.getName(), botList.getBotUrl())).collect(Collectors.joining(", "))
);
}

}
16 changes: 16 additions & 0 deletions src/main/java/de/kittybot/kittybot/main/KittyBot.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
package de.kittybot.kittybot.main;

import de.kittybot.kittybot.modules.LavalinkModule;
import de.kittybot.kittybot.objects.enums.Environment;
import de.kittybot.kittybot.objects.exceptions.MissingConfigValuesException;
import de.kittybot.kittybot.objects.module.Modules;
import de.kittybot.kittybot.utils.Config;
import dev.mlnr.blh.api.BLHBuilder;
import dev.mlnr.blh.api.BLHEventListener;
import dev.mlnr.blh.api.BotList;
import net.dv8tion.jda.api.GatewayEncoding;
import net.dv8tion.jda.api.OnlineStatus;
import net.dv8tion.jda.api.entities.Activity;
Expand All @@ -26,6 +30,17 @@ public class KittyBot{
public KittyBot() throws IOException, MissingConfigValuesException, LoginException, InterruptedException{
Config.init("./config.json");
var modules = new Modules(this);
var botListHandler = new BLHBuilder()
.setDevModePredicate(jda -> Environment.is(Environment.DEVELOPMENT))
.addBotList(BotList.TOP_GG, Config.TOP_GG_TOKEN)
.addBotList(BotList.DBOATS, Config.DISCORD_BOATS_TOKEN)
.addBotList(BotList.BOTLIST_SPACE, Config.BOTLIST_SPACE_TOKEN)
.addBotList(BotList.BOTS_FOR_DISCORD, Config.BOTS_FOR_DISCORD_TOKEN)
.addBotList(BotList.DSERVICES, Config.DISCORD_SERVICES_TOKEN)
.addBotList(BotList.DBL, Config.DISCORD_BOT_LIST_TOKEN)
.addBotList(BotList.DEL, Config.DISCORD_EXTREME_LIST_TOKEN)
.addBotList(BotList.DBOTS_GG, Config.DISCORD_BOTS_TOKEN)
.build();

RestAction.setDefaultFailure(null);
this.shardManager = DefaultShardManagerBuilder.create(
Expand All @@ -46,6 +61,7 @@ public KittyBot() throws IOException, MissingConfigValuesException, LoginExcepti
.setMemberCachePolicy(MemberCachePolicy.VOICE)
.setChunkingFilter(ChunkingFilter.NONE)
.addEventListeners(modules.getModules())
.addEventListeners(new BLHEventListener(botListHandler))
.setRawEventsEnabled(true)
.setHttpClient(modules.getHttpClient())
.setVoiceDispatchInterceptor(modules.get(LavalinkModule.class).getVoiceInterceptor())
Expand Down
62 changes: 0 additions & 62 deletions src/main/java/de/kittybot/kittybot/modules/BotListsModule.java

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,13 @@ public Set<Class<? extends Module>> getDependencies(){
@Override
public void onEnable(){
scanCommands();
var env = Environment.getCurrentEnv();
var env = Environment.getCurrent();
if(env == Environment.PRODUCTION){
deployAllCommands(-1L);
}
else if(env == Environment.DEVELOPMENT){
if(Config.TEST_GUILD != -1){
deployAllCommands(Config.TEST_GUILD);
if(Config.SUPPORT_GUILD_ID != -1){
deployAllCommands(Config.SUPPORT_GUILD_ID);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ public void onEnable(){
initTable("guilds",
"member_roles",
"guild_tags",
"voters",
"guild_invites",
"guild_invite_roles",
"self_assignable_role_groups",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ protected JdaLink getExistingLink(long guildId){
return this.lavalink.getExistingLink(guildId);
}


public JdaLavalink getLavalink(){
return this.lavalink;
}
Expand Down
16 changes: 5 additions & 11 deletions src/main/java/de/kittybot/kittybot/modules/NotificationModule.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@
import de.kittybot.kittybot.slashcommands.application.Category;
import de.kittybot.kittybot.utils.Colors;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.events.ReadyEvent;
import org.jetbrains.annotations.NotNull;

import java.time.Instant;
import java.time.LocalDateTime;
Expand All @@ -26,12 +24,17 @@ public class NotificationModule extends Module{
public void onEnable(){
this.notifications = new HashMap<>();
this.modules.scheduleAtFixedRate(this::update, 0, 30, TimeUnit.MINUTES);
this.modules.scheduleAtFixedRate(this::scheduleNext, 0, 5, TimeUnit.MINUTES);
}

private void update(){
this.notifications.putAll(retrieveNotifications(LocalDateTime.now().plus(60, ChronoUnit.MINUTES)));
}

private void scheduleNext(){
schedule(getAndRemoveNext(LocalDateTime.now().plus(5, ChronoUnit.MINUTES)));
}

private Map<Long, Notification> retrieveNotifications(LocalDateTime to){
try(var ctx = this.modules.get(DatabaseModule.class).getCtx().selectFrom(NOTIFICATIONS)){
return ctx.where(NOTIFICATIONS.NOTIFICATION_TIME.lessOrEqual(to)).fetch().stream().collect(
Expand All @@ -40,15 +43,6 @@ private Map<Long, Notification> retrieveNotifications(LocalDateTime to){
}
}

@Override
public void onReady(@NotNull ReadyEvent event){
this.modules.scheduleAtFixedRate(this::scheduleNext, 0, 5, TimeUnit.MINUTES);
}

private void scheduleNext(){
schedule(getAndRemoveNext(LocalDateTime.now().plus(5, ChronoUnit.MINUTES)));
}

private void schedule(Set<Notification> notifs){
var now = LocalDateTime.now();
for(var notification : notifs){
Expand Down
13 changes: 0 additions & 13 deletions src/main/java/de/kittybot/kittybot/modules/RequestModule.java
Original file line number Diff line number Diff line change
Expand Up @@ -142,19 +142,6 @@ public void postToHastebin(String content, Consumer<String> callback){
}, (call, response) -> callback.accept(null));
}

public void updateStats(API api, int guildCount, String token){
var requestBody = RequestBody.create(
DataObject.empty()
.put(api.getStatsParameter(), guildCount)
.toString(),
MediaType.parse("application/json; charset=utf-8")
);
this.requestBuilder.url(String.format(api.getUrl(), Config.BOT_ID));
this.requestBuilder.header("Authorization", token);
this.requestBuilder.post(requestBody);
executeAsync(requestBuilder.build(), api);
}

public void executeAsync(Request request, API api){
executeAsync(request, api, null, null);
}
Expand Down
74 changes: 74 additions & 0 deletions src/main/java/de/kittybot/kittybot/modules/VoteModule.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package de.kittybot.kittybot.modules;

import de.kittybot.kittybot.objects.enums.BotList;
import de.kittybot.kittybot.objects.module.Module;
import de.kittybot.kittybot.utils.Config;
import de.kittybot.kittybot.utils.MessageUtils;
import net.dv8tion.jda.api.events.guild.GuildReadyEvent;
import org.jetbrains.annotations.NotNull;
import org.jooq.types.YearToSecond;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

import static de.kittybot.kittybot.jooq.Tables.VOTERS;

public class VoteModule extends Module{

private static final Logger LOG = LoggerFactory.getLogger(VoteModule.class);

@Override
public void onGuildReady(@NotNull GuildReadyEvent event){
if(event.getGuild().getIdLong() == Config.SUPPORT_GUILD_ID){
this.modules.scheduleAtFixedRate(this::checkVoters, 0, 30, TimeUnit.MINUTES);
}
}

private void checkVoters(){
var guild = this.modules.getGuildById(Config.SUPPORT_GUILD_ID);
if(guild == null){
return;
}
var role = guild.getRoleById(Config.VOTER_ROLE_ID);
if(role == null){
return;
}
var result = this.modules.get(DatabaseModule.class).getCtx().deleteFrom(VOTERS).where(VOTERS.VOTE_EXPIRY.lessOrEqual(LocalDateTime.now())).returning().fetch();
for(var r : result){
guild.removeRoleFromMember(r.getUserId(), role).reason("vote expired").queue();
}
}

public void addVote(long userId, BotList botList, int voteMultiplier){
var voteDuration = Duration.of(botList.getVoteCooldown(), botList.getTimeUnit()).multipliedBy(voteMultiplier);

this.modules.get(DatabaseModule.class).getCtx().insertInto(VOTERS)
.columns(VOTERS.USER_ID, VOTERS.VOTE_EXPIRY)
.values(userId, LocalDateTime.now().plus(voteDuration))
.onConflict(VOTERS.USER_ID)
.doUpdate()
.set(VOTERS.VOTE_EXPIRY, VOTERS.VOTE_EXPIRY.add(YearToSecond.valueOf(voteDuration)))
.execute();

var jda = this.modules.getJDA();
jda.retrieveUserById(userId).queue(user -> this.modules.get(EventLogModule.class).send(jda, "Vote", "´" + user.getAsTag() + "`(`" + user.getId() + "`) voted on " + MessageUtils.maskLink("`" + botList.getName() + "`", botList.getUrl())));

var guild = this.modules.getGuildById(Config.SUPPORT_GUILD_ID);
if(guild == null){
return;
}
var role = guild.getRoleById(Config.VOTER_ROLE_ID);
if(role == null){
return;
}
if(!guild.getSelfMember().canInteract(role)){
LOG.error("I can't interact with the provided voter role: {}", role.getId());
return;
}
guild.addRoleToMember(userId, role).reason("voted on " + botList.getName()).queue();
}

}
4 changes: 4 additions & 0 deletions src/main/java/de/kittybot/kittybot/modules/WebModule.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import de.kittybot.kittybot.web.login.PostLoginRoute;
import de.kittybot.kittybot.web.shards.GetShardsRoute;
import de.kittybot.kittybot.web.user.GetUserInfoRoute;
import de.kittybot.kittybot.web.webhooks.votes.PostVotesRoute;
import io.javalin.Javalin;
import io.javalin.http.*;
import io.jsonwebtoken.ExpiredJwtException;
Expand Down Expand Up @@ -94,6 +95,9 @@ public void onEnable(){
before("/*", this::checkDiscordLogin);
get(new GetUserInfoRoute(this.modules));
});
path("/webhooks/votes/:botlist", () ->
post(new PostVotesRoute(this.modules))
);
path("/guilds", () -> {
before("/*", this::checkDiscordLogin);
get(new GetAllGuildsRoute(this.modules));
Expand Down
21 changes: 0 additions & 21 deletions src/main/java/de/kittybot/kittybot/objects/enums/API.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,35 +4,17 @@

public enum API{

// stats APIs
DISCORD_BOTS("discord.bots.gg", "https://discord.bots.gg/api/v1/bots/%s/stats", "guildCount"),
TOP_GG("top.gg", "https://top.gg/api/bots/%s/stats", "server_count"),
DISCORD_EXTREME_LIST("discordextremelist.xyz", "https://api.discordextremelist.xyz/v2/bot/%s/stats", "guildCount"),
DISCORD_BOATS("discord.boats", "https://discord.boats/api/bot/%s", "server_count"),
BOTS_FOR_DISCORD("botsfordiscord.com", "https://botsfordiscord.com/api/bot/%s", "server_count"),
BOTLIST_SPACE("botlist.space", "https://botsfordiscord.com/api/bot/%s", "server_count"),
DISCORDBOTLIST_COM("discordbotlist.com", "https://discordbotlist.com/api/v1/bots/%s/stats", "guilds"),
DISCORD_SERVICES("discordservices.net", "https://api.discordservices.net/bot/%s/stats", "servers"),

// other
PURR_BOT("purr bot", "https://purrbot.site/api/img/%s/%s/%s"),
HASTEBIN("hastebin", Config.HASTEBIN_URL),
GOOGLE_TRANSLATE_API("google translate api", "https://translate.google.com/translate_a/single?client=gtx&sl=%s&tl=%s&dt=t&q=%s&ie=UTF-8&oe=UTF-8");

private final String name;
private final String url;
private final String statsParameter;

API(final String name, final String url, final String statsParameter){
this.name = name;
this.url = url;
this.statsParameter = statsParameter;
}

API(final String name, final String url){
this.name = name;
this.url = url;
this.statsParameter = null;
}

public String getName(){
Expand All @@ -43,7 +25,4 @@ public String getUrl(){
return this.url;
}

public String getStatsParameter(){
return this.statsParameter;
}
}
Loading

0 comments on commit 5c8d2c9

Please sign in to comment.