idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
30,800
public static MessageBuilder fromMessage ( Message message ) { MessageBuilder builder = new MessageBuilder ( ) ; builder . getStringBuilder ( ) . append ( message . getContent ( ) ) ; if ( ! message . getEmbeds ( ) . isEmpty ( ) ) { builder . setEmbed ( message . getEmbeds ( ) . get ( 0 ) . toBuilder ( ) ) ; } for ( Me...
Creates a message builder from a message .
30,801
public MessageBuilder appendCode ( String language , String code ) { delegate . appendCode ( language , code ) ; return this ; }
Appends code to the message .
30,802
public MessageBuilder append ( String message , MessageDecoration ... decorations ) { delegate . append ( message , decorations ) ; return this ; }
Appends a sting with or without decoration to the message .
30,803
public MessageBuilder addAttachment ( BufferedImage image , String fileName ) { delegate . addAttachment ( image , fileName ) ; return this ; }
Adds an attachment to the message .
30,804
public MessageBuilder addAttachmentAsSpoiler ( InputStream stream , String fileName ) { delegate . addAttachment ( stream , "SPOILER_" + fileName ) ; return this ; }
Adds an attachment to the message and marks it as spoiler .
30,805
public void addReaction ( Emoji emoji , boolean you ) { Optional < Reaction > reaction = reactions . stream ( ) . filter ( r -> emoji . equalsEmoji ( r . getEmoji ( ) ) ) . findAny ( ) ; reaction . ifPresent ( r -> ( ( ReactionImpl ) r ) . incrementCount ( you ) ) ; if ( ! reaction . isPresent ( ) ) { reactions . add (...
Adds an emoji to the list of reactions .
30,806
public void removeReaction ( Emoji emoji , boolean you ) { Optional < Reaction > reaction = reactions . stream ( ) . filter ( r -> emoji . equalsEmoji ( r . getEmoji ( ) ) ) . findAny ( ) ; reaction . ifPresent ( r -> ( ( ReactionImpl ) r ) . decrementCount ( you ) ) ; reactions . removeIf ( r -> r . getCount ( ) <= 0 ...
Removes an emoji from the list of reactions .
30,807
public static List < Class < ? > > getInterfaces ( Class < ? > clazz ) { return getInterfacesAsStream ( clazz ) . collect ( Collectors . toList ( ) ) ; }
Get all interfaces of the given class including extended interfaces and interfaces of all superclasses . If the given class is an interface it will be included in the result otherwise not .
30,808
public static Stream < Class < ? > > getInterfacesAsStream ( Class < ? > clazz ) { return getSuperclassesAsStream ( clazz , true ) . flatMap ( superClass -> Stream . concat ( superClass . isInterface ( ) ? Stream . of ( superClass ) : Stream . empty ( ) , Arrays . stream ( superClass . getInterfaces ( ) ) . flatMap ( C...
Get a stream of all interfaces of the given class including extended interfaces and interfaces of all superclasses . If the given class is an interface it will be included in the result otherwise not .
30,809
public static List < Class < ? > > getSuperclasses ( Class < ? > clazz ) { return getSuperclassesAsStream ( clazz ) . collect ( Collectors . toList ( ) ) ; }
Get all superclasses of the given class . If the given class is an interface the result will be empty . The given class will not be included in the result .
30,810
public void clean ( ) { Instant minAge = Instant . now ( ) . minus ( storageTimeInSeconds , ChronoUnit . SECONDS ) ; synchronized ( messages ) { messages . removeIf ( messageRef -> Optional . ofNullable ( messageRef . get ( ) ) . map ( message -> ! message . isCachedForever ( ) && message . getCreationTimestamp ( ) . i...
Cleans the cache .
30,811
public List < FileContainer > getRequiredAttachments ( ) { List < FileContainer > requiredAttachments = new ArrayList < > ( ) ; if ( footerIconContainer != null ) { requiredAttachments . add ( footerIconContainer ) ; } if ( imageContainer != null ) { requiredAttachments . add ( imageContainer ) ; } if ( authorIconConta...
Gets the required attachments for this embed .
30,812
public static Logger getLogger ( String name ) { AtomicBoolean logWarning = new AtomicBoolean ( false ) ; initialized . updateAndGet ( initialized -> { if ( ! initialized && ! ProviderUtil . hasProviders ( ) ) { noLogger . set ( true ) ; logWarning . set ( true ) ; } return true ; } ) ; if ( noLogger . get ( ) ) { retu...
Get or create a logger with the given name .
30,813
public static void setDebug ( boolean debug ) { FallbackLoggerConfiguration . debug . set ( debug ) ; if ( ! debug ) { trace . set ( false ) ; } }
Sets whether debug logging should be enabled . Disabling debug logging automatically disables trace logging too .
30,814
public static void setTrace ( boolean trace ) { FallbackLoggerConfiguration . trace . set ( trace ) ; if ( trace ) { debug . set ( true ) ; } }
Sets whether trace logging should be enabled . Enabling trace logging automatically enables debug logging too .
30,815
private void handleServerVoiceChannel ( JsonNode channelJson ) { long serverId = channelJson . get ( "guild_id" ) . asLong ( ) ; long channelId = channelJson . get ( "id" ) . asLong ( ) ; api . getPossiblyUnreadyServerById ( serverId ) . ifPresent ( server -> server . getVoiceChannelById ( channelId ) . ifPresent ( cha...
Handles server voice channel deletion .
30,816
private void handlePrivateChannel ( JsonNode channel ) { UserImpl recipient = ( UserImpl ) api . getOrCreateUser ( channel . get ( "recipients" ) . get ( 0 ) ) ; recipient . getPrivateChannel ( ) . ifPresent ( privateChannel -> { PrivateChannelDeleteEvent event = new PrivateChannelDeleteEventImpl ( privateChannel ) ; a...
Handles a private channel deletion .
30,817
private void handleGroupChannel ( JsonNode channel ) { long channelId = channel . get ( "id" ) . asLong ( ) ; api . getGroupChannelById ( channelId ) . ifPresent ( groupChannel -> { GroupChannelDeleteEvent event = new GroupChannelDeleteEventImpl ( groupChannel ) ; api . getEventDispatcher ( ) . dispatchGroupChannelDele...
Handles a group channel deletion .
30,818
private void dispatchServerChannelDeleteEvent ( ServerChannel channel ) { ServerChannelDeleteEvent event = new ServerChannelDeleteEventImpl ( channel ) ; api . getEventDispatcher ( ) . dispatchServerChannelDeleteEvent ( ( DispatchQueueSelector ) channel . getServer ( ) , channel . getServer ( ) , channel , event ) ; }
Dispatches a server channel delete event .
30,819
public CompletableFuture < byte [ ] > asByteArray ( DiscordApi api ) { CompletableFuture < byte [ ] > future = new CompletableFuture < > ( ) ; try { if ( fileAsByteArray != null ) { future . complete ( fileAsByteArray ) ; return future ; } if ( fileAsBufferedImage != null || fileAsFile != null || fileAsIcon != null || ...
Gets the byte array for the file .
30,820
public CompletableFuture < InputStream > asInputStream ( DiscordApi api ) { CompletableFuture < InputStream > future = new CompletableFuture < > ( ) ; try { if ( fileAsBufferedImage != null ) { ByteArrayOutputStream os = new ByteArrayOutputStream ( ) ; ImageIO . write ( fileAsBufferedImage , getFileType ( ) , os ) ; fu...
Gets the input stream for the file .
30,821
public < T extends Permissionable & DiscordEntity > ServerChannelUpdater addPermissionOverwrite ( T permissionable , Permissions permissions ) { delegate . addPermissionOverwrite ( permissionable , permissions ) ; return this ; }
Adds a permission overwrite for the given entity .
30,822
public PermissionsBuilder setState ( PermissionType type , PermissionState state ) { delegate . setState ( type , state ) ; return this ; }
Sets the new state of the given type .
30,823
public static UnicodeEmojiImpl fromString ( String emoji ) { return unicodeEmojis . computeIfAbsent ( emoji , key -> new UnicodeEmojiImpl ( emoji ) ) ; }
Gets a unicode emoji by its string representation .
30,824
public EmbedBuilder setFooter ( String text , InputStream icon ) { delegate . setFooter ( text , icon ) ; return this ; }
Sets the footer of the embed . This method assumes the file type is png !
30,825
public EmbedBuilder addInlineField ( String name , String value ) { delegate . addField ( name , value , true ) ; return this ; }
Adds an inline field to the embed .
30,826
public EmbedBuilder addField ( String name , String value ) { delegate . addField ( name , value , false ) ; return this ; }
Adds a non - inline field to the embed .
30,827
public EmbedBuilder addField ( String name , String value , boolean inline ) { delegate . addField ( name , value , inline ) ; return this ; }
Adds a field to the embed .
30,828
public EmbedBuilder updateFields ( Predicate < EmbedField > predicate , Consumer < EditableEmbedField > updater ) { delegate . updateFields ( predicate , updater ) ; return this ; }
Updates all fields of the embed that satisfy the given predicate using the given updater .
30,829
public EmbedBuilder updateAllFields ( Consumer < EditableEmbedField > updater ) { delegate . updateFields ( field -> true , updater ) ; return this ; }
Updates all fields of the embed using the given updater .
30,830
private void handleResponse ( RestRequest < ? > request , RestRequestResult result , RatelimitBucket bucket , long responseTimestamp ) { if ( result == null || result . getResponse ( ) == null ) { return ; } Response response = result . getResponse ( ) ; boolean global = response . header ( "X-RateLimit-Global" , "fals...
Updates the ratelimit information and sets the result if the request was successful .
30,831
private void calculateOffset ( long currentTime , RestRequestResult result ) { if ( ( api . getTimeOffset ( ) != null ) || ( result == null ) || ( result . getResponse ( ) == null ) ) { return ; } synchronized ( api ) { if ( api . getTimeOffset ( ) == null ) { String date = result . getResponse ( ) . header ( "Date" ) ...
Calculates the offset of the local time and discord s time .
30,832
public Optional < String > getMajorUrlParameter ( ) { if ( customMajorParam != null ) { return Optional . of ( customMajorParam ) ; } Optional < Integer > majorParameterPosition = endpoint . getMajorParameterPosition ( ) ; if ( ! majorParameterPosition . isPresent ( ) ) { return Optional . empty ( ) ; } if ( majorParam...
Gets the major url parameter of this request . If an request has a major parameter it means that the ratelimits for this request are based on this parameter .
30,833
public RestRequest < T > addQueryParameter ( String key , String value ) { queryParameters . put ( key , value ) ; return this ; }
Adds a query parameter to the url .
30,834
public CompletableFuture < T > execute ( Function < RestRequestResult , T > function ) { api . getRatelimitManager ( ) . queueRequest ( this ) ; CompletableFuture < T > future = new CompletableFuture < > ( ) ; result . whenComplete ( ( result , throwable ) -> { if ( throwable != null ) { future . completeExceptionally ...
Executes the request . This will automatically retry if we hit a ratelimit .
30,835
public RestRequestInformation asRestRequestInformation ( ) { try { return new RestRequestInformationImpl ( api , new URL ( endpoint . getFullUrl ( urlParameters ) ) , queryParameters , headers , body ) ; } catch ( MalformedURLException e ) { throw new AssertionError ( e ) ; } }
Gets the information for this rest request .
30,836
private void handleChannelCategory ( JsonNode jsonChannel ) { long channelCategoryId = jsonChannel . get ( "id" ) . asLong ( ) ; api . getChannelCategoryById ( channelCategoryId ) . map ( ChannelCategoryImpl . class :: cast ) . ifPresent ( channel -> { boolean oldNsfwFlag = channel . isNsfw ( ) ; boolean newNsfwFlag = ...
Handles a channel category update .
30,837
private void handleServerTextChannel ( JsonNode jsonChannel ) { long channelId = jsonChannel . get ( "id" ) . asLong ( ) ; api . getTextChannelById ( channelId ) . map ( c -> ( ( ServerTextChannelImpl ) c ) ) . ifPresent ( channel -> { String oldTopic = channel . getTopic ( ) ; String newTopic = jsonChannel . has ( "to...
Handles a server text channel update .
30,838
private void handleServerVoiceChannel ( JsonNode jsonChannel ) { long channelId = jsonChannel . get ( "id" ) . asLong ( ) ; api . getServerVoiceChannelById ( channelId ) . map ( ServerVoiceChannelImpl . class :: cast ) . ifPresent ( channel -> { int oldBitrate = channel . getBitrate ( ) ; int newBitrate = jsonChannel ....
Handles a server voice channel update .
30,839
private void handleGroupChannel ( JsonNode jsonChannel ) { long channelId = jsonChannel . get ( "id" ) . asLong ( ) ; api . getGroupChannelById ( channelId ) . map ( GroupChannelImpl . class :: cast ) . ifPresent ( channel -> { String oldName = channel . getName ( ) . orElseThrow ( AssertionError :: new ) ; String newN...
Handles a group channel update .
30,840
private void dispatchServerChannelChangeOverwrittenPermissionsEvent ( ServerChannel channel , Permissions newPermissions , Permissions oldPermissions , DiscordEntity entity ) { if ( newPermissions . equals ( oldPermissions ) ) { return ; } ServerChannelChangeOverwrittenPermissionsEvent event = new ServerChannelChangeOv...
Dispatches a ServerChannelChangeOverwrittenPermissionsEvent .
30,841
public void purgeCache ( ) { synchronized ( users ) { users . values ( ) . stream ( ) . map ( Reference :: get ) . filter ( Objects :: nonNull ) . map ( Cleanupable . class :: cast ) . forEach ( Cleanupable :: cleanup ) ; users . clear ( ) ; } userIdByRef . clear ( ) ; servers . values ( ) . stream ( ) . map ( Cleanupa...
Purges all cached entities . This method is only meant to be called after receiving a READY packet .
30,842
public Collection < Server > getAllServers ( ) { ArrayList < Server > allServers = new ArrayList < > ( nonReadyServers . values ( ) ) ; allServers . addAll ( servers . values ( ) ) ; return Collections . unmodifiableList ( allServers ) ; }
Gets a collection with all servers including ready and not ready ones .
30,843
public Optional < Server > getPossiblyUnreadyServerById ( long id ) { if ( nonReadyServers . containsKey ( id ) ) { return Optional . ofNullable ( nonReadyServers . get ( id ) ) ; } return Optional . ofNullable ( servers . get ( id ) ) ; }
Gets a server by it s id including ready and not ready ones .
30,844
public void addServerToCache ( ServerImpl server ) { removeServerFromCache ( server . getId ( ) ) ; nonReadyServers . put ( server . getId ( ) , server ) ; server . addServerReadyConsumer ( s -> { nonReadyServers . remove ( s . getId ( ) ) ; removeUnavailableServerFromCache ( s . getId ( ) ) ; servers . put ( s . getId...
Adds the given server to the cache .
30,845
public void removeServerFromCache ( long serverId ) { servers . computeIfPresent ( serverId , ( key , server ) -> { ( ( Cleanupable ) server ) . cleanup ( ) ; return null ; } ) ; nonReadyServers . computeIfPresent ( serverId , ( key , server ) -> { ( ( Cleanupable ) server ) . cleanup ( ) ; return null ; } ) ; }
Removes the given server from the cache .
30,846
public void addUserToCache ( User user ) { users . compute ( user . getId ( ) , ( key , value ) -> { Optional . ofNullable ( value ) . map ( Reference :: get ) . filter ( oldUser -> oldUser != user ) . map ( Cleanupable . class :: cast ) . ifPresent ( Cleanupable :: cleanup ) ; WeakReference < User > result = new WeakR...
Adds the given user to the cache .
30,847
public void addChannelToCache ( Channel channel ) { Channel oldChannel = channels . put ( channel . getId ( ) , channel ) ; if ( oldChannel != channel && oldChannel instanceof Cleanupable ) { ( ( Cleanupable ) oldChannel ) . cleanup ( ) ; } }
Adds a channel to the cache .
30,848
public void removeChannelFromCache ( long channelId ) { channels . computeIfPresent ( channelId , ( key , channel ) -> { if ( channel instanceof Cleanupable ) { ( ( Cleanupable ) channel ) . cleanup ( ) ; } return null ; } ) ; }
Removes a channel from the cache .
30,849
public User getOrCreateUser ( JsonNode data ) { long id = Long . parseLong ( data . get ( "id" ) . asText ( ) ) ; synchronized ( users ) { return getCachedUserById ( id ) . orElseGet ( ( ) -> { if ( ! data . has ( "username" ) ) { throw new IllegalStateException ( "Couldn't get or created user. Please inform the develo...
Gets a user or creates a new one from the given data .
30,850
public KnownCustomEmoji getOrCreateKnownCustomEmoji ( Server server , JsonNode data ) { long id = Long . parseLong ( data . get ( "id" ) . asText ( ) ) ; return customEmojis . computeIfAbsent ( id , key -> new KnownCustomEmojiImpl ( this , server , data ) ) ; }
Gets or creates a new known custom emoji object .
30,851
public Message getOrCreateMessage ( TextChannel channel , JsonNode data ) { long id = Long . parseLong ( data . get ( "id" ) . asText ( ) ) ; synchronized ( messages ) { return getCachedMessageById ( id ) . orElseGet ( ( ) -> new MessageImpl ( this , channel , data ) ) ; } }
Gets or creates a new message object .
30,852
@ SuppressWarnings ( "unchecked" ) public < T extends ObjectAttachableListener > ListenerManager < T > addObjectListener ( Class < ? > objectClass , long objectId , Class < T > listenerClass , T listener ) { Map < ObjectAttachableListener , ListenerManagerImpl < ? extends ObjectAttachableListener > > listeners = object...
Adds an object listener . Adding a listener multiple times to the same object will only add it once and return the same listener manager on each invocation . The order of invocation is according to first addition .
30,853
public < T extends ObjectAttachableListener > void removeObjectListener ( Class < ? > objectClass , long objectId , Class < T > listenerClass , T listener ) { synchronized ( objectListeners ) { if ( objectClass == null ) { return ; } Map < Long , Map < Class < ? extends ObjectAttachableListener > , Map < ObjectAttachab...
Removes an object listener .
30,854
public void removeObjectListeners ( Class < ? > objectClass , long objectId ) { if ( objectClass == null ) { return ; } synchronized ( objectListeners ) { Map < Long , Map < Class < ? extends ObjectAttachableListener > , Map < ObjectAttachableListener , ListenerManagerImpl < ? extends ObjectAttachableListener > > > > o...
Remove all listeners attached to an object .
30,855
@ SuppressWarnings ( "unchecked" ) public < T extends ObjectAttachableListener > List < T > getObjectListeners ( Class < ? > objectClass , long objectId , Class < T > listenerClass ) { return Collections . unmodifiableList ( ( List < T > ) Optional . ofNullable ( objectClass ) . map ( objectListeners :: get ) . map ( o...
Gets all object listeners of the given class .
30,856
private void updateActivity ( ActivityType type , String name , String streamingUrl ) { if ( name == null ) { activity = null ; } else if ( streamingUrl == null ) { activity = new ActivityImpl ( type , name , null ) ; } else { activity = new ActivityImpl ( type , name , streamingUrl ) ; } websocketAdapter . updateStatu...
Sets the current activity along with type and streaming Url .
30,857
public MessageSet getCachedMessagesWhere ( Predicate < Message > filter ) { synchronized ( messages ) { return messages . values ( ) . stream ( ) . map ( Reference :: get ) . filter ( Objects :: nonNull ) . filter ( filter ) . collect ( Collectors . toCollection ( MessageSetImpl :: new ) ) ; } }
Get messages from the cache that satisfy a given condition .
30,858
public void forEachCachedMessageWhere ( Predicate < Message > filter , Consumer < Message > action ) { synchronized ( messages ) { messages . values ( ) . stream ( ) . map ( Reference :: get ) . filter ( Objects :: nonNull ) . filter ( filter ) . forEach ( action ) ; } }
Execute a task for every message in cache that satisfied a given condition .
30,859
public int getTimeTillSpaceGetsAvailable ( ) { long globalRatelimitResetTimestamp = RatelimitBucket . globalRatelimitResetTimestamp . getOrDefault ( api . getToken ( ) , 0L ) ; long timestamp = System . currentTimeMillis ( ) + ( api . getTimeOffset ( ) == null ? 0 : api . getTimeOffset ( ) ) ; if ( ratelimitRemaining >...
Gets the time in seconds how long you have to wait till there s space in the bucket again .
30,860
private void handleChannelCategory ( JsonNode channel ) { long serverId = channel . get ( "guild_id" ) . asLong ( ) ; api . getPossiblyUnreadyServerById ( serverId ) . ifPresent ( server -> { ChannelCategory channelCategory = ( ( ServerImpl ) server ) . getOrCreateChannelCategory ( channel ) ; ServerChannelCreateEvent ...
Handles channel category creation .
30,861
private void handleServerTextChannel ( JsonNode channel ) { long serverId = channel . get ( "guild_id" ) . asLong ( ) ; api . getPossiblyUnreadyServerById ( serverId ) . ifPresent ( server -> { ServerTextChannel textChannel = ( ( ServerImpl ) server ) . getOrCreateServerTextChannel ( channel ) ; ServerChannelCreateEven...
Handles server text channel creation .
30,862
private void handleServerVoiceChannel ( JsonNode channel ) { long serverId = channel . get ( "guild_id" ) . asLong ( ) ; api . getPossiblyUnreadyServerById ( serverId ) . ifPresent ( server -> { ServerVoiceChannel voiceChannel = ( ( ServerImpl ) server ) . getOrCreateServerVoiceChannel ( channel ) ; ServerChannelCreate...
Handles server voice channel creation .
30,863
private void handlePrivateChannel ( JsonNode channel ) { UserImpl recipient = ( UserImpl ) api . getOrCreateUser ( channel . get ( "recipients" ) . get ( 0 ) ) ; if ( ! recipient . getPrivateChannel ( ) . isPresent ( ) ) { PrivateChannel privateChannel = recipient . getOrCreateChannel ( channel ) ; PrivateChannelCreate...
Handles a private channel creation .
30,864
private void handleGroupChannel ( JsonNode channel ) { long channelId = channel . get ( "id" ) . asLong ( ) ; if ( ! api . getGroupChannelById ( channelId ) . isPresent ( ) ) { GroupChannel groupChannel = new GroupChannelImpl ( api , channel ) ; GroupChannelCreateEvent event = new GroupChannelCreateEventImpl ( groupCha...
Handles a group channel creation .
30,865
public void addServerReadyConsumer ( Consumer < Server > consumer ) { synchronized ( readyConsumers ) { if ( ready ) { consumer . accept ( this ) ; } else { readyConsumers . add ( consumer ) ; } } }
Adds a consumer which will be informed once the server is ready . If the server is already ready it will immediately call the consumer otherwise it will be called from the websocket reading thread .
30,866
public Role getOrCreateRole ( JsonNode data ) { long id = Long . parseLong ( data . get ( "id" ) . asText ( ) ) ; synchronized ( this ) { return getRoleById ( id ) . orElseGet ( ( ) -> { Role role = new RoleImpl ( api , this , data ) ; this . roles . put ( role . getId ( ) , role ) ; return role ; } ) ; } }
Gets or create a new role .
30,867
public ChannelCategory getOrCreateChannelCategory ( JsonNode data ) { long id = Long . parseLong ( data . get ( "id" ) . asText ( ) ) ; ChannelType type = ChannelType . fromId ( data . get ( "type" ) . asInt ( ) ) ; synchronized ( this ) { if ( type == ChannelType . CHANNEL_CATEGORY ) { return getChannelCategoryById ( ...
Gets or creates a channel category .
30,868
public ServerTextChannel getOrCreateServerTextChannel ( JsonNode data ) { long id = Long . parseLong ( data . get ( "id" ) . asText ( ) ) ; ChannelType type = ChannelType . fromId ( data . get ( "type" ) . asInt ( ) ) ; synchronized ( this ) { if ( type == ChannelType . SERVER_TEXT_CHANNEL || type == ChannelType . SERV...
Gets or creates a server text channel .
30,869
public ServerVoiceChannel getOrCreateServerVoiceChannel ( JsonNode data ) { long id = Long . parseLong ( data . get ( "id" ) . asText ( ) ) ; ChannelType type = ChannelType . fromId ( data . get ( "type" ) . asInt ( ) ) ; synchronized ( this ) { if ( type == ChannelType . SERVER_VOICE_CHANNEL ) { return getVoiceChannel...
Gets or creates a server voice channel .
30,870
public void removeMember ( User user ) { long userId = user . getId ( ) ; members . remove ( userId ) ; nicknames . remove ( userId ) ; selfMuted . remove ( userId ) ; selfDeafened . remove ( userId ) ; muted . remove ( userId ) ; deafened . remove ( userId ) ; getRoles ( ) . forEach ( role -> ( ( RoleImpl ) role ) . r...
Removes a member from the server .
30,871
public void addMember ( JsonNode member ) { User user = api . getOrCreateUser ( member . get ( "user" ) ) ; members . put ( user . getId ( ) , user ) ; if ( member . hasNonNull ( "nick" ) ) { nicknames . put ( user . getId ( ) , member . get ( "nick" ) . asText ( ) ) ; } if ( member . hasNonNull ( "mute" ) ) { setMuted...
Adds a member to the server .
30,872
public void setNickname ( User user , String nickname ) { nicknames . compute ( user . getId ( ) , ( key , value ) -> nickname ) ; }
Sets the nickname of the user .
30,873
public void setSelfMuted ( long userId , boolean muted ) { if ( muted ) { selfMuted . add ( userId ) ; } else { selfMuted . remove ( userId ) ; } }
Sets the self - muted state of the user with the given id .
30,874
public void setSelfDeafened ( long userId , boolean deafened ) { if ( deafened ) { selfDeafened . add ( userId ) ; } else { selfDeafened . remove ( userId ) ; } }
Sets the self - deafened state of the user with the given id .
30,875
public void setMuted ( long userId , boolean muted ) { if ( muted ) { this . muted . add ( userId ) ; } else { this . muted . remove ( userId ) ; } }
Sets the muted state of the user with the given id .
30,876
public void setDeafened ( long userId , boolean deafened ) { if ( deafened ) { this . deafened . add ( userId ) ; } else { this . deafened . remove ( userId ) ; } }
Sets the deafened state of the user with the given id .
30,877
private void dispatchEditEvent ( MessageEditEvent event ) { Optional < Server > optionalServer = event . getChannel ( ) . asServerChannel ( ) . map ( ServerChannel :: getServer ) ; api . getEventDispatcher ( ) . dispatchMessageEditEvent ( optionalServer . map ( DispatchQueueSelector . class :: cast ) . orElse ( api ) ,...
Dispatches an edit event .
30,878
public void addEntries ( JsonNode data ) { for ( JsonNode webhookJson : data . get ( "webhooks" ) ) { boolean alreadyAdded = involvedWebhooks . stream ( ) . anyMatch ( webhook -> webhook . getId ( ) == webhookJson . get ( "id" ) . asLong ( ) ) ; if ( ! alreadyAdded ) { involvedWebhooks . add ( new WebhookImpl ( api , w...
Adds entries to the audit log .
30,879
public void handlePacket ( final JsonNode packet ) { if ( async ) { executorService . submit ( ( ) -> { try { handle ( packet ) ; } catch ( Throwable t ) { logger . warn ( "Couldn't handle packet of type {}. Please contact the developer! (packet: {})" , getType ( ) , packet , t ) ; } } ) ; } else { try { handle ( packe...
Handles the packet .
30,880
private static String getGateway ( DiscordApiImpl api ) { gatewayReadLock . lock ( ) ; if ( gateway == null ) { gatewayReadLock . unlock ( ) ; gatewayWriteLock . lock ( ) ; try { if ( gateway == null ) { gateway = new RestRequest < String > ( api , RestMethod . GET , RestEndpoint . GATEWAY ) . includeAuthorizationHeade...
Gets the gateway used to connect . If no gateway was requested or set so far it will request one from Discord .
30,881
public static void setGateway ( String gateway ) { gatewayWriteLock . lock ( ) ; try { DiscordWebSocketAdapter . gateway = gateway ; } finally { gatewayWriteLock . unlock ( ) ; } }
Sets the gateway used to connect .
30,882
public void disconnect ( ) { reconnect = false ; websocket . get ( ) . sendClose ( WebSocketCloseReason . DISCONNECT . getNumericCloseCode ( ) ) ; api . getThreadPool ( ) . getDaemonScheduler ( ) . schedule ( ( ) -> heartbeatTimer . updateAndGet ( future -> { if ( future != null ) { future . cancel ( false ) ; } return...
Disconnects from the websocket .
30,883
private void waitForIdentifyRateLimit ( ) { String token = api . getPrefixedToken ( ) ; connectionDelaySemaphorePerAccount . computeIfAbsent ( token , key -> new Semaphore ( 1 ) ) . acquireUninterruptibly ( ) ; for ( long delay = 5100 - ( System . currentTimeMillis ( ) - lastIdentificationPerAccount . getOrDefault ( to...
Identification is rate limited to once every 5 seconds so don t try to more often per account even in different instances . This method waits for the identification rate limit to be over then returns .
30,884
private Future < ? > startHeartbeat ( final WebSocket websocket , final int heartbeatInterval ) { heartbeatAckReceived . set ( true ) ; return api . getThreadPool ( ) . getScheduler ( ) . scheduleWithFixedDelay ( ( ) -> { try { if ( heartbeatAckReceived . getAndSet ( false ) ) { sendHeartbeat ( websocket ) ; logger . d...
Starts the heartbeat .
30,885
private void sendHeartbeat ( WebSocket websocket ) { ObjectNode heartbeatPacket = JsonNodeFactory . instance . objectNode ( ) ; heartbeatPacket . put ( "op" , GatewayOpcode . HEARTBEAT . getCode ( ) ) ; heartbeatPacket . put ( "d" , lastSeq ) ; WebSocketFrame heartbeatFrame = WebSocketFrame . createTextFrame ( heartbea...
Sends the heartbeat .
30,886
private void sendResume ( WebSocket websocket ) { ObjectNode resumePacket = JsonNodeFactory . instance . objectNode ( ) . put ( "op" , GatewayOpcode . RESUME . getCode ( ) ) ; resumePacket . putObject ( "d" ) . put ( "token" , api . getPrefixedToken ( ) ) . put ( "session_id" , sessionId ) . put ( "seq" , lastSeq ) ; l...
Sends the resume packet .
30,887
private void sendIdentify ( WebSocket websocket ) { ObjectNode identifyPacket = JsonNodeFactory . instance . objectNode ( ) . put ( "op" , GatewayOpcode . IDENTIFY . getCode ( ) ) ; ObjectNode data = identifyPacket . putObject ( "d" ) ; String token = api . getPrefixedToken ( ) ; data . put ( "token" , token ) . put ( ...
Sends the identify packet .
30,888
public void sendVoiceStateUpdate ( Server server , ServerVoiceChannel channel , Boolean selfMuted , Boolean selfDeafened ) { ObjectNode updateVoiceStatePacket = JsonNodeFactory . instance . objectNode ( ) . put ( "op" , GatewayOpcode . VOICE_STATE_UPDATE . getCode ( ) ) ; if ( server == null ) { if ( channel == null ) ...
Sends the voice state update packet .
30,889
private void registerHandlers ( ) { addHandler ( new ReadyHandler ( api ) ) ; addHandler ( new ResumedHandler ( api ) ) ; addHandler ( new GuildBanAddHandler ( api ) ) ; addHandler ( new GuildBanRemoveHandler ( api ) ) ; addHandler ( new GuildCreateHandler ( api ) ) ; addHandler ( new GuildDeleteHandler ( api ) ) ; add...
Registers all handlers .
30,890
public void updateStatus ( ) { Optional < Activity > activity = api . getActivity ( ) ; ObjectNode updateStatus = JsonNodeFactory . instance . objectNode ( ) . put ( "op" , GatewayOpcode . STATUS_UPDATE . getCode ( ) ) ; ObjectNode data = updateStatus . putObject ( "d" ) . put ( "status" , api . getStatus ( ) . getStat...
Sends the update status packet .
30,891
public void queueRequestGuildMembers ( Server server ) { logger . debug ( "Queued {} for request guild members packet" , server ) ; requestGuildMembersQueue . add ( server . getId ( ) ) ; }
Adds a server id to be queued for the request guild members packet .
30,892
public static < T > Indexed < T > index ( long index , T value ) { return new Indexed < > ( index , value ) ; }
Combine an index and a value into an indexed value .
30,893
public static < S , O > Transition < S , O > to ( S newState , O ... outputs ) { return to ( newState , Stream . of ( outputs ) ) ; }
Create a transition to a new state with zero or more outputs .
30,894
public static < S , O > Transition < S , O > to ( S newState , Stream < O > outputs ) { return new Transition < > ( newState , outputs ) ; }
Create a transition to a new state with the given outputs .
30,895
public static < T , Y extends Comparable < Y > > Collector < T , ? , Optional < T > > maxBy ( Function < T , Y > projection ) { return maxBy ( projection , Comparable :: compareTo ) ; }
Find the item for which the supplied projection returns the maximum value .
30,896
public static < L , R , O > Stream < O > zip ( Stream < L > lefts , Stream < R > rights , BiFunction < L , R , O > combiner ) { return StreamSupport . stream ( ZippingSpliterator . zipping ( lefts . spliterator ( ) , rights . spliterator ( ) , combiner ) , false ) . onClose ( closerFor ( lefts , rights ) ) ; }
Zip together the left and right streams until either runs out of values . Each pair of values is combined into a single value using the supplied combiner function .
30,897
public static < L , M , R , O > Stream < O > zip ( Stream < L > lefts , Stream < M > middles , Stream < R > rights , TriFunction < L , M , R , O > combiner ) { return StreamSupport . stream ( TriZippingSpliterator . zipping ( lefts . spliterator ( ) , middles . spliterator ( ) , rights . spliterator ( ) , combiner ) , ...
Zip together the left middle and right streams until any stream runs out of values . Each triple of values is combined into a single value using the supplied combiner function .
30,898
public static < T , O > Stream < O > zip ( List < Stream < T > > streams , Function < List < T > , O > combiner ) { List < Spliterator < T > > spliterators = streams . stream ( ) . map ( Stream :: spliterator ) . collect ( Collectors . toList ( ) ) ; return StreamSupport . stream ( ListZippingSpliterator . zipping ( sp...
Zip together a list of streams until one of them runs out of values . Each tuple of values is combined into a single value using the supplied combiner function .
30,899
public static < T > Stream < T > takeWhile ( Stream < T > source , Predicate < T > condition ) { return StreamSupport . stream ( TakeWhileSpliterator . over ( source . spliterator ( ) , condition ) , false ) . onClose ( source :: close ) ; }
Construct a stream which takes values from the source stream for as long as they meet the supplied condition and stops as soon as a value is encountered which does not meet the condition .