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

The following examples show how to use net.dv8tion.jda.api.entities.Activity. 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: 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 #2
Source File: PresenceUpdateHandler.java    From JDA with Apache License 2.0 6 votes vote down vote up
private boolean parseActivities(long userId, DataArray activityArray, List<Activity> newActivities)
{
    boolean parsedActivity = false;
    try
    {
        if (activityArray != null)
        {
            for (int i = 0; i < activityArray.length(); i++)
                newActivities.add(EntityBuilder.createActivity(activityArray.getObject(i)));
            parsedActivity = true;
        }
    }
    catch (Exception ex)
    {
        if (EntityBuilder.LOG.isDebugEnabled())
            EntityBuilder.LOG.warn("Encountered exception trying to parse a presence! UserID: {} JSON: {}", userId, activityArray, ex);
        else
            EntityBuilder.LOG.warn("Encountered exception trying to parse a presence! UserID: {} Message: {} Enable debug for details", userId, ex.getMessage());
    }
    return parsedActivity;
}
 
Example #3
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 #4
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 #5
Source File: PresenceImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
private DataObject getGameJson(Activity activity)
{
    if (activity == null || activity.getName() == null || activity.getType() == null)
        return null;
    DataObject gameObj = DataObject.empty();
    gameObj.put("name", activity.getName());
    gameObj.put("type", activity.getType().getKey());
    if (activity.getUrl() != null)
        gameObj.put("url", activity.getUrl());

    return gameObj;
}
 
Example #6
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 #7
Source File: PresenceProviderConfig.java    From JDA with Apache License 2.0 4 votes vote down vote up
public void setActivityProvider(@Nullable IntFunction<? extends Activity> activityProvider)
{
    this.activityProvider = activityProvider;
}
 
Example #8
Source File: SkyBot.java    From SkyBot with GNU Affero General Public License v3.0 4 votes vote down vote up
private SkyBot() throws Exception {
        // Set our animated emotes as default reactions
        MessageUtils.setErrorReaction("a:_no:577795484060483584");
        MessageUtils.setSuccessReaction("a:_yes:577795293546938369");

        // Load in our container
        final Variables variables = new Variables();
        final DunctebotConfig config = variables.getConfig();
        final CommandManager commandManager = variables.getCommandManager();
        final Logger logger = LoggerFactory.getLogger(SkyBot.class);

        // Set the user-agent of the bot
        WebUtils.setUserAgent("Mozilla/5.0 (compatible; SkyBot/" + Settings.VERSION + "; +https://dunctebot.com;)");
        EmbedUtils.setEmbedBuilder(
            () -> new EmbedBuilder()
                .setColor(Settings.DEFAULT_COLOUR)
//                .setFooter("DuncteBot", Settings.DEFAULT_ICON)
//                .setTimestamp(Instant.now())
        );

        Settings.PREFIX = config.discord.prefix;

        // Set some defaults for rest-actions
        RestAction.setPassContext(true);
        RestAction.setDefaultFailure(ignore(UNKNOWN_MESSAGE));
        // If any rest-action doesn't get executed within 2 minutes we will mark it as failed
        RestAction.setDefaultTimeout(2L, TimeUnit.MINUTES);

        if (variables.useApi()) {
            logger.info(TextColor.GREEN + "Using api for all connections" + TextColor.RESET);
        } else {
            logger.warn("Using SQLite as the database");
            logger.warn("Please note that is is not recommended for production");
        }

        //Load the settings before loading the bot
        GuildSettingsUtils.loadAllSettings(variables);

        //Set the token to a string
        final String token = config.discord.token;

        //But this time we are going to shard it
        final int totalShards = config.discord.totalShards;

        this.activityProvider = (shardId) -> Activity.playing(
            config.discord.prefix + "help | Shard " + (shardId + 1)
        );

        final LongLongPair commandCount = commandManager.getCommandCount();

        logger.info("{} commands with {} aliases loaded.", commandCount.getFirst(), commandCount.getSecond());
        LavalinkManager.ins.start(config, variables.getAudioUtils());

        final EventManager eventManager = new EventManager(variables);
        // Build our shard manager
        final DefaultShardManagerBuilder builder = DefaultShardManagerBuilder.create(
            GatewayIntent.GUILD_MEMBERS,
            GatewayIntent.GUILD_BANS,
            GatewayIntent.GUILD_EMOJIS,
            GatewayIntent.GUILD_VOICE_STATES,
            GatewayIntent.GUILD_MESSAGES
        )
            .setToken(token)
            .setShardsTotal(totalShards)
            .setActivityProvider(this.activityProvider)
            .setBulkDeleteSplittingEnabled(false)
            .setEventManagerProvider((id) -> eventManager)
            // Keep guild owners, voice members and patrons in cache
            .setMemberCachePolicy(MemberCachePolicy.DEFAULT.or(PATRON_POLICY))
//            .setMemberCachePolicy(MemberCachePolicy.NONE)
            // Enable lazy loading
            .setChunkingFilter(ChunkingFilter.NONE)
            // Enable lazy loading for guilds other than our own
//            .setChunkingFilter((guildId) -> guildId == Settings.SUPPORT_GUILD_ID)
            .enableCache(CacheFlag.VOICE_STATE, CacheFlag.EMOTE, CacheFlag.MEMBER_OVERRIDES)
            .disableCache(CacheFlag.ACTIVITY, CacheFlag.CLIENT_STATUS)
            .setHttpClientBuilder(
                new OkHttpClient.Builder()
                    .connectTimeout(30L, TimeUnit.SECONDS)
                    .readTimeout(30L, TimeUnit.SECONDS)
                    .writeTimeout(30L, TimeUnit.SECONDS)
            );

        this.startGameTimer();

        // If lavalink is enabled we will hook it into jda
        if (LavalinkManager.ins.isEnabled()) {
            builder.setVoiceDispatchInterceptor(LavalinkManager.ins.getLavalink().getVoiceInterceptor());
        }

        this.shardManager = builder.build();

        HelpEmbeds.init(commandManager);

        // Load the web server if we are not running "locally"
        // TODO: change this config value to "web_server" or something
        if (!config.discord.local) {
            webRouter = new WebRouter(shardManager, variables);
        }
    }
 
