net.dv8tion.jda.api.OnlineStatus Java Examples

The following examples show how to use net.dv8tion.jda.api.OnlineStatus. 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: AudioEchoExample.java    From JDA with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws LoginException
{
    if (args.length == 0)
    {
        System.err.println("Unable to start without token!");
        System.exit(1);
    }
    String token = args[0];

    // We only need 2 gateway intents enabled for this example:
    EnumSet<GatewayIntent> intents = EnumSet.of(
        // We need messages in guilds to accept commands from users
        GatewayIntent.GUILD_MESSAGES,
        // We need voice states to connect to the voice channel
        GatewayIntent.GUILD_VOICE_STATES
    );

    // Start the JDA session with light mode (minimal cache)
    JDABuilder.createLight(token, intents)           // Use provided token from command line arguments
         .addEventListeners(new AudioEchoExample())  // Start listening with this listener
         .setActivity(Activity.listening("to jams")) // Inform users that we are jammin' it out
         .setStatus(OnlineStatus.DO_NOT_DISTURB)     // Please don't disturb us while we're jammin'
         .enableCache(CacheFlag.VOICE_STATE)         // Enable the VOICE_STATE cache to find a user's connected voice channel
         .build();                                   // Login with these options
}
 
Example #2
Source File: PresenceImpl.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Override
public void setPresence(OnlineStatus status, Activity activity, boolean idle)
{
    DataObject gameObj = getGameJson(activity);

    Checks.check(status != OnlineStatus.UNKNOWN,
            "Cannot set the presence status to an unknown OnlineStatus!");
    if (status == OnlineStatus.OFFLINE || status == null)
        status = OnlineStatus.INVISIBLE;

    DataObject object = DataObject.empty();

    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.activity = gameObj == null ? null : activity;
}
 
Example #3
Source File: MemberListener.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
@Override
@Transactional
public void onUserUpdateOnlineStatus(@Nonnull UserUpdateOnlineStatusEvent event) {
    OnlineStatus newStatus = event.getNewOnlineStatus();
    OnlineStatus oldStatus = event.getOldOnlineStatus();
    if (event.getUser().isBot()
            || oldStatus == OnlineStatus.OFFLINE
            || oldStatus == OnlineStatus.INVISIBLE
            || (newStatus != OnlineStatus.OFFLINE && newStatus != OnlineStatus.INVISIBLE)) {
        return;
    }

    try {
        // this event is executed multiple times for each mutual guild, we want this only once at least per minute
        statusCache.get(event.getUser().getId(), () -> {
            LocalUser user = entityAccessor.getOrCreate(event.getUser());
            user.setLastOnline(new Date());
            userService.save(user);
            return newStatus;
        });
    } catch (ExecutionException e) {
        throw new RuntimeException(e);
    }
}
 
Example #4
Source File: DefaultShardManager.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Override
public void setPresenceProvider(IntFunction<OnlineStatus> statusProvider, IntFunction<? extends Activity> activityProvider)
{
    ShardManager.super.setPresenceProvider(statusProvider, activityProvider);
    presenceConfig.setStatusProvider(statusProvider);
    presenceConfig.setActivityProvider(activityProvider);
}
 
Example #5
Source File: ImagingServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
private BufferedImage getStatusLayer(Member member, OnlineStatus status) {
    if (member == null && status == null) {
        return null;
    }
    if (member != null) {
        if (member.getActivities().stream().anyMatch(e -> e.getType() == Activity.ActivityType.STREAMING)) {
            return getResourceImage("avatar-status-streaming.png");
        }
        status = member.getOnlineStatus();
    }
    return getResourceImage(String.format("avatar-status-%s.png", status.getKey()));
}
 
Example #6
Source File: DiscordServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
private void setUpStatus() {
    shardManager.setStatus(OnlineStatus.IDLE);
    String playingStatus = workerProperties.getDiscord().getPlayingStatus();
    if (StringUtils.isNotEmpty(playingStatus)) {
        shardManager.setActivity(Activity.playing(playingStatus));
    }
}
 
Example #7
Source File: BotManager.java    From Arraybot with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the default shard manager.
 * @return The default shard manager.
 * @throws LoginException If the bot could not log in.
 */
private ShardManager createShardManager()
        throws LoginException {
    return new DefaultShardManagerBuilder()
            .setToken(configuration.isBotBeta() ? configuration.getBotBetaToken() : configuration.getBotToken())
            .setStatus(OnlineStatus.DO_NOT_DISTURB)
            .setShardsTotal(configuration.getBotShards())
            .addEventListeners(new ReadyListener())
            .setUseShutdownNow(true)
            .setActivity(Activity.listening(configuration.getBotPrefix() + "help || v" + configuration.getBotVersion()))
            .build();
}
 
