Search in sources :

Example 11 with IUser

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

the class DiscordVoiceWS method onWebSocketText.

@Override
public void onWebSocketText(String message) {
    try {
        JsonNode json = DiscordUtils.MAPPER.readTree(message);
        VoiceOps op = VoiceOps.get(json.get("op").asInt());
        JsonNode d = json.has("d") && !json.get("d").isNull() ? json.get("d") : null;
        switch(op) {
            case READY:
                try {
                    VoiceReadyResponse ready = DiscordUtils.MAPPER.treeToValue(d, VoiceReadyResponse.class);
                    voiceSocket.setup(endpoint, ready.port, ready.ssrc);
                    beginHeartbeat(ready.heartbeat_interval);
                } catch (IOException e) {
                    Discord4J.LOGGER.error(LogMarkers.VOICE_WEBSOCKET, "Encountered error handling voice ready payload: ", e);
                }
                break;
            case SESSION_DESCRIPTION:
                VoiceDescriptionResponse description = DiscordUtils.MAPPER.treeToValue(d, VoiceDescriptionResponse.class);
                voiceSocket.setSecret(description.secret_key);
                voiceSocket.begin();
                break;
            case SPEAKING:
                VoiceSpeakingResponse response = DiscordUtils.MAPPER.treeToValue(d, VoiceSpeakingResponse.class);
                IUser user = getGuild().getUserByID(Long.parseUnsignedLong(response.user_id));
                users.put(response.ssrc, user);
                guild.getClient().getDispatcher().dispatch(new UserSpeakingEvent(user.getVoiceStateForGuild(guild).getChannel(), user, response.ssrc, response.speaking));
                break;
            case UNKNOWN:
                Discord4J.LOGGER.debug(LogMarkers.VOICE_WEBSOCKET, "Received unknown voice opcode, {}", message);
                break;
        }
    } catch (IOException e) {
        Discord4J.LOGGER.error(LogMarkers.WEBSOCKET, "JSON Parsing exception!", e);
    }
}
Also used : UserSpeakingEvent(sx.blah.discord.handle.impl.events.guild.voice.user.UserSpeakingEvent) VoiceSpeakingResponse(sx.blah.discord.api.internal.json.responses.voice.VoiceSpeakingResponse) IUser(sx.blah.discord.handle.obj.IUser) JsonNode(com.fasterxml.jackson.databind.JsonNode) VoiceReadyResponse(sx.blah.discord.api.internal.json.responses.voice.VoiceReadyResponse) IOException(java.io.IOException) VoiceDescriptionResponse(sx.blah.discord.api.internal.json.responses.voice.VoiceDescriptionResponse)

Example 12 with IUser

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

the class Reaction method getUsers.

@Override
public List<IUser> getUsers() {
    List<IUser> users = new ArrayList<>();
    String emoji = getEmoji().isUnicode() ? getEmoji().getName() : getEmoji().getName() + ":" + getEmoji().getStringID();
    String endpoint = String.format(DiscordEndpoints.REACTIONS_USER_LIST, getMessage().getChannel().getStringID(), getMessage().getStringID(), emoji);
    String after = "0";
    while (users.size() < count) {
        UserObject[] json = ((DiscordClientImpl) getClient()).REQUESTS.GET.makeRequest(endpoint + "?after=" + after + "&limit=100", UserObject[].class);
        for (UserObject obj : json) {
            users.add(getMessage().getShard().getUserByID(Long.parseUnsignedLong(obj.id)));
        }
        // Temporary measure so a refactor can be applied later.
        if (json.length == 0)
            break;
        after = json[json.length - 1].id;
    }
    return users;
}
Also used : ArrayList(java.util.ArrayList) IUser(sx.blah.discord.handle.obj.IUser) UserObject(sx.blah.discord.api.internal.json.objects.UserObject) DiscordClientImpl(sx.blah.discord.api.internal.DiscordClientImpl)

Example 13 with IUser

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

the class TimerHandler method reportHandling.

