Skip to content

Commit

Permalink
server count automated now, since no more real guild count
Browse files Browse the repository at this point in the history
  • Loading branch information
jagrosh committed Sep 2, 2022
1 parent 7e3b821 commit 09598cd
Show file tree
Hide file tree
Showing 6 changed files with 130 additions and 9 deletions.
11 changes: 7 additions & 4 deletions src/main/java/com/jagrosh/giveawaybot/GiveawayBot.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;


/**
Expand All @@ -39,7 +40,6 @@
public class GiveawayBot
{
private final String cmdPrefix;
private final int serverCountOverride;
private final long botId, controlChannel;

private final WebhookLog webhook;
Expand All @@ -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)
{
Expand All @@ -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"));
Expand All @@ -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 =
Expand Down Expand Up @@ -126,6 +127,7 @@ public void start() throws Exception
manager.start();
premium.start();
uptimer.start();
countUpdater.start();
}

public void shutdown()
Expand All @@ -141,6 +143,7 @@ public void shutdown(String reason)
{
Thread.sleep(500);
uptimer.shutdown();
countUpdater.shutdown();
interClient.shutdown();
premium.shutdown();
manager.shutdown();
Expand All @@ -167,9 +170,9 @@ public long getBotId()
return botId;
}

public int getServerCountOverride()
public int getServerCount()
{
return serverCountOverride;
return countUpdater.getServerCount();
}

public long getControlChannel()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 9 additions & 3 deletions src/main/java/com/jagrosh/giveawaybot/commands/GBCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -40,6 +42,7 @@
public abstract class GBCommand implements Command
{
private final Logger log = LoggerFactory.getLogger(GBCommand.class);
private final Set<Long> currentlyUpdating = new HashSet<>();
protected final GiveawayBot bot;
protected ApplicationCommand app;

Expand Down Expand Up @@ -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
Expand Down
5 changes: 4 additions & 1 deletion src/main/java/com/jagrosh/giveawaybot/data/Database.java
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
* Copyright 2022 John Grosh ([email protected]).
*
* 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 ([email protected])
*/
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<String,String> tokens;

private int serverCount = 0;

public ServerCountUpdater(GiveawayBot bot, Map<String,String> 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);
}
}
}
16 changes: 16 additions & 0 deletions src/test/java/com/jagrosh/giveawaybot/MiscTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/**
Expand All @@ -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<String,String> 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"));
}
}

0 comments on commit 09598cd

Please sign in to comment.