Example #8
Source File: MemberImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
public MemberImpl setOnlineStatus(ClientType type, OnlineStatus status)
{
    if (this.clientStatus == null || type == ClientType.UNKNOWN || type == null)
        return this;
    if (status == null || status == OnlineStatus.UNKNOWN || status == OnlineStatus.OFFLINE)
        this.clientStatus.remove(type);
    else
        this.clientStatus.put(type, status);
    return this;
}
 
Example #9
Source File: DiscordBotServer.java    From MtgDesktopCompanion with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void stop() throws IOException {
	if(jda!=null)
	{
		jda.shutdown();
		jda.getPresence().setPresence(OnlineStatus.OFFLINE,false);
	}
}
 
Example #10
Source File: MemberImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public OnlineStatus getOnlineStatus(@Nonnull ClientType type)
{
    Checks.notNull(type, "Type");
    if (this.clientStatus == null || this.clientStatus.isEmpty())
        return OnlineStatus.OFFLINE;
    OnlineStatus status = this.clientStatus.get(type);
    return status == null ? OnlineStatus.OFFLINE : status;
}
 
Example #11
Source File: PresenceImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
public PresenceImpl setCacheStatus(OnlineStatus status)
{
    if (status == null)
        throw new NullPointerException("Null OnlineStatus is not allowed.");
    if (status == OnlineStatus.OFFLINE)
        status = OnlineStatus.INVISIBLE;
    this.status = status;
    return this;
}
 
Example #12
Source File: WidgetUtil.java    From JDA with Apache License 2.0 5 votes vote down vote up
private Member(@Nonnull DataObject json, @Nonnull Widget widget)
{
    this.widget = widget;
    this.bot = json.getBoolean("bot");
    this.id = json.getLong("id");
    this.username = json.getString("username");
    this.discriminator = json.getString("discriminator");
    this.avatar = json.getString("avatar", null);
    this.nickname = json.getString("nick", null);
    this.status = OnlineStatus.fromKey(json.getString("status"));
    this.game = json.isNull("game") ? null : EntityBuilder.createActivity(json.getObject("game"));
}
 
Example #13
Source File: PresenceProviderConfig.java    From JDA with Apache License 2.0 4 votes vote down vote up
@Nullable
public IntFunction<OnlineStatus> getStatusProvider()
{
    return statusProvider;
}
 
Example #14
Source File: UserUpdateOnlineStatusEvent.java    From JDA with Apache License 2.0 4 votes vote down vote up
/**
 * The new status
 *
 * @return The new status
 */
@Nonnull
public OnlineStatus getNewOnlineStatus()
{
    return getNewValue();
}
 
Example #15
Source File: UserUpdateOnlineStatusEvent.java    From JDA with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public OnlineStatus getOldValue()
{
    return super.getOldValue();
}
 
Example #16
Source File: UserUpdateOnlineStatusEvent.java    From JDA with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public OnlineStatus getNewValue() {
    return super.getNewValue();
}
 
Example #17
Source File: PresenceUpdateHandler.java    From JDA with Apache License 2.0 4 votes vote down vote up
@Override
protected Long handleInternally(DataObject content)
{
    // Ignore events for relationships, presences are guild only to us
    if (content.isNull("guild_id"))
    {
        log.debug("Received PRESENCE_UPDATE without guild_id. Ignoring event.");
        return null;
    }

    //Do a pre-check to see if this is for a Guild, and if it is, if the guild is currently locked or not cached.
    final long guildId = content.getLong("guild_id");
    if (getJDA().getGuildSetupController().isLocked(guildId))
        return guildId;
    GuildImpl guild = (GuildImpl) getJDA().getGuildById(guildId);
    if (guild == null)
    {
        getJDA().getEventCache().cache(EventCache.Type.GUILD, guildId, responseNumber, allContent, this::handle);
        EventCache.LOG.debug("Received a PRESENCE_UPDATE for a guild that is not yet cached! GuildId:{} UserId: {}",
                             guildId, content.getObject("user").get("id"));
        return null;
    }

    DataObject jsonUser = content.getObject("user");
    final long userId = jsonUser.getLong("id");
    UserImpl user = (UserImpl) getJDA().getUsersView().get(userId);

    // The user is not yet known to us, maybe due to lazy loading. Try creating it.
    if (user == null)
    {
        // If this presence update doesn't have a user or the status is offline we ignore it
        if (jsonUser.isNull("username") || "offline".equals(content.get("status")))
            return null;
        // We should have somewhat enough information to create this member, so lets do it!
        user = (UserImpl) createMember(content, guildId, guild, jsonUser).getUser();
    }

    if (jsonUser.hasKey("username"))
    {
        // username implies this is an update to a user - fire events and update properties
        getJDA().getEntityBuilder().updateUser(user, jsonUser);
    }

    //Now that we've update the User's info, lets see if we need to set the specific Presence information.
    // This is stored in the Member objects.
    //We set the activities to null to prevent parsing if the cache was disabled
    final DataArray activityArray = !getJDA().isCacheFlagSet(CacheFlag.ACTIVITY) || content.isNull("activities") ? null : content.getArray("activities");
    List<Activity> newActivities = new ArrayList<>();
    boolean parsedActivity = parseActivities(userId, activityArray, newActivities);

    MemberImpl member = (MemberImpl) guild.getMember(user);
    //Create member from presence if not offline
    if (member == null)
    {
        if (jsonUser.isNull("username") || "offline".equals(content.get("status")))
        {
            log.trace("Ignoring incomplete PRESENCE_UPDATE for member with id {} in guild with id {}", userId, guildId);
            return null;
        }
        member = createMember(content, guildId, guild, jsonUser);
    }

    if (getJDA().isCacheFlagSet(CacheFlag.CLIENT_STATUS) && !content.isNull("client_status"))
        handleClientStatus(content, member);

    // Check if activities changed
    if (parsedActivity)
        handleActivities(newActivities, member);

    //The member is already cached, so modify the presence values and fire events as needed.
    OnlineStatus status = OnlineStatus.fromKey(content.getString("status"));
    if (!member.getOnlineStatus().equals(status))
    {
        OnlineStatus oldStatus = member.getOnlineStatus();
        member.setOnlineStatus(status);
        getJDA().getEntityBuilder().updateMemberCache(member);
        getJDA().handleEvent(
            new UserUpdateOnlineStatusEvent(
                getJDA(), responseNumber,
                member, oldStatus));
    }
    return null;
}
 