private static void reportHandling(GuildObject task) {
    List<UserRateObject> offenders = task.getRateLimiting();
    IRole muteRole = task.getRoleByID(task.config.getMutedRoleID());
    if (muteRole == null)
        return;
    IChannel admin = task.getChannelByType(ChannelSetting.ADMIN);
    for (UserRateObject u : offenders) {
        if (u.counter - 3 > task.config.messageLimit) {
            List<IChannel> channels = u.getChannels(task);
            if (admin == null && !channels.isEmpty()) {
                admin = channels.get(channels.size() - 1);
            }
            StringHandler output = new StringHandler();
            StringHandler modNote = new StringHandler();
            IUser offender = u.getUser(task);
            long rate = u.counter - task.config.messageLimit;
            String formattedChannels = String.join(", ", channels.stream().map(channel -> channel.mention()).collect(Collectors.toList()));
            // Admin Message output
            output.append("> ").append(offender.mention());
            output.append(" Has Been muted for breaking the guild rate limit (");
            output.append(rate);
            output.append(" Over Rate)");
            if (channels.size() == 1) {
                output.append(" in ").append(channels.get(0).mention());
            } else if (channels.size() > 1) {
                output.append(" in channels: ");
                output.append(formattedChannels);
            }
            output.append(".");
            // modNote Output
            modNote.append("> Muted by Rate Limiter, ");
            modNote.append(rate).append(" Over Rate, ");
            modNote.append("Channel");
            if (channels.size() > 1)
                modNote.append("s");
            modNote.append(": ").append(formattedChannels);
            // logging
            if (task.config.deleteLogging) {
                Utility.sendLog("> **@" + offender.getName() + "#" + offender.getDiscriminator() + "** was muted for breaking rate limit.", task, true);
            }
            ProfileObject profile = task.users.getUserByID(u.getID());
            profile.addSailModNote(modNote.toString(), u.timeStamp, false);
            RequestHandler.sendMessage(output.toString(), admin);
        }
    }
}
Also used : IChannel(sx.blah.discord.handle.obj.IChannel) IRole(sx.blah.discord.handle.obj.IRole) IUser(sx.blah.discord.handle.obj.IUser)

Example 14 with IUser

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

the class Main method main.

public static void main(String[] args) throws UnknownHostException {
    // important, do not move
    PatchHandler.preInitPatches();
    logger = LoggerFactory.getLogger(Main.class);
    logger.info("Starting bot...");
    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            logger.info(">>> Running Shutdown Process <<<");
            if (Globals.savingFiles) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Utility.sendStack(e);
                }
            }
            Globals.saveFiles(true);
        }
    });
    String token = null;
    // you need to set a token in Token/Token.txt for the bot to run
    try {
        Discord4J.disableAudio();
        FileHandler.createDirectory(Constants.DIRECTORY_STORAGE);
        FileHandler.createDirectory(Constants.DIRECTORY_GLOBAL_IMAGES);
        FileHandler.createDirectory(Constants.DIRECTORY_COMP);
        FileHandler.createDirectory(Constants.DIRECTORY_BACKUPS);
        FileHandler.createDirectory(Constants.DIRECTORY_TEMP);
        FileHandler.createDirectory(Constants.DIRECTORY_OLD_FILES);
        FileHandler.createDirectory(Constants.DIRECTORY_ERROR);
        // load config phase 1
        Config config = (Config) Config.create(Constants.FILE_CONFIG, new Config());
        GlobalData globalData = (GlobalData) GlobalData.create(Constants.FILE_GLOBAL_DATA, new GlobalData());
        config = Config.check(config);
        // getting bot token
        try {
            token = FileHandler.readFromFile(Constants.FILE_TOKEN).get(0);
        } catch (IndexOutOfBoundsException e) {
            logger.error("!!!BOT TOKEN NOT VALID PLEASE CHECK \"Storage/Token.txt\" AND UPDATE THE TOKEN!!!");
            System.exit(Constants.EXITCODE_STOP);
        }
        try {
            List<String> pastebinToken = FileHandler.readFromFile(Constants.FILE_PASTEBIN_TOKEN);
            Client.initPastebin(pastebinToken);
        } catch (IndexOutOfBoundsException e) {
            logger.info("No Pastebin Token found.");
        }
        // stuff that i cant getToggles to work because reasons, ignore completely
        // try{
        // List<String> richPresesnce = FileHandler.readFromFile(Constants.FILE_RPC_TOKEN);
        // Client.initRichPresence(richPresesnce);
        // }catch (IndexOutOfBoundsException e){
        // logger.info("Rich presence information missing.");
        // }
        // try {
        // List<String> imgurToken = FileHandler.readFromFile(Constants.FILE_IMGUR_TOKEN);
        // Client.initImgur(imgurToken);
        // } catch (IndexOutOfBoundsException e) {
        // logger.info("No Patreon Token found.");
        // }
        IDiscordClient client = Client.createClient(token, false);
        // load config phase 2
        Globals.initConfig(client, config, globalData);
        if (Globals.creatorID == 153159020528533505L) {
            try {
                List<String> patreonToken = FileHandler.readFromFile(Constants.FILE_PATREON_TOKEN);
                Client.initPatreon(patreonToken);
            } catch (IndexOutOfBoundsException e) {
                logger.info("No Patreon Token found.");
            }
        }
        Globals.validateConfig();
        if (Globals.errorStack != null) {
            logger.error(">\n> Begin Config Error Report <<\n" + "at " + Constants.DIRECTORY_STORAGE + Constants.FILE_CONFIG + "\n" + Globals.errorStack + ">> End Error Report <<");
            System.exit(Constants.EXITCODE_STOP);
        }
        ThreadGroup group = new ThreadGroup("GuildCreateGroup");
        final int[] count = new int[] { 0 };
        // login + register listener.
        client.login();
        // initialize creatorID if it is completely unset:
        if (config.creatorID == 0) {
            IUser botOwner = client.getApplicationOwner();
            config.creatorID = botOwner.getLongID();
            Globals.creatorID = config.creatorID;
            logger.info("Default creatorID set to user " + botOwner.getName() + "#" + botOwner.getDiscriminator());
            // save it back out to file.
            config.flushFile();
        }
        ExecutorService guildService = new ThreadPoolExecutor(2, 50, 1, TimeUnit.MINUTES, new ArrayBlockingQueue<>(1000), r -> new Thread(group, r, group.getName() + "-Thread-" + ++count[0]));
        ExecutorService commandService = new ThreadPoolExecutor(2, 50, 1, TimeUnit.MINUTES, new ArrayBlockingQueue<>(1000), r -> new Thread(group, r, group.getName() + "-Thread-" + ++count[0]));
        ExecutorService creatorService = new ThreadPoolExecutor(2, 50, 1, TimeUnit.MINUTES, new ArrayBlockingQueue<>(1000), r -> new Thread(group, r, group.getName() + "-Thread-" + ++count[0]));
        EventDispatcher dispatcher = client.getDispatcher();
        dispatcher.registerListener(guildService, new GuildCreateListener());
        dispatcher.registerListener(commandService, new AnnotationListener());
        dispatcher.registerListener(creatorService, new CreatorHandler());
        dispatcher.registerTemporaryListener(new InitEvent());
        // validate config file
        Globals.setVersion();
        // Init Patch system.
        // timed events getSlashCommands
        new TimerHandler();
    } catch (DiscordException ex) {
        logger.error(ex.getErrorMessage());
    } catch (RateLimitException e) {
        Utility.sendStack(e);
    }
}
Also used : RateLimitException(sx.blah.discord.util.RateLimitException) Config(com.github.vaerys.pogos.Config) IDiscordClient(sx.blah.discord.api.IDiscordClient) EventDispatcher(sx.blah.discord.api.events.EventDispatcher) GlobalData(com.github.vaerys.pogos.GlobalData) ExecutorService(java.util.concurrent.ExecutorService) DiscordException(sx.blah.discord.util.DiscordException) IUser(sx.blah.discord.handle.obj.IUser) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor)

