use of org.bukkit.configuration.MemorySection in project DiscordSRV by Scarsz.
the class DiscordSRV method init.
public void init() {
// check if the person is trying to use the plugin without updating to ASM 5
try {
File specialSourceFile = new File("libraries/net/md-5/SpecialSource/1.7-SNAPSHOT/SpecialSource-1.7-SNAPSHOT.jar");
if (!specialSourceFile.exists())
specialSourceFile = new File("bin/net/md-5/SpecialSource/1.7-SNAPSHOT/SpecialSource-1.7-SNAPSHOT.jar");
if (specialSourceFile.exists() && DigestUtils.md5Hex(FileUtils.readFileToByteArray(specialSourceFile)).equalsIgnoreCase("096777a1b6098130d6c925f1c04050a3")) {
DiscordSRV.warning(LangUtil.InternalMessage.ASM_WARNING.toString().replace("{specialsourcefolder}", specialSourceFile.getParentFile().getPath()));
}
} catch (IOException e) {
e.printStackTrace();
}
// remove all event listeners from existing jda to prevent having multiple listeners when jda is recreated
if (jda != null)
jda.getRegisteredListeners().forEach(o -> jda.removeEventListener(o));
// make sure configuration file exists, save default ones if they don't
if (!configFile.exists()) {
LangUtil.saveConfig();
reloadConfig();
}
// make sure lang file exists, save default ones if they don't
if (!messagesFile.exists()) {
LangUtil.saveMessages();
LangUtil.reloadMessages();
}
ConfigUtil.migrate();
try {
getConfig();
} catch (IllegalArgumentException e) {
DiscordSRV.error(LangUtil.InternalMessage.INVALID_CONFIG + ": " + e.getMessage());
try {
new Yaml().load(FileUtils.readFileToString(getConfigFile(), Charset.forName("UTF-8")));
} catch (IOException io) {
DiscordSRV.error(io.getMessage());
}
return;
}
// update check
if (!getConfig().getBoolean("UpdateCheckDisabled")) {
updateIsAvailable = UpdateUtil.checkForUpdates();
// don't load other shit if the plugin was disabled by the update checker
if (!isEnabled())
return;
}
// cool kids club thank yous
if (!getConfig().getBoolean("CoolKidsClubThankYousDisabled")) {
String thankYou = HttpUtil.requestHttp("https://github.com/Scarsz/DiscordSRV/raw/randomaccessfiles/coolkidsclub").replace("\n", "");
if (thankYou.length() > 1)
DiscordSRV.info(LangUtil.InternalMessage.DONATOR_THANKS + ": " + thankYou);
}
// random phrases for debug handler
if (!getConfig().getBoolean("RandomPhrasesDisabled"))
Collections.addAll(randomPhrases, HttpUtil.requestHttp("https://raw.githubusercontent.com/Scarsz/DiscordSRV/randomaccessfiles/randomphrases").split("\n"));
// shutdown previously existing jda if plugin gets reloaded
if (jda != null)
try {
jda.shutdown();
jda = null;
} catch (Exception e) {
e.printStackTrace();
}
// set proxy just in case this JVM is fucking stupid
if (ProxySelector.getDefault() == null) {
ProxySelector.setDefault(new ProxySelector() {
private final List<Proxy> DIRECT_CONNECTION = Collections.unmodifiableList(Collections.singletonList(Proxy.NO_PROXY));
public void connectFailed(URI arg0, SocketAddress arg1, IOException arg2) {
}
public List<Proxy> select(URI uri) {
return DIRECT_CONNECTION;
}
});
}
// check log4j capabilities
boolean serverIsLog4jCapable = false;
try {
serverIsLog4jCapable = Class.forName("org.apache.logging.log4j.core.Logger") != null;
} catch (ClassNotFoundException e) {
error("Log4j classes are NOT available, console channel will not be attached");
}
// add log4j filter for JDA messages
if (serverIsLog4jCapable)
((org.apache.logging.log4j.core.Logger) org.apache.logging.log4j.LogManager.getRootLogger()).addFilter(new JdaFilter());
// log in to discord
try {
jda = new JDABuilder(AccountType.BOT).setAudioEnabled(false).setAutoReconnect(true).setBulkDeleteSplittingEnabled(false).setToken(getConfig().getString("BotToken")).addEventListener(new DiscordBanListener()).addEventListener(new DiscordChatListener()).addEventListener(new DiscordConsoleListener()).addEventListener(new DiscordDebugListener()).addEventListener(new DiscordAccountLinkListener()).buildAsync();
} catch (LoginException e) {
DiscordSRV.error(LangUtil.InternalMessage.FAILED_TO_CONNECT_TO_DISCORD + ": " + e.getMessage());
return;
} catch (Exception e) {
DiscordSRV.error("An unknown error occurred building JDA...");
e.printStackTrace();
return;
}
while (jda.getStatus() != JDA.Status.CONNECTED) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// game status
if (!getConfig().getString("DiscordGameStatus").isEmpty()) {
DiscordUtil.setGameStatus(getConfig().getString("DiscordGameStatus"));
}
// print the things the bot can see
for (Guild server : jda.getGuilds()) {
DiscordSRV.info(LangUtil.InternalMessage.FOUND_SERVER + " " + server);
for (TextChannel channel : server.getTextChannels()) DiscordSRV.info("- " + channel);
}
// show warning if bot wasn't in any guilds
if (jda.getGuilds().size() == 0) {
DiscordSRV.error(LangUtil.InternalMessage.BOT_NOT_IN_ANY_SERVERS);
return;
}
// set console channel
String consoleChannelId = getConfig().getString("DiscordConsoleChannelId");
if (consoleChannelId != null)
consoleChannel = DiscordUtil.getTextChannelById(consoleChannelId);
// see if console channel exists; if it does, tell user where it's been assigned & add console appender
if (serverIsLog4jCapable && consoleChannel != null) {
DiscordSRV.info(LangUtil.InternalMessage.CONSOLE_FORWARDING_ASSIGNED_TO_CHANNEL + " " + consoleChannel);
// attach appender to queue console messages
new ConsoleAppender();
// start console message queue worker thread
if (consoleMessageQueueWorker != null) {
if (consoleMessageQueueWorker.getState() == Thread.State.NEW) {
consoleMessageQueueWorker.start();
} else {
consoleMessageQueueWorker.interrupt();
consoleMessageQueueWorker = new ConsoleMessageQueueWorker();
consoleMessageQueueWorker.start();
}
} else {
consoleMessageQueueWorker = new ConsoleMessageQueueWorker();
consoleMessageQueueWorker.start();
}
} else {
DiscordSRV.info(LangUtil.InternalMessage.NOT_FORWARDING_CONSOLE_OUTPUT.toString());
}
// load channels
for (Map.Entry<String, Object> channelEntry : ((MemorySection) getConfig().get("Channels")).getValues(true).entrySet()) channels.put(channelEntry.getKey(), DiscordUtil.getTextChannelById((String) channelEntry.getValue()));
// warn if no channels have been linked
if (getMainTextChannel() == null)
DiscordSRV.warning(LangUtil.InternalMessage.NO_CHANNELS_LINKED);
if (getMainTextChannel() == null && consoleChannel == null)
DiscordSRV.error(LangUtil.InternalMessage.NO_CHANNELS_LINKED_NOR_CONSOLE);
// warn if the console channel is connected to a chat channel
if (getMainTextChannel() != null && consoleChannel != null && getMainTextChannel().getId().equals(consoleChannel.getId()))
DiscordSRV.warning(LangUtil.InternalMessage.CONSOLE_CHANNEL_ASSIGNED_TO_LINKED_CHANNEL);
// send server startup message
DiscordUtil.sendMessage(getMainTextChannel(), LangUtil.Message.SERVER_STARTUP_MESSAGE.toString(), 0, false);
// start channel topic updater
if (serverWatchdog != null) {
if (serverWatchdog.getState() == Thread.State.NEW) {
serverWatchdog.start();
} else {
serverWatchdog.interrupt();
serverWatchdog = new ServerWatchdog();
serverWatchdog.start();
}
} else {
serverWatchdog = new ServerWatchdog();
serverWatchdog.start();
}
// start lag (tps) monitor
Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(this, new Lag(), 100L, 1L);
// cancellation detector
if (getConfig().getInt("DebugLevel") > 0) {
if (cancellationDetector != null) {
cancellationDetector.close();
cancellationDetector = null;
}
cancellationDetector = new CancellationDetector<>(AsyncPlayerChatEvent.class);
cancellationDetector.addListener((plugin, event) -> DiscordSRV.info(LangUtil.InternalMessage.PLUGIN_CANCELLED_CHAT_EVENT.toString().replace("{plugin}", plugin.toString()).replace("{author}", event.getPlayer().getName()).replace("{message}", event.getMessage())));
DiscordSRV.info(LangUtil.InternalMessage.CHAT_CANCELLATION_DETECTOR_ENABLED);
}
// load account links
accountLinkManager = new AccountLinkManager();
// register events
Bukkit.getPluginManager().registerEvents(this, this);
new PlayerAchievementsListener();
try {
if (Class.forName("org.bukkit.advancement.Advancement") != null)
new PlayerAdvancementDoneListener();
} catch (ClassNotFoundException ignored) {
}
new PlayerBanListener();
new PlayerDeathListener();
new PlayerJoinLeaveListener();
// in-game chat events
if (PluginUtil.pluginHookIsEnabled("herochat")) {
DiscordSRV.info(LangUtil.InternalMessage.PLUGIN_HOOK_ENABLING.toString().replace("{plugin}", "HeroChat"));
getServer().getPluginManager().registerEvents(new HerochatHook(), this);
} else if (PluginUtil.pluginHookIsEnabled("legendchat")) {
DiscordSRV.info(LangUtil.InternalMessage.PLUGIN_HOOK_ENABLING.toString().replace("{plugin}", "LegendChat"));
getServer().getPluginManager().registerEvents(new LegendChatHook(), this);
} else if (PluginUtil.pluginHookIsEnabled("lunachat")) {
DiscordSRV.info(LangUtil.InternalMessage.PLUGIN_HOOK_ENABLING.toString().replace("{plugin}", "LunaChat"));
getServer().getPluginManager().registerEvents(new LunaChatHook(), this);
} else if (PluginUtil.checkIfPluginEnabled("towny") && PluginUtil.pluginHookIsEnabled("townychat")) {
DiscordSRV.info(LangUtil.InternalMessage.PLUGIN_HOOK_ENABLING.toString().replace("{plugin}", "TownyChat"));
getServer().getPluginManager().registerEvents(new TownyChatHook(), this);
} else if (PluginUtil.pluginHookIsEnabled("ultimatechat")) {
DiscordSRV.info(LangUtil.InternalMessage.PLUGIN_HOOK_ENABLING.toString().replace("{plugin}", "UltimateChat"));
getServer().getPluginManager().registerEvents(new UltimateChatHook(), this);
} else if (PluginUtil.pluginHookIsEnabled("venturechat")) {
DiscordSRV.info(LangUtil.InternalMessage.PLUGIN_HOOK_ENABLING.toString().replace("{plugin}", "VentureChat"));
getServer().getPluginManager().registerEvents(new VentureChatHook(), this);
} else {
DiscordSRV.info(LangUtil.InternalMessage.PLUGIN_HOOKS_NOT_ENABLED);
getServer().getPluginManager().registerEvents(new PlayerChatListener(), this);
}
// load user-defined colors
colors.clear();
for (Map.Entry<String, Object> colorEntry : ((MemorySection) getConfig().get("DiscordChatChannelColorTranslations")).getValues(true).entrySet()) colors.put(colorEntry.getKey().toUpperCase(), (String) colorEntry.getValue());
// load canned responses
responses.clear();
for (Map.Entry<String, Object> responseEntry : ((MemorySection) getConfig().get("DiscordCannedResponses")).getValues(true).entrySet()) responses.put(responseEntry.getKey(), (String) responseEntry.getValue());
// start server watchdog
if (channelTopicUpdater != null) {
if (channelTopicUpdater.getState() == Thread.State.NEW) {
channelTopicUpdater.start();
} else {
channelTopicUpdater.interrupt();
channelTopicUpdater = new ChannelTopicUpdater();
channelTopicUpdater.start();
}
} else {
channelTopicUpdater = new ChannelTopicUpdater();
channelTopicUpdater.start();
}
// enable metrics
if (!getConfig().getBoolean("MetricsDisabled")) {
try {
MCStats MCStats = new MCStats(this);
MCStats.start();
} catch (IOException e) {
DiscordSRV.warning("Unable to start metrics: " + e.getMessage());
}
BStats bStats = new BStats(this);
bStats.addCustomChart(new BStats.LambdaSimplePie("linked_channels", () -> String.valueOf(channels.size())));
bStats.addCustomChart(new BStats.LambdaSimplePie("console_channel_enabled", () -> String.valueOf(consoleChannel != null)));
bStats.addCustomChart(new BStats.LambdaSingleLineChart("messages_sent_to_discord", () -> metrics.get("messages_sent_to_discord")));
bStats.addCustomChart(new BStats.LambdaSingleLineChart("messages_sent_to_minecraft", () -> metrics.get("messages_sent_to_minecraft")));
bStats.addCustomChart(new BStats.LambdaSingleLineChart("console_commands_processed", () -> metrics.get("console_commands_processed")));
bStats.addCustomChart(new BStats.LambdaSimpleBarChart("hooked_plugins", () -> new HashMap<String, Integer>() {
{
if (hookedPlugins.size() == 0) {
put("none", 1);
} else {
for (String hookedPlugin : hookedPlugins) {
put(hookedPlugin.toLowerCase(), 1);
}
}
}
}));
bStats.addCustomChart(new BStats.LambdaSingleLineChart("minecraft-discord_account_links", () -> accountLinkManager.getLinkedAccounts().size()));
}
// dummy sync target to initialize class
GroupSynchronizationUtil.reSyncGroups(null);
// set ready status
if (jda.getStatus() == JDA.Status.CONNECTED)
isReady = true;
}
use of org.bukkit.configuration.MemorySection in project AuthMeReloaded by AuthMe.
the class HelpMessagesConsistencyTest method shouldOnlyHaveDescriptionForOneCommand.
/**
* Since CommandInitializer contains all descriptions for commands in English, the help_en.yml file
* only contains an entry for one command as to provide an example.
*/
@Test
public void shouldOnlyHaveDescriptionForOneCommand() {
// given
FileConfiguration configuration = YamlConfiguration.loadConfiguration(DEFAULT_MESSAGES_FILE);
// when
Object commands = configuration.get("commands");
// then
assertThat(commands, instanceOf(MemorySection.class));
assertThat(((MemorySection) commands).getKeys(false), contains("authme"));
}
use of org.bukkit.configuration.MemorySection in project AuthMeReloaded by AuthMe.
the class HelpTranslationVerifier method getLeafKeys.
/**
* Returns the leaf keys of the section at the given path of the file configuration.
*
* @param path the path whose leaf keys should be retrieved
* @return leaf keys of the memory section,
* empty set if the configuration does not have a memory section at the given path
*/
private Set<String> getLeafKeys(String path) {
if (!(configuration.get(path) instanceof MemorySection)) {
return Collections.emptySet();
}
MemorySection memorySection = (MemorySection) configuration.get(path);
// MemorySection#getKeys(true) returns all keys on all levels, e.g. if the configuration has
// 'commands.authme.register' then it also has 'commands.authme' and 'commands'. We can traverse each node and
// build its parents (e.g. for commands.authme.register.description: commands.authme.register, commands.authme,
// and commands, which we can remove from the collection since we know they are not a leaf.
Set<String> leafKeys = memorySection.getKeys(true);
Set<String> allKeys = new HashSet<>(leafKeys);
for (String key : allKeys) {
List<String> pathParts = Arrays.asList(key.split("\\."));
// with the next node since another node has already removed the concerned parents.
for (int i = pathParts.size() - 1; i > 0; --i) {
// e.g. for commands.authme.register -> i = {2, 1} => {commands.authme, commands}
String parentPath = String.join(".", pathParts.subList(0, i));
if (!leafKeys.remove(parentPath)) {
break;
}
}
}
return leafKeys.stream().map(leaf -> path + "." + leaf).collect(Collectors.toSet());
}
use of org.bukkit.configuration.MemorySection in project AuthMeReloaded by AuthMe.
the class HelpTranslationGeneratorIntegrationTest method checkArgs.
private static void checkArgs(Object memorySection, Argument... arguments) {
if (memorySection instanceof MemorySection) {
MemorySection memSection = (MemorySection) memorySection;
int i = 1;
for (Argument arg : arguments) {
assertThat(memSection.getString("arg" + i + ".label"), equalTo(arg.label));
assertThat(memSection.getString("arg" + i + ".description"), equalTo(arg.description));
++i;
}
assertThat(memSection.get("arg" + i), nullValue());
} else {
fail("Expected MemorySection, got '" + memorySection + "'");
}
}
Aggregations