Example #9
Source File: PresenceProviderConfig.java    From JDA with Apache License 2.0 4 votes vote down vote up
@Nullable
public IntFunction<? extends Activity> getActivityProvider()
{
    return activityProvider;
}
 
Example #10
Source File: PresenceImpl.java    From JDA with Apache License 2.0 4 votes vote down vote up
public PresenceImpl setCacheActivity(Activity game)
{
    this.activity = game;
    return this;
}
 
Example #11
Source File: PresenceImpl.java    From JDA with Apache License 2.0 4 votes vote down vote up
@Override
public void setPresence(Activity game, boolean idle)
{
    setPresence(status, game, idle);
}
 
Example #12
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 #13
Source File: PresenceImpl.java    From JDA with Apache License 2.0 4 votes vote down vote up
@Override
public void setActivity(Activity game)
{
    setPresence(status, game);
}
 
Example #14
Source File: PresenceImpl.java    From JDA with Apache License 2.0 4 votes vote down vote up
@Override
public Activity getActivity()
{
    return activity;
}
 
Example #15
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 #16
Source File: UserActivityStartEvent.java    From JDA with Apache License 2.0 4 votes vote down vote up
public UserActivityStartEvent(@Nonnull JDA api, long responseNumber, @Nonnull Member member, @Nonnull Activity newActivity)
{
    super(api, responseNumber, member.getUser());
    this.newActivity = newActivity;
    this.member = member;
}
 
Example #17
Source File: UserActivityEndEvent.java    From JDA with Apache License 2.0 4 votes vote down vote up
/**
 * The old activity
 *
 * @return The old activity
 */
@Nonnull
public Activity getOldActivity()
{
    return oldActivity;
}
 
Example #18
Source File: UserActivityEndEvent.java    From JDA with Apache License 2.0 4 votes vote down vote up
public UserActivityEndEvent(@Nonnull JDA api, long responseNumber, @Nonnull Member member, @Nonnull Activity oldActivity)
{
    super(api, responseNumber, member.getUser());
    this.oldActivity = oldActivity;
    this.member = member;
}
 
