net.dv8tion.jda.api.entities.Guild Java Examples

The following examples show how to use net.dv8tion.jda.api.entities.Guild. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ManagerMethods.java    From Arraybot with Apache License 2.0 6 votes vote down vote up
/**
 * Manages the roles of a user.
 * @param user The user.
 * @param role The role.
 * @param add True = add, false = remove.
 * @return True if successful, false otherwise.
 */
private synchronized boolean manageRole(ScriptUser user, ScriptRole role, boolean add) {
    try {
        Guild guild = environment.getGuild();
        Member member = environment.getGuild().getMemberById(user.getID());
        Role rank = environment.getGuild().getRoleById(role.getID());
        if(member != null
                && rank != null) {
            if(add) {
                guild.addRoleToMember(member, rank).complete();
            } else {
                guild.removeRoleFromMember(member, rank).complete();
            }
        }
        return true;
    } catch(Exception exception) {
        return false;
    }
}
 
Example #2
Source File: DiscordEntityAccessorImpl.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
private GuildConfig updateIfRequred(Guild guild, GuildConfig config) {
    try {
        boolean shouldSave = false;
        if (!Objects.equals(config.getName(), guild.getName())) {
            config.setName(guild.getName());
            shouldSave = true;
        }
        if (!Objects.equals(config.getIconUrl(), guild.getIconUrl())) {
            config.setIconUrl(guild.getIconUrl());
            shouldSave = true;
        }
        if (shouldSave) {
            configService.save(config);
        }
    } catch (ObjectOptimisticLockingFailureException e) {
        // it's ok to ignore optlock here, anyway it will be updated later
    }
    return config;
}
 
Example #3
Source File: DefaultAudioServiceImpl.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void closeConnection(Guild guild) {
    if (lavaLink != null) {
        Link link = lavaLink.getExistingLink(guild);
        if (link != null
                && link.getState() != Link.State.DESTROYED
                && link.getState() != Link.State.DESTROYING) {
            link.destroy();

            // Sometimes JDA thinks that bot is connected to channel,
            // we should manually clear this state to let Lavalink connect to it again
            if (guild.getSelfMember().getVoiceState() instanceof GuildVoiceStateImpl) {
                GuildVoiceStateImpl voiceState = (GuildVoiceStateImpl) guild.getSelfMember().getVoiceState();
                voiceState.setConnectedChannel(null);
            }
        }
    } else {
        guild.getAudioManager().closeAudioConnection();
    }
}
 
Example #4
Source File: ContextServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> T withContext(Guild guild, Supplier<T> action) {
    Object[] holder = new Object[1];
    withContext(guild, () -> {
        holder[0] = action.get();
    });
    return (T) holder[0];
}
 
Example #5
Source File: RoleImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public AuditableRestAction<Void> delete()
{
    Guild guild = getGuild();
    if (!guild.getSelfMember().hasPermission(Permission.MANAGE_ROLES))
        throw new InsufficientPermissionException(guild, Permission.MANAGE_ROLES);
    if(!PermissionUtil.canInteract(guild.getSelfMember(), this))
        throw new HierarchyException("Can't delete role >= highest self-role");
    if (managed)
        throw new UnsupportedOperationException("Cannot delete a Role that is managed. ");

    Route.CompiledRoute route = Route.Roles.DELETE_ROLE.compile(guild.getId(), getId());
    return new AuditableRestActionImpl<>(getJDA(), route);
}
 
Example #6
Source File: RoleImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public RoleAction createCopy(@Nonnull Guild guild)
{
    Checks.notNull(guild, "Guild");
    return guild.createRole()
                .setColor(color)
                .setHoisted(hoisted)
                .setMentionable(mentionable)
                .setName(name)
                .setPermissions(rawPermissions);
}
 
Example #7
Source File: WebhookQueueListener.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@RabbitListener(queues = RabbitConfiguration.QUEUE_WEBHOOK_GET_REQUEST)
public WebhookDto getWebhook(WebhookRequest request) {
    Guild guild = getGuildById(request.getGuildId());
    if (guild == null || !guild.getSelfMember().hasPermission(Permission.MANAGE_WEBHOOKS)) {
        return WebhookDto.EMPTY;
    }
    Webhook webhook = webHookService.getWebHook(request.getId(), guild);
    if (webhook == null) {
        return WebhookDto.EMPTY;
    }
    WebhookDto dto = discordMapperService.getWebhookDto(webhook);
    dto.setId(request.getId());
    return dto;
}
 
Example #8
Source File: InviteDeleteHandler.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Override
protected Long handleInternally(DataObject content)
{
    long guildId = content.getUnsignedLong("guild_id");
    if (getJDA().getGuildSetupController().isLocked(guildId))
        return guildId;
    Guild guild = getJDA().getGuildById(guildId);
    if (guild == null)
    {
        EventCache.LOG.debug("Caching INVITE_DELETE for unknown guild {}", guildId);
        getJDA().getEventCache().cache(EventCache.Type.GUILD, guildId, responseNumber, allContent, this::handle);
        return null;
    }
    long channelId = content.getUnsignedLong("channel_id");
    GuildChannel channel = guild.getGuildChannelById(channelId);
    if (channel == null)
    {
        EventCache.LOG.debug("Caching INVITE_DELETE for unknown channel {} in guild {}", channelId, guildId);
        getJDA().getEventCache().cache(EventCache.Type.CHANNEL, channelId, responseNumber, allContent, this::handle);
        return null;
    }

    String code = content.getString("code");
    getJDA().handleEvent(
        new GuildInviteDeleteEvent(
            getJDA(), responseNumber,
            code, channel));
    return null;
}
 
Example #9
Source File: GuildUpdateOwnerEvent.java    From JDA with Apache License 2.0 5 votes vote down vote up
public GuildUpdateOwnerEvent(@Nonnull JDA api, long responseNumber, @Nonnull Guild guild, @Nullable Member oldOwner,
                             long prevId, long nextId)
{
    super(api, responseNumber, guild, oldOwner, guild.getOwner(), IDENTIFIER);
    this.prevId = prevId;
    this.nextId = nextId;
}
 
Example #10
Source File: DefaultShardManager.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Override
public Guild getGuildById(long id)
{
    int shardId = MiscUtil.getShardForGuild(id, getShardsTotal());
    JDA shard = this.getShardById(shardId);
    return shard == null ? null : shard.getGuildById(id);
}
 
Example #11
Source File: WebSocketSendingThread.java    From JDA with Apache License 2.0 5 votes vote down vote up
private void handleAudioRequest(ConnectionRequest audioRequest)
{
    long channelId = audioRequest.getChannelId();
    long guildId = audioRequest.getGuildIdLong();
    Guild guild = api.getGuildById(guildId);
    if (guild == null)
    {
        LOG.debug("Discarding voice request due to null guild {}", guildId);
        // race condition on guild delete, avoid NPE on DISCONNECT requests
        queuedAudioConnections.remove(guildId);
        return;
    }
    ConnectionStage stage = audioRequest.getStage();
    AudioManager audioManager = guild.getAudioManager();
    DataObject packet;
    switch (stage)
    {
        case RECONNECT:
        case DISCONNECT:
            packet = newVoiceClose(guildId);
            break;
        default:
        case CONNECT:
            packet = newVoiceOpen(audioManager, channelId, guild.getIdLong());
    }
    LOG.debug("Sending voice request {}", packet);
    if (send(packet.toString()))
    {
        //If we didn't get RateLimited, Next request attempt will be 2 seconds from now
        // we remove it in VoiceStateUpdateHandler once we hear that it has updated our status
        // in 2 seconds we will attempt again in case we did not receive an update
        audioRequest.setNextAttemptEpoch(System.currentTimeMillis() + 2000);
        //If we are already in the correct state according to voice state
        // we will not receive a VOICE_STATE_UPDATE that would remove it
        // thus we update it here
        final GuildVoiceState voiceState = guild.getSelfMember().getVoiceState();
        client.updateAudioConnection0(guild.getIdLong(), voiceState.getChannel());
    }
}
 
Example #12
Source File: ServerInfoCommand.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
protected MessageEmbed.Field getCreatedAt(Guild guild, BotContext context) {
    DateTimeFormatter formatter = DateTimeFormat.mediumDateTime()
            .withLocale(contextService.getLocale())
            .withZone(context.getTimeZone());
    return getDateField(guild.getTimeCreated().toEpochSecond(), "discord.command.server.createdAt",
            formatter);
}
 
Example #13
Source File: PunishmentManager.java    From Arraybot with Apache License 2.0 5 votes vote down vote up
/**
 * Logs the punishment into a logging channel.
 * @param guild The guild.
 * @param punishmentObject The punishment.
 * @param onRevoke If this log occurred during the revocation.
 * @param revoker The person who revoked this punishment, can be null if automatic or not revoked.
 */
private void log(Guild guild, PunishmentObject punishmentObject, boolean onRevoke, Long revoker) {
    GuildEntry entry = (GuildEntry) Category.GUILD.getEntry();
    long channelId = Long.valueOf(entry.fetch(entry.getField(GuildEntry.Fields.PUNISHMENT_CHANNEL), guild.getIdLong(), null));
    TextChannel channel = guild.getTextChannelById(channelId);
    if(channel == null
            || UChannel.cantTalk(channel)) {
        return;
    }
    CustomEmbedBuilder embed = getEmbed(guild, punishmentObject, onRevoke, revoker);
    channel.sendMessage(embed.build()).queue();
}
 
Example #14
Source File: BotApplicationManager.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private synchronized BotGuildContext getContext(Guild guild) {
  long guildId = Long.parseLong(guild.getId());
  BotGuildContext context = guildContexts.get(guildId);

  if (context == null) {
    context = createGuildState(guildId, guild);
    guildContexts.put(guildId, context);
  }

  return context;
}
 
Example #15
Source File: GuildActionImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
@CheckReturnValue
public GuildActionImpl setVerificationLevel(Guild.VerificationLevel level)
{
    this.verificationLevel = level;
    return this;
}
 
Example #16
Source File: AudioUtils.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
public synchronized GuildMusicManager getMusicManager(Guild guild) {
    final long guildId = guild.getIdLong();
    GuildMusicManager mng = musicManagers.get(guildId);

    if (mng == null) {
        mng = new GuildMusicManager(guild, variables);
        musicManagers.put(guildId, mng);
    }

    if (!LavalinkManager.ins.isEnabled() && guild.getAudioManager().getSendingHandler() == null) {
        guild.getAudioManager().setSendingHandler(mng.getSendHandler());
    }

    return mng;
}
 
Example #17
Source File: AirUtils.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void loadGuildMembers(Guild guild) {
    try {
        guild.retrieveMembers().get();
    }
    catch (InterruptedException | ExecutionException e) {
        Sentry.capture(e);
    }
}
 
Example #18
Source File: InviteCommand.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
private MessageEmbed createInfoMessage(InviteInfo inviteInfo, BotContext context) {
    EmbedBuilder builder = messageService.getBaseEmbed(false);

    if (inviteInfo.getGuild() != null) {
        InviteInfo.Guild guildInfo = inviteInfo.getGuild();
        String iconUrl = AvatarType.ICON.getUrl(guildInfo.getId(), guildInfo.getIcon());
        String inviteUrl = "https://discord.gg/" + (StringUtils.isNotEmpty(guildInfo.getVanityUrlCode()) ? guildInfo.getVanityUrlCode() : inviteInfo.getCode());
        builder.setTitle(String.format("%s (ID: %s)", guildInfo.getName(), guildInfo.getId()), inviteUrl);
        builder.setDescription(guildInfo.getDescription());
        builder.setThumbnail(iconUrl);

        Guild guild = discordService.getGuildById(Long.valueOf(guildInfo.getId()));
        if (guild != null) {
            builder.addField(getMemberListField(guild));
            builder.addField(getChannelListField(guild));
            builder.addField(getShard(guild));
            builder.addField(getVerificationLevel(guild.getVerificationLevel()));
            builder.addField(getRegion(guild));
            builder.addField(getOwner(guild));
            builder.addField(getCreatedAt(guild, context));
        } else {
            if (guildInfo.getVerificationLevel() != null) {
                builder.addField(getVerificationLevel(Guild.VerificationLevel.fromKey(guildInfo.getVerificationLevel())));
            }
        }
    }

    if (inviteInfo.getChannel() != null) {
        InviteInfo.Channel channel = inviteInfo.getChannel();
        String info = String.format("`#%s` (ID: %s)", channel.getName(), channel.getId());
        builder.addField(messageService.getMessage("discord.command.invite.channel"), info, true);
    }

    if (inviteInfo.getInviter() != null) {
        InviteInfo.Inviter inviter = inviteInfo.getInviter();
        String avatarUrl = StringUtils.isNotEmpty(inviter.getAvatar()) ? AvatarType.AVATAR.getUrl(inviter.getId(), inviter.getAvatar()) : null;
        builder.setFooter(String.format("%s#%s (ID: %s)", inviter.getUsername(), inviter.getDiscriminator(), inviter.getId()), avatarUrl);
    }
    return builder.build();
}
 
Example #19
Source File: BotApplicationManager.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private BotGuildContext createGuildState(long guildId, Guild guild) {
  BotGuildContext context = new BotGuildContext(guildId);

  for (BotController controller : controllerManager.createControllers(this, context, guild)) {
    context.controllers.put(controller.getClass(), controller);
  }

  return context;
}
 
Example #20
Source File: GuildManagerImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
@CheckReturnValue
public GuildManagerImpl setExplicitContentLevel(@Nonnull Guild.ExplicitContentLevel level)
{
    Checks.notNull(level, "Level");
    Checks.check(level != Guild.ExplicitContentLevel.UNKNOWN, "Level must not be UNKNOWN");
    this.explicitContentLevel = level.getKey();
    set |= EXPLICIT_CONTENT_LEVEL;
    return this;
}
 
Example #21
Source File: PlayerServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean resume(Guild guild, boolean resetMessage) {
    if (!isActive(guild)) {
        return false;
    }
    PlaybackInstance instance = get(guild);
    if (instance.resumeTrack(resetMessage)) {
        contextService.withContext(instance.getGuildId(), () -> messageManager.onTrackResume(instance.getCurrent()));
        return true;
    }
    return false;
}
 
Example #22
Source File: PlayerServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
@Transactional
public boolean shuffle(Guild guild) {
    PlaybackInstance instance = get(guild);
    boolean result = instance != null && instance.shuffle();
    if (result) {
        storedPlaylistService.refreshStoredPlaylist(instance);
    }
    return result;
}
 
Example #23
Source File: PunishmentManager.java    From Arraybot with Apache License 2.0 5 votes vote down vote up
/**
 * Gets all punishments for a guild.
 * @param guild The guild.
 * @return A list of all punishments.
 */
public List<PunishmentObject> getAllPunishments(Guild guild) {
    long guildId = guild.getIdLong();
    SetEntry entry = (SetEntry) Category.PUNISHMENT_IDS.getEntry();
    List<PunishmentObject> punishments = new ArrayList<>();
    for(String punishment : entry.values(guildId)) {
        punishments.add(PunishmentObject.fromRedis(guild, Integer.valueOf(punishment)));
    }
    return punishments;
}
 
Example #24
Source File: GuildUpdateExplicitContentLevelEvent.java    From JDA with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public Guild.ExplicitContentLevel getOldValue()
{
    return super.getOldValue();
}
 
Example #25
Source File: GuildUpdateBannerEvent.java    From JDA with Apache License 2.0 4 votes vote down vote up
public GuildUpdateBannerEvent(@Nonnull JDA api, long responseNumber, @Nonnull Guild guild, @Nullable String previous)
{
    super(api, responseNumber, guild, previous, guild.getBannerId(), IDENTIFIER);
}
 
Example #26
Source File: UserUpdateActivityOrderEvent.java    From JDA with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public Guild getGuild()
{
    return member.getGuild();
}
 
Example #27
Source File: JdaLavalink.java    From Lavalink-Client with MIT License 4 votes vote down vote up
@SuppressWarnings("WeakerAccess")
@Nullable
public JdaLink getExistingLink(Guild guild) {
    return getExistingLink(guild.getId());
}
 
Example #28
Source File: RoleActionImpl.java    From JDA with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public Guild getGuild()
{
    return guild;
}
 
Example #29
Source File: GuildUpdateSplashEvent.java    From JDA with Apache License 2.0 4 votes vote down vote up
public GuildUpdateSplashEvent(@Nonnull JDA api, long responseNumber, @Nonnull Guild guild, @Nullable String oldSplashId)
{
    super(api, responseNumber, guild, oldSplashId, guild.getSplashId(), IDENTIFIER);
}
 
Example #30
Source File: GuildUpdateNotificationLevelEvent.java    From JDA with Apache License 2.0 4 votes vote down vote up
/**
 * The new {@link net.dv8tion.jda.api.entities.Guild.NotificationLevel NotificationLevel}
 *
 * @return The new NotificationLevel
 */
@Nonnull
public Guild.NotificationLevel getNewNotificationLevel()
{
    return getNewValue();
}