diff --git a/src/main/java/com/jagrosh/giveawaybot/GiveawayBot.java b/src/main/java/com/jagrosh/giveawaybot/GiveawayBot.java index e755de1a..02facc4f 100644 --- a/src/main/java/com/jagrosh/giveawaybot/GiveawayBot.java +++ b/src/main/java/com/jagrosh/giveawaybot/GiveawayBot.java @@ -26,6 +26,7 @@ import com.jagrosh.interactions.requests.Route; import com.typesafe.config.Config; import java.util.concurrent.ExecutionException; +import java.util.stream.Collectors; /** @@ -39,7 +40,6 @@ public class GiveawayBot { private final String cmdPrefix; - private final int serverCountOverride; private final long botId, controlChannel; private final WebhookLog webhook; @@ -50,6 +50,7 @@ public class GiveawayBot private final GiveawayManager manager; private final PremiumChecker premium; private final Uptimer uptimer; + private final ServerCountUpdater countUpdater; protected GiveawayBot(Config config) { @@ -61,7 +62,6 @@ protected GiveawayBot(Config config) cmdPrefix = config.getString("cmd-prefix"); botId = config.hasPath("bot-id") ? config.getLong("bot-id") : config.getLong("app-id"); controlChannel = config.hasPath("control-channel") ? config.getLong("control-channel") : 0L; - serverCountOverride = config.hasPath("server-count") ? config.getInt("server-count") : 0; // connect to the database database = new Database(config.getString("database.host"), config.getString("database.user"), config.getString("database.pass")); @@ -75,6 +75,7 @@ protected GiveawayBot(Config config) premium = new PremiumChecker(database, webhook, config.getString("checker-token")); manager = new GiveawayManager(database, restClient, uploader, emojis, botId); uptimer = new Uptimer(this); + countUpdater = new ServerCountUpdater(this, config.getConfig("bot-lists").entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().unwrapped().toString()))); // instantiate commands Command[] commands = @@ -126,6 +127,7 @@ public void start() throws Exception manager.start(); premium.start(); uptimer.start(); + countUpdater.start(); } public void shutdown() @@ -141,6 +143,7 @@ public void shutdown(String reason) { Thread.sleep(500); uptimer.shutdown(); + countUpdater.shutdown(); interClient.shutdown(); premium.shutdown(); manager.shutdown(); @@ -167,9 +170,9 @@ public long getBotId() return botId; } - public int getServerCountOverride() + public int getServerCount() { - return serverCountOverride; + return countUpdater.getServerCount(); } public long getControlChannel() diff --git a/src/main/java/com/jagrosh/giveawaybot/commands/AboutCmd.java b/src/main/java/com/jagrosh/giveawaybot/commands/AboutCmd.java index 8daa6020..28f4d7a9 100644 --- a/src/main/java/com/jagrosh/giveawaybot/commands/AboutCmd.java +++ b/src/main/java/com/jagrosh/giveawaybot/commands/AboutCmd.java @@ -60,7 +60,7 @@ public InteractionResponse gbExecute(Interaction interaction) .setDescription(LocalizedMessage.INFO_ABOUT_LONG.getLocalizedMessage(wl)) .addField(STATS + LocalizedMessage.INFO_ABOUT_STATS.getLocalizedMessage(wl), LocalizedMessage.INFO_ABOUT_STATS_GIVEAWAYS.getLocalizedMessage(wl, bot.getDatabase().countAllGiveaways()) - + "\n" + LocalizedMessage.INFO_ABOUT_STATS_SERVERS.getLocalizedMessage(wl, bot.getServerCountOverride()), true) + + "\n" + LocalizedMessage.INFO_ABOUT_STATS_SERVERS.getLocalizedMessage(wl, bot.getServerCount()), true) .addField(LINKS + LocalizedMessage.INFO_ABOUT_LINKS.getLocalizedMessage(wl), "[" + LocalizedMessage.INFO_ABOUT_LINKS_WEBSITE.getLocalizedMessage(wl) + "](" + Constants.WEBSITE + ")\n[" + LocalizedMessage.INFO_ABOUT_LINKS_INVITE.getLocalizedMessage(wl) + "](" + Constants.INVITE diff --git a/src/main/java/com/jagrosh/giveawaybot/commands/GBCommand.java b/src/main/java/com/jagrosh/giveawaybot/commands/GBCommand.java index 43dec586..0e068439 100644 --- a/src/main/java/com/jagrosh/giveawaybot/commands/GBCommand.java +++ b/src/main/java/com/jagrosh/giveawaybot/commands/GBCommand.java @@ -29,6 +29,8 @@ import com.jagrosh.interactions.responses.InteractionResponse; import com.jagrosh.interactions.responses.MessageCallback; import java.time.Instant; +import java.util.HashSet; +import java.util.Set; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,6 +42,7 @@ public abstract class GBCommand implements Command { private final Logger log = LoggerFactory.getLogger(GBCommand.class); + private final Set currentlyUpdating = new HashSet<>(); protected final GiveawayBot bot; protected ApplicationCommand app; @@ -67,21 +70,24 @@ public InteractionResponse execute(Interaction interaction) // update cached guild info GuildSettings gs = bot.getDatabase().getSettings(interaction.getGuildId()); Instant now = Instant.now(); - if(gs.getLatestRetrieval().plusSeconds(60*20).isBefore(now)) + long gid = interaction.getGuildId(); + if(gs.getLatestRetrieval().plusSeconds(60*20).isBefore(now) && !currentlyUpdating.contains(gid)) { + currentlyUpdating.add(gid); Guild g; try { - JSONObject gjson = bot.getRestClient().request(Route.GET_GUILD.format(interaction.getGuildId()), "").get().getBody(); + JSONObject gjson = bot.getRestClient().request(Route.GET_GUILD.format(gid), "").get().getBody(); //log.info(String.format("Retrieved guild: " + gjson)); g = new Guild(gjson); } catch(Exception ex) { g = null; - log.error(String.format("Failed to retrieve guild: %s, %s", ex, ex.getMessage())); + log.error(String.format("Failed to retrieve guild: %s", ex)); } bot.getDatabase().setAutomaticGuildSettings(interaction.getGuildId(), now, g); + currentlyUpdating.remove(gid); } // attempt to run command diff --git a/src/main/java/com/jagrosh/giveawaybot/data/Database.java b/src/main/java/com/jagrosh/giveawaybot/data/Database.java index 9fc08415..7e821df5 100644 --- a/src/main/java/com/jagrosh/giveawaybot/data/Database.java +++ b/src/main/java/com/jagrosh/giveawaybot/data/Database.java @@ -79,13 +79,16 @@ public synchronized void setAutomaticGuildSettings(long guildId, Instant now, Gu { gs = new GuildSettings(); gs.setGuildId(guildId); + gs.setLocale(WebLocale.UNKNOWN); em.persist(gs); } gs.setLatestRetrieval(now); if(guild != null) { gs.setOwnerId(guild.getOwnerId()); - if(gs.getLocale() == null || gs.getLocale() == WebLocale.UNKNOWN) + if(guild.getPreferredLocale() != null && guild.getPreferredLocale() != WebLocale.UNKNOWN) + gs.setLocale(guild.getPreferredLocale()); + /*if(gs.getLocale() == null || gs.getLocale() == WebLocale.UNKNOWN) { gs.setLocale(guild.getPreferredLocale()); } diff --git a/src/main/java/com/jagrosh/giveawaybot/entities/ServerCountUpdater.java b/src/main/java/com/jagrosh/giveawaybot/entities/ServerCountUpdater.java new file mode 100644 index 00000000..e479bbfc --- /dev/null +++ b/src/main/java/com/jagrosh/giveawaybot/entities/ServerCountUpdater.java @@ -0,0 +1,93 @@ +/* + * Copyright 2022 John Grosh (john.a.grosh@gmail.com). + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.jagrosh.giveawaybot.entities; + +import com.jagrosh.giveawaybot.GiveawayBot; +import com.jagrosh.interactions.requests.RestClient.RestResponse; +import com.jagrosh.interactions.requests.Route; +import java.util.Map; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * + * @author John Grosh (john.a.grosh@gmail.com) + */ +public class ServerCountUpdater +{ + private final static String API_ENDPOINT = "https://botblock.org/api/count"; + + private final Logger log = LoggerFactory.getLogger(ServerCountUpdater.class); + private final ScheduledExecutorService schedule = Executors.newSingleThreadScheduledExecutor(); + + private final GiveawayBot bot; + private final Map tokens; + + private int serverCount = 0; + + public ServerCountUpdater(GiveawayBot bot, Map tokens) + { + this.bot = bot; + this.tokens = tokens; + } + + public void start() + { + schedule.scheduleAtFixedRate(this::updateServerCount, 0, 60, TimeUnit.MINUTES); + } + + public void shutdown() + { + schedule.shutdown(); + } + + public int getServerCount() + { + return serverCount; + } + + public void updateServerCount() + { + try + { + // get estimated guild count + RestResponse res = bot.getRestClient().request(Route.GET_GATEWAY.format()).get(); + int guilds = res.getBody().getInt("shards") * 1000; + if(guilds <= 0) + throw new IllegalArgumentException("Invalid guild count"); + serverCount = guilds; + + // post guild count + JSONObject json = new JSONObject() + .put("server_count", guilds) + .put("bot_id", Long.toString(bot.getBotId())); + tokens.forEach((key,val) -> json.put(key, val)); + RestResponse res2 = bot.getRestClient().simpleRequest(API_ENDPOINT, Route.Type.POST, json.toString()).get(); + if(res2.isSuccess() && res2.getBody().has("failure")) + res2.getBody().getJSONObject("failure").toMap().forEach((site,val) -> log.warn(String.format("Updating server count for '%s' failed: %s", site, val))); + else + log.warn("Updating server counts failed: " + res2.getBody().toString()); + } + catch(Exception ex) + { + log.error("Exception when updating guild count: ", ex); + } + } +} diff --git a/src/test/java/com/jagrosh/giveawaybot/MiscTest.java b/src/test/java/com/jagrosh/giveawaybot/MiscTest.java index 3c9999e5..2a37aca7 100644 --- a/src/test/java/com/jagrosh/giveawaybot/MiscTest.java +++ b/src/test/java/com/jagrosh/giveawaybot/MiscTest.java @@ -15,6 +15,11 @@ */ package com.jagrosh.giveawaybot; +import com.typesafe.config.Config; +import com.typesafe.config.ConfigFactory; +import java.util.Map; +import java.util.stream.Collectors; +import org.junit.Assert; import org.junit.Test; /** @@ -34,4 +39,15 @@ public void distributionTest() System.out.println(i + ": " + e + " " + f); } } + + @Test + public void mappingTest() + { + Config config = ConfigFactory.parseString("{ map: { a : a_value , b : b_value } }"); + Assert.assertEquals("a_value", config.getConfig("map").getString("a")); + Map map = config.getConfig("map").entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().unwrapped().toString())); + System.out.println(map); + Assert.assertEquals(2, map.entrySet().size()); + Assert.assertEquals("b_value", map.get("b")); + } }