Search in sources :

Example 1 with IDiscordClient

use of sx.blah.discord.api.IDiscordClient in project KaellyBot by Kaysoro.

the class Main method main.

public static void main(String[] args) {
    LoggerFactory.getLogger(Main.class).info("=======================================================");
    LoggerFactory.getLogger(Main.class).info("               " + Constants.name + " v" + Constants.version + " for " + Constants.game);
    LoggerFactory.getLogger(Main.class).info("=======================================================");
    IDiscordClient client = ClientConfig.DISCORD();
    client.getDispatcher().registerListener(new ReadyListener());
}
Also used : ReadyListener(listeners.ReadyListener) IDiscordClient(sx.blah.discord.api.IDiscordClient)

Example 2 with IDiscordClient

use of sx.blah.discord.api.IDiscordClient in project lavaplayer by sedmelluq.

the class Main method main.

public static void main(String[] args) throws Exception {
    IDiscordClient client = new ClientBuilder().withToken(System.getProperty("botToken")).login();
    client.getDispatcher().registerListener(new Main());
}
Also used : IDiscordClient(sx.blah.discord.api.IDiscordClient) ClientBuilder(sx.blah.discord.api.ClientBuilder)

Example 3 with IDiscordClient

use of sx.blah.discord.api.IDiscordClient in project DisCal-Discord-Bot by NovaFox161.

the class DevCommand method moduleEval.

@SuppressWarnings("all")
private void moduleEval(MessageReceivedEvent event) {
    IGuild guild = event.getGuild();
    IUser user = event.getAuthor();
    IMessage message = event.getMessage();
    IDiscordClient client = event.getClient();
    IChannel channel = event.getChannel();
    String input = message.getContent().substring(message.getContent().indexOf("eval") + 5).replaceAll("`", "");
    Object o = null;
    factory.put("guild", guild);
    factory.put("channel", channel);
    factory.put("user", user);
    factory.put("message", message);
    factory.put("command", this);
    factory.put("client", client);
    factory.put("builder", new EmbedBuilder());
    factory.put("cUser", client.getOurUser());
    try {
        o = factory.eval(input);
    } catch (Exception ex) {
        EmbedBuilder em = new EmbedBuilder();
        em.withAuthorIcon(guild.getIconURL());
        em.withAuthorName("Error");
        em.withDesc(ex.getMessage());
        em.withFooterText("Eval failed");
        em.withColor(56, 138, 237);
        Message.sendMessage(em.build(), channel);
        return;
    }
    EmbedBuilder em = new EmbedBuilder();
    em.withAuthorIcon(guild.getIconURL());
    em.withAuthorName("Success!");
    em.withColor(56, 138, 237);
    em.withTitle("Evaluation output.");
    em.withDesc(o == null ? "No output, object is null" : o.toString());
    em.appendField("Input", "```java\n" + input + "\n```", false);
    em.withFooterText("Eval successful!");
    Message.sendMessage(em.build(), channel);
}
Also used : EmbedBuilder(sx.blah.discord.util.EmbedBuilder) IChannel(sx.blah.discord.handle.obj.IChannel) IMessage(sx.blah.discord.handle.obj.IMessage) IUser(sx.blah.discord.handle.obj.IUser) IGuild(sx.blah.discord.handle.obj.IGuild) IDiscordClient(sx.blah.discord.api.IDiscordClient) DiscordException(sx.blah.discord.util.DiscordException)

Example 4 with IDiscordClient

use of sx.blah.discord.api.IDiscordClient in project BoltBot by DiscordBolt.

the class BoltBot method main.

public static void main(String[] args) {
    if (args.length < 1) {
        Logger.error("No Bot Token specified.");
        return;
    }
    try {
        MySQL.getDataSource().getConnection();
    } catch (SQLException e) {
        Logger.error("Can not connect to MySQL database. Configure database.properties");
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e1) {
        }
        System.exit(1);
    }
    IDiscordClient client = new ClientBuilder().withToken(args[0]).login();
    client.getDispatcher().registerListener((IListener<ReadyEvent>) (ReadyEvent e) -> {
        Logger.info("Logged in as " + e.getClient().getOurUser().getName());
        registerModules(client);
    });
}
Also used : ReadyEvent(sx.blah.discord.handle.impl.events.ReadyEvent) SQLException(java.sql.SQLException) IDiscordClient(sx.blah.discord.api.IDiscordClient) ClientBuilder(sx.blah.discord.api.ClientBuilder)

Example 5 with IDiscordClient

use of sx.blah.discord.api.IDiscordClient 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)

Aggregations

IDiscordClient (sx.blah.discord.api.IDiscordClient)12 ClientBuilder (sx.blah.discord.api.ClientBuilder)8 ReadyEvent (sx.blah.discord.handle.impl.events.ReadyEvent)6 DiscordException (sx.blah.discord.util.DiscordException)5 IListener (sx.blah.discord.api.events.IListener)4 File (java.io.File)2 SQLException (java.sql.SQLException)2 IUser (sx.blah.discord.handle.obj.IUser)2 CommandManager (com.discordbolt.api.command.CommandManager)1 DiceModule (com.discordbolt.boltbot.modules.dice.DiceModule)1 DisconnectModule (com.discordbolt.boltbot.modules.disconnect.DisconnectModule)1 CuntModule (com.discordbolt.boltbot.modules.misc.CuntModule)1 TableFixerModule (com.discordbolt.boltbot.modules.misc.TableFixerModule)1 MusicModule (com.discordbolt.boltbot.modules.music.MusicModule)1 RedditModule (com.discordbolt.boltbot.modules.reddit.RedditModule)1 SeenModule (com.discordbolt.boltbot.modules.seen.SeenModule)1 TagModule (com.discordbolt.boltbot.modules.tags.TagModule)1 TwitchModule (com.discordbolt.boltbot.modules.twitch.TwitchModule)1 MySQL (com.discordbolt.boltbot.system.mysql.MySQL)1 DataSync (com.discordbolt.boltbot.system.mysql.data.DataSync)1