Example #18
Source File: PresenceImpl.java    From JDA with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public OnlineStatus getStatus()
{
    return status;
}
 
Example #19
Source File: UserUpdateOnlineStatusEvent.java    From JDA with Apache License 2.0 4 votes vote down vote up
/**
 * The old status
 *
 * @return The old status
 */
@Nonnull
public OnlineStatus getOldOnlineStatus()
{
    return getOldValue();
}
 
Example #20
Source File: PresenceImpl.java    From JDA with Apache License 2.0 4 votes vote down vote up
@Override
public void setStatus(OnlineStatus status)
{
    setPresence(status, activity, idle);
}
 
Example #21
Source File: PresenceImpl.java    From JDA with Apache License 2.0 4 votes vote down vote up
@Override
public void setPresence(OnlineStatus status, Activity activity)
{
    setPresence(status, activity, idle);
}
 
Example #22
Source File: PresenceImpl.java    From JDA with Apache License 2.0 4 votes vote down vote up
@Override
public void setPresence(OnlineStatus status, boolean idle)
{
    setPresence(status, activity, idle);
}
 
Example #23
Source File: ImagingServiceImpl.java    From JuniperBot with GNU General Public License v3.0 4 votes vote down vote up
@Override
public BufferedImage getAvatarWithStatus(LocalMember member) {
    BufferedImage avatar = getAvatar(member.getUser());
    BufferedImage statusLayer = getStatusLayer(null, OnlineStatus.OFFLINE);
    return getAvatarWithStatus(avatar, statusLayer);
}
 
Example #24
Source File: PresenceProviderConfig.java    From JDA with Apache License 2.0 4 votes vote down vote up
public void setStatusProvider(@Nullable IntFunction<OnlineStatus> statusProvider)
{
    this.statusProvider = statusProvider;
}
 
Example #25
Source File: MemberImpl.java    From JDA with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public OnlineStatus getOnlineStatus()
{
    return onlineStatus;
}
 
Example #26
Source File: MemberImpl.java    From JDA with Apache License 2.0 4 votes vote down vote up
public MemberImpl setOnlineStatus(OnlineStatus onlineStatus)
{
    this.onlineStatus = onlineStatus;
    return this;
}
 
