Search in sources :

Example 1 with Event

use of com.github.jikoo.planarwrappers.event.Event in project Easterlyn by Easterlyn.

the class MinecraftBridge method setup.

public void setup() {
    client.getEventDispatcher().on(MessageCreateEvent.class).flatMap(event -> Mono.fromRunnable(() -> {
        if (event.getMessage().getAuthor().isEmpty() || event.getMessage().getAuthor().get().isBot()) {
            return;
        }
        User author = event.getMessage().getAuthor().get();
        String msg = event.getMessage().getContent();
        MessageChannel channel = event.getMessage().getChannel().block();
        String command = null;
        String commandData = null;
        if (msg.startsWith(plugin.getCommandPrefix())) {
            int prefixLength = plugin.getCommandPrefix().length();
            int space = msg.indexOf(' ');
            if (space < prefixLength) {
                space = msg.length();
            }
            command = msg.substring(prefixLength, space).toLowerCase();
            commandData = msg.substring(space < msg.length() ? space + 1 : space);
        }
        if (command != null && command.equals("link")) {
            UUID pendingLink = plugin.getPendingLink(commandData);
            if (pendingLink == null) {
                channel.createMessage("Invalid link code! If your code expired, rerun `/link` in" + " Minecraft.\n" + "If you're having trouble, try clicking the message to" + " copy the code!");
            } else {
                plugin.addLink(pendingLink, author.getId());
            }
        }
        boolean main = channel instanceof GuildMessageChannel && plugin.isChannelType(channel.getId(), ChannelType.MAIN);
        if (!main && command == null) {
            return;
        }
        DiscordUser sender = plugin.getUser(author.getId());
        if (sender == null) {
            Snowflake id = author.getId();
            if (warnings.getIfPresent(id) != null) {
                return;
            }
            warnings.put(id, true);
            channel.createMessage(author.getMention() + ", you must run `/link` in Minecraft to use this" + " feature!").subscribe();
            return;
        }
        if (command != null) {
            handleCommand(sender, channel, command, commandData);
            return;
        }
        handleDiscordChat(sender, event.getMessage());
    }).onErrorResume(error -> {
        System.out.println("Caught exception handling Discord event:");
        error.printStackTrace();
        return Mono.empty();
    }).thenReturn(event)).subscribe();
    Event.register(UserChatEvent.class, event -> {
        // TODO may want to try to softdepend on chat instead of hard
        if (event.isAsynchronous()) {
            handleMinecraftChat(event);
        } else {
            // Ensure handling is done asynchronously even if chat is somehow sent on main thread
            plugin.getServer().getScheduler().runTaskAsynchronously(plugin, () -> handleMinecraftChat(event));
        }
    }, plugin);
    Event.register(PlayerCommandPreprocessEvent.class, event -> {
        if (event.getPlayer().hasPermission("easterlyn.discord.exempt.commandlog")) {
            return;
        }
        RegisteredServiceProvider<EasterlynCore> registration = plugin.getServer().getServicesManager().getRegistration(EasterlynCore.class);
        if (registration == null) {
            return;
        }
        int space = event.getMessage().indexOf(' ');
        String commandName = event.getMessage().substring(1, space > 0 ? space : event.getMessage().length()).toLowerCase();
        SimpleCommandMap commandMap = registration.getProvider().getSimpleCommandMap();
        if (commandMap == null) {
            return;
        }
        Command command = commandMap.getCommand(commandName);
        if (command != null && !plugin.getConfig().getStringList("command-log-blacklist").contains(command.getName())) {
            plugin.postMessage(ChannelType.LOG, event.getPlayer().getName() + " issued command: " + event.getMessage());
        }
    }, plugin, EventPriority.MONITOR);
    Event.register(PlayerJoinEvent.class, event -> plugin.postMessage(ChannelType.MAIN, ChatColor.stripColor(event.getPlayer().getDisplayName()) + " logs in."), plugin, EventPriority.MONITOR);
    Event.register(PlayerQuitEvent.class, event -> plugin.postMessage(ChannelType.MAIN, ChatColor.stripColor(event.getPlayer().getDisplayName()) + " logs out."), plugin);
}
Also used : MessageChannel(discord4j.core.object.entity.channel.MessageChannel) UserChatEvent(com.easterlyn.chat.event.UserChatEvent) SimpleCommandMap(org.bukkit.command.SimpleCommandMap) Snowflake(discord4j.common.util.Snowflake) Attachment(discord4j.core.object.entity.Attachment) GuildChannel(discord4j.core.object.entity.channel.GuildChannel) GuildMessageChannel(discord4j.core.object.entity.channel.GuildMessageChannel) Matcher(java.util.regex.Matcher) PlayerCommandPreprocessEvent(org.bukkit.event.player.PlayerCommandPreprocessEvent) EasterlynDiscord(com.easterlyn.EasterlynDiscord) ChatColor(net.md_5.bungee.api.ChatColor) User(discord4j.core.object.entity.User) PlayerJoinEvent(org.bukkit.event.player.PlayerJoinEvent) MessageCreateEvent(discord4j.core.event.domain.message.MessageCreateEvent) EasterlynCore(com.easterlyn.EasterlynCore) Mono(reactor.core.publisher.Mono) UUID(java.util.UUID) ReactionEmoji(discord4j.core.object.reaction.ReactionEmoji) TimeUnit(java.util.concurrent.TimeUnit) Event(com.github.jikoo.planarwrappers.event.Event) Message(discord4j.core.object.entity.Message) EventPriority(org.bukkit.event.EventPriority) PlayerQuitEvent(org.bukkit.event.player.PlayerQuitEvent) Channel(discord4j.core.object.entity.channel.Channel) Command(org.bukkit.command.Command) CacheBuilder(com.google.common.cache.CacheBuilder) GatewayDiscordClient(discord4j.core.GatewayDiscordClient) Pattern(java.util.regex.Pattern) Cache(com.google.common.cache.Cache) NotNull(org.jetbrains.annotations.NotNull) RegisteredServiceProvider(org.bukkit.plugin.RegisteredServiceProvider) EasterlynChat(com.easterlyn.EasterlynChat) User(discord4j.core.object.entity.User) EasterlynCore(com.easterlyn.EasterlynCore) SimpleCommandMap(org.bukkit.command.SimpleCommandMap) GuildMessageChannel(discord4j.core.object.entity.channel.GuildMessageChannel) MessageChannel(discord4j.core.object.entity.channel.MessageChannel) GuildMessageChannel(discord4j.core.object.entity.channel.GuildMessageChannel) Command(org.bukkit.command.Command) Snowflake(discord4j.common.util.Snowflake) UUID(java.util.UUID)

