Search in sources :

Example 1 with MessageReceivedEvent

use of sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent in project DisCal-Discord-Bot by NovaFox161.

the class EventListCommand method moduleDay.

@SuppressWarnings("Duplicates")
private void moduleDay(String[] args, MessageReceivedEvent event, GuildSettings settings) {
    if (args.length == 1) {
        // Get the upcoming events in the next 24 hours.
        try {
            Calendar service;
            if (settings.useExternalCalendar()) {
                service = CalendarAuth.getCalendarService(settings);
            } else {
                service = CalendarAuth.getCalendarService();
            }
            DateTime now = new DateTime(System.currentTimeMillis());
            DateTime twentyFourHoursFromNow = new DateTime(now.getValue() + 86400000L);
            CalendarData calendarData = DatabaseManager.getManager().getMainCalendar(event.getGuild().getLongID());
            Events events = service.events().list(calendarData.getCalendarAddress()).setMaxResults(20).setTimeMin(now).setTimeMax(twentyFourHoursFromNow).setOrderBy("startTime").setSingleEvents(true).setShowDeleted(false).execute();
            List<Event> items = events.getItems();
            if (items.size() == 0) {
                Message.sendMessage(MessageManager.getMessage("Event.List.Found.None", settings), event);
            } else if (items.size() == 1) {
                Message.sendMessage(EventMessageFormatter.getEventEmbed(items.get(0), settings), MessageManager.getMessage("Event.List.Found.One", settings), event);
            } else {
                // List events by Id only.
                Message.sendMessage(MessageManager.getMessage("Event.List.Found.Many", "%amount%", items.size() + "", settings), event);
                for (Event e : items) {
                    Message.sendMessage(EventMessageFormatter.getCondensedEventEmbed(e, settings), event);
                }
            }
        } catch (Exception e) {
            Message.sendMessage(MessageManager.getMessage("Notification.Error.Unknown", settings), event);
            Logger.getLogger().exception(event.getAuthor(), "Failed to list events.", e, this.getClass(), true);
            e.printStackTrace();
        }
    }
}
Also used : Events(com.google.api.services.calendar.model.Events) CalendarData(com.cloudcraftgaming.discal.api.object.calendar.CalendarData) Calendar(com.google.api.services.calendar.Calendar) Event(com.google.api.services.calendar.model.Event) MessageReceivedEvent(sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent) DateTime(com.google.api.client.util.DateTime)

Example 2 with MessageReceivedEvent

use of sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent in project DisCal-Discord-Bot by NovaFox161.

the class EventListCommand method moduleSimpleList.

@SuppressWarnings("Duplicates")
private void moduleSimpleList(String[] args, MessageReceivedEvent event, GuildSettings settings) {
    if (args.length == 0) {
        try {
            Calendar service;
            if (settings.useExternalCalendar()) {
                service = CalendarAuth.getCalendarService(settings);
            } else {
                service = CalendarAuth.getCalendarService();
            }
            DateTime now = new DateTime(System.currentTimeMillis());
            CalendarData calendarData = DatabaseManager.getManager().getMainCalendar(event.getGuild().getLongID());
            Events events = service.events().list(calendarData.getCalendarAddress()).setMaxResults(1).setTimeMin(now).setOrderBy("startTime").setSingleEvents(true).setShowDeleted(false).execute();
            List<Event> items = events.getItems();
            if (items.size() == 0) {
                Message.sendMessage(MessageManager.getMessage("Event.List.Found.None", settings), event);
            } else if (items.size() == 1) {
                Message.sendMessage(EventMessageFormatter.getEventEmbed(items.get(0), settings), MessageManager.getMessage("Event.List.Found.One", settings), event);
            }
        } catch (Exception e) {
            Message.sendMessage(MessageManager.getMessage("Notification.Error.Unknown", settings), event);
            Logger.getLogger().exception(event.getAuthor(), "Failed to list events.", e, this.getClass(), true);
            e.printStackTrace();
        }
    } else if (args.length == 1) {
        try {
            Integer eventNum = Integer.valueOf(args[0]);
            if (eventNum > 15) {
                Message.sendMessage(MessageManager.getMessage("Event.List.Amount.Over", settings), event);
                return;
            }
            if (eventNum < 1) {
                Message.sendMessage(MessageManager.getMessage("Event.List.Amount.Under", settings), event);
                return;
            }
            try {
                Calendar service;
                if (settings.useExternalCalendar()) {
                    service = CalendarAuth.getCalendarService(settings);
                } else {
                    service = CalendarAuth.getCalendarService();
                }
                DateTime now = new DateTime(System.currentTimeMillis());
                CalendarData calendarData = DatabaseManager.getManager().getMainCalendar(event.getGuild().getLongID());
                Events events = service.events().list(calendarData.getCalendarAddress()).setMaxResults(eventNum).setTimeMin(now).setOrderBy("startTime").setSingleEvents(true).execute();
                List<Event> items = events.getItems();
                if (items.size() == 0) {
                    Message.sendMessage(MessageManager.getMessage("Event.List.Found.None", settings), event);
                } else if (items.size() == 1) {
                    Message.sendMessage(EventMessageFormatter.getEventEmbed(items.get(0), settings), MessageManager.getMessage("Event.List.Found.One", settings), event);
                } else {
                    // List events by Id only.
                    Message.sendMessage(MessageManager.getMessage("Event.List.Found.Many", "%amount%", items.size() + "", settings), event);
                    for (Event e : items) {
                        Message.sendMessage(EventMessageFormatter.getCondensedEventEmbed(e, settings), event);
                    }
                }
            } catch (Exception e) {
                Message.sendMessage(MessageManager.getMessage("Notification.Error.Unknown", settings), event);
                Logger.getLogger().exception(event.getAuthor(), "Failed to list events.", e, this.getClass(), true);
                e.printStackTrace();
            }
        } catch (NumberFormatException e) {
            Message.sendMessage(MessageManager.getMessage("Notification.Args.Value.Integer", settings), event);
        }
    } else {
        Message.sendMessage(MessageManager.getMessage("Event.List.Args.Many", settings), event);
    }
}
Also used : Events(com.google.api.services.calendar.model.Events) CalendarData(com.cloudcraftgaming.discal.api.object.calendar.CalendarData) Calendar(com.google.api.services.calendar.Calendar) Event(com.google.api.services.calendar.model.Event) MessageReceivedEvent(sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent) ArrayList(java.util.ArrayList) List(java.util.List) DateTime(com.google.api.client.util.DateTime)