Example #27
Source File: EntityBuilder.java    From JDA with Apache License 2.0 4 votes vote down vote up
public void createPresence(MemberImpl member, DataObject presenceJson)
{
    if (member == null)
        throw new NullPointerException("Provided member was null!");
    boolean cacheGame = getJDA().isCacheFlagSet(CacheFlag.ACTIVITY);
    boolean cacheStatus = getJDA().isCacheFlagSet(CacheFlag.CLIENT_STATUS);

    DataArray activityArray = !cacheGame || presenceJson.isNull("activities") ? null : presenceJson.getArray("activities");
    DataObject clientStatusJson = !cacheStatus || presenceJson.isNull("client_status") ? null : presenceJson.getObject("client_status");
    OnlineStatus onlineStatus = OnlineStatus.fromKey(presenceJson.getString("status"));
    List<Activity> activities = new ArrayList<>();
    boolean parsedActivity = false;

    if (cacheGame && activityArray != null)
    {
        for (int i = 0; i < activityArray.length(); i++)
        {
            try
            {
                activities.add(createActivity(activityArray.getObject(i)));
                parsedActivity = true;
            }
            catch (Exception ex)
            {
                String userId;
                userId = member.getUser().getId();
                if (LOG.isDebugEnabled())
                    LOG.warn("Encountered exception trying to parse a presence! UserId: {} JSON: {}", userId, activityArray, ex);
                else
                    LOG.warn("Encountered exception trying to parse a presence! UserId: {} Message: {} Enable debug for details", userId, ex.getMessage());
            }
        }
    }
    if (cacheGame && parsedActivity)
        member.setActivities(activities);
    member.setOnlineStatus(onlineStatus);
    if (clientStatusJson != null)
    {
        for (String key : clientStatusJson.keys())
        {
            ClientType type = ClientType.fromKey(key);
            OnlineStatus status = OnlineStatus.fromKey(clientStatusJson.getString(key));
            member.setOnlineStatus(type, status);
        }
    }
}
 
Example #28
Source File: DefaultShardManager.java    From JDA with Apache License 2.0 4 votes vote down vote up
@Override
public void setStatusProvider(IntFunction<OnlineStatus> statusProvider)
{
    ShardManager.super.setStatusProvider(statusProvider);
    presenceConfig.setStatusProvider(statusProvider);
}
 
Example #29
Source File: DiscordMethods.java    From SkyBot with GNU Affero General Public License v3.0 4 votes vote down vote up
private static Member getRandomOnlineMember(Environment environment) throws ParseException {
    return getRandomMember(environment, (member) -> member.getOnlineStatus() == OnlineStatus.ONLINE);
}
 
Example #30
Source File: UserInfoCommand.java    From JuniperBot with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean doCommand(MemberReference reference, GuildMessageReceivedEvent event, BotContext context, String query) {
    DateTimeFormatter formatter = DateTimeFormat.mediumDateTime()
            .withLocale(contextService.getLocale())
            .withZone(context.getTimeZone());

    LocalMember localMember = reference.getLocalMember();
    LocalUser localUser = reference.getLocalUser();

    EmbedBuilder builder = messageService.getBaseEmbed();
    builder.setTitle(messageService.getMessage("discord.command.user.title", reference.getEffectiveName()));
    builder.setThumbnail(reference.getEffectiveAvatarUrl());
    builder.setFooter(messageService.getMessage("discord.command.info.identifier", reference.getId()), null);

    StringBuilder commonBuilder = new StringBuilder();
    getName(commonBuilder, reference);

    if (reference.getMember() != null) {
        Member member = reference.getMember();
        getOnlineStatus(commonBuilder, member);
        if (CollectionUtils.isNotEmpty(member.getActivities())) {
            getActivities(commonBuilder, member);
        }
        if (member.getOnlineStatus() == OnlineStatus.OFFLINE || member.getOnlineStatus() == OnlineStatus.INVISIBLE) {
            if (localUser != null && localUser.getLastOnline() != null) {
                getLastOnlineAt(commonBuilder, localUser, formatter);
            }
        }
        getJoinedAt(commonBuilder, member, formatter);
        getCreatedAt(commonBuilder, member.getUser(), formatter);
    }

    builder.addField(messageService.getMessage("discord.command.user.common"), commonBuilder.toString(), false);

    Guild guild = event.getGuild();

    if (localMember != null) {
        RankingConfig config = rankingConfigService.get(event.getGuild());
        if (config != null && config.isEnabled()) {
            RankingInfo info = rankingService.getRankingInfo(event.getGuild().getIdLong(), reference.getId());
            rankCommand.addFields(builder, config, info, guild);
        }
    }

    MemberBio memberBio = bioRepository.findByGuildIdAndUserId(guild.getIdLong(), reference.getId());
    String bio = memberBio != null ? memberBio.getBio() : null;
    if (StringUtils.isEmpty(bio)
            && Objects.equals(event.getAuthor(), reference.getUser())
            && !commandsService.isRestricted(BioCommand.KEY, event.getChannel(), event.getMember())) {
        String bioCommand = messageService.getMessageByLocale("discord.command.bio.key",
                context.getCommandLocale());
        bio = messageService.getMessage("discord.command.user.bio.none", context.getConfig().getPrefix(),
                bioCommand);
    }
    if (StringUtils.isNotEmpty(bio)) {
        builder.setDescription(CommonUtils.trimTo(bio, MessageEmbed.TEXT_MAX_LENGTH));
    }
    messageService.sendMessageSilent(event.getChannel()::sendMessage, builder.build());
    return true;
}