Example #19
Source File: UserUpdateActivityOrderEvent.java    From JDA with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public List<Activity> getNewValue()
{
    return super.getNewValue();
}
 
Example #20
Source File: UserUpdateActivityOrderEvent.java    From JDA with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public List<Activity> getOldValue()
{
    return super.getOldValue();
}
 
Example #21
Source File: UserUpdateActivityOrderEvent.java    From JDA with Apache License 2.0 4 votes vote down vote up
public UserUpdateActivityOrderEvent(@Nonnull JDAImpl api, long responseNumber, @Nonnull List<Activity> previous, @Nonnull Member member)
{
    super(api, responseNumber, member.getUser(), previous, member.getActivities(), IDENTIFIER);
    this.member = member;
}
 
Example #22
Source File: DefaultShardManager.java    From JDA with Apache License 2.0 4 votes vote down vote up
@Override
public void setActivityProvider(IntFunction<? extends Activity> activityProvider)
{
    ShardManager.super.setActivityProvider(activityProvider);
    presenceConfig.setActivityProvider(activityProvider);
}
 
Example #23
Source File: JDABuilder.java    From JDA with Apache License 2.0 3 votes vote down vote up
/**
 * Sets the {@link net.dv8tion.jda.api.entities.Activity Activity} for our session.
 * <br>This value can be changed at any time in the {@link net.dv8tion.jda.api.managers.Presence Presence} from a JDA instance.
 *
 * <p><b>Hint:</b> You can create a {@link net.dv8tion.jda.api.entities.Activity Activity} object using
 * {@link net.dv8tion.jda.api.entities.Activity#playing(String)} or {@link net.dv8tion.jda.api.entities.Activity#streaming(String, String)}.
 *
 * @param  activity
 *         An instance of {@link net.dv8tion.jda.api.entities.Activity Activity} (null allowed)
 *
 * @return The JDABuilder instance. Useful for chaining.
 *
 * @see    net.dv8tion.jda.api.managers.Presence#setActivity(net.dv8tion.jda.api.entities.Activity)  Presence.setActivity(Activity)
 */
@Nonnull
public JDABuilder setActivity(@Nullable Activity activity)
{
    this.activity = activity;
    return this;
}
 
Example #24
Source File: DefaultShardManagerBuilder.java    From JDA with Apache License 2.0 3 votes vote down vote up
/**
 * Sets the {@link net.dv8tion.jda.api.entities.Activity Activity} for our session.
 * <br>This value can be changed at any time in the {@link net.dv8tion.jda.api.managers.Presence Presence} from a JDA instance.
 *
 * <p><b>Hint:</b> You can create a {@link net.dv8tion.jda.api.entities.Activity Activity} object using
 * {@link net.dv8tion.jda.api.entities.Activity#playing(String) Activity.playing(String)} or
 * {@link net.dv8tion.jda.api.entities.Activity#streaming(String, String) Activity.streaming(String, String)}.
 *
 * @param  activityProvider
 *         An instance of {@link net.dv8tion.jda.api.entities.Activity Activity} (null allowed)
 *
 * @return The DefaultShardManagerBuilder instance. Useful for chaining.
 *
 * @see    net.dv8tion.jda.api.managers.Presence#setActivity(net.dv8tion.jda.api.entities.Activity)
 */
@Nonnull
public DefaultShardManagerBuilder setActivityProvider(@Nullable final IntFunction<? extends Activity> activityProvider)
{
    this.activityProvider = activityProvider;
    return this;
}
 
Example #25
Source File: UserActivityStartEvent.java    From JDA with Apache License 2.0 2 votes vote down vote up
/**
 * The new activity
 *
 * @return The activity
 */
public Activity getNewActivity()
{
    return newActivity;
}
 
