Search in sources :

Example 1 with DisconnectedEvent

use of sx.blah.discord.handle.impl.events.shard.DisconnectedEvent in project Discord4J by Discord4J.

the class TestBot method main.

/**
 * Starts the bot. This can be done any place you want.
 * The main method is for demonstration.
 *
 * @param args Command line arguments passed to the program.
 */
public static void main(String... args) {
    try {
        if (Discord4J.LOGGER instanceof Discord4J.Discord4JLogger) {
            ((Discord4J.Discord4JLogger) Discord4J.LOGGER).setLevel(Discord4J.Discord4JLogger.Level.TRACE);
        }
        // temp
        Configuration.LOAD_EXTERNAL_MODULES = false;
        boolean isTesting = args[args.length - 1].equals("CITest");
        IDiscordClient client = new ClientBuilder().withToken(args[0]).withPingTimeout(1).build();
        client.getDispatcher().registerListener((IListener<DisconnectedEvent>) (event) -> {
            Discord4J.LOGGER.warn("Client disconnected for reason: {}", event.getReason());
        });
        if (isTesting) {
            // CI Testing
            Discord4J.LOGGER.debug("CI Test Initiated");
            Discord4J.LOGGER.debug("Discord API has a response time of {}ms", DiscordStatus.getAPIResponseTimeForDay());
            for (DiscordStatus.Maintenance maintenance : DiscordStatus.getUpcomingMaintenances()) {
                Discord4J.LOGGER.warn("Discord has upcoming maintenance: {} on {}", maintenance.getName(), maintenance.getStart().toString());
            }
            client.login();
            final AtomicBoolean didTest = new AtomicBoolean(false);
            client.getDispatcher().registerListener(new IListener<ReadyEvent>() {

                @Override
                public void handle(ReadyEvent readyEvent) {
                    try {
                        // Initialize required data
                        final IChannel testChannel = client.getChannelByID(Long.parseUnsignedLong(System.getenv("CHANNEL")));
                        final IChannel spoofChannel = client.getChannelByID(Long.parseUnsignedLong(System.getenv("SPOOF_CHANNEL")));
                        String buildNumber = System.getenv("BUILD_ID");
                        IVoiceChannel channel = client.getVoiceChannels().stream().filter(voiceChannel -> voiceChannel.getName().equalsIgnoreCase("Annoying Shit")).findFirst().orElse(null);
                        if (channel != null) {
                            channel.join();
                            // Mono test
                            AudioPlayer.getAudioPlayerForGuild(channel.getGuild()).queue(new File("./test.mp3"));
                            // Mono test
                            AudioPlayer.getAudioPlayerForGuild(channel.getGuild()).queue(new File("./test.flac"));
                            // Stereo test
                            AudioPlayer.getAudioPlayerForGuild(channel.getGuild()).queue(new File("./test2.mp3"));
                            // Stereo test
                            AudioPlayer.getAudioPlayerForGuild(channel.getGuild()).queue(new File("./test2.flac"));
                        }
                        // Start testing
                        new MessageBuilder(client).withChannel(testChannel).withContent("Initiating Discord4J Unit Tests for Build #" + buildNumber, MessageBuilder.Styles.BOLD).build();
                        // Clearing spoofbot's mess from before
                        synchronized (client) {
                            for (IMessage message : spoofChannel.getMessageHistory()) {
                                RequestBuffer.request(() -> {
                                    try {
                                        message.delete();
                                    } catch (MissingPermissionsException | DiscordException e) {
                                        e.printStackTrace();
                                    }
                                });
                            }
                        }
                        // Time to unleash the ai
                        SpoofBot spoofBot = new SpoofBot(client, System.getenv("SPOOF"), Long.parseUnsignedLong(System.getenv("SPOOF_CHANNEL")));
                        final long now = System.currentTimeMillis();
                        new Thread(() -> {
                            while (!didTest.get()) {
                                if (now + MAX_TEST_TIME <= System.currentTimeMillis()) {
                                    // Test timer up!
                                    synchronized (client) {
                                        try {
                                            new MessageBuilder(client).withChannel(testChannel).withContent("Success! The build is complete. See the log here: " + CI_URL + buildNumber, MessageBuilder.Styles.BOLD).build();
                                        } catch (RateLimitException | MissingPermissionsException | DiscordException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                    didTest.set(true);
                                }
                            }
                        }).start();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            while (!didTest.get()) {
            }
        } else {
            // Dev testing
            client.login();
            client.getDispatcher().registerListener(new IListener<ReadyEvent>() {

                @Override
                public void handle(ReadyEvent event) {
                    Discord4J.LOGGER.info("Connected to {} guilds.", event.getClient().getGuilds().size());
                }
            });
            client.getDispatcher().registerListener(new IListener<MessageReceivedEvent>() {

                @Override
                public void handle(MessageReceivedEvent messageReceivedEvent) {
                    try {
                        IMessage m = messageReceivedEvent.getMessage();
                        if (m.getAuthor().equals(client.getApplicationOwner())) {
                            if (m.getContent().startsWith(".meme") || m.getContent().startsWith(".nicememe")) {
                                try {
                                    new MessageBuilder(client).appendContent("MEMES REQUESTED:", MessageBuilder.Styles.UNDERLINE_BOLD_ITALICS).appendContent(" http://niceme.me/").withChannel(messageReceivedEvent.getMessage().getChannel()).build();
                                } catch (RateLimitException | DiscordException | MissingPermissionsException e) {
                                    e.printStackTrace();
                                }
                            } else if (m.getContent().startsWith(".clear")) {
                                IChannel c = client.getChannelByID(m.getChannel().getLongID());
                                if (null != c) {
                                    c.getMessageHistory().stream().filter(message -> message.getAuthor().getLongID() == client.getOurUser().getLongID()).forEach(message -> {
                                        try {
                                            Discord4J.LOGGER.debug("Attempting deletion of message {} by \"{}\" ({})", message.getStringID(), message.getAuthor().getName(), message.getContent());
                                            message.delete();
                                        } catch (MissingPermissionsException | RateLimitException | DiscordException e) {
                                            e.printStackTrace();
                                        }
                                    });
                                }
                            } else if (m.getContent().startsWith(".name ")) {
                                String s = m.getContent().split(" ", 2)[1];
                                try {
                                    client.changeUsername(s);
                                    m.reply("is this better?");
                                } catch (RateLimitException | MissingPermissionsException | DiscordException e) {
                                    e.printStackTrace();
                                }
                            } else if (m.getContent().startsWith(".pm")) {
                                try {
                                    IPrivateChannel channel = client.getOrCreatePMChannel(m.getAuthor());
                                    new MessageBuilder(client).withChannel(channel).withContent("SUP DUDE").build();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else if (m.getContent().startsWith(".presence")) {
                                client.changePresence(StatusType.IDLE);
                            } else if (m.getContent().startsWith(".game")) {
                                String game = m.getContent().length() > 6 ? m.getContent().substring(6) : null;
                                client.changePresence(StatusType.ONLINE, ActivityType.PLAYING, game);
                            } else if (m.getContent().startsWith(".type")) {
                                m.getChannel().toggleTypingStatus();
                            } else if (m.getContent().startsWith(".invite")) {
                                try {
                                    m.reply("http://discord.gg/" + m.getChannel().createInvite(1800, 0, false, false).getCode());
                                } catch (MissingPermissionsException | RateLimitException | DiscordException e) {
                                    e.printStackTrace();
                                }
                            } else if (m.getContent().startsWith(".avatar")) {
                                try {
                                    if (m.getContent().split(" ").length > 1) {
                                        String url = m.getContent().split(" ")[1];
                                        client.changeAvatar(Image.forUrl(url.substring(url.lastIndexOf('.')), url));
                                    } else {
                                        client.changeAvatar(Image.defaultAvatar());
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else if (m.getContent().startsWith(".permissions")) {
                                if (m.getMentions().size() < 1)
                                    return;
                                StringJoiner roleJoiner = new StringJoiner(", ");
                                StringJoiner permissionsJoiner = new StringJoiner(", ");
                                for (IRole role : m.getMentions().get(0).getRolesForGuild(m.getChannel().getGuild())) {
                                    Discord4J.LOGGER.info("{}", role.getStringID());
                                    for (Permissions permissions : role.getPermissions()) {
                                        permissionsJoiner.add(permissions.toString());
                                    }
                                    roleJoiner.add(role.getName() + " (" + permissionsJoiner.toString() + ")");
                                    permissionsJoiner = new StringJoiner(", ");
                                }
                                try {
                                    Discord4J.LOGGER.info("{}", m.getAuthor().getStringID());
                                    m.reply("This user has the following roles and permissions: " + roleJoiner.toString());
                                } catch (MissingPermissionsException | RateLimitException | DiscordException e) {
                                    e.printStackTrace();
                                }
                            } else if (m.getContent().startsWith(".join")) {
                                IVoiceChannel channel = m.getGuild().getVoiceChannelsByName(m.getContent().split(" ")[1]).get(0);
                                channel.join();
                            } else if (m.getContent().startsWith(".leave")) {
                                IVoiceChannel channel = m.getGuild().getVoiceChannelsByName(m.getContent().split(" ")[1]).get(0);
                                channel.leave();
                            } else if (m.getContent().startsWith(".play")) {
                                AudioPlayer player = AudioPlayer.getAudioPlayerForGuild(m.getGuild());
                                player.queue(new File("./test.mp3"));
                                player.queue(new File("./test.flac"));
                                player.queue(new File("./test2.mp3"));
                                player.queue(new File("./test2.flac"));
                            // player.queue(new URL("https://github.com/austinv11/Discord4J/raw/master/test.mp3"));
                            // player.queue(new URL("https://github.com/austinv11/Discord4J/raw/master/test2.mp3"));
                            } else if (m.getContent().startsWith(".pause")) {
                                AudioPlayer player = AudioPlayer.getAudioPlayerForGuild(m.getGuild());
                                player.setPaused(true);
                            } else if (m.getContent().startsWith(".resume")) {
                                AudioPlayer player = AudioPlayer.getAudioPlayerForGuild(m.getGuild());
                                player.setPaused(false);
                            } else if (m.getContent().startsWith(".volume")) {
                                AudioPlayer player = AudioPlayer.getAudioPlayerForGuild(m.getGuild());
                                player.setVolume(Float.parseFloat(m.getContent().split(" ")[1]));
                            } else if (m.getContent().startsWith(".stop")) {
                                client.getConnectedVoiceChannels().stream().filter((IVoiceChannel channel) -> channel.getGuild().equals(m.getGuild())).findFirst().ifPresent(IVoiceChannel::leave);
                            } else if (m.getContent().startsWith(".skip")) {
                                AudioPlayer player = AudioPlayer.getAudioPlayerForGuild(m.getGuild());
                                player.skip();
                            } else if (m.getContent().startsWith(".toggleloop")) {
                                AudioPlayer player = AudioPlayer.getAudioPlayerForGuild(m.getGuild());
                                player.setLoop(!player.isLooping());
                            } else if (m.getContent().startsWith(".rewind")) {
                                AudioPlayer player = AudioPlayer.getAudioPlayerForGuild(m.getGuild());
                                player.getCurrentTrack().rewind(Long.parseLong(m.getContent().split(" ")[1]));
                            } else if (m.getContent().startsWith(".forward")) {
                                AudioPlayer player = AudioPlayer.getAudioPlayerForGuild(m.getGuild());
                                player.getCurrentTrack().fastForward(Long.parseLong(m.getContent().split(" ")[1]));
                            } else if (m.getContent().startsWith(".shuffle")) {
                                AudioPlayer player = AudioPlayer.getAudioPlayerForGuild(m.getGuild());
                                player.shuffle();
                            } else if (m.getContent().startsWith(".spam")) {
                                new Timer().scheduleAtFixedRate(new TimerTask() {

                                    @Override
                                    public void run() {
                                        RequestBuffer.request(() -> {
                                            try {
                                                return m.getChannel().sendMessage("spam");
                                            } catch (MissingPermissionsException | DiscordException e) {
                                                e.printStackTrace();
                                            }
                                            return null;
                                        });
                                    }
                                }, 0, 50);
                            } else if (m.getContent().startsWith(".move ")) {
                                String target = m.getContent().split(" ")[1];
                                try {
                                    client.getOurUser().moveToVoiceChannel(m.getGuild().getVoiceChannels().stream().filter((IVoiceChannel channel) -> channel.getName().equals(target)).findFirst().orElseGet(null));
                                } catch (DiscordException | RateLimitException | MissingPermissionsException e) {
                                    e.printStackTrace();
                                }
                            } else if (m.getContent().startsWith(".logout")) {
                                client.logout();
                            } else if (m.getContent().startsWith(".test")) {
                                test(m);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                // Used for convenience in testing
                private void test(IMessage message) throws Exception {
                    message.reply(message.getClient().fetchUser(Long.parseUnsignedLong(message.getContent().split(" ")[1])).mention());
                }
            });
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : Configuration(sx.blah.discord.modules.Configuration) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.junit.Test) Timer(java.util.Timer) sx.blah.discord.util(sx.blah.discord.util) File(java.io.File) ReadyEvent(sx.blah.discord.handle.impl.events.ReadyEvent) MessageReceivedEvent(sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent) IDiscordClient(sx.blah.discord.api.IDiscordClient) sx.blah.discord.handle.obj(sx.blah.discord.handle.obj) StringJoiner(java.util.StringJoiner) DisconnectedEvent(sx.blah.discord.handle.impl.events.shard.DisconnectedEvent) AudioPlayer(sx.blah.discord.util.audio.AudioPlayer) IListener(sx.blah.discord.api.events.IListener) TimerTask(java.util.TimerTask) ClientBuilder(sx.blah.discord.api.ClientBuilder) DiscordStatus(sx.blah.discord.api.DiscordStatus) AudioPlayer(sx.blah.discord.util.audio.AudioPlayer) MessageReceivedEvent(sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent) ReadyEvent(sx.blah.discord.handle.impl.events.ReadyEvent) TimerTask(java.util.TimerTask) DisconnectedEvent(sx.blah.discord.handle.impl.events.shard.DisconnectedEvent) StringJoiner(java.util.StringJoiner) ClientBuilder(sx.blah.discord.api.ClientBuilder) IDiscordClient(sx.blah.discord.api.IDiscordClient) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Timer(java.util.Timer) File(java.io.File) DiscordStatus(sx.blah.discord.api.DiscordStatus)

Example 2 with DisconnectedEvent

use of sx.blah.discord.handle.impl.events.shard.DisconnectedEvent in project Discord4J by Discord4J.

the class DiscordWS method onWebSocketClose.

@Override
public void onWebSocketClose(int statusCode, String reason) {
    super.onWebSocketClose(statusCode, reason);
    Discord4J.LOGGER.info(LogMarkers.WEBSOCKET, "Shard {} websocket disconnected with status code {} and reason \"{}\".", shard.getInfo()[0], statusCode, reason);
    isReady = false;
    hasReceivedReady = false;
    heartbeatHandler.shutdown();
    if (!(this.state == State.DISCONNECTING || statusCode == 4003 || statusCode == 4004 || statusCode == 4005 || statusCode == 4010) && !(statusCode == 1001 && reason != null && reason.equals("Shutdown"))) {
        this.state = State.RESUMING;
        client.getDispatcher().dispatch(new DisconnectedEvent(DisconnectedEvent.Reason.ABNORMAL_CLOSE, shard));
        client.reconnectManager.scheduleReconnect(this);
    }
}
Also used : DisconnectedEvent(sx.blah.discord.handle.impl.events.shard.DisconnectedEvent)

Example 3 with DisconnectedEvent

use of sx.blah.discord.handle.impl.events.shard.DisconnectedEvent in project Discord4J by Discord4J.

the class DiscordWS method onWebSocketText.

@Override
public void onWebSocketText(String message) {
    try {
        if (Discord4J.LOGGER.isTraceEnabled(LogMarkers.WEBSOCKET_TRAFFIC)) {
            Discord4J.LOGGER.trace(LogMarkers.WEBSOCKET_TRAFFIC, "Received: " + message);
        }
        JsonNode json = DiscordUtils.MAPPER.readTree(message);
        GatewayOps op = GatewayOps.get(json.get("op").asInt());
        JsonNode d = json.has("d") && !json.get("d").isNull() ? json.get("d") : null;
        if (json.has("s") && !json.get("s").isNull())
            seq = json.get("s").longValue();
        switch(op) {
            case HELLO:
                Discord4J.LOGGER.trace(LogMarkers.WEBSOCKET, "Shard {} _trace: {}", shard.getInfo()[0], d.get("_trace").toString());
                heartbeatHandler.begin(d.get("heartbeat_interval").intValue());
                if (this.state != State.RESUMING) {
                    send(GatewayOps.IDENTIFY, new IdentifyRequest(client.getToken(), shard.getInfo(), identifyPresence));
                } else {
                    client.reconnectManager.onReconnectSuccess();
                    send(GatewayOps.RESUME, new ResumeRequest(client.getToken(), sessionId, seq));
                }
                break;
            case RECONNECT:
                this.state = State.RESUMING;
                client.getDispatcher().dispatch(new DisconnectedEvent(DisconnectedEvent.Reason.RECONNECT_OP, shard));
                heartbeatHandler.shutdown();
                send(GatewayOps.RESUME, new ResumeRequest(client.getToken(), sessionId, seq));
                break;
            case DISPATCH:
                try {
                    dispatchHandler.handle(json);
                } catch (Exception e) {
                    Discord4J.LOGGER.error(LogMarkers.WEBSOCKET, "Discord4J Internal Exception", e);
                }
                break;
            case INVALID_SESSION:
                this.state = State.RECONNECTING;
                client.getDispatcher().dispatch(new DisconnectedEvent(DisconnectedEvent.Reason.INVALID_SESSION_OP, shard));
                invalidate();
                // TODO: try to maintain previous presence?
                send(GatewayOps.IDENTIFY, new IdentifyRequest(client.getToken(), shard.getInfo(), null));
                break;
            case HEARTBEAT:
                send(GatewayOps.HEARTBEAT, seq);
            case HEARTBEAT_ACK:
                heartbeatHandler.ack();
                break;
            case UNKNOWN:
                Discord4J.LOGGER.debug(LogMarkers.WEBSOCKET, "Received unknown opcode, {}", message);
                break;
        }
    } catch (IOException e) {
        Discord4J.LOGGER.error(LogMarkers.WEBSOCKET, "JSON Parsing exception!", e);
    }
}
Also used : IdentifyRequest(sx.blah.discord.api.internal.json.requests.IdentifyRequest) DisconnectedEvent(sx.blah.discord.handle.impl.events.shard.DisconnectedEvent) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) ResumeRequest(sx.blah.discord.api.internal.json.requests.ResumeRequest) ClosedChannelException(java.nio.channels.ClosedChannelException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) UpgradeException(org.eclipse.jetty.websocket.api.UpgradeException) UnresolvedAddressException(java.nio.channels.UnresolvedAddressException)

Example 4 with DisconnectedEvent

use of sx.blah.discord.handle.impl.events.shard.DisconnectedEvent in project Discord4J by Discord4J.

the class ShardImpl method logout.

@Override
public void logout() {
    checkLoggedIn("logout");
    Discord4J.LOGGER.info(LogMarkers.API, "Shard {} logging out.", getInfo()[0]);
    getConnectedVoiceChannels().forEach(channel -> RequestBuffer.request(() -> {
        channel.leave();
        return channel;
    }).get());
    getClient().getDispatcher().dispatch(new DisconnectedEvent(DisconnectedEvent.Reason.LOGGED_OUT, this));
    ws.shutdown();
}
Also used : DisconnectedEvent(sx.blah.discord.handle.impl.events.shard.DisconnectedEvent)

Aggregations

DisconnectedEvent (sx.blah.discord.handle.impl.events.shard.DisconnectedEvent)4 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 File (java.io.File)1 IOException (java.io.IOException)1 UnknownHostException (java.net.UnknownHostException)1 ClosedChannelException (java.nio.channels.ClosedChannelException)1 UnresolvedAddressException (java.nio.channels.UnresolvedAddressException)1 StringJoiner (java.util.StringJoiner)1 Timer (java.util.Timer)1 TimerTask (java.util.TimerTask)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1 UpgradeException (org.eclipse.jetty.websocket.api.UpgradeException)1 Test (org.junit.Test)1 ClientBuilder (sx.blah.discord.api.ClientBuilder)1 DiscordStatus (sx.blah.discord.api.DiscordStatus)1 IDiscordClient (sx.blah.discord.api.IDiscordClient)1 IListener (sx.blah.discord.api.events.IListener)1 IdentifyRequest (sx.blah.discord.api.internal.json.requests.IdentifyRequest)1 ResumeRequest (sx.blah.discord.api.internal.json.requests.ResumeRequest)1