public void start() throws RateLimitedException, InterruptedException, LoginException { this.discordAPI = new JDABuilder(AccountType.BOT) .setToken(settings.getToken()) .setGame(new GameImpl(settings.getGame(), settings.getGameUrl(), settings.isTwitch() ? Game.GameType.TWITCH : Game.GameType.DEFAULT)) .addListener(new EventCaller(this)) .setAutoReconnect(true) .setAudioEnabled(true) .setBulkDeleteSplittingEnabled(false) .buildBlocking(); if (settings.getRedis().isEnabled()) { redisConnection.start(); keepDataThread.start(); } initCommands(); initListeners(); }
void updateStatus() { Runnable changeStatus = () -> { AtomicInteger users = new AtomicInteger(0), guilds = new AtomicInteger(0); if (MantaroRPG.getInstance() != null) { Arrays.stream(MantaroRPG.getInstance().getShards()).map(MantaroShard::getJDA).forEach(jda -> { users.addAndGet(jda.getUsers().size()); guilds.addAndGet(jda.getGuilds().size()); }); } String newStatus = random(SPLASHES.get(), RANDOM) .replace("%ramgb%", String.valueOf(((long) (Runtime.getRuntime().maxMemory() * 1.2D)) >> 30L)) .replace("%usercount%", users.toString()) .replace("%guildcount%", guilds.toString()) .replace("%shardcount%", String.valueOf(getTotalShards())) .replace("%prettyusercount%", pretty(users.get())) .replace("%prettyguildcount%", pretty(guilds.get())); getJDA().getPresence().setGame(Game.of(config().get().prefix + "help | " + newStatus + " | [" + getId() + "]")); log.debug("Changed status to: " + newStatus); }; changeStatus.run(); Async.task("Splash Thread", changeStatus, 600); }
@Override protected Message execute(CommandManager.ParsedCommandInvocation parsedCommandInvocation, UserPermissions userPermissions) { Configuration configuration = RubiconBot.getConfiguration(); if(!configuration.has(configKey)) { configuration.set(configKey, "0"); } if(parsedCommandInvocation.args.length == 0) { configuration.set(configKey, "0"); return null; } String message = ""; for (String s : parsedCommandInvocation.args) message += s + " "; RubiconBot.getConfiguration().set(configKey, message); parsedCommandInvocation.getMessage().getJDA().getPresence().setGame(Game.playing(message)); return new MessageBuilder().setEmbed(EmbedUtil.success("Status set!", "Successfully set the playing status!").build()).build(); }
public static void main(String[] args) throws IOException { //Code by ZekroTJA(github.com/ZekroTJA) StartArgumentHandler.args = args; //MY CODE builder = new JDABuilder(AccountType.BOT) .setToken(SECRETS.TOKEN) .setAudioEnabled(true) .setAutoReconnect(true) .setStatus(STATICS.STATUS) .setGame(Game.of(STATICS.CUSTOM_MESSAGE + " | _help | coded by Lee", "http://twitch.tv/lordleeyt")) ; initializeListeners(); initializeCommands(); SQL.connect(); LVL.connect(); try { builder.buildBlocking(); } catch (InterruptedException | RateLimitedException | LoginException e) { e.printStackTrace(); } }
@SuppressWarnings("UnusedReturnValue") private static String fetch() { try { info = Unirest.get("https://gensokyoradio.net/xml").asString().getBody(); JSONObject data = XML.toJSONObject(GensokyoInfoAgent.getInfo()).getJSONObject("GENSOKYORADIODATA"); String newSong = data.getJSONObject("SONGINFO").getString("TITLE"); if (!newSong.equals(lastSong)) { List<FredBoat> shards = FredBoat.getShards(); for(FredBoat shard : shards) { shard.getJda().getPresence().setGame(Game.of(newSong)); } log.info("Now playing " + newSong); } lastSong = data.getJSONObject("SONGINFO").getString("TITLE"); return info; } catch (UnirestException e) { throw new RuntimeException(e); } }
public static void main(final String[] args) throws Exception { Thread.currentThread().setName("JukeBot-Main"); ConfigurationFactory.setConfigurationFactory(new Log4JConfig()); LOG = LogManager.getLogger("JukeBot"); playerManager = new DefaultAudioPlayerManager(); defaultPrefix = Database.getPropertyFromConfig("prefix"); String colour = Database.getPropertyFromConfig("color"); if (colour.equalsIgnoreCase("")) { LOG.error("Missing property 'color' in the database."); return; } embedColour = Color.decode(colour); playerManager.setPlayerCleanupThreshold(30000); playerManager.getConfiguration().setResamplingQuality(AudioConfiguration.ResamplingQuality.LOW); playerManager.getConfiguration().setOpusEncodingQuality(9); YoutubeAudioSourceManager yt = new YoutubeAudioSourceManager(); yt.setPlaylistPageCount(Integer.MAX_VALUE); playerManager.registerSourceManager(yt); AudioSourceManagers.registerRemoteSources(playerManager); printBanner(); shardManager = new DefaultShardManagerBuilder() .setToken(Database.getPropertyFromConfig("token")) .setShardsTotal(-1) .addEventListeners(new EventListener(), waiter) .setAudioSendFactory(new NativeAudioSendFactory()) .setGame(Game.of(Game.GameType.LISTENING, defaultPrefix + "help | jukebot.xyz")) .build(); }
@Override public boolean onCommand(Message message, String[] args) { if (args.length == 0) { return false; } Game game = parseGame(args); message.getJDA().getPresence().setGame(game); MessageFactory.makeSuccess(message, "Changed status to **:type :status**") .set("type", getTypeAsString(game.getType())) .set("status", game.getName()) .queue(); return true; }
private Game getGameFromType(String status, AvaireShard shard) { Game game = Game.playing(status); if (status.contains(":")) { String[] split = status.split(":"); status = String.join(":", Arrays.copyOfRange(split, 1, split.length)); switch (split[0].toLowerCase()) { case "listen": case "listening": return Game.listening(formatGame(status, shard)); case "watch": case "watching": return Game.watching(formatGame(status, shard)); case "play": case "playing": return Game.playing(formatGame(status, shard)); case "stream": case "streaming": return Game.streaming(formatGame(status, shard), "https://www.twitch.tv/senither"); } } return game; }
public void start() throws LoginException, InterruptedException, RateLimitedException { running = true; // init logger AnsiConsole.systemInstall(); log = Logger.getLogger("Kyoko"); log.setUseParentHandlers(false); ColoredFormatter formatter = new ColoredFormatter(); ConsoleHandler handler = new ConsoleHandler(); handler.setFormatter(formatter); log.addHandler(handler); log.info("Kyoko v" + Constants.VERSION + " is starting..."); i18n.loadMessages(); JDABuilder builder = new JDABuilder(AccountType.BOT); if (settings.getToken() != null) { if (settings.getToken().equalsIgnoreCase("Change me")) { System.out.println("No token specified, please set it in config.json"); System.exit(1); } builder.setToken(settings.getToken()); } boolean gameEnabled = false; if (settings.getGame() != null && !settings.getGame().isEmpty()) { gameEnabled = true; builder.setGame(Game.of("booting...")); } builder.setAutoReconnect(true); builder.setBulkDeleteSplittingEnabled(false); builder.addEventListener(eventHandler); builder.setAudioEnabled(true); builder.setStatus(OnlineStatus.IDLE); jda = builder.buildBlocking(); log.info("Invite link: " + "https://discordapp.com/oauth2/authorize?&client_id=" + jda.getSelfUser().getId() + "&scope=bot&permissions=" + Constants.PERMISSIONS); if (gameEnabled) { Thread t = new Thread(new Kyoko.BlinkThread()); t.start(); } registerCommands(); }
public PlaystatusHandler() { String json; try { json = IOUtils.toString(getClass().getResourceAsStream("/Playstatuses.json"), "UTF-8"); } catch (IOException e) { LOG.log(Level.SEVERE, "Cannot load play statuses. Disabling playstatus handler."); return; } this.random = new Random(); Gson gson = new Gson(); this.statuses = gson.fromJson(json, PlaystatusFile.class).getData(); Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { Grimoire.getInstance().getDiscord().getPresence().setGame(Game.of(getRandomStatus())); } }, 0, CHANGE_INTERVAL); }
@Override protected void execute(CommandEvent event) { String[] parts = event.getArgs().split("\\s+", 2); if(parts.length<2) { event.replyError("Please include a twitch username and the name of the game to 'stream'"); return; } try { event.getJDA().getPresence().setGame(Game.streaming(parts[1], "https://twitch.tv/"+parts[0])); event.replySuccess("**"+event.getSelfUser().getName() +"** is now streaming `"+parts[1]+"`"); } catch(Exception e) { event.reply(event.getClient().getError()+" The game could not be set!"); } }
@Override protected void execute(CommandEvent event) { if(event.getArgs().isEmpty()) { event.replyError("Please include a title to listen to!"); return; } String title = event.getArgs().toLowerCase().startsWith("to") ? event.getArgs().substring(2).trim() : event.getArgs(); try { event.getJDA().getPresence().setGame(Game.listening(title)); event.replySuccess("**"+event.getSelfUser().getName()+"** is now listening to `"+title+"`"); } catch(Exception e) { event.reply(event.getClient().getError()+" The game could not be set!"); } }
@Override protected void execute(CommandEvent event) { if(event.getArgs().isEmpty()) { event.replyError("Please include a title to watch!"); return; } String title = event.getArgs(); try { event.getJDA().getPresence().setGame(Game.watching(title)); event.replySuccess("**"+event.getSelfUser().getName()+"** is now watching `"+title+"`"); } catch(Exception e) { event.reply(event.getClient().getError()+" The game could not be set!"); } }
@Override public void dispatch(String[] args, MessageChannel channel, Message msg) { if (args.length > 1 && args[0].toLowerCase().matches("(game)|(stream=.+)")) { if (args[0].equalsIgnoreCase("game")) { UserBot.getInstance().getJda().getPresence() .setGame(Game.of(Arrays.stream(args).skip(1).collect(Collectors.joining(" ")))); msg.deleteMessage().queue(); } else { Matcher m = GET_STREAM_URL_PATTERN.matcher(args[0]); if (m.matches()) { if (Game.isValidStreamingUrl(m.group(1))) { UserBot.getInstance().getJda().getPresence() .setGame(Game.of(Arrays.stream(args).skip(1).collect(Collectors.joining(" ")), m.group(1))); msg.deleteMessage().queue(); } else { UserBot.getInstance().getJda().getPresence() .setGame(Game.of(Arrays.stream(args).skip(1).collect(Collectors.joining(" ")))); msg.deleteMessage().queue(); } } } } }
@Override public void onReady(ReadyEvent event) { if(!event.getJDA().getSelfUser().isBot()) { LOG.error("JDA-Utilities does not support CLIENT accounts."); event.getJDA().shutdown(); return; } textPrefix = prefix.equals(DEFAULT_PREFIX) ? "@"+event.getJDA().getSelfUser().getName()+" " : prefix; event.getJDA().getPresence().setStatus(status==null ? OnlineStatus.ONLINE : status); if(game!=null) event.getJDA().getPresence().setGame("default".equals(game.getName()) ? Game.playing("Type "+textPrefix+helpWord) : game); sendStats(event.getJDA()); }
/** * Starts JDA. * * @return {@code true} if everything went well, {@code false} otherwise. */ private boolean initJda() { try { SimpleLog.Level level = JDAImpl.LOG.getLevel(); SimpleLog.Level socketLevel = WebSocketClient.LOG.getLevel(); JDAImpl.LOG.setLevel(SimpleLog.Level.OFF); WebSocketClient.LOG.setLevel(SimpleLog.Level.OFF); jda = new JDABuilder(AccountType.BOT).setToken(botToken).buildBlocking(); jda.getPresence().setGame(Game.of("2.0.2")); logger.writeFrom("jda", "Successfully connected!"); logger.writeFrom("jda WebSocket", "Connected to WebSocket!"); JDAImpl.LOG.setLevel(level); WebSocketClient.LOG.setLevel(socketLevel); } catch (LoginException | InterruptedException | RateLimitedException e) { logger.writeFrom("jda", "Couldn't connect!"); e.printStackTrace(); return false; } return true; }
@Override public void setPresence(OnlineStatus status, Game game, boolean idle) { JSONObject gameObj = getGameJson(game); Checks.check(status != OnlineStatus.UNKNOWN, "Cannot set the presence status to an unknown OnlineStatus!"); if (status == OnlineStatus.OFFLINE || status == null) status = OnlineStatus.INVISIBLE; JSONObject object = new JSONObject(); if (gameObj == null) object.put("game", JSONObject.NULL); else object.put("game", gameObj); object.put("afk", idle); object.put("status", status.getKey()); object.put("since", System.currentTimeMillis()); update(object); this.idle = idle; this.status = status; this.game = gameObj == null ? null : game; }
public static final void main(String[] args) { try { Standard.setStarted(Instant.now()); System.setOut(new SystemOutputStream(System.out, false)); System.setErr(new SystemOutputStream(System.err, true)); Runtime.getRuntime().addShutdownHook(new Thread(() -> { //Standard.STANDARD_SETTINGS.saveSettings(); //FIXME WTF This is deleting the settings file all the time?! Standard.saveAllGuildSettings(); })); Standard.JDA_SUPPLIER = () -> jda; NetworkUtil.init(); reload(); MySQL.init(); builder = new JDABuilder(AccountType.BOT); builder.setAutoReconnect(true); //builder.setAudioSendFactory(null); builder.setStatus(OnlineStatus.ONLINE); builder.setGame(game = Game.of("Supreme-Bot")); initListeners(); initCommands(); init(); initPlugins(); loadAllGuilds(); startJDA(); } catch (Exception ex) { System.err.println("Main Error: " + ex); ex.printStackTrace(); } }
public void restartJDA(boolean force) throws RateLimitedException, LoginException, InterruptedException { if (jda != null) { log.info("Attempting to drop shard #" + shardId); if (!force) prepareShutdown(); jda.shutdown(false); log.info("Dropped shard #" + shardId); } JDABuilder jdaBuilder = new JDABuilder(AccountType.BOT) .setToken(config().get().token) .setEventManager(manager) .setAutoReconnect(true) .setCorePoolSize(15) .setGame(Game.of("Hold on to your seatbelts!")); if (totalShards > 1) jdaBuilder.useSharding(shardId, totalShards); jda = jdaBuilder.buildBlocking(); readdListeners(); }
@Override public void update() throws Exception { if (!lastMessage.equals(MainDialog.scheduleStatusShort)) { lastMessage = MainDialog.scheduleStatusShort; jda.getPresence().setGame(Game.of(MainDialog.scheduleStatusShort)); } }
@Override protected void execute(CommandEvent event) { try { event.getJDA().getPresence().setGame(Game.playing("Type "+event.getClient().getPrefix()+"help | Version " + Const.VERSION + " | On " + event.getJDA().getGuilds().size() + " Guilds | " + event.getJDA().getUsers().size() + " Users | " + event.getJDA().getTextChannels().size() + " Channels")); event.replySuccess("Game updated."); } catch(Exception e) { event.replyError("Error when updating the game! Check the Bot console for more information."); e.printStackTrace(); } }
private static void startJda() throws LoginException, RateLimitedException, InterruptedException { jda = new JDABuilder(AccountType.BOT) .setToken(config.getToken()) .setGame(Game.playing(config.getGame())) .setStatus(config.getStatus()) .setBulkDeleteSplittingEnabled(false) .setAutoReconnect(true) .setEnableShutdownHook(true) .addEventListener(waiter, createClient(), new Endless(), new Logging(config), new ServerLogging(gsdm), new GuildEvents(config, tdm, gsdm), new UserEvents(config)) .buildBlocking(); }
@Override public void run() { // The code here is ran onReady // Setup a MySQL connection using user root with no password on localhost and use the database exampleBot. setupMySQL("root", "", "localhost", "exampleBot"); // Register a new command registerCommand(new PingCommand()); getClient().getPresence().setGame(Game.of("Thrones")); // Log that the bot has fully started. LOGGER.info("Started the example bot successfully! JBA is running v" + getJBAVersion()); }
/** * Initializes the JDA instance. */ public static void initJDA() { if (instance == null) throw new NullPointerException("RubiconBot has not been initialized yet."); JDABuilder builder = new JDABuilder(AccountType.BOT); builder.setToken(instance.configuration.getString("token")); builder.setGame(Game.playing("Starting....")); // add all EventListeners for (EventListener listener : instance.eventListeners) builder.addEventListener(listener); new ListenerManager(builder); try { instance.jda = builder.buildBlocking(); } catch (LoginException | InterruptedException e) { Logger.error(e.getMessage()); } CommandVote.loadPolls(instance.jda); Info.lastRestart = new Date(); // CommandGiveaway.startGiveawayManager(instance.jda); getJDA().getPresence().setGame(Game.playing("Started.")); GameAnimator.start(); }
public static synchronized void start() { if (!RubiconBot.getConfiguration().has("playingStatus")) { RubiconBot.getConfiguration().set("playingStatus", "0"); } if (!running) { t = new Thread(() -> { long last = 0; while (running) { if (System.currentTimeMillis() >= last + 60000) { if (RubiconBot.getConfiguration().has("playingStatus")) { String playStat = RubiconBot.getConfiguration().getString("playingStatus"); if (!playStat.equals("0") && !playStat.equals("")) { RubiconBot.getJDA().getPresence().setGame(Game.playing(playStat)); last = System.currentTimeMillis(); } else { RubiconBot.getJDA().getPresence().setGame(Game.playing("rc!help | " + gameAnimations[currentGame])); if (currentGame == gameAnimations.length - 1) currentGame = 0; else currentGame += 1; last = System.currentTimeMillis(); } } } } }); t.setName("GameAnimator"); running = true; t.start(); } }
@Override public void login(String token, ShardInfo shardInfo, SessionReconnectQueue reconnectQueue) throws LoginException, RateLimitedException { setStatus(Status.LOGGING_IN); if(token == null || token.isEmpty()) throw new LoginException("Provided token was null or empty!"); setToken(token); verifyToken(); this.shardInfo = shardInfo; JDAImpl.LOG.info("Login Successful!"); client = new ServerWebSocketClient(this, reconnectQueue, gatewayServer); JSONObject cachedPresence = gatewayServer.cachedPresence; if(cachedPresence != null) { JSONObject game = cachedPresence.optJSONObject("game"); if(game != null) { getPresence().setPresence( OnlineStatus.fromKey(cachedPresence.getString("status")), Game.of(game.getString("name"), game.optString("url")), cachedPresence.getBoolean("afk") ); } else { getPresence().setPresence( OnlineStatus.fromKey(cachedPresence.getString("status")), null, cachedPresence.getBoolean("afk") ); } gatewayServer.cachedPresence = null; } if(shutdownHook != null) { Runtime.getRuntime().addShutdownHook(shutdownHook); } }
public static void update() { for (JDA jda : Bot.shards) { jda.getPresence().setGame(Game.of(game .replaceAll("\\{prefix\\}", prefix) .replaceAll("\\{guilds\\}", String.valueOf(DiscordUtils.getGuilds().size())) .replaceAll("\\{users\\}", String.valueOf(DiscordUtils.getUsers().size())) .replaceAll("\\{channels\\}", String.valueOf(DiscordUtils.getTextChannels().size())) )); if (!"".equals(name)) { jda.getSelfUser().getManager().setName(name).queue(); } } }
public static void main(String[] args) { bot.setListener(botListener); bot.start(); User owner = bot.getJDA().getUserById(bot.getAuth().getOwnerID()); User botUser = bot.getJDA().getSelfUser(); bot.getJDA().getPresence() .setGame(Game.of("@" + botUser.getName() + " help | " + bot.getAuth().getPrefix() + "help" + " | Owner: @" + owner.getName() + "#" + owner.getDiscriminator())); }
@Override public void start() { final Runnable run = () -> { Game game = Game.streaming("on " + ((StatsPlugin)getBot().getPluginManager().getPlugin("statsPlugin").getPlugin()).getGuildCount() + " servers","https://github.com/greatman/legendarybot"); getBot().getJDA().forEach(jda -> jda.getPresence().setGame(game)); }; scheduler.scheduleAtFixedRate(run,0,30, TimeUnit.MINUTES); log.info("BotPlay loaded!"); }
public GuildBot(final File config, final String token, final String webhookURL) throws LoginException, IllegalArgumentException, RateLimitedException, FileNotFoundException, IOException { this.config = JsonValue.readHjson(FileUtils.readFileToString(config, "UTF-8")).asObject(); this.threadPool = new ScheduledThreadPoolExecutor(4, r -> { final Thread t = new Thread(r, "GuildBot-" + GuildBot.threadCounter.getAndIncrement()); t.setUncaughtExceptionHandler((thread, throwable) -> { GuildBot.log.error("An error occurred", throwable); handleThrowable(throwable, "Uncaught error in thread: " + thread.getName()); }); return t; }); this.threadPool.setKeepAliveTime(1, TimeUnit.MINUTES); this.webhook = webhookURL == null ? null : new WebhookClientBuilder(webhookURL) .setExecutorService(threadPool) .setDaemon(true) .setThreadFactory(r -> new Thread(r, "Error-Webhook-Thread")) .build(); final JDABuilder builder = new JDABuilder(AccountType.BOT); builder.setEventManager(new AnnotatedEventManager()); builder.setToken(token); builder.setGame(Game.of("loading...")); builder.setStatus(OnlineStatus.DO_NOT_DISTURB); builder.addEventListener(this); this.jda = builder.buildAsync(); }
public void onEnable(Phonon phononPlugin) { if (phononPlugin.getConfigAdapter(CoreModule.ID, CoreConfigAdapter.class).isPresent()) { CoreConfig config = phononPlugin.getConfigAdapter(CoreModule.ID, CoreConfigAdapter.class).get().getNodeOrDefault(); String token = config.getToken(); if (config.getPrefix().equals("/")) { phononPlugin.getLogger().warn("Using '/' as a command prefix is highly discouraged."); } codes = new HashMap<>(); try { if (config.getToken().isEmpty()) { return; } jda = new JDABuilder(AccountType.BOT) .setToken(token) .setAudioEnabled(false) .setAutoReconnect(true) .setEnableShutdownHook(true) .buildAsync(); if (!config.getGame().isEmpty()) { jda.getPresence().setGame(Game.of(config.getGame())); } jda.addEventListener(new CommandListener(phononPlugin)); } catch (LoginException | RateLimitedException e) { e.printStackTrace(); } } }
@Override public void action(String[] args, MessageReceivedEvent event) { String text = new String(); for(String arg : args) { text += arg + " "; } SelfBot.getJda().getPresence().setGame(Game.of(text)); event.getMessage().editMessage("Current activity set to \"" + text + "\"").queue(); }
public SelfBot() { config = new LoadingProperties(); clientID = config.getClientID(); prefix = config.getPrefix(); pwd = config.getPwd(); try { jda = new JDABuilder(AccountType.CLIENT).setToken(config.getToken()).buildBlocking(); jda.addEventListener(new CommandListener()); jda.getPresence().setGame(Game.of(config.getActivity())); System.out.println("\nSelfbot ready !"); } catch (InterruptedException | LoginException | RateLimitedException e) { System.out.println("No internet connection or invalid or missing token. Please edit config.blue and try again."); } //Commands commands.put("lenny", new LennyCommand()); commands.put("game", new GameCommand()); commands.put("avatars", new AvatarCommand()); commands.put("ascii", new AsciiCommand()); commands.put("info", new InfoCommand()); commands.put("whois", new WhoisCommand()); commands.put("poll", new PollCommand()); commands.put("server", new ServerCommand()); commands.put("idgf", new IdgfCommand()); commands.put("binary", new BinaryCommand()); commands.put("reverse", new ReverseCommand()); }
private static void initBot() throws Exception { System.setProperty("http.agent", token); bot = new JDABuilder(AccountType.BOT).setToken(token).buildAsync(); bot.addEventListener(new EventListener()); bot.addEventListener(new PlayerControl()); bot.addEventListener(new MentionListener()); bot.addEventListener(new StatsListener()); bot.addEventListener(new OnJoinListener()); bot.getPresence().setGame(Game.playing("!help")); }
private String getTypeAsString(Game.GameType type) { switch (type) { case STREAMING: return "Streaming"; case WATCHING: return "Watching"; case LISTENING: return "Listening to"; default: return "Playing"; } }
private Game parseGame(String[] args) { if (Game.isValidStreamingUrl(args[0])) { String url = args[0]; String streamStatus = String.join(" ", args).substring(url.length()); if (args.length == 1) { streamStatus = "Streaming on Twitch.tv"; } return Game.streaming(streamStatus, url); } String status = String.join(" ", args); if (status.contains(":")) { String[] split = status.split(":"); status = String.join(":", Arrays.copyOfRange(split, 1, split.length)); switch (split[0].toLowerCase()) { case "listen": case "listening": return Game.listening(status); case "watch": case "watching": return Game.watching(status); case "play": case "playing": return Game.playing(status); case "stream": case "streaming": return Game.streaming(status, "https://www.twitch.tv/senither"); } } return Game.playing(status); }
public void start(String[] args) throws LoginException, IllegalArgumentException, InterruptedException, RateLimitedException { if (!loadProperties()) { logger.error("Could not load Bot.properties correctly." + " Make sure every field is filled, including MaxSongLength"); System.exit(1); } jdaClients = new ArrayList<>(SHARD_COUNT); if (SHARD_COUNT > 1) { for (int i = 0; i < SHARD_COUNT; i++) { jdaClients.add(new JDABuilder(AccountType.BOT) .setToken(botConfig.getToken()) .setStatus(OnlineStatus.DO_NOT_DISTURB) .setGame(Game.of("launching...")) .addEventListener(new Listeners(), new ModerationListeners(), new VoiceChannelListeners()) .useSharding(i, SHARD_COUNT) .buildBlocking()); } } else { jdaClients.add(new JDABuilder(AccountType.BOT) .setToken(botConfig.getToken()) .setStatus(OnlineStatus.DO_NOT_DISTURB) .setGame(Game.of("launching...")) .addEventListener(new Listeners(), new ModerationListeners(), new VoiceChannelListeners()) .buildBlocking()); } shards = new Shards(); State.changeBotAvatar(new File("resources/avatar/" + Bot.getInstance().getConfig().getAvatar())); State.changeBotPresence(OnlineStatus.ONLINE); State.changeBotStatus("www.momobot.io"); initialize(); isReady = true; }
/** * Handles the event of the bot being ready. * * @param event The event to handle. */ @SubscribeEvent public void onReady(ReadyEvent event) { ZLogger.info("Registering comands..."); ZLevels.handler.registerCommand(new HelpCommand()); ZLevels.handler.registerCommand(new RankCommand()); ZLevels.handler.registerCommand(new TopCommand()); ZLevels.handler.registerCommand(new LeaderboardCommand()); ZLevels.handler.registerCommand(new RewardsCommand()); ZLevels.handler.registerCommand(new InactiveCommand()); ZLevels.handler.registerCommand(new FlushCommand()); ZLevels.handler.registerCommand(new InfoCommand()); ZLevels.handler.registerCommand(new StopCommand()); ZLogger.info("Successfully registered " + ZLevels.handler.getCommands().values().size() + " cmd!"); if (!Config.GAME_STATUS.isEmpty()) { ZLogger.info("Setting game status..."); event.getJDA().getPresence().setGame(Game.of(Config.GAME_STATUS)); } ZLevels.async.submit(() -> { Database.load(); UserData.startFlushTimer(); ZLogger.info("ZLevels " + ZLevels.VERSION + " is ready!"); }); ZLevels.jda.getTextChannelById(Config.LOG_CHANNEL) .sendMessage("ZLevels " + ZLevels.VERSION + " started successfully!").queue(); }
@Override protected void doCommand(CommandEvent event) { try { event.getJDA().getPresence().setGame(event.getArgs().isEmpty() ? null : Game.of(event.getArgs())); String notPlaying = Locale.getCommandsMessage("setgame.notplaying").f(event.getJDA().getSelfUser().getName()); String playing = Locale.getCommandsMessage("setgame.playing").f(event.getJDA().getSelfUser().getName()); respond(event, event.getClient().getSuccess() + (event.getArgs().isEmpty() ? notPlaying : playing + "`" + event.getArgs() + "`")); } catch (Exception e) { event.reply(event.getClient().getError() + " The game could not be set!"); } }
@Override protected void execute(String args, MessageReceivedEvent event) { String result; if(args.isEmpty()) { event.getJDA().getPresence().setGame(null); result = "Game cleared."; } else { try { Game game; if(args.startsWith("twitch")) { String[] parts = args.substring(6).trim().split("\\s+",2); args = parts[1]; game = Game.of(args, "http://twitch.tv/"+parts[0]); } else game = Game.of(args); event.getJDA().getPresence().setGame(game); result = "Game set to "+(game.getUrl()==null ? "Playing": "Streaming")+" `"+args+"`. Note that it will appear to everyone else but will not show in your own client."; } catch(Exception e) { result = "Game could not be set to `"+args+"`"; } } tempReply(result, event); }