Example 3 with MessageReceivedEvent

use of sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent in project DisCal-Discord-Bot by NovaFox161.

the class EventCreator method confirmEvent.

/**
 * Confirms the event in the creator for the specific guild.
 *
 * @param e The event received upon confirmation.
 * @return The response containing detailed info about the confirmation.
 */
public EventCreatorResponse confirmEvent(MessageReceivedEvent e, GuildSettings settings) {
    if (hasPreEvent(e.getGuild().getLongID())) {
        long guildId = e.getGuild().getLongID();
        PreEvent preEvent = getPreEvent(guildId);
        if (preEvent.hasRequiredValues()) {
            Event event = new Event();
            event.setSummary(preEvent.getSummary());
            event.setDescription(preEvent.getDescription());
            event.setStart(preEvent.getStartDateTime().setTimeZone(preEvent.getTimeZone()));
            event.setEnd(preEvent.getEndDateTime().setTimeZone(preEvent.getTimeZone()));
            event.setVisibility("public");
            if (!preEvent.getColor().equals(EventColor.NONE)) {
                event.setColorId(String.valueOf(preEvent.getColor().getId()));
            }
            if (preEvent.getLocation() != null && !preEvent.getLocation().equalsIgnoreCase("")) {
                event.setLocation(preEvent.getLocation());
            }
            // Set recurrence
            if (preEvent.shouldRecur()) {
                String[] recurrence = new String[] { preEvent.getRecurrence().toRRule() };
                event.setRecurrence(Arrays.asList(recurrence));
            }
            // TODO handle multiple calendars...
            String calendarId = DatabaseManager.getManager().getMainCalendar(guildId).getCalendarAddress();
            if (!preEvent.isEditing()) {
                event.setId(KeyGenerator.generateEventId());
                try {
                    Event confirmed;
                    if (settings.useExternalCalendar()) {
                        confirmed = CalendarAuth.getCalendarService(settings).events().insert(calendarId, event).execute();
                    } else {
                        confirmed = CalendarAuth.getCalendarService().events().insert(calendarId, event).execute();
                    }
                    if (preEvent.getEventData().shouldBeSaved()) {
                        preEvent.getEventData().setEventId(confirmed.getId());
                        preEvent.getEventData().setEventEnd(confirmed.getEnd().getDateTime().getValue());
                        DatabaseManager.getManager().updateEventData(preEvent.getEventData());
                    }
                    terminate(e);
                    EventCreatorResponse response = new EventCreatorResponse(true, confirmed);
                    response.setEdited(false);
                    return response;
                } catch (Exception ex) {
                    Logger.getLogger().exception(e.getAuthor(), "Failed to create event.", ex, this.getClass(), true);
                    EventCreatorResponse response = new EventCreatorResponse(false);
                    response.setEdited(false);
                    return response;
                }
            } else {
                try {
                    Event confirmed;
                    if (settings.useExternalCalendar()) {
                        confirmed = CalendarAuth.getCalendarService(settings).events().update(calendarId, preEvent.getEventId(), event).execute();
                    } else {
                        confirmed = CalendarAuth.getCalendarService().events().update(calendarId, preEvent.getEventId(), event).execute();
                    }
                    if (preEvent.getEventData().shouldBeSaved()) {
                        preEvent.getEventData().setEventId(confirmed.getId());
                        preEvent.getEventData().setEventEnd(confirmed.getEnd().getDateTime().getValue());
                        DatabaseManager.getManager().updateEventData(preEvent.getEventData());
                    }
                    terminate(e);
                    EventCreatorResponse response = new EventCreatorResponse(true, confirmed);
                    response.setEdited(true);
                    return response;
                } catch (Exception ex) {
                    Logger.getLogger().exception(e.getAuthor(), "Failed to update event.", ex, this.getClass(), true);
                    EventCreatorResponse response = new EventCreatorResponse(false);
                    response.setEdited(true);
                    return response;
                }
            }
        }
    }
    return new EventCreatorResponse(false);
}
Also used : EventCreatorResponse(com.cloudcraftgaming.discal.api.object.event.EventCreatorResponse) PreEvent(com.cloudcraftgaming.discal.api.object.event.PreEvent) Event(com.google.api.services.calendar.model.Event) MessageReceivedEvent(sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent) PreEvent(com.cloudcraftgaming.discal.api.object.event.PreEvent) IOException(java.io.IOException)

