Java源码示例:net.dv8tion.jda.api.entities.Activity
示例1
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;
}
示例2
@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;
}
示例3
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()));
}
示例4
/**
* 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();
}
示例5
@Override
public void setPresenceProvider(IntFunction<OnlineStatus> statusProvider, IntFunction<? extends Activity> activityProvider)
{
ShardManager.super.setPresenceProvider(statusProvider, activityProvider);
presenceConfig.setStatusProvider(statusProvider);
presenceConfig.setActivityProvider(activityProvider);
}
示例6
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;
}
示例7
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);
}
}
示例8
@Override
public void setActivityProvider(IntFunction<? extends Activity> activityProvider)
{
ShardManager.super.setActivityProvider(activityProvider);
presenceConfig.setActivityProvider(activityProvider);
}
示例9
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;
}
示例10
@Nonnull
@Override
public List<Activity> getOldValue()
{
return super.getOldValue();
}
示例11
@Nonnull
@Override
public List<Activity> getNewValue()
{
return super.getNewValue();
}
示例12
public UserActivityEndEvent(@Nonnull JDA api, long responseNumber, @Nonnull Member member, @Nonnull Activity oldActivity)
{
super(api, responseNumber, member.getUser());
this.oldActivity = oldActivity;
this.member = member;
}
示例13
/**
* The old activity
*
* @return The old activity
*/
@Nonnull
public Activity getOldActivity()
{
return oldActivity;
}
示例14
public UserActivityStartEvent(@Nonnull JDA api, long responseNumber, @Nonnull Member member, @Nonnull Activity newActivity)
{
super(api, responseNumber, member.getUser());
this.newActivity = newActivity;
this.member = member;
}
示例15
@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;
}
示例16
@Override
public Activity getActivity()
{
return activity;
}
示例17
@Override
public void setActivity(Activity game)
{
setPresence(status, game);
}
示例18
@Override
public void setPresence(OnlineStatus status, Activity activity)
{
setPresence(status, activity, idle);
}
示例19
@Override
public void setPresence(Activity game, boolean idle)
{
setPresence(status, game, idle);
}
示例20
public PresenceImpl setCacheActivity(Activity game)
{
this.activity = game;
return this;
}
示例21
@Nullable
public IntFunction<? extends Activity> getActivityProvider()
{
return activityProvider;
}
示例22
public void setActivityProvider(@Nullable IntFunction<? extends Activity> activityProvider)
{
this.activityProvider = activityProvider;
}
示例23
/**
* 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;
}
示例24
/**
* 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;
}
示例25
/**
* The current Activity for this session.
* <br>This might not be what the Discord Client displays due to session clashing!
*
* @return The {@link net.dv8tion.jda.api.entities.Activity Activity}
* of the current session or null if no activity is set
*/
@Nullable
Activity getActivity();
示例26
/**
* 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);
示例27
/**
* 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);
示例28
/**
* 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);
示例29
/**
* 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);
示例30
/**
* 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);
}