Example 2 with Event

use of com.github.jikoo.planarwrappers.event.Event in project Easterlyn by Easterlyn.

the class EasterlynEffects method applyEffects.

/**
 * Applies all effects to the given LivingEntity.
 *
 * @param entity the LivingEntity
 */
private void applyEffects(@NotNull LivingEntity entity, @Nullable org.bukkit.event.Event event) {
    EntityEquipment equipment = entity.getEquipment();
    if (equipment == null) {
        return;
    }
    Map<Effect, Integer> effects = new HashMap<>();
    equipmentSlotMap.forEach((equipmentSlot, equipmentSlotFunction) -> getEffects(false, equipmentSlotFunction.apply(equipment)).forEach((effect, level) -> {
        if (!effect.getTarget().apply(equipmentSlot)) {
            return;
        }
        effects.compute(effect, (value, current) -> {
            if (current == null) {
                current = level;
            } else {
                current += level;
            }
            return current > effect.getMaxTotalLevel() ? effect.getMaxTotalLevel() : current;
        });
    }));
    effects.forEach((effect, level) -> effect.applyEffect(entity, level, event));
}
Also used : HashMap(java.util.HashMap) Player(org.bukkit.entity.Player) Reflections(org.reflections.Reflections) Constructor(java.lang.reflect.Constructor) Function(java.util.function.Function) ArrayList(java.util.ArrayList) Matcher(java.util.regex.Matcher) PluginEnableEvent(org.bukkit.event.server.PluginEnableEvent) Map(java.util.Map) PlayerInteractEvent(org.bukkit.event.player.PlayerInteractEvent) Material(org.bukkit.Material) EntityDamageByEntityEvent(org.bukkit.event.entity.EntityDamageByEntityEvent) EntityDamageEvent(org.bukkit.event.entity.EntityDamageEvent) EquipmentSlot(org.bukkit.inventory.EquipmentSlot) NumberUtil(com.easterlyn.util.NumberUtil) Iterator(java.util.Iterator) FurnaceExtractEvent(org.bukkit.event.inventory.FurnaceExtractEvent) Set(java.util.Set) BlockBreakEvent(org.bukkit.event.block.BlockBreakEvent) Pair(com.github.jikoo.planarwrappers.tuple.Pair) LivingEntity(org.bukkit.entity.LivingEntity) EconomyUtil(com.easterlyn.util.EconomyUtil) Collectors(java.util.stream.Collectors) InvocationTargetException(java.lang.reflect.InvocationTargetException) ItemStack(org.bukkit.inventory.ItemStack) JavaPlugin(org.bukkit.plugin.java.JavaPlugin) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) Effect(com.easterlyn.effect.Effect) Event(com.github.jikoo.planarwrappers.event.Event) EventPriority(org.bukkit.event.EventPriority) Modifier(java.lang.reflect.Modifier) ChatColor(org.bukkit.ChatColor) Pattern(java.util.regex.Pattern) EntityEquipment(org.bukkit.inventory.EntityEquipment) NotNull(org.jetbrains.annotations.NotNull) RegisteredServiceProvider(org.bukkit.plugin.RegisteredServiceProvider) PlayerChangedWorldEvent(org.bukkit.event.player.PlayerChangedWorldEvent) HashMap(java.util.HashMap) EntityEquipment(org.bukkit.inventory.EntityEquipment) Effect(com.easterlyn.effect.Effect)

