Search in sources :

Example 26 with IGuild

use of sx.blah.discord.handle.obj.IGuild in project DisCal-Discord-Bot by NovaFox161.

the class GuildEndpoint method getUserGuilds.

public static String getUserGuilds(Request request, Response response) {
    try {
        JSONObject jsonMain = new JSONObject(request.body());
        long userId = jsonMain.getLong("USER_ID");
        IUser user = Main.client.getUserByID(userId);
        // Find all guilds user is in...
        ArrayList<IGuild> guilds = new ArrayList<>();
        for (IGuild g : Main.client.getGuilds()) {
            if (g.getUserByID(userId) != null) {
                guilds.add(g);
            }
        }
        // Get needed data
        ArrayList<JSONObject> guildData = new ArrayList<>();
        for (IGuild g : guilds) {
            JSONObject d = new JSONObject();
            d.put("GUILD_ID", g.getLongID());
            d.put("IS_OWNER", g.getOwnerLongID() == userId);
            d.put("MANAGE_SERVER", PermissionChecker.hasManageServerRole(g, user));
            d.put("DISCAL_CONTROL", PermissionChecker.hasSufficientRole(g, user));
            guildData.add(d);
        }
        JSONObject body = new JSONObject();
        body.put("USER_ID", userId);
        body.put("GUILD_COUNT", guildData.size());
        body.put("GUILDS", guildData);
        response.type("application/json");
        response.status(200);
        response.body(body.toString());
    } catch (JSONException e) {
        e.printStackTrace();
        halt(400, "Bad Request");
    } catch (Exception e) {
        Logger.getLogger().exception(null, "[WEB-API] Internal get guilds from users error", e, GuildEndpoint.class, true);
    }
    return response.body();
}
Also used : JSONObject(org.json.JSONObject) ArrayList(java.util.ArrayList) IUser(sx.blah.discord.handle.obj.IUser) JSONException(org.json.JSONException) IGuild(sx.blah.discord.handle.obj.IGuild) JSONException(org.json.JSONException)

Example 27 with IGuild

use of sx.blah.discord.handle.obj.IGuild in project DisCal-Discord-Bot by NovaFox161.

the class DashboardHandler method handleSettingsUpdate.