Example 15 with IUser

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

the class EnterComp method execute.

@Override
public String execute(String args, CommandObject command) {
    GuildConfig guildconfig = command.guild.config;
    IMessage message = command.message.get();
    IUser author = command.user.get();
    if (guildconfig.compEntries) {
        String fileName;
        String fileUrl;
        if (message.getAttachments().size() > 0) {
            List<IMessage.Attachment> attatchments = message.getAttachments();
            IMessage.Attachment a = attatchments.get(0);
            fileName = a.getFilename();
            fileUrl = a.getUrl();
        } else if (!args.isEmpty()) {
            fileName = author.getName() + "'s Entry";
            fileUrl = args;
        } else {
            return "> Missing a File or Image link to enter into the competition.";
        }
        DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy - HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        command.guild.competition.newEntry(new CompObject(author.getDisplayName(command.guild.get()), author.getLongID(), fileName, fileUrl, dateFormat.format(cal.getTime())));
        return "> Thank you " + author.getDisplayName(command.guild.get()) + " For entering the Competition.";
    } else {
        return "> Competition Entries are closed.";
    }
}
Also used : GuildConfig(com.github.vaerys.pogos.GuildConfig) IMessage(sx.blah.discord.handle.obj.IMessage) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) Calendar(java.util.Calendar) IUser(sx.blah.discord.handle.obj.IUser) CompObject(com.github.vaerys.objects.CompObject) SimpleDateFormat(java.text.SimpleDateFormat)

Aggregations

IUser (sx.blah.discord.handle.obj.IUser)67 ArrayList (java.util.ArrayList)15 IGuild (sx.blah.discord.handle.obj.IGuild)13 EmbedBuilder (sx.blah.discord.util.EmbedBuilder)13 XEmbedBuilder (com.github.vaerys.objects.XEmbedBuilder)9 IMessage (sx.blah.discord.handle.obj.IMessage)9 IRole (sx.blah.discord.handle.obj.IRole)8 List (java.util.List)7 MissingArgumentException (me.shadorc.shadbot.exception.MissingArgumentException)7 IllegalCmdArgumentException (me.shadorc.shadbot.exception.IllegalCmdArgumentException)6 IChannel (sx.blah.discord.handle.obj.IChannel)6 HashMap (java.util.HashMap)5 CCommandObject (com.github.vaerys.objects.CCommandObject)4 AbstractCommand (me.shadorc.shadbot.core.command.AbstractCommand)4 CommandCategory (me.shadorc.shadbot.core.command.CommandCategory)4 Context (me.shadorc.shadbot.core.command.Context)4 Command (me.shadorc.shadbot.core.command.annotation.Command)4 BotUtils (me.shadorc.shadbot.utils.BotUtils)4 FormatUtils (me.shadorc.shadbot.utils.FormatUtils)4 TextUtils (me.shadorc.shadbot.utils.TextUtils)4