Example 3 with Event

use of com.github.jikoo.planarwrappers.event.Event in project Easterlyn by Easterlyn.

the class EasterlynMachines method onEnable.

@Override
public void onEnable() {
    saveDefaultConfig();
    new Reflections("com.easterlyn.machine", getClassLoader()).getSubTypesOf(Machine.class).stream().filter(clazz -> !Modifier.isAbstract(clazz.getModifiers())).forEach(clazz -> {
        Constructor<? extends Machine> constructor;
        Machine machine;
        try {
            constructor = clazz.getConstructor(this.getClass());
            machine = constructor.newInstance(this);
        } catch (ReflectiveOperationException e) {
            getLogger().severe("Unable to load machine " + clazz.getName());
            e.printStackTrace();
            return;
        }
        nameRegistry.put(machine.getClass().getSimpleName().toLowerCase(), machine);
        nameRegistry.put(machine.getName().toLowerCase(), machine);
        iconRegistry.put(machine.getUniqueDrop(), machine);
    });
    Event.register(BlockPlaceEvent.class, event -> {
        Player player = event.getPlayer();
        Pair<Machine, ConfigurationSection> pair = getMachine(event.getBlock());
        if (pair != null) {
            // Block registered as part of a machine. Most likely removed by explosion or similar.
            // Prevents place PGO as diamond block, blow up PGO, place and break dirt in PGO's
            // location to unregister, wait for CreeperHeal to regenerate diamond block for profit.
            event.setCancelled(true);
            player.sendMessage("machines.noTouch");
            // fire a reportable event and repair.
            if (exploded.get(event.getBlock()) == null) {
                pair.getLeft().reassemble(pair.getRight());
                ReportableEvent.call(String.format("Repairing broken %s at %s %s %s after internal placement by %s", pair.getLeft().getName(), event.getBlock().getX(), event.getBlock().getY(), event.getBlock().getZ(), event.getPlayer().getName()));
            }
            return;
        }
        // Machine place logic
        for (Map.Entry<ItemStack, Machine> entry : iconRegistry.entrySet()) {
            if (entry.getKey().isSimilar(event.getItemInHand())) {
                pair = createMachine(event.getBlock(), entry.getValue(), event.getPlayer().getUniqueId(), Direction.getFacingDirection(event.getPlayer()));
                if (pair == null) {
                    event.setCancelled(true);
                    return;
                }
                if (pair.getLeft().failedAssembly(pair.getRight())) {
                    event.setCancelled(true);
                }
                if (!event.isCancelled() && player.getGameMode() != GameMode.CREATIVE) {
                    if (player.getInventory().getItemInMainHand().equals(event.getItemInHand())) {
                        player.getInventory().setItemInMainHand(ItemUtil.decrement(event.getItemInHand(), 1));
                    } else {
                        player.getInventory().setItemInOffHand(ItemUtil.decrement(event.getItemInHand(), 1));
                    }
                }
                event.setCancelled(true);
                break;
            }
        }
    }, this, EventPriority.HIGHEST);
    hookCreeperHeal();
    // Machine event handlers
    Event.register(PlayerInteractEvent.class, event -> {
        if (event.getClickedBlock() == null) {
            return;
        }
        Pair<Machine, ConfigurationSection> machine = getMachine(event.getClickedBlock());
        if (machine != null) {
            machine.getLeft().handleInteract(event, machine.getRight());
        }
    }, this, EventPriority.LOW);
    Event.register(InventoryMoveItemEvent.class, event -> {
        InventoryHolder inventoryHolder = event.getDestination().getHolder();
        // For now, sending inv is not checked, as no machines require it.
        if (inventoryHolder instanceof BlockState) {
            Pair<Machine, ConfigurationSection> pair = getMachine(((BlockState) inventoryHolder).getBlock());
            if (pair != null) {
                pair.getLeft().handleHopperMoveItem(event, pair.getRight());
            }
        }
    }, this, EventPriority.LOW);
    Event.register(InventoryPickupItemEvent.class, event -> {
        InventoryHolder inventoryHolder = event.getInventory().getHolder();
        // For now, sending inv is not checked, as no machines require it.
        if (inventoryHolder instanceof BlockState) {
            Pair<Machine, ConfigurationSection> pair = getMachine(((BlockState) inventoryHolder).getBlock());
            if (pair != null) {
                pair.getLeft().handleHopperPickupItem(event, pair.getRight());
            }
        }
    }, this, EventPriority.LOW);
    registerInventoryEvent(InventoryClickEvent.class, machine -> machine::handleClick);
    registerInventoryEvent(InventoryDragEvent.class, machine -> machine::handleDrag);
    registerInventoryEvent(InventoryOpenEvent.class, machine -> machine::handleOpen);
    registerInventoryEvent(InventoryCloseEvent.class, machine -> machine::handleClose);
    Event.register(InventoryCloseEvent.class, event -> {
        if (event.getView().getTopInventory() instanceof MerchantInventory) {
            merchants.remove(((MerchantInventory) event.getView().getTopInventory()).getMerchant());
        }
    }, this, EventPriority.HIGH);
    Event.register(TradeSelectEvent.class, event -> {
        Pair<Machine, ConfigurationSection> machineData = merchants.get(event.getMerchant());
        if (machineData != null) {
            machineData.getLeft().selectTrade(event, machineData.getRight());
        }
    }, this);
    Event.register(BlockPistonExtendEvent.class, event -> {
        if (isMachine(event.getBlock()) || event.getBlocks().stream().anyMatch(this::isMachine)) {
            event.setCancelled(true);
        }
    }, this, EventPriority.LOW);
    Event.register(BlockPistonRetractEvent.class, event -> {
        if (isMachine(event.getBlock()) || event.getBlocks().stream().anyMatch(this::isMachine)) {
            event.setCancelled(true);
        }
    }, this, EventPriority.LOW);
    Event.register(PlayerBucketEmptyEvent.class, event -> {
        if (isMachine(event.getBlockClicked().getRelative(event.getBlockFace()))) {
            // If we do end up creating a lava well etc. this will need to be added to an event.
            event.setCancelled(true);
        }
    }, this, EventPriority.LOW);
    Consumer<PlayerBucketEvent> bucketConsumer = event -> {
        if (isMachine(event.getBlockClicked().getRelative(event.getBlockFace()))) {
            event.setCancelled(true);
        }
    };
    Event.register(PlayerBucketEmptyEvent.class, bucketConsumer::accept, this, EventPriority.LOW);
    Event.register(PlayerBucketFillEvent.class, bucketConsumer::accept, this, EventPriority.LOW);
    registerBlockEvent(BlockBreakEvent.class, machine -> machine::handleBreak);
    registerBlockEvent(BlockFadeEvent.class, machine -> machine::handleFade);
    registerBlockEvent(BlockFromToEvent.class, machine -> machine::handleFromTo);
    registerBlockEvent(BlockIgniteEvent.class, machine -> machine::handleIgnite);
    registerBlockEvent(BlockSpreadEvent.class, machine -> machine::handleSpread);
    // Prevent all external machine manipulation
    Event.register(BlockPhysicsEvent.class, event -> {
        if (isMachine(event.getBlock())) {
            event.setCancelled(true);
        }
    }, this);
    Event.register(EntityChangeBlockEvent.class, event -> {
        if (isMachine(event.getBlock())) {
            event.setCancelled(true);
        }
    }, this);
    Event.register(ChunkLoadEvent.class, event -> getServer().getScheduler().runTask(this, () -> loadChunkMachines(event.getChunk())), this);
    // TODO periodic save system (timer triggered by chunk unload?)
    Event.register(ChunkUnloadEvent.class, event -> getServer().getScheduler().runTask(this, () -> unloadChunkMachines(event.getChunk())), this);
    for (World world : getServer().getWorlds()) {
        if (getConfig().getStringList("+disabled-worlds+").contains(world.getName())) {
            continue;
        }
        for (Chunk chunk : world.getLoadedChunks()) {
            loadChunkMachines(chunk);
        }
    }
    RegisteredServiceProvider<EasterlynCore> registration = getServer().getServicesManager().getRegistration(EasterlynCore.class);
    if (registration != null) {
        register(registration.getProvider());
    }
    Event.register(PluginEnableEvent.class, pluginEnableEvent -> {
        if (pluginEnableEvent.getPlugin() instanceof EasterlynCore) {
            register((EasterlynCore) pluginEnableEvent.getPlugin());
        }
    }, this);
}
Also used : BlockPistonExtendEvent(org.bukkit.event.block.BlockPistonExtendEvent) Arrays(java.util.Arrays) InventoryEvent(org.bukkit.event.inventory.InventoryEvent) TradeSelectEvent(org.bukkit.event.inventory.TradeSelectEvent) ChunkUnloadEvent(org.bukkit.event.world.ChunkUnloadEvent) ConfigurationSection(org.bukkit.configuration.ConfigurationSection) Player(org.bukkit.entity.Player) Reflections(org.reflections.Reflections) Inventory(org.bukkit.inventory.Inventory) Merchant(org.bukkit.inventory.Merchant) CreeperConfig(com.nitnelave.CreeperHeal.config.CreeperConfig) Block(org.bukkit.block.Block) BlockPistonRetractEvent(org.bukkit.event.block.BlockPistonRetractEvent) Location(org.bukkit.Location) World(org.bukkit.World) PluginEnableEvent(org.bukkit.event.server.PluginEnableEvent) Map(java.util.Map) Chunk(org.bukkit.Chunk) BlockEvent(org.bukkit.event.block.BlockEvent) BlockPlaceEvent(org.bukkit.event.block.BlockPlaceEvent) Bukkit(org.bukkit.Bukkit) BlockPhysicsEvent(org.bukkit.event.block.BlockPhysicsEvent) BlockSpreadEvent(org.bukkit.event.block.BlockSpreadEvent) Machine(com.easterlyn.machine.Machine) Collection(java.util.Collection) Set(java.util.Set) InventoryClickEvent(org.bukkit.event.inventory.InventoryClickEvent) CHBlockHealEvent(com.nitnelave.CreeperHeal.events.CHBlockHealEvent) InventoryDragEvent(org.bukkit.event.inventory.InventoryDragEvent) Pair(com.github.jikoo.planarwrappers.tuple.Pair) UUID(java.util.UUID) EntityType(org.bukkit.entity.EntityType) BlockIgniteEvent(org.bukkit.event.block.BlockIgniteEvent) PlayerBucketFillEvent(org.bukkit.event.player.PlayerBucketFillEvent) ItemStack(org.bukkit.inventory.ItemStack) JavaPlugin(org.bukkit.plugin.java.JavaPlugin) Nullable(org.jetbrains.annotations.Nullable) Event(com.github.jikoo.planarwrappers.event.Event) InventoryOpenEvent(org.bukkit.event.inventory.InventoryOpenEvent) Modifier(java.lang.reflect.Modifier) BlockUtil(com.easterlyn.util.BlockUtil) BlockMultimap(com.github.jikoo.planarwrappers.collections.BlockMultimap) EntityExplodeEvent(org.bukkit.event.entity.EntityExplodeEvent) NotNull(org.jetbrains.annotations.NotNull) InventoryPickupItemEvent(org.bukkit.event.inventory.InventoryPickupItemEvent) BlockMap(com.github.jikoo.planarwrappers.collections.BlockMap) HashMap(java.util.HashMap) Coords(com.github.jikoo.planarwrappers.util.Coords) InventoryCloseEvent(org.bukkit.event.inventory.InventoryCloseEvent) BlockFadeEvent(org.bukkit.event.block.BlockFadeEvent) Constructor(java.lang.reflect.Constructor) Function(java.util.function.Function) GameMode(org.bukkit.GameMode) EntityChangeBlockEvent(org.bukkit.event.entity.EntityChangeBlockEvent) InventoryMoveItemEvent(org.bukkit.event.inventory.InventoryMoveItemEvent) ChunkLoadEvent(org.bukkit.event.world.ChunkLoadEvent) BiConsumer(java.util.function.BiConsumer) PlayerInteractEvent(org.bukkit.event.player.PlayerInteractEvent) ItemUtil(com.easterlyn.util.inventory.ItemUtil) Direction(com.github.jikoo.planarwrappers.world.Direction) Iterator(java.util.Iterator) ReportableEvent(com.easterlyn.event.ReportableEvent) BlockState(org.bukkit.block.BlockState) BlockBreakEvent(org.bukkit.event.block.BlockBreakEvent) Consumer(java.util.function.Consumer) InventoryHolder(org.bukkit.inventory.InventoryHolder) PlayerBucketEmptyEvent(org.bukkit.event.player.PlayerBucketEmptyEvent) EventPriority(org.bukkit.event.EventPriority) PlayerBucketEvent(org.bukkit.event.player.PlayerBucketEvent) Collections(java.util.Collections) RegisteredServiceProvider(org.bukkit.plugin.RegisteredServiceProvider) BlockFromToEvent(org.bukkit.event.block.BlockFromToEvent) MerchantInventory(org.bukkit.inventory.MerchantInventory) Player(org.bukkit.entity.Player) MerchantInventory(org.bukkit.inventory.MerchantInventory) PlayerBucketEvent(org.bukkit.event.player.PlayerBucketEvent) World(org.bukkit.World) Chunk(org.bukkit.Chunk) Machine(com.easterlyn.machine.Machine) BlockState(org.bukkit.block.BlockState) ItemStack(org.bukkit.inventory.ItemStack) Map(java.util.Map) BlockMap(com.github.jikoo.planarwrappers.collections.BlockMap) HashMap(java.util.HashMap) InventoryHolder(org.bukkit.inventory.InventoryHolder) Reflections(org.reflections.Reflections) ConfigurationSection(org.bukkit.configuration.ConfigurationSection)

Aggregations

Event (com.github.jikoo.planarwrappers.event.Event)3 EventPriority (org.bukkit.event.EventPriority)3 Pair (com.github.jikoo.planarwrappers.tuple.Pair)2 Constructor (java.lang.reflect.Constructor)2 Modifier (java.lang.reflect.Modifier)2 HashMap (java.util.HashMap)2 Iterator (java.util.Iterator)2 Map (java.util.Map)2 Set (java.util.Set)2 UUID (java.util.UUID)2 Function (java.util.function.Function)2 Matcher (java.util.regex.Matcher)2 Pattern (java.util.regex.Pattern)2 RegisteredServiceProvider (org.bukkit.plugin.RegisteredServiceProvider)2 NotNull (org.jetbrains.annotations.NotNull)2 EasterlynChat (com.easterlyn.EasterlynChat)1 EasterlynCore (com.easterlyn.EasterlynCore)1 EasterlynDiscord (com.easterlyn.EasterlynDiscord)1 UserChatEvent (com.easterlyn.chat.event.UserChatEvent)1 Effect (com.easterlyn.effect.Effect)1