public static String handleSettingsUpdate(Request request, Response response) {
    try {
        if (request.queryParams().contains("bot-nick")) {
            // Update bot nickname...
            Map m = DiscordAccountHandler.getHandler().getAccount(request.session().id());
            WebGuild g = (WebGuild) m.get("selected");
            if (g.isManageServer()) {
                g.setBotNick(request.queryParams("bot-nick"));
                IGuild guild = Main.client.getGuildByID(Long.valueOf(g.getId()));
                guild.setUserNickname(Main.client.getOurUser(), g.getBotNick());
            }
        } else if (request.queryParams().contains("prefix")) {
            // Update prefix...
            Map m = DiscordAccountHandler.getHandler().getAccount(request.session().id());
            WebGuild g = (WebGuild) m.get("selected");
            if (g.isManageServer()) {
                g.setSettings(DatabaseManager.getManager().getSettings(Long.valueOf(g.getId())));
                g.getSettings().setPrefix(request.queryParams("prefix"));
                DatabaseManager.getManager().updateSettings(g.getSettings());
            }
        } else if (request.queryParams().contains("lang")) {
            // Update lang...
            Map m = DiscordAccountHandler.getHandler().getAccount(request.session().id());
            WebGuild g = (WebGuild) m.get("selected");
            if (g.isManageServer()) {
                g.setSettings(DatabaseManager.getManager().getSettings(Long.valueOf(g.getId())));
                g.getSettings().setLang(request.queryParams("lang"));
                DatabaseManager.getManager().updateSettings(g.getSettings());
            }
        } else if (request.queryParams().contains("con-role")) {
            // Update control role...
            Map m = DiscordAccountHandler.getHandler().getAccount(request.session().id());
            WebGuild g = (WebGuild) m.get("selected");
            if (g.isManageServer()) {
                g.setSettings(DatabaseManager.getManager().getSettings(Long.valueOf(g.getId())));
                IGuild guild = Main.client.getGuildByID(Long.valueOf(g.getId()));
                IRole role = guild.getRoleByID(Long.valueOf(request.queryParams("con-role")));
                if (role.isEveryoneRole()) {
                    g.getSettings().setControlRole("everyone");
                } else {
                    g.getSettings().setControlRole(role.getStringID());
                }
                DatabaseManager.getManager().updateSettings(g.getSettings());
                // Update role list to display properly...
                g.getRoles().clear();
                for (IRole r : guild.getRoles()) {
                    g.getRoles().add(new WebRole().fromRole(r, g.getSettings()));
                }
            }
        } else if (request.queryParams().contains("discal-channel")) {
            // Update control role...
            Map m = DiscordAccountHandler.getHandler().getAccount(request.session().id());
            WebGuild g = (WebGuild) m.get("selected");
            if (g.isDiscalRole()) {
                g.setSettings(DatabaseManager.getManager().getSettings(Long.valueOf(g.getId())));
                IGuild guild = Main.client.getGuildByID(Long.valueOf(g.getId()));
                if (request.queryParams("discal-channel").equalsIgnoreCase("0")) {
                    // All channels
                    g.getSettings().setDiscalChannel("all");
                } else {
                    g.getSettings().setDiscalChannel(request.queryParams("discal-channel"));
                }
                DatabaseManager.getManager().updateSettings(g.getSettings());
                // Update channel list to display properly...
                g.getChannels().clear();
                WebChannel all = new WebChannel();
                all.setId(0);
                all.setName("All Channels");
                all.setDiscalChannel(g.getSettings().getDiscalChannel().equalsIgnoreCase("all"));
                g.getChannels().add(all);
                for (IChannel c : guild.getChannels()) {
                    g.getChannels().add(new WebChannel().fromChannel(c, g.getSettings()));
                }
            }
        } else if (request.queryParams().contains("branding")) {
            // Update bot nickname...
            Map m = DiscordAccountHandler.getHandler().getAccount(request.session().id());
            WebGuild g = (WebGuild) m.get("selected");
            if (g.isManageServer()) {
                g.setSettings(DatabaseManager.getManager().getSettings(Long.valueOf(g.getId())));
                if (g.getSettings().isPatronGuild()) {
                    if (request.queryParams().contains("value")) {
                        g.getSettings().setBranded(true);
                    } else {
                        g.getSettings().setBranded(false);
                    }
                    DatabaseManager.getManager().updateSettings(g.getSettings());
                }
            }
        } else if (request.queryParams().contains("simple-ann")) {
            // Update simple announcements...
            Map m = DiscordAccountHandler.getHandler().getAccount(request.session().id());
            WebGuild g = (WebGuild) m.get("selected");
            // Guess this one never checked for perms so...
            g.setSettings(DatabaseManager.getManager().getSettings(Long.valueOf(g.getId())));
            if (request.queryParams().contains("value")) {
                g.getSettings().setSimpleAnnouncements(true);
            } else {
                g.getSettings().setSimpleAnnouncements(false);
            }
            DatabaseManager.getManager().updateSettings(g.getSettings());
            response.redirect("/dashboard/guild/announcements", 301);
            return response.body();
        }
        // Finally redirect back to the dashboard
        response.redirect("/dashboard/guild", 301);
    } catch (Exception e) {
        Logger.getLogger().exception(null, "[WEB] Settings update failed!", e, DashboardHandler.class, true);
        halt(500, "Internal Server Exception");
    }
    return response.body();
}
Also used : WebChannel(com.cloudcraftgaming.discal.api.object.web.WebChannel) IChannel(sx.blah.discord.handle.obj.IChannel) IRole(sx.blah.discord.handle.obj.IRole) WebRole(com.cloudcraftgaming.discal.api.object.web.WebRole) WebGuild(com.cloudcraftgaming.discal.api.object.web.WebGuild) IGuild(sx.blah.discord.handle.obj.IGuild) HashMap(java.util.HashMap) Map(java.util.Map) JSONException(org.json.JSONException)

