@Override public void login(String token, ShardInfo shardInfo, SessionReconnectQueue reconnectQueue) throws LoginException, RateLimitedException { setStatus(Status.LOGGING_IN); if(token == null || token.isEmpty()) throw new LoginException("Provided token was null or empty!"); setToken(token); verifyToken(); this.shardInfo = shardInfo; JDAImpl.LOG.info("Login Successful!"); client = new ClientWebSocketClient(this, reconnectQueue, gatewayClient); client.send(new JSONObject() .put("d", presence.getFullPresence()) .put("op", WebSocketCode.PRESENCE).toString()); if(shutdownHook != null) { Runtime.getRuntime().addShutdownHook(shutdownHook); } }
/** * Starts JDA. * * @return {@code true} if everything went well, {@code false} otherwise. */ private boolean initJda() { try { SimpleLog.Level level = JDAImpl.LOG.getLevel(); SimpleLog.Level socketLevel = WebSocketClient.LOG.getLevel(); JDAImpl.LOG.setLevel(SimpleLog.Level.OFF); WebSocketClient.LOG.setLevel(SimpleLog.Level.OFF); jda = new JDABuilder(AccountType.BOT).setToken(botToken).buildBlocking(); jda.getPresence().setGame(Game.of("2.0.2")); logger.writeFrom("jda", "Successfully connected!"); logger.writeFrom("jda WebSocket", "Connected to WebSocket!"); JDAImpl.LOG.setLevel(level); WebSocketClient.LOG.setLevel(socketLevel); } catch (LoginException | InterruptedException | RateLimitedException e) { logger.writeFrom("jda", "Couldn't connect!"); e.printStackTrace(); return false; } return true; }
@Override protected Long handleInternally(JSONObject content) { final long guildId = content.getLong("guild_id"); List<JSONArray> memberChunks = memberChunksCache.get(guildId); int expectMemberCount = expectedGuildMembers.get(guildId); JSONArray members = content.getJSONArray("members"); JDAImpl.LOG.debug("GUILD_MEMBER_CHUNK for: {}\tMembers: {}", guildId, members.length()); memberChunks.add(members); int currentTotal = 0; for (JSONArray arr : memberChunks) currentTotal += arr.length(); if (currentTotal >= expectMemberCount) { JDAImpl.LOG.debug("Finished chunking for: {}", guildId); api.getEntityBuilder().createGuildSecondPass(guildId, memberChunks); memberChunksCache.remove(guildId); expectedGuildMembers.remove(guildId); } return null; }
@Override protected Long handleInternally(JSONObject content) { final long guildId = content.getLong("id"); if (!api.getGuildMap().containsKey(guildId)) { JDAImpl.LOG.error("Received a GUILD_SYNC for a Guild that does not yet exist in JDA's guild cache. This is a BAD ERROR FOR CLIENTS!"); return null; } GuildImpl guild = (GuildImpl) api.getGuildMap().get(guildId); JSONArray members = content.getJSONArray("members"); JSONArray presences = content.getJSONArray("presences"); api.getEntityBuilder().handleGuildSync(guild, members, presences); return null; }
public AudioWebSocket(ConnectionListener listener, String endpoint, JDAImpl api, Guild guild, String sessionId, String token, boolean shouldReconnect) { this.listener = listener; this.endpoint = endpoint; this.api = api; this.guild = guild; this.sessionId = sessionId; this.token = token; this.shouldReconnect = shouldReconnect; keepAlivePool = api.getAudioKeepAlivePool(); //Append the Secure Websocket scheme so that our websocket library knows how to connect wssEndpoint = String.format("wss://%s/?v=%d", endpoint, AUDIO_GATEWAY_VERSION); if (sessionId == null || sessionId.isEmpty()) throw new IllegalArgumentException("Cannot create a voice connection using a null/empty sessionId!"); if (token == null || token.isEmpty()) throw new IllegalArgumentException("Cannot create a voice connection using a null/empty token!"); }
private synchronized void setupSendSystem() { if (udpSocket != null && !udpSocket.isClosed() && sendHandler != null && sendSystem == null) { IntBuffer error = IntBuffer.allocate(4); opusEncoder = Opus.INSTANCE.opus_encoder_create(OPUS_SAMPLE_RATE, OPUS_CHANNEL_COUNT, Opus.OPUS_APPLICATION_AUDIO, error); IAudioSendFactory factory = ((JDAImpl) channel.getJDA()).getAudioSendFactory(); sendSystem = factory.createSendSystem(new PacketProvider()); sendSystem.setContextMap(contextMap); sendSystem.start(); } else if (sendHandler == null && sendSystem != null) { sendSystem.shutdown(); sendSystem = null; if (opusEncoder != null) { Opus.INSTANCE.opus_encoder_destroy(opusEncoder); opusEncoder = null; } } }
public RichPresence(JDAImpl jda) { //JDA object can be casted to a JDAImpl JSONObject obj = new JSONObject(); JSONObject gameObj = new JSONObject(); /* LAYOUT: * name * details * time elapsed (timestamps) * status */ gameObj.put("name", "Name Here"); gameObj.put("type", 0); //1 if streaming gameObj.put("details", "Details Here"); gameObj.put("state", "Spotify - PLAYING"); gameObj.put("timestamps", new JSONObject().put("start", 1508373056)); //somehow used for the time elapsed thing I assume, you can probably also set the end to make it show "xx:xx left" JSONObject assetsObj = new JSONObject(); assetsObj.put("large_image", "376410582829498368"); //ID of large icon assetsObj.put("large_text", "Large Text"); assetsObj.put("small_image", "376410693861244928"); //ID of small icon gameObj.put("assets", assetsObj); gameObj.put("application_id", "354736186516045835"); //Application ID obj.put("game", gameObj); obj.put("afk", jda.getPresence().isIdle()); obj.put("status", jda.getPresence().getStatus().getKey()); obj.put("since", System.currentTimeMillis()); System.out.println(obj); jda.getClient().send(new JSONObject() .put("d", obj) .put("op", WebSocketCode.PRESENCE).toString()); }
public ClientWebSocketClient(JDAImpl api, SessionReconnectQueue reconnectQueue, GatewayClient gatewayClient) { super(api, reconnectQueue); this.gatewayClient = gatewayClient; try { gatewayClient.register(this); } catch(IOException e) { throw new UncheckedIOException(e); } ratelimitThread.interrupt(); setupSendThread(); }
@Override public void login(String token, ShardInfo shardInfo, SessionReconnectQueue reconnectQueue) throws LoginException, RateLimitedException { setStatus(Status.LOGGING_IN); if(token == null || token.isEmpty()) throw new LoginException("Provided token was null or empty!"); setToken(token); verifyToken(); this.shardInfo = shardInfo; JDAImpl.LOG.info("Login Successful!"); client = new ServerWebSocketClient(this, reconnectQueue, gatewayServer); JSONObject cachedPresence = gatewayServer.cachedPresence; if(cachedPresence != null) { JSONObject game = cachedPresence.optJSONObject("game"); if(game != null) { getPresence().setPresence( OnlineStatus.fromKey(cachedPresence.getString("status")), Game.of(game.getString("name"), game.optString("url")), cachedPresence.getBoolean("afk") ); } else { getPresence().setPresence( OnlineStatus.fromKey(cachedPresence.getString("status")), null, cachedPresence.getBoolean("afk") ); } gatewayServer.cachedPresence = null; } if(shutdownHook != null) { Runtime.getRuntime().addShutdownHook(shutdownHook); } }
public static void setGame() { if (McLink.instance.bot != null) { JSONObject obj = new JSONObject(); JSONObject gameObj = new JSONObject(); gameObj.put("name", "SuperiorNetworks"); gameObj.put("type", 0); gameObj.put("details", "Playing on the lobby"); gameObj.put("state", "SuperiorNetworks - PLAYING"); gameObj.put("timestamps", new JSONObject().put("start", 1508373056)); JSONObject assetsObj = new JSONObject(); assetsObj.put("large_image", "lobby"); assetsObj.put("large_text", "In the lobby"); assetsObj.put("small_image", "lobby"); gameObj.put("assets", assetsObj); gameObj.put("application_id", McLink.instance.bot.bot.getToken()); obj.put("game", gameObj); obj.put("afk", McLink.instance.bot.bot.getPresence().isIdle()); obj.put("status", McLink.instance.bot.bot.getPresence().getStatus().getKey()); obj.put("since", System.currentTimeMillis()); ((JDAImpl) McLink.instance.bot.bot).getClient() .send(new JSONObject().put("d", obj).put("op", WebSocketCode.PRESENCE).toString()); } }
public static void edit(DiscordUser user, DiscordConversation conversation, String message) throws WebhookException { TextChannel channel = (TextChannel) conversation.getChannel(); Guild guild = channel.getGuild(); JDAImpl jda = (JDAImpl) guild.getJDA(); if (!initialized) { Webhook.initBotHooks(jda); initialized = true; } Webhook hook = Webhook.getBotHook(jda, channel); if (hook == null) { throw new WebhookException("creating", channel.getName()); } if (!hook.execute(jda, new JSONObject(new HashMap<String, Object>() { { put("username", user.getUsername()); put("avatar_url", user.getAvatar()); put("content", message); } }))) { throw new WebhookException("sending", channel.getName()); } }
public void setExpectedGuildMembers(long guildId, int count) { if (expectedGuildMembers.containsKey(guildId)) JDAImpl.LOG.warn("Set the count of expected users from GuildMembersChunk even though a value already exists! GuildId: {}", guildId); expectedGuildMembers.put(guildId, count); if (memberChunksCache.containsKey(guildId)) JDAImpl.LOG.warn("Set the memberChunks for MemberChunking for a guild that was already setup for chunking! GuildId: {}", guildId); memberChunksCache.put(guildId, new LinkedList<>()); }
@Override public void appendSession(SessionConnectNode node) { if (queue != null && node.isReconnect()) queue.appendSession(((JDAImpl) node.getJDA()).getClient()); else super.appendSession(node); }
@Override public void removeSession(SessionConnectNode node) { if (queue != null && node.isReconnect()) queue.removeSession(((JDAImpl) node.getJDA()).getClient()); else super.removeSession(node); }
public Attachment(long id, String url, String proxyUrl, String fileName, int size, int height, int width, JDAImpl jda) { this.id = id; this.url = url; this.proxyUrl = proxyUrl; this.fileName = fileName; this.size = size; this.height = height; this.width = width; this.jda = jda; }
/** * Downloads this attachment to given File * * @param file * The file, where the attachment will get downloaded to * * @return boolean true, if successful, otherwise false */ public boolean download(File file) { try { withInputStream((in) -> Files.copy(in, Paths.get(file.getAbsolutePath()))); return true; } catch (Exception e) { JDAImpl.LOG.error("Error while downloading an attachment", e); } return false; }
@Override public void handle(Event event) { for (EventListener listener : listeners) { try { listener.onEvent(event); } catch (Throwable throwable) { JDAImpl.LOG.error("One of the EventListeners had an uncaught exception", throwable); } } }
@Override @SuppressWarnings("unchecked") public void handle(Event event) { Class<? extends Event> eventClass = event.getClass(); do { Map<Object, List<Method>> listeners = methods.get(eventClass); if (listeners != null) { listeners.entrySet().forEach(e -> e.getValue().forEach(method -> { try { method.setAccessible(true); method.invoke(e.getKey(), event); } catch (IllegalAccessException | InvocationTargetException e1) { JDAImpl.LOG.error("Couldn't access annotated eventlistener method", e1); } catch (Throwable throwable) { JDAImpl.LOG.error("One of the EventListeners had an uncaught exception", throwable); } })); } eventClass = eventClass == Event.class ? null : (Class<? extends Event>) eventClass.getSuperclass(); } while (eventClass != null); }
/** * Builds a new {@link net.dv8tion.jda.core.JDA} instance and uses the provided token to start the login process. * <br>The login process runs in a different thread, so while this will return immediately, {@link net.dv8tion.jda.core.JDA} has not * finished loading, thus many {@link net.dv8tion.jda.core.JDA} methods have the chance to return incorrect information. * <br>The main use of this method is to start the JDA connect process and do other things in parallel while startup is * being performed like database connection or local resource loading. * * <p>If you wish to be sure that the {@link net.dv8tion.jda.core.JDA} information is correct, please use * {@link net.dv8tion.jda.core.JDABuilder#buildBlocking() buildBlocking()} or register an * {@link net.dv8tion.jda.core.hooks.EventListener EventListener} to listen for the * {@link net.dv8tion.jda.core.events.ReadyEvent ReadyEvent} . * * @throws LoginException * If the provided token is invalid. * @throws IllegalArgumentException * If the provided token is empty or null. * * @return A {@link net.dv8tion.jda.core.JDA} instance that has started the login process. It is unknown as * to whether or not loading has finished when this returns. */ public JDA buildAsync() throws LoginException { OkHttpClient.Builder httpClientBuilder = this.httpClientBuilder == null ? new OkHttpClient.Builder() : this.httpClientBuilder; WebSocketFactory wsFactory = this.wsFactory == null ? new WebSocketFactory() : this.wsFactory; if (controller == null) { if (reconnectQueue != null || shardRateLimiter != null) controller = new ProvidingSessionController(reconnectQueue, shardRateLimiter); else if (shardInfo != null) controller = new SessionControllerAdapter(); } JDAImpl jda = new JDAImpl(accountType, token, controller, httpClientBuilder, wsFactory, autoReconnect, enableVoice, enableShutdownHook, enableBulkDeleteSplitting, requestTimeoutRetry, enableContext, corePoolSize, maxReconnectDelay, contextMap); if (eventManager != null) jda.setEventManager(eventManager); if (audioSendFactory != null) jda.setAudioSendFactory(audioSendFactory); listeners.forEach(jda::addEventListener); jda.setStatus(JDA.Status.INITIALIZED); //This is already set by JDA internally, but this is to make sure the listeners catch it. String gateway = jda.getGateway(); // Set the presence information before connecting to have the correct information ready when sending IDENTIFY ((PresenceImpl) jda.getPresence()) .setCacheGame(game) .setCacheIdle(idle) .setCacheStatus(status); jda.login(gateway, shardInfo); return jda; }
public AudioConnection(AudioWebSocket webSocket, VoiceChannel channel) { this.channel = channel; this.webSocket = webSocket; this.webSocket.audioConnection = this; final JDAImpl api = (JDAImpl) channel.getJDA(); this.threadIdentifier = api.getIdentifierString() + " AudioConnection Guild: " + channel.getGuild().getId(); this.contextMap = api.getContextMap(); }
public WebSocketClient(JDAImpl api) { this.api = api; this.shardInfo = api.getShardInfo(); this.shouldReconnect = api.isAutoReconnect(); this.connectNode = new StartingNode(); api.getSessionController().appendSession(connectNode); }
public Requester(JDA api, AccountType accountType) { if (accountType == null) throw new NullPointerException("Provided accountType was null!"); this.api = (JDAImpl) api; if (accountType == AccountType.BOT) rateLimiter = new BotRateLimiter(this, 5); else rateLimiter = new ClientRateLimiter(this, 5); this.httpClient = this.api.getHttpClientBuilder().build(); }
public void unlock(long guildId) { if (isLocked(guildId)) { cached.remove(guildId); List<JSONObject> events = cache.remove(guildId); if(events.size() > 0) { LOG.debug("Replaying {} events for unlocked guild with id {}", events.size(), guildId); ((JDAImpl) api).getClient().handle(events); LOG.debug("Finished replaying events for guild with id {}", guildId); } } }
public Request(RestAction<T> restAction, Consumer<T> onSuccess, Consumer<Throwable> onFailure, boolean shouldQueue, RequestBody body, Object rawBody, Route.CompiledRoute route, CaseInsensitiveMap<String, String> headers) { this.restAction = restAction; this.onSuccess = onSuccess; this.onFailure = onFailure; this.shouldQueue = shouldQueue; this.body = body; this.rawBody = rawBody; this.route = route; this.headers = headers; this.api = (JDAImpl) restAction.getJDA(); }
public RestJDA(String token) { fakeJDA = new JDAImpl(AccountType.BOT, token, null, new OkHttpClient.Builder(), null, false, false, false, false, true, false, 2, 900, null); }
public ServerWebSocketClient(JDAImpl api, SessionReconnectQueue reconnectQueue, GatewayServer gatewayServer) { super(api, reconnectQueue); this.gatewayServer = gatewayServer; gatewayServer.register(this); }
VoiceServerUpdateInterceptor(Lavalink lavalink, JDAImpl jda) { super(jda); this.lavalink = lavalink; }
@Override public void onReady(ReadyEvent event) { ((JDAImpl) event.getJDA()).getClient().getHandlers() .put("VOICE_SERVER_UPDATE", new VoiceServerUpdateInterceptor(this, (JDAImpl) event.getJDA())); }
@Override public void onMessage(String message) { JSONObject json = new JSONObject(message); if (!Objects.equals(json.getString("op"), "playerUpdate")) { log.debug(message); } switch (json.getString("op")) { case "sendWS": JDAImpl jda = (JDAImpl) lavalink.getJda(json.getInt("shardId")); jda.getClient().send(json.getString("message")); break; case "validationReq": int sId = LavalinkUtil.getShardFromSnowflake(json.getString("guildId"), lavalink.getNumShards()); JDA jda2 = lavalink.getJda(sId); String guildId = json.getString("guildId"); String channelId = json.optString("channelId"); if (channelId.equals("")) channelId = null; JSONObject res = new JSONObject(); res.put("op", "validationRes"); res.put("guildId", guildId); VoiceChannel vc = null; if (channelId != null) vc = jda2.getVoiceChannelById(channelId); Guild guild = jda2.getGuildById(guildId); if (guild == null && channelId == null) { res.put("valid", false); send(res.toString()); } else if (guild == null) { res.put("valid", false); res.put("channelId", channelId); send(res.toString()); } else if (channelId != null) { res.put("valid", vc != null && PermissionUtil.checkPermission(vc, guild.getSelfMember(), Permission.VOICE_CONNECT, Permission.VOICE_SPEAK)); res.put("channelId", channelId); send(res.toString()); } else { res.put("valid", true); send(res.toString()); } break; case "isConnectedReq": JDAImpl jda3 = (JDAImpl) lavalink.getJda(json.getInt("shardId")); JSONObject res2 = new JSONObject(); res2.put("op", "isConnectedRes"); res2.put("shardId", json.getInt("shardId")); res2.put("connected", jda3.getClient().isConnected()); send(res2.toString()); break; case "playerUpdate": lavalink.getLink(json.getString("guildId")) .getPlayer() .provideState(json.getJSONObject("state")); break; case "stats": stats = new RemoteStats(json); break; case "event": try { handleEvent(json); } catch (IOException e) { throw new RuntimeException(e); } break; default: log.warn("Unexpected operation: " + json.getString("op")); break; } }
/** * This sends OP 4 to Discord. This should close any voice connection for our guild by setting the channel to null. */ private void forcefullyDisconnect() { ((JDAImpl) getJda()).getClient() .send("{\"op\":4,\"d\":{\"self_deaf\":false,\"guild_id\":\"" + guild + "\",\"channel_id\":null,\"self_mute\":false}}"); }
public static void initBotHooks(JDAImpl jda) { for (Guild guild : jda.getGuilds()) { if (!guild.getSelfMember().hasPermission(Permission.MANAGE_WEBHOOKS)) continue; RestAction<JSONArray> action = new RestAction<JSONArray>(jda, Route.Custom.GET_ROUTE.compile("guilds/" + guild.getId() + "/webhooks"), null) { @SuppressWarnings("unchecked") @Override protected void handleResponse(Response response, Request request) { if (response.isOk()) { request.onSuccess(response.getArray()); } else { request.onFailure(response); } } }; try { JSONArray hooks = action.block(); for (Object obj : hooks) { JSONObject hook = (JSONObject) obj; JSONObject user = hook.getJSONObject("user"); String channelId = hook.getString("channel_id"); String id = hook.getString("id"); String token = hook.getString("token"); TextChannel channel = jda.getTextChannelById(channelId); if (user.getString("id").equals(jda.getSelfUser().getId())) { webhooks.put(channel, new Webhook(channel, id, token)); } } } catch (RateLimitedException | ErrorResponseException e) { logger().error("Can't get guild webhooks: ", e); } } }
public static Webhook getBotHook(JDAImpl jda, TextChannel channel) { return !webhooks.containsKey(channel) ? createBotHook(jda, channel) : webhooks.get(channel); }
public CallUpdateHandler(JDAImpl api) { super(api); }
public CallCreateHandler(JDAImpl api) { super(api); }
public ChannelRecipientAddHandler(JDAImpl api) { super(api); }
public ChannelRecipientRemoveHandler(JDAImpl api) { super(api); }
public RelationshipAddHandler(JDAImpl api) { super(api); }
public CallDeleteHandler(JDAImpl api) { super(api); }
public RelationshipRemoveHandler(JDAImpl api) { super(api); }
public JDAClientImpl(JDAImpl api) { this.api = api; this.userSettings = new UserSettingsImpl(api); }