Search in sources :

Example 1 with MessageContext

use of com.gamebuster19901.excite.bot.command.MessageContext in project ExciteBot by TheGameCommunity.

the class Player method addPlayer.

@SuppressWarnings({ "rawtypes", "unchecked" })
public static Player addPlayer(MessageContext context, boolean automatic, int playerID, String friendCode, String name) throws SQLException {
    if (context.getEvent() instanceof UnknownPlayer) {
        UnknownPlayer player = (UnknownPlayer) context.getEvent();
        player.name = name;
        player.friendCode = friendCode;
    }
    PreparedStatement ps = Insertion.insertInto(PLAYERS).setColumns(PLAYER_ID, FRIEND_CODE, PLAYER_NAME).to(playerID, friendCode, name).prepare(ConsoleContext.INSTANCE);
    ps.execute();
    Player ret = getPlayerByID(context, playerID);
    DiscoveryAudit.addProfileDiscovery(context, automatic, ret);
    return ret;
}
Also used : PreparedStatement(com.gamebuster19901.excite.bot.database.sql.PreparedStatement)

Example 2 with MessageContext

use of com.gamebuster19901.excite.bot.command.MessageContext in project ExciteBot by TheGameCommunity.

the class Player method ban.

@SuppressWarnings({ "rawtypes" })
public Ban ban(MessageContext context, Duration duration, String reason) {
    Ban ban = Ban.addBan(context, this, reason, duration);
    DiscordUser discord = DiscordUser.getDiscordUserIncludingUnknown(context, getDiscord());
    if (!(discord instanceof UnknownDiscordUser)) {
        discord.sendMessage(context, toString() + " " + reason);
    }
    return ban;
}
Also used : DiscordUser(com.gamebuster19901.excite.bot.user.DiscordUser) UnknownDiscordUser(com.gamebuster19901.excite.bot.user.UnknownDiscordUser) UnknownDiscordUser(com.gamebuster19901.excite.bot.user.UnknownDiscordUser) Ban(com.gamebuster19901.excite.bot.audit.ban.Ban)

Example 3 with MessageContext

use of com.gamebuster19901.excite.bot.command.MessageContext in project ExciteBot by TheGameCommunity.

the class Player method toString.

@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public String toString() {
    String name = getName();
    long discordID = getDiscord();
    String prefix = calculatePrefix();
    String suffix = "";
    if (isBot()) {
        suffix += BOT;
    }
    if (discordID != 0) {
        MessageContext context = new MessageContext(DiscordUser.getDiscordUserIncludingUnknown(ConsoleContext.INSTANCE, discordID));
        if (context.isOperator()) {
            suffix = suffix + Emote.getEmote(BOT_OPERATOR);
        } else if (context.isAdmin()) {
            suffix = suffix + Emote.getEmote(BOT_ADMIN);
        }
    }
    if (isLegacy()) {
        suffix += Emote.getEmote(LEGACY);
    }
    if (isVerified()) {
        suffix += Emote.getEmote(VERIFIED);
        if (this.isBanned()) {
            if (!isOnline()) {
                suffix += Emote.getEmote(BANNED);
            }
        }
        return String.format(prefix + " " + name + " - Discord❲" + getPrettyDiscord() + "❳" + suffix);
    } else if (this.isBanned()) {
        if (!isOnline()) {
            suffix += Emote.getEmote(BANNED);
        }
    }
    if (!suffix.isEmpty()) {
        suffix = suffix + " ";
    }
    return String.format(prefix + " " + name + " " + suffix);
}
Also used : MessageContext(com.gamebuster19901.excite.bot.command.MessageContext)

Example 4 with MessageContext

use of com.gamebuster19901.excite.bot.command.MessageContext in project ExciteBot by TheGameCommunity.

the class Wiimmfi method updateOnlinePlayers.