Example 28 with IGuild

use of sx.blah.discord.handle.obj.IGuild in project DiscordSailv2 by Vaerys-Dawn.

the class TransferCC method execute.

@Override
public String execute(String args, CommandObject command) {
    String filePath = Constants.DIRECTORY_OLD_FILES + command.guild.longID + "_CustomCommands.json";
    IGuild guild = command.guild.get();
    IUser author = command.user.get();
    IChannel channel = command.channel.get();
    CustomCommands customCommands = command.guild.customCommands;
    if (Paths.get(filePath).toFile().exists()) {
        com.github.vaerys.oldcode.CustomCommands oldCommands = null;
        if (oldCommands == null) {
            oldCommands = (com.github.vaerys.oldcode.CustomCommands) FileHandler.readFromJson(filePath, com.github.vaerys.oldcode.CustomCommands.class);
        }
        CCommandObject transfering = oldCommands.convertCommand(args);
        if (transfering == null) {
            return Constants.ERROR_CC_NOT_FOUND;
        }
        boolean locked = transfering.isLocked();
        long userID = transfering.getUserID();
        if (guild.getUserByID(userID) == null) {
            RequestHandler.sendMessage("> This command's old owner no longer is part of this server.\n" + Constants.PREFIX_INDENT + author.getDisplayName(guild) + " will become the new owner of this command.\n" + "> I am now attempting to transfer the command over.", channel);
            userID = author.getLongID();
        } else {
            RequestHandler.sendMessage("> I am now attempting to transfer " + guild.getUserByID(userID).getDisplayName(guild) + "'s command.", channel);
        }
        String name = transfering.getName();
        String contents = transfering.getContents(false);
        contents = contents.replace("#author!#", "#username#");
        boolean shitpost = transfering.isShitPost();
        command.setAuthor(Globals.getClient().getUserByID(userID));
        return customCommands.addCommand(locked, name, contents, shitpost, command);
    } else {
        return "> Your Server has no Legacy commands to transfer.";
    }
}
Also used : CCommandObject(com.github.vaerys.objects.CCommandObject) IChannel(sx.blah.discord.handle.obj.IChannel) IUser(sx.blah.discord.handle.obj.IUser) IGuild(sx.blah.discord.handle.obj.IGuild) CustomCommands(com.github.vaerys.pogos.CustomCommands)

Example 29 with IGuild

use of sx.blah.discord.handle.obj.IGuild in project Discord4J by Discord4J.

the class RoleBot method handle.

/**
 * Client is ready to interact with Discord.
 * @see ReadyBot
 */
@Override
public void handle(ReadyEvent event) {
    try {
        // Gets the first guild the bot is a member of. (NOTE: This is only for demonstration. Getting guilds in this way is NOT recommended. Use IDs or events instead.)
        IGuild guild = event.getClient().getGuilds().get(0);
        // Instantiate a RoleBuilder which will aide in the creation of the role.
        RoleBuilder roleBuilder = new RoleBuilder(guild);
        // Set the new role's name
        roleBuilder.withName("Awesome Role");
        // Set the new role's color
        roleBuilder.withColor(Color.GREEN);
        // Make the new role display separately from others in Discord.
        roleBuilder.setHoist(true);
        // Allow this role to be mentionable in chat.
        roleBuilder.setMentionable(true);
        // Assign the Administrator permission to this role.
        roleBuilder.withPermissions(EnumSet.of(Permissions.ADMINISTRATOR));
        // Add the role to the guild in Discord.
        IRole role = roleBuilder.build();
        // Gets the user of the bot
        IUser ourUser = event.getClient().getOurUser();
        // Assigns our new role to the bot. NOTE: This will make the bot's ONLY role our role.
        guild.editUserRoles(ourUser, new IRole[] { role });
    } catch (MissingPermissionsException | RateLimitException | DiscordException e) {
        // Error occurred
        e.printStackTrace();
    }
}
Also used : IRole(sx.blah.discord.handle.obj.IRole) RateLimitException(sx.blah.discord.util.RateLimitException) DiscordException(sx.blah.discord.util.DiscordException) IUser(sx.blah.discord.handle.obj.IUser) MissingPermissionsException(sx.blah.discord.util.MissingPermissionsException) IGuild(sx.blah.discord.handle.obj.IGuild) RoleBuilder(sx.blah.discord.util.RoleBuilder)

