@Override public void execute(String arg, User author, MessageChannel channel, Guild guild) { if(!AudioPlayerThread.isPlaying()) { channel.sendMessage(author.getAsMention() + " ``Currently I'm not playing.``").queue(); return; } int seconds; if(arg == null) { seconds = 10; } else { try { seconds = Integer.parseInt(arg); if(seconds == 0) { throw new NumberFormatException(); } } catch(NumberFormatException e) { channel.sendMessage(author.getAsMention() + " ``Invalid number``").queue(); return; } } AudioTrack track = AudioPlayerThread.getMusicManager().player.getPlayingTrack(); track.setPosition(track.getPosition() + (1000*seconds)); // Lavaplayer handles values < 0 or > track length }
@Override public boolean run(DiscordBot bot, GuildMessageReceivedEvent event, String args) { if (embed == null) { JDA shard = event.getJDA(); DSLContext database = bot.getDatabase(); Guild guild = event.getGuild(); EmbedBuilder builder = new EmbedBuilder(); builder.setAuthor("Safety Jim - Commands", null, shard.getSelfUser().getAvatarUrl()); builder.setDescription(getUsageTexts(bot, DatabaseUtils.getGuildSettings(database, guild).getPrefix())); builder.setColor(new Color(0x4286F4)); embed = builder.build(); } DiscordUtils.successReact(bot, event.getMessage()); DiscordUtils.sendMessage(event.getChannel(), embed); return false; }
public static void assignRole(UserData data) { User user = ZLevels.jda.getUserById(data.getUserId()); Guild guild = ZLevels.jda.getGuildById(Config.SERVER); int level = data.getLevel(); for (int requiredLevel : roles.keySet()) { if (level < requiredLevel) return; Member member = guild.getMember(user); Role role = guild.getRolesByName(roles.get(requiredLevel).getString("name"), false).get(0); if (member == null || role == null) return; if (member.getRoles().contains(role)) return; try { guild.getController().addRolesToMember(member, role).queue(); } catch (Exception e) { ZLogger.warn("Could not assign role to " + user.getName() + "!"); } } }
public boolean hasSettings(Guild guild) { try { Statement statement = connection.createStatement(); statement.closeOnCompletion(); try(ResultSet results = statement.executeQuery(String.format("SELECT * FROM GUILD_SETTINGS WHERE GUILD_ID = %s", guild.getId()))) { return results.next(); } } catch(SQLException e) { LOG.warn(e.toString()); return false; } }
private GuildMusicManager getMusicManager(Guild guild) { String guildId = guild.getId(); GuildMusicManager mng = musicManagers.get(guildId); if (mng == null) { synchronized (musicManagers) { mng = musicManagers.get(guildId); if (mng == null) { mng = new GuildMusicManager(playerManager); mng.player.setVolume(DEFAULT_VOLUME); musicManagers.put(guildId, mng); } } } return mng; }
@Override public void run() { if (!avaire.areWeReadyYet() || !hasLoadedGuilds()) { return; } Metrics.guilds.set(avaire.getShardEntityCounter().getGuilds()); for (Region region : Region.values()) { Metrics.geoTracker.labels(region.getName()).set(0); } for (AvaireShard shard : avaire.getShards()) { for (Guild guild : shard.getJDA().getGuilds()) { Metrics.geoTracker.labels(guild.getRegion().getName()).inc(); } } }
public String getLeaveMessage(Guild guild) { try { Statement statement = connection.createStatement(); statement.closeOnCompletion(); String message; try (ResultSet results = statement.executeQuery(String.format("SELECT leave_msg FROM GUILD_SETTINGS WHERE GUILD_ID = %s", guild.getId()))) { if(results.next()) message = results.getString("leave_msg"); else message=""; } return message; } catch(SQLException e) { LOG.warn(e.toString()); return null; } }
@Scheduled(cron = "0 0 0 1 1 ?") // NEW YEAR (0 0 0 1 1 ?) | EVERY MIN (0 * * ? * *) public void execute() { if (!discordService.isConnected()) { return; } NewYearNotification notification = repository.findOneByGuildId(null); JDA jda = discordService.getJda(); for (Guild guild : jda.getGuilds()) { if (!discordService.isConnected()) { return; } try { notifyNewYear(notification, guild); } catch (Exception e) { LOGGER.error("Cannot send happy new year to guild {} (ID={})", guild.getName(), guild.getId(), e); } } }
private List<RewardDetails> getRewards(long serverId, RankingConfig config) { if (discordService.isConnected() && CollectionUtils.isNotEmpty(config.getRewards())) { Guild guild = discordService.getJda().getGuildById(serverId); if (guild != null) { List<RewardDetails> details = new ArrayList<>(); for (Reward reward : config.getRewards()) { Role role = guild.getRoleById(reward.getRoleId()); if (role != null) { details.add(new RewardDetails(role, reward)); } } details.sort(Comparator.comparing(RewardDetails::getLevel)); return details; } } return null; }
public static void handleReaction(MessageReactionAddEvent e) { if (awaitingConfirm.containsKey(e.getMessageIdLong())) { if (e.getReactionEmote().getName().equals("✅") && e.getUser() != e.getJDA().getSelfUser()) { EmbedBuilder embedBuilder = new EmbedBuilder(); embedBuilder.setAuthor("Message from developers!", null, e.getJDA().getSelfUser().getEffectiveAvatarUrl()); embedBuilder.setDescription(awaitingConfirm.get(e.getMessageIdLong())); embedBuilder.setColor(Colors.COLOR_ERROR); List<Long> sentOwners = new ArrayList<>(); for (Guild guild : e.getJDA().getGuilds()) { if (!sentOwners.contains(guild.getOwner().getUser().getIdLong())) { guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> privateChannel.sendMessage(embedBuilder.build()).queue()); sentOwners.add(guild.getOwner().getUser().getIdLong()); } } } awaitingConfirm.remove(e.getMessageIdLong()); e.getTextChannel().deleteMessageById(e.getMessageId()).queue(); } }
public static boolean add(Tier tier, String id, Guild guild) { Level level = tierMap.get(tier.getName()); if (level.getTIER().equals(Tier.BOT_DEVELOPER)) { ArrayList<String> IDS = (ArrayList<String>) level.getOBJECT(); IDS.add(id); level.setOBJECT(IDS); return true; } if (level.getTIER().equals(Tier.GUILD_WHITELIST)) { HashMap<Guild, ArrayList<String>> GUILD_MAP = (HashMap<Guild, ArrayList<String>>) level.getOBJECT(); GUILD_MAP.get(guild).add(id); level.setOBJECT(GUILD_MAP); return true; } try { throw new Exception("You entered an invalid tier!"); } catch (Exception e) { e.printStackTrace(); } return false; }
public static void killAudioHandlers(Guild guild) { final AudioReceiveListener audioReceiveListener = (AudioReceiveListener) guild.getAudioManager().getReceiveHandler(); if (audioReceiveListener != null) { audioReceiveListener.canReceive = false; audioReceiveListener.compiledVoiceData = null; guild.getAudioManager().setReceivingHandler(null); } final AudioSendListener audioSendListener = (AudioSendListener) guild.getAudioManager().getSendingHandler(); if (audioSendListener != null) { audioSendListener.canProvide = false; audioSendListener.voiceData = null; guild.getAudioManager().setSendingHandler(null); } System.out.println(String.format("Destroyed AudioHandlers for \"%s\"", guild.getName())); System.gc(); //FIXME Fraglich! }
@Override public void onGuildJoin(GuildJoinEvent event) { Guild guild = event.getGuild(); MessageEmbed embed = createWelcomeMessage(guild); guild.getOwner().getUser().openPrivateChannel().submit().whenComplete((e, t) -> { if (e != null) { e.sendMessage(embed).submit(); return; } TextChannel channel = guild.getDefaultChannel(); if (channel != null && PermissionUtil.checkPermission(channel, guild.getSelfMember(), Permission.MESSAGE_WRITE)) { channel.sendMessage(embed).submit(); } else { for (TextChannel textChannel : guild.getTextChannels()) { if (PermissionUtil.checkPermission(textChannel, guild.getSelfMember(), Permission.MESSAGE_WRITE)) { textChannel.sendMessage(embed).submit(); break; } } } }); }
@Override public void action(String[] args, GuildMessageReceivedEvent event) throws ParseException, IOException { Guild g = event.getGuild(); if (core.permissionHandler.check(2, event)) if (args.length < 2) event.getChannel().sendMessage(help()); String reason = String.join(" ", args).split(args[0])[1]; User kick = event.getMessage().getMentionedUsers().get(0); String channel = SQL.getValue(g, "logchannel"); event.getGuild().getTextChannelById(channel).sendMessage(":mans_shoe: " + kick.getAsMention() + " got kicked by " + event.getAuthor().getAsMention() + " (" + event.getMember().getRoles().get(0).getName() + ").\n\n" + "Reason: " + reason ).queue(); event.getChannel().sendMessage(":white_check_mark: Sucessfully kicked" + kick.getName()).queue(); PrivateChannel pc = event.getMessage().getMentionedUsers().get(0).openPrivateChannel().complete(); pc.sendMessage( "Sorry, you got kicked from Server " + event.getGuild().getName() + " by " + event.getAuthor().getAsMention() + " (" + event.getMember().getRoles().get(0).getName() + ").\n\n" + "Reason: " + reason ).queue(); event.getGuild().getController().kick(event.getGuild().getMember(event.getMessage().getMentionedUsers().get(0)) , reason).queue(); }
@Command( name = "stop", description = "Stops the player", usage = "`>>stop`", permission = CommandPermission.USER, category = CommandCategory.MUSIC ) public static void stop(@Argument("event")GuildMessageReceivedEvent event, @Argument("channel") TextChannel channel, @Argument("guild") Guild guild) { if(checkVC(event)) return; GuildMusicPlayer gmp = GabrielBot.getInstance().getPlayer(guild.getIdLong()); if(gmp == null) { channel.sendMessage("I'm not playing any song").queue(); return; } boolean dj = isDJ(event.getMember(), gmp.scheduler.currentTrack()); if(dj) { gmp.textChannel.sendMessage("The DJ decided to stop").queue(); GabrielBot.getInstance().interruptPlayer(gmp.guildId); } else { channel.sendMessage("You are not a DJ").queue(); } }
@Override public void execute(String arg, User author, MessageChannel channel, Guild guild) { if(!AudioPlayerThread.isPlaying()) { channel.sendMessage(author.getAsMention() + " ``Currently I'm not playing.``").queue(); return; } int skips; if (arg == null) { skips = 1; } else { try { skips = Integer.parseInt(arg); if (skips < 1) { throw new NumberFormatException(); } } catch (NumberFormatException e) { channel.sendMessage(author.getAsMention() + " ``Invalid number``").queue(); return; } } AudioPlayerThread.getMusicManager().scheduler.nextTrack(skips); }
@Command( name = "pause", description = "Pauses the player", usage = "`>>pause`", permission = CommandPermission.USER, category = CommandCategory.MUSIC ) public static void pause(@Argument("channel") TextChannel channel, @Argument("guild") Guild guild) { GuildMusicPlayer gmp = GabrielBot.getInstance().getPlayer(guild.getIdLong()); if(gmp == null) { channel.sendMessage("No music is playing").queue(); return; } gmp.player.setPaused(!gmp.player.isPaused()); channel.sendMessage(gmp.player.isPaused() ? "Music paused" : "Music resumed").queue(); }
public TextChannel getLeaveChannel(Guild guild) { try { Statement statement = connection.createStatement(); statement.closeOnCompletion(); TextChannel tc; try (ResultSet results = statement.executeQuery(String.format("SELECT leave_id FROM GUILD_SETTINGS WHERE GUILD_ID = %s", guild.getId()))) { if(results.next()) tc = guild.getTextChannelById(Long.toString(results.getLong("leave_id"))); else tc=null; } return tc; } catch(SQLException e) { LOG.warn(e.toString()); return null; } }
public static void createGuildSettings(DiscordBot bot, DSLContext database, Guild guild) { SettingsRecord record = database.newRecord(Tables.SETTINGS); record.setGuildid(guild.getId()); record.setSilentcommands(false); record.setInvitelinkremover(false); record.setModlog(false); record.setModlogchannelid(DiscordUtils.getDefaultChannel(guild).getId()); record.setHoldingroom(false); record.setHoldingroomroleid(null); record.setHoldingroomminutes(3); record.setPrefix(bot.getConfig().jim.default_prefix); record.setWelcomemessage(false); record.setMessage(DEFAULT_WELCOME_MESSAGE); record.setWelcomemessagechannelid(DiscordUtils.getDefaultChannel(guild).getId()); record.setNospaceprefix(false); record.setStatistics(false); record.store(); }
public CGuild(Guild guild, Charrizard charrizard) { this.guild = guild; this.charrizard = charrizard; this.settings = charrizard.getSettings(); this.redisConnection = charrizard.getRedisConnection(); this.executor = new ThreadPoolExecutor(2, 16, 60, TimeUnit.SECONDS, new SynchronousQueue<>()); this.userCache = CacheBuilder.newBuilder().expireAfterAccess(5, TimeUnit.MINUTES).build(); this.textChannelCache = CacheBuilder.newBuilder().expireAfterAccess(5, TimeUnit.MINUTES).build(); this.voiceChannelCache = CacheBuilder.newBuilder().expireAfterAccess(5, TimeUnit.MINUTES).build(); this.audio = new CAudio(this); }
@Override public PlaybackInstance getInstance(Guild guild) { return instances.computeIfAbsent(guild.getIdLong(), e -> { AudioPlayer player = playerManager.createPlayer(); player.addListener(this); return new PlaybackInstance(player); }); }
/** * Cache a bunch of guilds * Difference to the sync method is that this won't double check the saved DiscordGuilds against their presence in * the bot. This method is fine to call to cache only a subset of all guilds * * @param dbWrapper The database to run the sync on * @param guilds Stream over all guilds to be cached * @param clazz Class of the actual DiscordGuild entity * @return DatabaseExceptions caused by the execution of this method */ @Nonnull public static <E extends DiscordGuild<E>> Collection<DatabaseException> cacheAll(@Nonnull final DatabaseWrapper dbWrapper, @Nonnull final Stream<Guild> guilds, @Nonnull final Class<E> clazz) { long started = System.currentTimeMillis(); final List<DatabaseException> exceptions = new ArrayList<>(); final AtomicInteger joined = new AtomicInteger(0); final AtomicInteger streamed = new AtomicInteger(0); final Function<Guild, Function<E, E>> cacheAndJoin = (guild) -> (discordguild) -> { E result = discordguild.set(guild); if (!result.present) { result = result.join(); joined.incrementAndGet(); } return result; }; final Stream<Transfiguration<Long, E>> transfigurations = guilds.map( guild -> { if (streamed.incrementAndGet() % 100 == 0) { log.debug("{} guilds processed while caching", streamed.get()); } return Transfiguration.of(EntityKey.of(guild.getIdLong(), clazz), cacheAndJoin.apply(guild)); } ); exceptions.addAll(dbWrapper.findApplyAndMergeAll(transfigurations)); log.debug("Cached {} DiscordGuild entities of class {} in {}ms with {} exceptions, joined {}", streamed.get(), clazz.getSimpleName(), System.currentTimeMillis() - started, exceptions.size(), joined.get()); return exceptions; }
public static Guild getGuildById(String id) { for (JDA jda : Bot.shards) { Guild guild = jda.getGuildById(id); if (guild != null) return guild; } return null; }
public MessageChannel getGroupCreationChannel(Guild guild) { if (guild == null) { return null; } for (MessageChannel c : guild.getTextChannels()) { if (c.getName().equalsIgnoreCase(groupCreationChannel)) { return c; } } return null; }
/** * Remove a reddit feed by two params * @param subreddit Name of subreddit to remove * @param guild Guild to remove from * @return True if removed, false if the feed never existed */ public static boolean removeRedditFeed(String subreddit, Guild guild) { subreddit = subreddit.toLowerCase(); RedditFeedObserver observer; if ((observer = getObserver(subreddit, guild)) == null) return false; redditFeed.get(subreddit).remove(observer); saveFeed(); return true; }
/** * Initialize music manager if not found and set audio provider * @param g Guild * @return GuildMusicManager */ public GuildMusicManager getMusicManager(Guild g) { if (this.musicManager == null) { this.musicManager = new GuildMusicManager(AudioManager.getMasterManager(), g.getId()); g.getAudioManager().setSendingHandler(this.musicManager.getSendHandler()); } return this.musicManager; }
@Command( name = "volume", description = "Changes volume for this server", usage = "`>>volume <new volume>`: Changes the volume\n" + "`>>volume 100`: Resets the volume", permission = CommandPermission.PREMIUM, category = CommandCategory.MUSIC ) public static void volume(@Argument("this") CommandReference thiz, @Argument("event")GuildMessageReceivedEvent event, @Argument("args") String[] args, @Argument("channel") TextChannel channel, @Argument("guild") Guild guild) { if(checkVC(event)) return; if(args.length == 0) { thiz.onHelp(event); return; } int i; try { i = Integer.parseInt(args[0]); } catch(NumberFormatException e) { channel.sendMessage(args[0] + " is not a valid integer").queue(); return; } if(i < 0) { i = 100; } else if (i > 150) { i = 150; } GuildMusicPlayer gmp = GabrielBot.getInstance().getPlayer(guild.getIdLong()); if(gmp == null) { channel.sendMessage("I'm not playing any music").queue(); return; } gmp.player.setVolume(i); channel.sendMessage("Volume set to " + i).queue(); }
@Override protected void doCommand(CommandEvent event) { if(MDCBot.mutedRole == null) { fail(event, "No muted role. Set one using the command:\n" + "%s config %s <role name>", MDCBot.PREFIX, EConfigs.MUTED_ROLE); return; } String args = event.getArgs(); if(args.isEmpty()) { fail(event, "Must provide a member to mute"); return; } Guild guild = event.getGuild(); Member member = getMemberFromString(event, guild, args); if(member == null) return; if(member.getRoles().contains(MDCBot.mutedRole)) { if(MuteHandler.unmuteMember(member)) { //Unmuted member info(event, "%s has been unmuted", member.getEffectiveName()); reply(event, "%s (%s) has been unmuted", member.getEffectiveName(), member.getRoles().get(0).getName()); } else { //Member is not muted warn(event, "%s is not muted", member.getEffectiveName()); reply(event, "%s (%s) is not muted", member.getEffectiveName(), member.getRoles().get(0).getName()); } } }
public Guild getGuildById(long id) { for(JDA shard: shards) { Guild g = shard.getGuildById(id); if(g!=null) return g; } return null; }
public Result run(String[] argsOrig, MessageReceivedEvent e) { //Check for proper argument length if (argsOrig.length < 2) { return new Result(Outcome.WARNING, ":warning: Please specify a message."); } //Extract channel String[] args = ArrayUtils.remove(MessageUtils.getContent(e.getMessage(), true), 0); TextChannel channel = null; if (args[0].matches(MessageUtils.channelRegex)) { channel = e.getMessage().getMentionedChannels().get(0); } else if (args[0].matches(MessageUtils.idRegex)) { channel = DiscordUtils.getTextChannelById(args[0]); } else { return new Result(Outcome.ERROR, ":x: Not a valid channel!"); } //Send the message String msg = String.join(" ", ArrayUtils.remove(args, 0)); channel.sendMessage(msg).queue(); //Log it EmbedBuilder eb = new EmbedBuilder(); Guild guild = channel.getGuild(); eb.setAuthor(e.getAuthor().getName() + " (" + e.getAuthor().getId() + ")", null, e.getAuthor().getAvatarUrl()); eb.setDescription("**Sent a msg to `" + channel.getName() + "` (" + channel.getId() + ")**\non `" + guild.getName() + "` (" + guild.getId() + "):\n" + msg); eb.setThumbnail(guild.getIconUrl()); MessageUtils.log(eb.build()); return new Result(Outcome.SUCCESS); }
public synchronized GuildMusicManager getGuildAudioPlayer(Guild guild) { long guildId = Long.parseLong(guild.getId()); GuildMusicManager musicManager = musicManagers.get(guildId); if (musicManager == null) { musicManager = new GuildMusicManager(playerManager); musicManagers.put(guildId, musicManager); } guild.getAudioManager().setSendingHandler(musicManager.getSendHandler()); return musicManager; }
public Warn(int id, User warnedUser, Guild guild, User executor, String reason, long date) { this.id = id; this.warnedUser = warnedUser; this.guild = guild; this.executor = executor; this.reason = reason; this.date = date; }
public static void leaveServerIfUnauthorized(Guild guild) { long serverId = guild.getIdLong(); if (serverId != ConfigManager.getConfig().getServer()) { System.out.println("Bot was added to unauthorized server " + serverId + "!"); guild.leave().queue(); } }
public void onReady(ReadyEvent e) { initter(); List<Guild> g = e.getJDA().getGuilds(); g.forEach(guild -> { //Whitelist wl = new Whitelist(guild,ids); //Lib.getWhitelist().put(guild,wl); Lib.getWhitelist_().put(guild,Lib.WL); }); }
private void sendPortalNotification(Guild guild, String message) { EmbedBuilder builder = new EmbedBuilder(); builder.setAuthor("Portal Notification", null, guild.getIconUrl()); builder.setDescription(message); builder.setColor(Colors.COLOR_PRIMARY); guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> privateChannel.sendMessage(builder.build()).queue()); }
public final AdvancedGuild setGuild(Guild guild) { this.guild = guild; if (guild == null) { this.guild_id = 0; } else { this.guild_id = this.guild.getIdLong(); } return this; }
public final Emote getGuildReactionOnCommandNotFound(Guild guild) { final String reaction_on_command_not_found = getValue(guild.getIdLong(), 0, KEY_GUILD_REACTION_ON_COMMAND_NOT_FOUND, () -> Emoji.QUESTION_MARK); if (reaction_on_command_not_found == null) { return null; } final Matcher matcher = ArgumentList.PATTERN_MARKDOWN_CUSTOM_EMOJI.matcher(reaction_on_command_not_found); if (!matcher.matches()) { return null; } return guild.getEmoteById(matcher.group(2)); }
public boolean hasRow(Guild guild) throws SQLException { boolean returns; try (Statement statement = connection.createStatement()) { try (ResultSet results = statement.executeQuery("SELECT * FROM "+table.name()+" WHERE GUILD_ID = "+guild.getIdLong())) { // if there is a row then it will be true, if not it will be false returns = results.next(); } } return returns; }
public static Warn parseWarn(String id, String warnedUser, String guildid, String executor, String reason, String date) { int pId = Integer.parseInt(id); User pWarnedUser = RubiconBot.getJDA().getUserById(warnedUser); Guild guild = RubiconBot.getJDA().getGuildById(guildid); User pExecutor = RubiconBot.getJDA().getUserById(executor); long pDate = Long.valueOf(date); return new Warn(pId, pWarnedUser, guild, pExecutor, reason, pDate); }
@Test public void testCreateGetAndDeleteGroup() throws Exception { clockService.setMockTime(LocalTime.of(10, 0)); // We're not allowed to create signups at night, so mocking time final LocalDateTime now = clockService.getCurrentDateTime(); final LocalTime nowTime = now.toLocalTime(); LocalDateTime endOfRaid = now.plusMinutes(45); final Gym gym = gymRepository.findByName("Blenda", uppsalaRegion); Raid enteiRaid = new Raid(pokemonRepository.search("Entei", null), endOfRaid, gym, localeService, uppsalaRegion); String raidCreatorName = "testUser1"; User user = mock(User.class); when(user.getName()).thenReturn(raidCreatorName); Guild guild = mock(Guild.class); Config config = mock(Config.class); Raid enteiRaid1 = enteiRaid; try { enteiRaid1 = repo.newRaid(user, enteiRaid1, guild, config, "test"); } catch (RuntimeException e) { System.err.println(e.getMessage()); fail("Could not save raid: " + e.getMessage()); } enteiRaid = enteiRaid1; User user2 = mock(User.class); String userName = "testUser2"; when(user2.getName()).thenReturn(userName); LocalTime arrivalTime = nowTime.plusMinutes(30); RaidGroup group = new RaidGroup("testserver", "channel", "infoId", "emoteId", "userId", LocalDateTime.of(LocalDate.now(), arrivalTime)); group = repo.newGroupForRaid(user2, group, enteiRaid, guild, config); List<RaidGroup> groupsForServer = repo.getGroupsForServer("testserver"); assertThat(group != null, is(true)); assertThat(groupsForServer.size(), is(1)); assertThat(groupsForServer.iterator().next(), is(group)); RaidGroup deleted = repo.deleteGroup(enteiRaid.getId(), group.getId()); assertThat(deleted != null, is(true)); groupsForServer = repo.getGroupsForServer("testserver"); assertThat(groupsForServer.size(), is(0)); }