@SuppressWarnings({ "rawtypes", "unchecked" })
public Player[] updateOnlinePlayers() throws SQLException, WiimmfiResponseException {
    HashSet<Player> onlinePlayers = new HashSet<Player>();
    if (JSON != null) {
        JsonArray objects = null;
        JsonElement object1;
        HashMap<String, JsonElement> object1Entries = new HashMap<String, JsonElement>();
        if (JSON.isJsonArray()) {
            objects = JSON.getAsJsonArray();
            object1 = objects.get(0);
        } else {
            object1 = JSON;
        }
        for (Entry<String, JsonElement> e : object1.getAsJsonObject().entrySet()) {
            if (object1Entries.put(e.getKey(), e.getValue()) != null) {
                throw new WiimmfiResponseException("Duplicate key in json response:" + e.getKey());
            }
        }
        JsonElement typeJson = object1Entries.get("type");
        JsonElement identifyJson = object1Entries.get("identify");
        JsonElement gameJson = object1Entries.get("game_list");
        String type = null;
        String identify = null;
        String game = null;
        if (typeJson != null) {
            type = typeJson.getAsString();
        }
        if (type == null) {
            throw new WiimmfiResponseException("Unexpected response from wiimmfi api");
        }
        if (type.equals("error")) {
            JsonElement errorJson = object1Entries.get("error");
            JsonElement msgJson = object1Entries.get("msg");
            String error = null;
            String msg = null;
            if (errorJson != null) {
                error = errorJson.getAsString();
            } else {
                error = "No error type received from wiimmfi";
            }
            if (msgJson != null) {
                msg = msgJson.getAsString();
            }
            throw new WiimmfiErrorResponse(error + ": " + msg);
        }
        if (identifyJson != null) {
            identify = identifyJson.getAsString();
        }
        if (gameJson != null) {
            if (gameJson.getAsJsonArray().size() > 0) {
                game = gameJson.getAsJsonArray().get(0).getAsString();
            } else {
                throw new WiimmfiResponseException("No game data response");
            }
        }
        if (!"games".equals(identify)) {
            throw new WiimmfiResponseException("Unexpected response of type: " + identify);
        }
        if (!"exciteracewii".equals(game)) {
            throw new WiimmfiResponseException("Wiimmfi sent player list from incorrect game: " + game);
        }
        elementFinder: for (int i = 1; i < objects.size(); i++) {
            // should be safe to access w/o null check as it should error before now
            JsonElement obj = objects.get(i);
            HashMap<String, JsonElement> entries = new HashMap<String, JsonElement>();
            for (Entry<String, JsonElement> e : obj.getAsJsonObject().entrySet()) {
                if (entries.put(e.getKey(), e.getValue()) != null) {
                    throw new WiimmfiResponseException("Duplicate key in json response:" + e.getKey());
                }
            }
            if ("game-stats".equals(entries.get("type").getAsString())) {
                JsonArray playerList = entries.get("list").getAsJsonArray();
                for (JsonElement e : playerList) {
                    HashMap<String, JsonElement> playerDataEntries = new HashMap<String, JsonElement>();
                    for (Entry<String, JsonElement> e2 : e.getAsJsonObject().entrySet()) {
                        playerDataEntries.put(e2.getKey(), e2.getValue());
                    }
                    int pid = playerDataEntries.get("pid").getAsInt();
                    String fc = playerDataEntries.get("fc").getAsString();
                    int status = playerDataEntries.get("online_status").getAsInt();
                    int host = playerDataEntries.get("hoststate").getAsInt();
                    String name = playerDataEntries.get("name").getAsJsonArray().get(0).getAsString();
                    Player player = Player.getPlayerByID(ConsoleContext.INSTANCE, pid);
                    if (player instanceof UnknownPlayer) {
                        player = Player.addPlayer(new MessageContext(player), true, pid, fc, name);
                    } else {
                        player.setName(name);
                        player.setOnlineStatus(status);
                        player.setHost(host);
                    }
                    onlinePlayers.add(player);
                }
                ;
                break elementFinder;
            }
        }
    }
    for (Player player : onlinePlayers) {
        if (PREV_ONLINE_PLAYERS.contains(player)) {
            if (!(player.isPrivate() || player.isSearching() || player.isFriendsList())) {
                player.updateSecondsPlayed();
            }
            player.updateLastOnline();
        } else {
            LogInAudit.addLoginAudit(new MessageContext(player), player);
            player.updateLastOnline();
        }
        PREV_ONLINE_PLAYERS.remove(player);
    }
    for (Player player : PREV_ONLINE_PLAYERS) {
        LogOutAudit.addLogOutAudit(new MessageContext(player), player);
    }
    ONLINE_PLAYERS = onlinePlayers;
    PREV_ONLINE_PLAYERS = ONLINE_PLAYERS;
    return onlinePlayers.toArray(new Player[] {});
}
Also used : HashMap(java.util.HashMap) JsonArray(com.google.gson.JsonArray) WiimmfiResponseException(com.gamebuster19901.excite.exception.WiimmfiResponseException) Entry(java.util.Map.Entry) JsonElement(com.google.gson.JsonElement) MessageContext(com.gamebuster19901.excite.bot.command.MessageContext) WiimmfiErrorResponse(com.gamebuster19901.excite.exception.WiimmfiErrorResponse) HashSet(java.util.HashSet)