Example 4 with MessageReceivedEvent

use of sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent in project DisCal-Discord-Bot by NovaFox161.

the class EventCreator method edit.

public PreEvent edit(MessageReceivedEvent e, String eventId, GuildSettings settings, boolean handleMessage) {
    long guildId = e.getGuild().getLongID();
    if (!hasPreEvent(guildId)) {
        // TODO: Handle multiple calendars...
        try {
            String calId = DatabaseManager.getManager().getMainCalendar(guildId).getCalendarAddress();
            Calendar service;
            if (settings.useExternalCalendar()) {
                service = CalendarAuth.getCalendarService(settings);
            } else {
                service = CalendarAuth.getCalendarService();
            }
            Event calEvent = service.events().get(calId, eventId).execute();
            PreEvent event = new PreEvent(guildId, calEvent);
            event.setEditing(true);
            try {
                event.setTimeZone(service.calendars().get(calId).execute().getTimeZone());
            } catch (IOException e1) {
            // Failed to get tz, ignore safely.
            }
            if (handleMessage) {
                if (PermissionChecker.botHasMessageManagePerms(e)) {
                    IMessage message = Message.sendMessage(EventMessageFormatter.getPreEventEmbed(event, settings), MessageManager.getMessage("Creator.Event.Edit.Init", settings), e);
                    event.setCreatorMessage(message);
                    Message.deleteMessage(e);
                } else {
                    Message.sendMessage(MessageManager.getMessage("Creator.Notif.MANAGE_MESSAGES", settings), e);
                }
            }
            events.add(event);
            return event;
        } catch (Exception exc) {
        // Oops
        }
        return null;
    }
    return getPreEvent(guildId);
}
Also used : PreEvent(com.cloudcraftgaming.discal.api.object.event.PreEvent) Calendar(com.google.api.services.calendar.Calendar) IMessage(sx.blah.discord.handle.obj.IMessage) Event(com.google.api.services.calendar.model.Event) MessageReceivedEvent(sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent) PreEvent(com.cloudcraftgaming.discal.api.object.event.PreEvent) IOException(java.io.IOException) IOException(java.io.IOException)

Example 5 with MessageReceivedEvent

use of sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent 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

MessageReceivedEvent (sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent)5 Event (com.google.api.services.calendar.model.Event)4 Calendar (com.google.api.services.calendar.Calendar)3 CalendarData (com.cloudcraftgaming.discal.api.object.calendar.CalendarData)2 PreEvent (com.cloudcraftgaming.discal.api.object.event.PreEvent)2 DateTime (com.google.api.client.util.DateTime)2 Events (com.google.api.services.calendar.model.Events)2 IOException (java.io.IOException)2 EventCreatorResponse (com.cloudcraftgaming.discal.api.object.event.EventCreatorResponse)1 File (java.io.File)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 StringJoiner (java.util.StringJoiner)1 Timer (java.util.Timer)1 TimerTask (java.util.TimerTask)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)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