Advertisement
wolfy1506

Untitled

Nov 9th, 2018
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.51 KB | None | 0 0
  1. public void start(final File dataFolder) throws IOException, LoginException, InterruptedException {
  2. Objects.checkArgument(!this.running, "bot is already running");
  3. Objects.checkNotNull(dataFolder, "cannot start without a valid directory");
  4. Objects.checkArgument(dataFolder.exists(), String.format("data directory doesn't exist '%s'", dataFolder.getAbsolutePath()));
  5. Objects.checkArgument(dataFolder.isDirectory(), "provided data directory isn't a valid directory");
  6.  
  7. Bot.instance = this;
  8.  
  9. this.running = true;
  10. this.startTime = System.currentTimeMillis();
  11.  
  12. //check if the bot is already running (prevent accidentally starting 2 instances)
  13.  
  14. this.lockFile = new File(dataFolder, "bot.lock");
  15. try {
  16. if (this.lockFile.exists()) {
  17. this.lockFile.delete();
  18. }
  19.  
  20. this.lockFile.createNewFile();
  21.  
  22. this.channel = new RandomAccessFile(this.lockFile, "rw").getChannel();
  23. this.fileLock = this.channel.tryLock();
  24. } catch (final IOException ignored) {
  25. }
  26.  
  27. //If it's null, then a file lock couldn't be acquired so something else already has a read write access lock
  28. if (this.fileLock == null) {
  29. throw new IllegalStateException("Another instance is already running");
  30. }
  31.  
  32. //check for our config file
  33.  
  34. final File file = new File(dataFolder, "bot.toml");
  35. if (!file.exists()) {
  36. LOGGER.info("Configuration file couldn't be found, creating it...");
  37. FileUtils.copyURLToFile(this.getClass().getResource("/bot.toml"), file); //config wasn't found so copy internal one (resources/bot.json)
  38. LOGGER.info(String.format("Configuration file was created at %s, exiting...", file.getCanonicalPath()));
  39. return;
  40. }
  41.  
  42. LOGGER.info("Loading configuration...");
  43.  
  44. this.config = new Toml().read(file);
  45.  
  46. LOGGER.info("Loading databases...");
  47.  
  48. final String user = this.config.getString("mongo.user");
  49. final String pass = this.config.getString("mongo.psswd");
  50. final String host = this.config.getString("mongo.host");
  51. final int port = Math.toIntExact(this.config.getLong("mongo.port"));
  52.  
  53. if ((user == null || user.isEmpty()) || (pass == null || pass.isEmpty())) {
  54. LOGGER.info("MongoDB information is not configured, attempting to connect with no authentication.");
  55. this.mongoClient = new MongoClient(host, port);
  56. } else {
  57. this.mongoClient = new MongoClient(new MongoClientURI(String.format("mongodb://%s:%s@%s:%s", user, pass, host, port)));
  58. }
  59.  
  60. this.mongoDatabase = this.mongoClient.getDatabase(this.config.getString("mongo.database"));
  61.  
  62. LOGGER.info("A database connection was successfully established!");
  63.  
  64. LOGGER.info("Loading data managers...");
  65.  
  66. //just class initialization
  67. this.economy = new EconomyImpl();
  68. this.commandRegistry = new CommandRegistryImpl();
  69. this.eventRegistry = new EventRegistryImpl();
  70. this.moduleLoader = new ModuleLoaderImpl(this);
  71.  
  72. this.client = new WebhookClientBuilder(this.config.getString("client.webhook"))
  73. .setHttpClient(Bot.HTTP_CLIENT)
  74. .setDaemon(true)
  75. .build();
  76.  
  77. LOGGER.info("Retrieving recommended shard count from discord endpoint...");
  78.  
  79. final String token = this.config.getString("client.token");
  80.  
  81. final String auth = "Bot " + token;
  82. final Request request = new Request.Builder().url("https://discordapp.com/api/gateway/bot")
  83. .header("Content-Type", "application/json;charset=utf8mb4")
  84. .header("Authorization", auth)
  85. .build();
  86.  
  87. //Querying discord for how many shards we should be running
  88.  
  89. final int shardTotal;
  90. try (final Response response = HTTP_CLIENT.newCall(request).execute()) {
  91.  
  92. if (response.code() != 200) {
  93. throw new RuntimeException("Couldn't retrieve recommended shard count.");
  94. }
  95.  
  96. @SuppressWarnings("ConstantConditions")
  97. final String json = response.body().string();
  98. final JsonObject object = JSON_PARSER.parse(json).getAsJsonObject();
  99.  
  100. shardTotal = object.get("shards").getAsInt(); //get the recommended shard count
  101.  
  102. } catch (final IOException ex) { //an error occurred?
  103. throw new RuntimeException("Couldn't retrieve shard count", ex);
  104. }
  105.  
  106. final DefaultShardManagerBuilder builder = new DefaultShardManagerBuilder()
  107. .setToken(token)
  108. .setShardsTotal(shardTotal)
  109. .setShards(0, shardTotal - 1)
  110. .setAutoReconnect(true)
  111. .setEnableShutdownHook(false)
  112. .setGame(Game.of(Game.GameType.DEFAULT, this.config.getString("client.game", "Sheepy 2.0!")))
  113. .setAudioEnabled(true)
  114. .setBulkDeleteSplittingEnabled(false)
  115. .setUseShutdownNow(true)
  116. .setHttpClient(HTTP_CLIENT);
  117.  
  118. builder.addEventListeners(
  119. new ServerMessageListener(this),
  120. new ServerJoinQuitListener(this),
  121. new ServerMemberListener(this),
  122. new ServerMemberReactionListener(this),
  123. new ServerMemberVoiceListener(this),
  124. new ServerModerationListener(this),
  125. new ServerRoleListener(this)
  126. );
  127.  
  128. final String webhookUrl = this.config.getString("client.webhook");
  129. if (webhookUrl == null) {
  130. LOGGER.info("No webhook url was specified, JDA status logging has been disabled.");
  131. } else {
  132. LOGGER.info("Connecting to webhook...");
  133. this.client = new WebhookClientBuilder(webhookUrl)
  134. // .setExecutorService(SINGLE_EXECUTOR_SERVICE)
  135. .setHttpClient(HTTP_CLIENT)
  136. .build();
  137. builder.addEventListeners(new JdaStatusListener(this));
  138. }
  139.  
  140. LOGGER.info("Starting shards...");
  141.  
  142. this.shardManager = builder.build();
  143.  
  144. //Sleep until all shards are connected (shard manager builder doesn't have a buildBlocking method)
  145. while (this.shardManager.getShards().stream().anyMatch(shard -> shard.getStatus() != JDA.Status.CONNECTED)) {
  146. Thread.sleep(50L);
  147. }
  148.  
  149. LOGGER.info("Registering default commands...");
  150.  
  151. I18n.loanI18n(this.getClass());
  152.  
  153. //null is used in the command registry to represent this
  154. //as being a default command.
  155.  
  156. this.commandRegistry.registerCommand(Command.builder()
  157. .names("evaluate", "eval")
  158. .syntax(ArgumentParsers.REMAINING_STRING_NO_QUOTE)
  159. .executor(new EvaluateCommand())
  160. .build());
  161.  
  162. this.commandRegistry.registerCommand(Command.builder()
  163. .names("buildinfo")
  164. .executor(new BuildInfoCommand())
  165. .build());
  166.  
  167. LOGGER.info("Loading modules...");
  168.  
  169. //If there were no modules to loanI18n it just returns an empty list, so no harm done
  170. final Collection<Module> modules = this.moduleLoader.loadModules();
  171. modules.forEach(this.moduleLoader::enableModule);
  172.  
  173. LOGGER.info("Loaded " + this.moduleLoader.getEnabledModules().size() + " modules");
  174.  
  175. /*
  176. * Check if we're running on an official release
  177. * We don't want statistics of the dev bot being submitted
  178. * to DBL or Carbon.
  179. *
  180. * To determine whether we're running official or development
  181. * the environment variable "bot_env" is queried,
  182. *
  183. * If the environment variable doesn't exist,
  184. * we assume it's development, if it does then
  185. * we get the environment type by the value in the variable
  186. */
  187. if (Environment.getEnvironment().isRelease()) {
  188. LOGGER.info("Currently running an official release, loading bot list agents...");
  189.  
  190. LOGGER.info("Starting Carbonitex agent...");
  191. Scheduler.getInstance().runTaskRepeating(new CarbonitexAgent(this, this.config.getString("client.agent.carbon.key")), 0L, TimeUnit.MINUTES.toMillis(30));
  192.  
  193. LOGGER.info("Starting Discord Bot List agent...");
  194. Scheduler.getInstance().runTaskRepeating(new DiscordBotListAgent(this, this.config.getString("client.agent.dbl.key")), 0L, TimeUnit.MINUTES.toMillis(30));
  195. }
  196.  
  197. LOGGER.info("Starting metrics task...");
  198. Scheduler.getInstance().runTaskRepeating(new MetricsTask(this), TimeUnit.HOURS.toMillis(1), TimeUnit.HOURS.toMillis(1));
  199.  
  200. LOGGER.info("Starting heart beat...");
  201. Scheduler.getInstance().runTaskRepeating(new HeartBeatTask(this), 0L, TimeUnit.SECONDS.toMillis(15));
  202.  
  203. LOGGER.info("Registering shutdown hook...");
  204.  
  205. //register our shutdown hook so if something happens sheepy gets properly shutdown
  206. Runtime.getRuntime().addShutdownHook(new Thread(this::shutdown, "Sheepy-Shutdown-Thread"));
  207.  
  208. LOGGER.info(String.format("Startup completed! Took %dms, api version: %s.", (System.currentTimeMillis() - this.startTime), BotInfo.VERSION));
  209. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement