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

The following examples show how to use net.dv8tion.jda.api.entities.Guild. These examples are extracted from open source projects. 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 Project: Arraybot   Source File: ManagerMethods.java    License: 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
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
@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 Project: JDA   Source File: WebSocketSendingThread.java    License: 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 5
@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 6
Source Project: JDA   Source File: GuildManagerImpl.java    License: 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 7
Source Project: JuniperBot   Source File: InviteCommand.java    License: 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 8
Source Project: SkyBot   Source File: AirUtils.java    License: 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 9
Source Project: SkyBot   Source File: AudioUtils.java    License: 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 10
Source Project: lavaplayer   Source File: BotApplicationManager.java    License: 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 11
Source Project: JDA   Source File: GuildActionImpl.java    License: 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 12
Source Project: JDA   Source File: RoleImpl.java    License: 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 13
Source Project: Arraybot   Source File: PunishmentManager.java    License: 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 Project: JDA   Source File: InviteDeleteHandler.java    License: 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 15
@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 16
Source Project: lavaplayer   Source File: BotApplicationManager.java    License: 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 17
Source Project: JuniperBot   Source File: PlayerServiceImpl.java    License: 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 18
Source Project: JuniperBot   Source File: PlayerServiceImpl.java    License: 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 19
Source Project: Arraybot   Source File: PunishmentManager.java    License: 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 20
Source Project: JDA   Source File: RoleImpl.java    License: 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 21
Source Project: JDA   Source File: GuildUpdateOwnerEvent.java    License: 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 22
Source Project: JDA   Source File: DefaultShardManager.java    License: 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 23
Source Project: JuniperBot   Source File: ServerInfoCommand.java    License: 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 24
Source Project: JuniperBot   Source File: BonusCommand.java    License: GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean isAvailable(User user, Member member, Guild guild) {
    return patreonService.isAvailableForUser(user.getIdLong(), FeatureSet.BONUS);
}
 
Example 25
Source Project: Lavalink-Client   Source File: JdaLavalink.java    License: MIT License 4 votes vote down vote up
@SuppressWarnings("WeakerAccess")
@Nullable
public JdaLink getExistingLink(Guild guild) {
    return getExistingLink(guild.getId());
}
 
Example 26
Source Project: Arraybot   Source File: UTime.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Gets a displayable time string.
 * @param guild The guild where the string is taken from.
 * @param time The time, in milliseconds, to use.
 */
public static String getDisplayableTime(Guild guild, long time) {
    TimeZone timeZone;
    switch(guild.getRegion()) {
        case AMSTERDAM:
            timeZone = TimeZone.getTimeZone("Europe/Amsterdam");
            break;
        case BRAZIL:
            timeZone = TimeZone.getTimeZone("Brazil/Acre");
            break;
        case EU_CENTRAL:
        case FRANKFURT:
            timeZone = TimeZone.getTimeZone("Europe/Berlin");
            break;
        case EU_WEST:
        case LONDON:
            timeZone = TimeZone.getTimeZone("Europe/London");
            break;
        case HONG_KONG:
            timeZone = TimeZone.getTimeZone("Asia/Hong_Kong");
            break;
        case RUSSIA:
            timeZone = TimeZone.getTimeZone("Europe/Moscow");
            break;
        case SINGAPORE:
            timeZone = TimeZone.getTimeZone("Asia/Singapore");
            break;
        case SYDNEY:
            timeZone = TimeZone.getTimeZone("Australia/Sydney");
            break;
        case US_CENTRAL:
        case US_SOUTH:
            timeZone = TimeZone.getTimeZone("America/Chicago");
            break;
        case US_EAST:
            timeZone = TimeZone.getTimeZone("America/New_York");
            break;
        case US_WEST:
            timeZone = TimeZone.getTimeZone("America/Los_Angeles");
            break;
        case VIP_AMSTERDAM:
            timeZone = TimeZone.getTimeZone("Europe/Amsterdam");
            break;
        case VIP_BRAZIL:
            timeZone = TimeZone.getTimeZone("Brazil/Acre");
            break;
        case VIP_EU_CENTRAL:
        case VIP_FRANKFURT:
            timeZone = TimeZone.getTimeZone("Europe/Berlin");
            break;
        case VIP_EU_WEST:
        case VIP_LONDON:
            timeZone = TimeZone.getTimeZone("Europe/London");
            break;
        case VIP_SINGAPORE:
            timeZone = TimeZone.getTimeZone("Asia/Singapore");
            break;
        case VIP_SYDNEY:
            timeZone = TimeZone.getTimeZone("Australia/Sydney");
            break;
        case VIP_US_CENTRAL:
        case VIP_US_SOUTH:
            timeZone = TimeZone.getTimeZone("America/Chicago");
            break;
        case VIP_US_EAST:
            timeZone = TimeZone.getTimeZone("America/New_York");
            break;
        case VIP_US_WEST:
            timeZone = TimeZone.getTimeZone("America/Los_Angeles");
            break;
        default:
            timeZone = TimeZone.getTimeZone("Europe/Berlin");
            break;
    }
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy kk:mm:ss");
    simpleDateFormat.setTimeZone(timeZone);
    Calendar calendar = GregorianCalendar.getInstance();
    calendar.setTimeInMillis(time);
    return simpleDateFormat.format(calendar.getTime());
}
 
Example 27
Source Project: JDA   Source File: VoiceDispatchInterceptor.java    License: Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public Guild getGuild()
{
    return guild;
}
 
Example 28
Source Project: lavaplayer   Source File: Main.java    License: Apache License 2.0 4 votes vote down vote up
private void play(Guild guild, GuildMusicManager musicManager, AudioTrack track) {
  connectToFirstVoiceChannel(guild.getAudioManager());

  musicManager.scheduler.queue(track);
}
 
Example 29
Source Project: JuniperBot   Source File: AbstractCommand.java    License: GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean isAvailable(User user, Member member, Guild guild) {
    return true;
}
 
Example 30
Source Project: MantaroBot   Source File: DBGuild.java    License: GNU General Public License v3.0 4 votes vote down vote up
public Guild getGuild(JDA jda) {
    return jda.getGuildById(getId());
}