Example #26
Source File: DefaultShardManagerBuilder.java    From JDA with Apache License 2.0 2 votes vote down vote up
/**
 * Sets the {@link net.dv8tion.jda.api.entities.Activity Activity} for our session.
 * <br>This value can be changed at any time in the {@link net.dv8tion.jda.api.managers.Presence Presence} from a JDA instance.
 *
 * <p><b>Hint:</b> You can create a {@link net.dv8tion.jda.api.entities.Activity Activity} object using
 * {@link net.dv8tion.jda.api.entities.Activity#playing(String) Activity.playing(String)} or
 * {@link net.dv8tion.jda.api.entities.Activity#streaming(String, String)} Activity.streaming(String, String)}.
 *
 * @param  activity
 *         An instance of {@link net.dv8tion.jda.api.entities.Activity Activity} (null allowed)
 *
 * @return The DefaultShardManagerBuilder instance. Useful for chaining.
 *
 * @see    net.dv8tion.jda.api.managers.Presence#setActivity(net.dv8tion.jda.api.entities.Activity)
 */
@Nonnull
public DefaultShardManagerBuilder setActivity(@Nullable final Activity activity)
{
    return this.setActivityProvider(id -> activity);
}
 
Example #27
Source File: Presence.java    From JDA with Apache License 2.0 2 votes vote down vote up
/**
 * Sets two presence fields of this session.
 * <br>The third field stays untouched.
 *
 * @param  activity
 *         The {@link net.dv8tion.jda.api.entities.Activity Activity} for this session
 *         (See {@link #setActivity(net.dv8tion.jda.api.entities.Activity)} for more info)
 * @param  idle
 *         Whether to mark this session as idle (useful for client accounts {@link #setIdle(boolean)})
 */
void setPresence(@Nullable Activity activity, boolean idle);
 
Example #28
Source File: Presence.java    From JDA with Apache License 2.0 2 votes vote down vote up
/**
 * Sets two presence fields of this session.
 * <br>The third field stays untouched.
 *
 * @param  status
 *         The {@link net.dv8tion.jda.api.OnlineStatus OnlineStatus} for this session
 *         (See {@link #setStatus(OnlineStatus)})
 * @param  activity
 *         The {@link net.dv8tion.jda.api.entities.Activity Activity} for this session
 *         (See {@link #setActivity(net.dv8tion.jda.api.entities.Activity)} for more info)
 *
 * @throws java.lang.IllegalArgumentException
 *         If the specified OnlineStatus is {@link net.dv8tion.jda.api.OnlineStatus#UNKNOWN UNKNOWN}
 */
void setPresence(@Nullable OnlineStatus status, @Nullable Activity activity);
 
Example #29
Source File: Presence.java    From JDA with Apache License 2.0 2 votes vote down vote up
/**
 * Sets all presence fields of this session.
 *
 * @param  status
 *         The {@link net.dv8tion.jda.api.OnlineStatus OnlineStatus} for this session
 *         (See {@link #setStatus(OnlineStatus)})
 * @param  activity
 *         The {@link net.dv8tion.jda.api.entities.Activity Activity} for this session
 *         (See {@link #setActivity(net.dv8tion.jda.api.entities.Activity)} for more info)
 * @param  idle
 *         Whether to mark this session as idle (useful for client accounts {@link #setIdle(boolean)})
 *
 * @throws java.lang.IllegalArgumentException
 *         If the specified OnlineStatus is {@link net.dv8tion.jda.api.OnlineStatus#UNKNOWN UNKNOWN}
 */
void setPresence(@Nullable OnlineStatus status, @Nullable Activity activity, boolean idle);
 
Example #30
Source File: Presence.java    From JDA with Apache License 2.0 2 votes vote down vote up
/**
 * Sets the {@link net.dv8tion.jda.api.entities.Activity Activity} for this session.
 * <br>A Activity can be retrieved via {@link net.dv8tion.jda.api.entities.Activity#playing(String)}.
 * For streams you provide a valid streaming url as second parameter
 *
 * <p>Examples:
 * <br>{@code presence.setActivity(Activity.playing("Thrones"));}
 * <br>{@code presence.setActivity(Activity.streaming("Thrones", "https://twitch.tv/EasterEggs"));}
 *
 * @param  activity
 *         A {@link net.dv8tion.jda.api.entities.Activity Activity} instance or null to reset
 *
 * @see    net.dv8tion.jda.api.entities.Activity#playing(String)
 * @see    net.dv8tion.jda.api.entities.Activity#streaming(String, String)
 */
void setActivity(@Nullable Activity activity);