Example 5 with MessageContext

use of com.gamebuster19901.excite.bot.command.MessageContext in project ExciteBot by TheGameCommunity.

the class ArchiveCommand method archive.

private static int archive(MessageContext source, String argument) {
    if (source.isAdmin()) {
        if (source.isGuildMessage()) {
            if (argument.isEmpty()) {
                source.sendMessage("Usage: archive <TextChannels>");
                return 1;
            }
            DiscordServer server = source.getServer();
            Guild guild = server.getGuild();
            Member member = DiscordUser.getMember(source.getDiscordAuthor(), server);
            HashSet<TextChannel> channelsToArchive = getChannels(source, guild, Arrays.asList(argument.split(" ")));
            for (TextChannel channel : channelsToArchive) {
                if (!member.hasPermission(channel, Permission.MANAGE_CHANNEL, Permission.MESSAGE_MANAGE)) {
                    source.sendMessage("You must have the `MANAGE_CHANNEL` and `MESSAGE_MANAGE` permission in " + channel.getAsMention() + " in order to archive it.");
                    return 1;
                }
            }
            Thread workerThread = ThreadService.run("Archiver thread", new Thread() {

                private final Thread workerThread = this;

                private final int newlineSize = System.lineSeparator().length();

                public volatile WorkerStatus status = NOT_STARTED;

                public volatile byte updates = 0;

                public volatile int messagesArchived = 0;

                public volatile int wiiMessagesArchived = 0;

                public volatile int attachmentsArchived = 0;

                public volatile long estimatedSize = 0;

                private volatile Throwable error;

                @Override
                public void run() {
                    Thread monitorThread = ThreadService.run("Archive monitor", new Thread() {

                        public void run() {
                            Instant start = Instant.now();
                            EmbedBuilder embed = new EmbedBuilder();
                            embed.setTitle("Archive in progress...");
                            Field archivedDiscordMessagesField = new Field("Discord Messages archived:", "0", true, true);
                            Field archivedDiscordAttachmentsField = new Field("Discord Attachments archived:", "0", true, true);
                            Field emailsArchivedField = new Field("Wii Mails archived:", "0", true, true);
                            Field estimatedSizeField = new Field("Estimated size:", FileUtils.humanReadableByteCount(0), true, true);
                            Field timeElapsedField = new Field("Time elapsed:", "0 seconds", true, true);
                            embed.setTimestamp(start);
                            WorkerStatus currentStatus = status;
                            embed.addField(archivedDiscordMessagesField);
                            embed.addField(archivedDiscordAttachmentsField);
                            embed.addField(emailsArchivedField);
                            embed.addField(estimatedSizeField);
                            embed.addField(timeElapsedField);
                            Message message = source.sendMessage(embed.build());
                            while (!currentStatus.finished()) {
                                try {
                                    Thread.sleep(2500);
                                    currentStatus = status;
                                    Instant now = Instant.now();
                                    embed = new EmbedBuilder();
                                    if (currentStatus == NOT_STARTED) {
                                        embed.setColor(Color.DARK_GRAY);
                                    }
                                    if (currentStatus == WORKING) {
                                        if (updates++ % 2 == 0) {
                                            embed.setColor(Color.YELLOW);
                                        } else {
                                            // dark yellow
                                            embed.setColor(new Color(204, 204, 0));
                                        }
                                        embed.setTitle("Archive in progress...");
                                        embed.addField(archivedDiscordMessagesField = new Field("Discord Messages archived:", messagesArchived + "", true, true));
                                        embed.addField(archivedDiscordAttachmentsField = new Field("Discord Attachments archived:", attachmentsArchived + "", true, true));
                                        embed.addField(emailsArchivedField = new Field("Wii Messages archived:", wiiMessagesArchived + "", true, true));
                                        embed.addField(estimatedSizeField = new Field("Estimated size:", FileUtils.humanReadableByteCount(estimatedSize), true, true));
                                        embed.addField(timeElapsedField = new Field("Time elapsed:", TimeUtils.readableDuration(Duration.between(start, now)), true, true));
                                        embed.setTimestamp(now);
                                        message.editMessage(embed.build()).complete();
                                    }
                                    Thread.sleep(2500);
                                } catch (InterruptedException e) {
                                    currentStatus = ERRORED;
                                    embed.setTitle("Archive failed");
                                    embed.setColor(Color.RED);
                                    message.editMessage(embed.build()).complete();
                                    System.out.println("Monitor thread interrupted... stopping!");
                                    return;
                                }
                            }
                            Instant now = Instant.now();
                            embed.addField(archivedDiscordMessagesField = new Field("Discord Messages archived:", messagesArchived + "", true, true));
                            embed.addField(archivedDiscordAttachmentsField = new Field("Discord Attachments archived:", attachmentsArchived + "", true, true));
                            embed.addField(emailsArchivedField = new Field("Wii Messages archived:", wiiMessagesArchived + "", true, true));
                            embed.addField(estimatedSizeField = new Field("Estimated size:", FileUtils.humanReadableByteCount(estimatedSize), true, true));
                            embed.addField(timeElapsedField = new Field("Time elapsed:", TimeUtils.readableDuration(Duration.between(start, now)), true, true));
                            embed.setTimestamp(now);
                            message.editMessage(embed.build()).complete();
                            if (currentStatus == COMPLETE) {
                                embed.setColor(Color.GREEN);
                                embed.setTitle("Archive complete");
                                source.sendMessage(source.getDiscordAuthor().getJDAUser().getAsMention() + " Archive complete.");
                            } else {
                                embed.setColor(Color.RED);
                                embed.setTitle("Archive failed");
                                source.sendMessage(source.getDiscordAuthor().getJDAUser().getAsMention() + " Archive FAILED.");
                            }
                            message.editMessage(embed.build()).complete();
                        }
                    });
                    String date = TimeUtils.getDBDate(Instant.now());
                    try {
                        status = WORKING;
                        for (File f : org.apache.commons.io.FileUtils.listFiles(Mailbox.MAILBOX, null, true)) {
                            File archive = new File(".archive/" + date + "/" + f.getPath().replace("/run", ""));
                            if (!archive.getParentFile().mkdirs() && !archive.getParentFile().exists()) {
                                throw new IOException("Could not create " + archive.getAbsolutePath());
                            }
                            org.apache.commons.io.FileUtils.copyFile(f, archive);
                            wiiMessagesArchived++;
                            estimatedSize += archive.length();
                        }
                        for (TextChannel channel : channelsToArchive) {
                            try {
                                File file = new File(".archive/" + date + "/" + channel.getName() + "/" + channel.getName() + ".arc");
                                if (!file.getParentFile().mkdirs()) {
                                    throw new IOException("Could not create " + file.getAbsolutePath());
                                }
                                System.out.println(file.getAbsolutePath());
                                file.createNewFile();
                                MessagePaginationAction action = channel.getIterableHistory();
                                BufferedWriter fileWriter = new BufferedWriter(new FileWriter(file));
                                action.forEach((message) -> {
                                    try {
                                        List<Attachment> attachments = message.getAttachments();
                                        write(fileWriter, "==========START " + message.getIdLong() + " USER:" + message.getAuthor().getAsTag());
                                        write(fileWriter, message.getContentRaw());
                                        if (!attachments.isEmpty()) {
                                            write(fileWriter, "==========ATTACHMENTS " + message.getIdLong());
                                            for (Attachment attachment : attachments) {
                                                File attachmentFile = new File(file.getParentFile().getPath() + "/attach" + attachment.getIdLong() + attachment.getFileName());
                                                CompletableFuture<File> future = attachment.downloadToFile(attachmentFile);
                                                future.exceptionally(error -> {
                                                    int i = 0;
                                                    source.sendMessage("Encountered " + error.getClass().getSimpleName() + " while downloading " + attachmentFile + " retrying... (" + i++ + "/4)");
                                                    while (i < 4) {
                                                        try {
                                                            future.get();
                                                            i++;
                                                        } catch (Throwable t) {
                                                            if (t instanceof InterruptedException) {
                                                                throw new ThreadDeath();
                                                            }
                                                            if (i < 4) {
                                                                source.sendMessage("Encountered " + t.getClass().getSimpleName() + " while downloading " + attachmentFile + " retrying... (" + i + "/4)");
                                                            }
                                                        }
                                                    }
                                                    return null;
                                                }).get();
                                                write(fileWriter, attachment.getId() + attachmentFile.getName());
                                                estimatedSize += attachment.getSize();
                                                attachmentsArchived++;
                                            }
                                        }
                                        write(fileWriter, "==========END " + message.getIdLong());
                                        messagesArchived++;
                                    } catch (IOException | InterruptedException | ExecutionException e) {
                                        throw new RuntimeException(e);
                                    }
                                });
                                fileWriter.close();
                            } catch (Throwable t) {
                                source.sendMessage("Could not back up channel " + channel.getAsMention());
                                throw t;
                            }
                        }
                        status = COMPLETE;
                    } catch (Throwable t) {
                        source.sendMessage(StacktraceUtil.getStackTrace(t));
                        status = ERRORED;
                    }
                }

                private void write(BufferedWriter writer, String text) throws IOException {
                    estimatedSize += text.length() + newlineSize;
                    writer.write(text);
                    writer.newLine();
                }
            });
        } else {
            source.sendMessage("You must execute this command in a server");
        }
    } else {
        source.sendMessage("You must be an administator to execute this command");
    }
    return 1;
}
Also used : Color(java.awt.Color) ThreadService(com.gamebuster19901.excite.util.ThreadService) Arrays(java.util.Arrays) CommandDispatcher(com.mojang.brigadier.CommandDispatcher) Permission(net.dv8tion.jda.api.Permission) CompletableFuture(java.util.concurrent.CompletableFuture) Member(net.dv8tion.jda.api.entities.Member) Field(net.dv8tion.jda.api.entities.MessageEmbed.Field) TextChannel(net.dv8tion.jda.api.entities.TextChannel) MessagePaginationAction(net.dv8tion.jda.api.requests.restaction.pagination.MessagePaginationAction) HashSet(java.util.HashSet) StringArgumentType(com.mojang.brigadier.arguments.StringArgumentType) WorkerStatus(com.gamebuster19901.excite.bot.command.ArchiveCommand.WorkerStatus) Guild(net.dv8tion.jda.api.entities.Guild) Duration(java.time.Duration) Mailbox(com.gamebuster19901.excite.bot.mail.Mailbox) StacktraceUtil(com.gamebuster19901.excite.util.StacktraceUtil) Message(net.dv8tion.jda.api.entities.Message) Attachment(net.dv8tion.jda.api.entities.Message.Attachment) BufferedWriter(java.io.BufferedWriter) FileUtils(com.gamebuster19901.excite.util.file.FileUtils) FileWriter(java.io.FileWriter) DiscordUser(com.gamebuster19901.excite.bot.user.DiscordUser) IOException(java.io.IOException) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Instant(java.time.Instant) File(java.io.File) ExecutionException(java.util.concurrent.ExecutionException) DiscordServer(com.gamebuster19901.excite.bot.server.DiscordServer) List(java.util.List) TimeUtils(com.gamebuster19901.excite.util.TimeUtils) Message(net.dv8tion.jda.api.entities.Message) FileWriter(java.io.FileWriter) Attachment(net.dv8tion.jda.api.entities.Message.Attachment) Guild(net.dv8tion.jda.api.entities.Guild) BufferedWriter(java.io.BufferedWriter) Field(net.dv8tion.jda.api.entities.MessageEmbed.Field) TextChannel(net.dv8tion.jda.api.entities.TextChannel) CompletableFuture(java.util.concurrent.CompletableFuture) WorkerStatus(com.gamebuster19901.excite.bot.command.ArchiveCommand.WorkerStatus) List(java.util.List) Member(net.dv8tion.jda.api.entities.Member) Instant(java.time.Instant) Color(java.awt.Color) IOException(java.io.IOException) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) DiscordServer(com.gamebuster19901.excite.bot.server.DiscordServer) File(java.io.File) MessagePaginationAction(net.dv8tion.jda.api.requests.restaction.pagination.MessagePaginationAction)