Example 30 with IGuild

use of sx.blah.discord.handle.obj.IGuild in project Shadbot by Shadorc.

the class BotUtils method sendMessage.

public static RequestFuture<IMessage> sendMessage(MessageBuilder message, int retry) {
    IGuild guild = message.getChannel().isPrivate() ? null : message.getChannel().getGuild();
    long guildID = guild == null ? -1 : guild.getLongID();
    if (retry == 0) {
        LogUtils.infof("{Guild ID: %d} Abort attempt to send message (3 failed requests).", guildID);
        return null;
    }
    if (!message.getChannel().getShard().isReady()) {
        if (guild != null) {
            LogUtils.infof("{Guild ID: %d} A message couldn't be sent because shard isn't ready, adding it to queue.", guildID);
            ShardManager.getShadbotShard(guild.getShard()).queue(message);
        }
        return null;
    }
    return RequestBuffer.request(() -> {
        try {
            return message.send();
        } catch (MissingPermissionsException err) {
            BotUtils.sendMessage(TextUtils.missingPerm(err.getMissingPermissions()), message.getChannel());
            LogUtils.infof("{Guild ID: %d} %s", guildID, err.getMessage());
        } catch (DiscordException err) {
            if (err.getMessage().contains("Message was unable to be sent (Discord didn't return a response)")) {
                LogUtils.infof("{Guild ID: %d} A message could not be send because Discord didn't return a response, retrying.", guildID);
                RequestFuture<IMessage> msgRequest = BotUtils.sendMessage(message, retry - 1);
                if (msgRequest != null) {
                    return msgRequest.get();
                }
            } else if (err.getMessage().contains("Failed to make a 400 failed request after 5 tries!")) {
                LogUtils.infof("{Guild ID: %d} %s", guildID, err.getMessage());
            } else {
                LogUtils.error(err, "An error occurred while sending message.");
            }
        }
        return null;
    });
}
Also used : RequestFuture(sx.blah.discord.util.RequestBuffer.RequestFuture) DiscordException(sx.blah.discord.util.DiscordException) MissingPermissionsException(sx.blah.discord.util.MissingPermissionsException) IGuild(sx.blah.discord.handle.obj.IGuild)

Aggregations

IGuild (sx.blah.discord.handle.obj.IGuild)31 IUser (sx.blah.discord.handle.obj.IUser)13 EmbedBuilder (sx.blah.discord.util.EmbedBuilder)9 IChannel (sx.blah.discord.handle.obj.IChannel)7 ArrayList (java.util.ArrayList)5 IRole (sx.blah.discord.handle.obj.IRole)5 EventSubscriber (sx.blah.discord.api.events.EventSubscriber)4 IMessage (sx.blah.discord.handle.obj.IMessage)4 DiscordException (sx.blah.discord.util.DiscordException)4 WebGuild (com.cloudcraftgaming.discal.api.object.web.WebGuild)3 HashMap (java.util.HashMap)3 List (java.util.List)3 MissingPermissionsException (sx.blah.discord.util.MissingPermissionsException)3 EventColor (com.cloudcraftgaming.discal.api.enums.event.EventColor)2 EventData (com.cloudcraftgaming.discal.api.object.event.EventData)2 Calendar (com.google.api.services.calendar.Calendar)2 Language (enums.Language)2 FileWriter (java.io.FileWriter)2 IOException (java.io.IOException)2 SimpleDateFormat (java.text.SimpleDateFormat)2