Aggregations

SQLException (java.sql.SQLException)20 IOError (java.io.IOError)18 PreparedStatement (com.gamebuster19901.excite.bot.database.sql.PreparedStatement)17 Comparison (com.gamebuster19901.excite.bot.database.Comparison)9 MessageContext (com.gamebuster19901.excite.bot.command.MessageContext)8 DiscordUser (com.gamebuster19901.excite.bot.user.DiscordUser)8 Player (com.gamebuster19901.excite.Player)6 Ban (com.gamebuster19901.excite.bot.audit.ban.Ban)6 Result (com.gamebuster19901.excite.bot.database.Result)6 HashSet (java.util.HashSet)5 Duration (java.time.Duration)4 ElectronicAddress (com.gamebuster19901.excite.bot.mail.ElectronicAddress)3 ArrayList (java.util.ArrayList)3 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)3 Wiimmfi (com.gamebuster19901.excite.Wiimmfi)2 Audit (com.gamebuster19901.excite.bot.audit.Audit)2 Row (com.gamebuster19901.excite.bot.database.Row)2 DiscordServer (com.gamebuster19901.excite.bot.server.DiscordServer)2 UnknownDiscordUser (com.gamebuster19901.excite.bot.user.UnknownDiscordUser)2 Wii (com.gamebuster19901.excite.bot.user.Wii)2