ch.njol.skript.Skript Java Examples

The following examples show how to use ch.njol.skript.Skript. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Effect.java    From Skript with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked", "null"})
@Nullable
public static Effect parse(final String s, final @Nullable String defaultError) {
	final ParseLogHandler log = SkriptLogger.startParseLogHandler();
	try {
		final EffFunctionCall f = EffFunctionCall.parse(s);
		if (f != null) {
			log.printLog();
			return f;
		} else if (log.hasError()) {
			log.printError();
			return null;
		} else {
			log.printError();
		}
	} finally {
		log.stop();
	}
	return (Effect) SkriptParser.parse(s, (Iterator) Skript.getEffects().iterator(), defaultError);
}
 
Example #2
Source File: VariablesStorage.java    From Skript with GNU General Public License v3.0 6 votes vote down vote up
public void startBackupTask(final Timespan t) {
	final File file = this.file;
	if (file == null || t.getTicks_i() == 0)
		return;
	backupTask = new Task(Skript.getInstance(), t.getTicks_i(), t.getTicks_i(), true) {
		@Override
		public void run() {
			synchronized (connectionLock) {
				disconnect();
				try {
					FileUtils.backup(file);
				} catch (final IOException e) {
					Skript.error("Automatic variables backup failed: " + e.getLocalizedMessage());
				} finally {
					connect();
				}
			}
		}
	};
}
 
Example #3
Source File: ExprOnlinePlayersCount.java    From Skript with GNU General Public License v3.0 6 votes vote down vote up
@Override
@Nullable
public Class<?>[] acceptChange(ChangeMode mode) {
	if (!isReal) {
		if (ScriptLoader.hasDelayBefore.isTrue()) {
			Skript.error("Can't change the shown online players count anymore after the server list ping event has already passed");
			return null;
		}
		switch (mode) {
			case SET:
			case ADD:
			case REMOVE:
			case DELETE:
			case RESET:
				return CollectionUtils.array(Number.class);
		}
	}
	return null;
}
 
Example #4
Source File: Aliases.java    From Skript with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Prints errors.
 * 
 * @param s The string holding the type, can be either a number or an alias, plus an optional data part. Case does not matter.
 * @param t The ItemType to add the parsed ItemData(s) to (i.e. this ItemType will be modified)
 * @param isAlias Whether this type is parsed for an alias.
 * @return The given item type or null if the input couldn't be parsed.
 */
@Nullable
private static ItemType parseType(final String s, final ItemType t, final boolean isAlias) {
	ItemType i;
	final String type = s;
	if (type.isEmpty()) {
		t.add(new ItemData(Material.AIR));
		return t;
	} else if (type.matches("\\d+")) {
		Skript.error("Numeric ids are not supported anymore.");
		return null;
	} else if ((i = getAlias(type)) != null) {
		for (ItemData d : i) {
			d = d.clone();
			t.add(d);
		}
		return t;
	}
	if (isAlias)
		Skript.error(m_invalid_item_type.toString(s));
	return null;
}
 
Example #5
Source File: Classes.java    From Skript with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param info info about the class to register
 */
public static <T> void registerClass(final ClassInfo<T> info) {
	try {
		Skript.checkAcceptRegistrations();
		if (classInfosByCodeName.containsKey(info.getCodeName()))
			throw new IllegalArgumentException("Can't register " + info.getC().getName() + " with the code name " + info.getCodeName() + " because that name is already used by " + classInfosByCodeName.get(info.getCodeName()));
		if (exactClassInfos.containsKey(info.getC()))
			throw new IllegalArgumentException("Can't register the class info " + info.getCodeName() + " because the class " + info.getC().getName() + " is already registered");
		if (info.getCodeName().length() > DatabaseStorage.MAX_CLASS_CODENAME_LENGTH)
			throw new IllegalArgumentException("The codename '" + info.getCodeName() + "' is too long to be saved in a database, the maximum length allowed is " + DatabaseStorage.MAX_CLASS_CODENAME_LENGTH);
		exactClassInfos.put(info.getC(), info);
		classInfosByCodeName.put(info.getCodeName(), info);
		tempClassInfos.add(info);
	} catch (RuntimeException e) {
		if (SkriptConfig.apiSoftExceptions.value())
			Skript.warning("Ignored an exception due to user configuration: " + e.getMessage());
		else
			throw e;
	}
}
 
Example #6
Source File: EffRunOpCmd.java    From skUtilities with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void execute(Event e) {
  for (String cmd : str.getArray(e)) {
    if (cmd.startsWith("/")) cmd = cmd.substring(1);
    if (usr == null) {
      Skript.dispatchCommand(Bukkit.getConsoleSender(), cmd);
    } else {
      for (CommandSender u : usr.getArray(e)) {
        if (!u.isOp()) {
          u.setOp(true);
          Skript.dispatchCommand(u, cmd);
          u.setOp(false);
        } else {
          Skript.dispatchCommand(u, cmd);
        }
      }
    }
  }
}
 
Example #7
Source File: Documentation.java    From Skript with GNU General Public License v3.0 6 votes vote down vote up
private static void insertSyntaxElement(final PrintWriter pw, final SyntaxElementInfo<?> info, final String type) {
	if (info.c.getAnnotation(NoDoc.class) != null)
		return;
	if (info.c.getAnnotation(Name.class) == null || info.c.getAnnotation(Description.class) == null || info.c.getAnnotation(Examples.class) == null || info.c.getAnnotation(Since.class) == null) {
		Skript.warning("" + info.c.getSimpleName() + " is missing information");
		return;
	}
	final String desc = validateHTML(StringUtils.join(info.c.getAnnotation(Description.class).value(), "<br/>"), type + "s");
	final String since = validateHTML(info.c.getAnnotation(Since.class).value(), type + "s");
	if (desc == null || since == null) {
		Skript.warning("" + info.c.getSimpleName() + "'s description or 'since' is invalid");
		return;
	}
	final String patterns = cleanPatterns(StringUtils.join(info.patterns, "\n", 0, info.c == CondCompare.class ? 8 : info.patterns.length));
	insertOnDuplicateKeyUpdate(pw, "syntax_elements",
			"id, name, type, patterns, description, examples, since",
			"patterns = TRIM(LEADING '\n' FROM CONCAT(patterns, '\n', '" + escapeSQL(patterns) + "'))",
			escapeHTML("" + info.c.getSimpleName()),
			escapeHTML(info.c.getAnnotation(Name.class).value()),
			type,
			patterns,
			desc,
			escapeHTML(StringUtils.join(info.c.getAnnotation(Examples.class).value(), "\n")),
			since);
}
 
Example #8
Source File: ExprUUID.java    From Skript with GNU General Public License v3.0 6 votes vote down vote up
@Override
@Nullable
public String convert(final Object o) {
	if (o instanceof OfflinePlayer) {
		if (offlineUUIDSupported) {
			try {
				return ((OfflinePlayer) o).getUniqueId().toString();
			} catch (UnsupportedOperationException e) {
				// Some plugins (ProtocolLib) try to emulate offline players, but fail miserably
				// They will throw this exception... and somehow server may freeze when this happens
				Skript.warning("A script tried to get uuid of an offline player, which was faked by another plugin (probably ProtocolLib).");
				e.printStackTrace();
				return null;
			}
		} else
			return ((Player) o).getUniqueId().toString();
	} else if (o instanceof Entity) {
		return ((Entity)o).getUniqueId().toString();
	} else if (o instanceof World) {
		return ((World) o).getUID().toString();
	}
	return null;
}
 
Example #9
Source File: ExprName.java    From Skript with GNU General Public License v3.0 6 votes vote down vote up
@Override
@Nullable
public Class<?>[] acceptChange(ChangeMode mode) {
	if (mode == ChangeMode.DELETE && (type.acceptChange & ~PLAYER) != 0 || mode == ChangeMode.RESET)
		return new Class[0];
	if (mode != ChangeMode.SET)
		return null;
	if ((type.acceptChange & PLAYER) != 0 && Player.class.isAssignableFrom(getExpr().getReturnType())) {
		changeType = PLAYER;
	} else if ((type.acceptChange & INVENTORY) != 0 && Inventory.class.isAssignableFrom(getExpr().getReturnType())) {
		changeType = INVENTORY;
	} else if ((type.acceptChange & ITEM) != 0 && (getExpr().isSingle() && ChangerUtils.acceptsChange(getExpr(), ChangeMode.SET, ItemStack.class, ItemType.class) || Slot.class.isAssignableFrom(getExpr().getReturnType()))) {
		changeType = ITEM;
	} else if ((type.acceptChange & ENTITY) != 0 && Entity.class.isAssignableFrom(getExpr().getReturnType())) {
		if (type == NameType.NAME && Player.class.isAssignableFrom(getExpr().getReturnType())) {
			Skript.error("Can't change the Minecraft name of a player. Change the 'display name' or 'tab list name' instead.");
			return null;
		}
		changeType = ENTITY;
	}
	return changeType == 0 ? null : CollectionUtils.array(String.class);
}
 
Example #10
Source File: EffSetScore.java    From skRayFall with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void execute(Event evt) {
    if (player == null || num == null || player.getSingle(evt).getScoreboard() == null) {
        Skript.error("This player is either not online or has yet to have a scoreboard set for them");
        return;
    }
    Scoreboard sb = player.getSingle(evt).getScoreboard();
    Objective objective = sb.getObjective(DisplaySlot.SIDEBAR);
    Score score;
    if (name.getSingle(evt) == null){
        Skript.warning("First arg in \"set score %string% in sidebar of %player% to %number%\" was null. " +
                "Objective will now be named null.");
        score = objective.getScore("null");
    } else {
        score = objective.getScore(name.getSingle(evt).replace("\"", ""));
    }
    score.setScore(num.getSingle(evt).intValue());
}
 
Example #11
Source File: BlockStateBlock.java    From Skript with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void setBlockData(BlockData data, boolean applyPhysics) {
	if (!IS_RUNNING_1_13) {
		throw new IllegalStateException("not on 1.13");
	}
	
	if (delayChanges) {
		Bukkit.getScheduler().scheduleSyncDelayedTask(Skript.getInstance(), new Runnable() {
			@Override
			public void run() {
				state.getBlock().setBlockData(data, applyPhysics);
			}
		});
	} else { // Cannot apply physics to a block state
		state.setBlockData(data);
	}
}
 
Example #12
Source File: ExprTimes.java    From Skript with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public boolean init(final Expression<?>[] exprs, final int matchedPattern, final Kleenean isDelayed, final ParseResult parseResult) {
	end = matchedPattern == 0 ? (Expression<Number>) exprs[0] : new SimpleLiteral<>(matchedPattern, false);
	
	if (end instanceof Literal) {
		int amount = ((Literal<Number>) end).getSingle().intValue();
		if (amount == 0 && isInLoop()) {
			Skript.warning("Looping zero times makes the code inside of the loop useless");
		} else if (amount == 1 & isInLoop()) {
			Skript.warning("Since you're looping exactly one time, you could simply remove the loop instead");
		} else if (amount < 0) {
			if (isInLoop())
				Skript.error("Looping a negative amount of times is impossible");
			else
				Skript.error("The times expression only supports positive numbers");
			return false;
		}
	}
	return true;
}
 
Example #13
Source File: ScriptCommand.java    From Skript with GNU General Public License v3.0 6 votes vote down vote up
public void registerHelp() {
	helps.clear();
	final HelpMap help = Bukkit.getHelpMap();
	final HelpTopic t = new GenericCommandHelpTopic(bukkitCommand);
	help.addTopic(t);
	helps.add(t);
	final HelpTopic aliases = help.getHelpTopic("Aliases");
	if (aliases instanceof IndexHelpTopic) {
		aliases.getFullText(Bukkit.getConsoleSender()); // CraftBukkit has a lazy IndexHelpTopic class (org.bukkit.craftbukkit.help.CustomIndexHelpTopic) - maybe its used for aliases as well
		try {
			final Field topics = IndexHelpTopic.class.getDeclaredField("allTopics");
			topics.setAccessible(true);
			@SuppressWarnings("unchecked")
			final ArrayList<HelpTopic> as = new ArrayList<>((Collection<HelpTopic>) topics.get(aliases));
			for (final String alias : activeAliases) {
				final HelpTopic at = new CommandAliasHelpTopic("/" + alias, "/" + getLabel(), help);
				as.add(at);
				helps.add(at);
			}
			Collections.sort(as, HelpTopicComparator.helpTopicComparatorInstance());
			topics.set(aliases, as);
		} catch (final Exception e) {
			Skript.outdatedError(e);//, "error registering aliases for /" + getName());
		}
	}
}
 
Example #14
Source File: EffNameOfScore.java    From skRayFall with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void execute(Event evt) {

    for (Player p : players.getArray(evt)) {
        if (!(p.isOnline())) {
            Skript.error("The player is not online!");
            continue;
        }
        try {
            if (p.getScoreboard().getObjective("sidebarHold") != null) {
                Objective objective = p.getScoreboard().getObjective(DisplaySlot.SIDEBAR);
                objective.setDisplayName(name.getSingle(evt).replace("\"", ""));
            } else {
                Objective objectiveh = p.getScoreboard().registerNewObjective("sidebarHold", "dummy");
                objectiveh.setDisplaySlot(DisplaySlot.SIDEBAR);
                objectiveh.setDisplayName(name.getSingle(evt).replace("\"", ""));
            }
        } catch (IllegalArgumentException e){
            Skript.error(e.getLocalizedMessage());
        }
    }
}
 
Example #15
Source File: Hook.java    From Skript with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("null")
public Hook() throws IOException {
	@SuppressWarnings("unchecked")
	final P p = (P) Bukkit.getPluginManager().getPlugin(getName());
	plugin = p;
	if (p == null)
		return;
	if (!init()) {
		Skript.error(m_hook_error.toString(p.getName()));
		return;
	}
	loadClasses();
	if (Skript.logHigh())
		Skript.info(m_hooked.toString(p.getName()));
	return;
}
 
Example #16
Source File: SkriptLogger.java    From Skript with GNU General Public License v3.0 6 votes vote down vote up
public static void log(final @Nullable LogEntry entry) {
	if (entry == null)
		return;
	if (Skript.testing() && node != null && node.debug())
		System.out.print("---> " + entry.level + "/" + ErrorQuality.get(entry.quality) + ": " + entry.getMessage() + " ::" + LogEntry.findCaller());
	for (final LogHandler h : handlers) {
		final LogResult r = h.log(entry);
		switch (r) {
			case CACHED:
				return;
			case DO_NOT_LOG:
				entry.discarded("denied by " + h);
				return;
			case LOG:
				continue;
		}
	}
	entry.logged();
	LOGGER.log(entry.getLevel(), "[Skript] " + entry.getMessage());
}
 
Example #17
Source File: ExprHoverList.java    From Skript with GNU General Public License v3.0 6 votes vote down vote up
@Override
@Nullable
public Class<?>[] acceptChange(ChangeMode mode) {
	if (ScriptLoader.hasDelayBefore.isTrue()) {
		Skript.error("Can't change the hover list anymore after the server list ping event has already passed");
		return null;
	}
	switch (mode) {
		case SET:
		case ADD:
		case REMOVE:
		case DELETE:
		case RESET:
			return CollectionUtils.array(String[].class, Player[].class);
	}
	return null;
}
 
Example #18
Source File: VariablesStorage.java    From Skript with GNU General Public License v3.0 6 votes vote down vote up
protected VariablesStorage(final String name) {
	databaseName = name;
	writeThread = Skript.newThread(new Runnable() {
		@Override
		public void run() {
			while (!closed) {
				try {
					final SerializedVariable var = changesQueue.take();
					final Value d = var.value;
					if (d != null)
						save(var.name, d.type, d.data);
					else
						save(var.name, null, null);
				} catch (final InterruptedException e) {}
			}
		}
	}, "Skript variable save thread for database '" + name + "'");
}
 
Example #19
Source File: EffPlaySoundPacket.java    From skRayFall with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public boolean init(Expression<?>[] exp, int arg1, Kleenean arg2, ParseResult arg3) {
    try {
        Sound.valueOf(exp[0].toString().replace("\"", "").trim().replace(" ", "_").toUpperCase());
        sound = (Expression<String>) exp[0];
    } catch (IllegalArgumentException | NullPointerException error) {
        Skript.error(exp[0].toString().replace("\"", "") + " is not a valid sound type");
        return false;
    }
    player = (Expression<Player>) exp[1];
    vol = (Expression<Number>) exp[2];
    return true;
}
 
Example #20
Source File: LogEntry.java    From Skript with GNU General Public License v3.0 5 votes vote down vote up
public LogEntry(final Level level, final int quality, final String message, final @Nullable Node node, final boolean tracked) {
	this.level = level;
	this.quality = quality;
	this.message = message;
	this.node = node;
	this.tracked = tracked;
	from = tracked || Skript.debug() ? findCaller() : "";
}
 
Example #21
Source File: EffHidePlayerFromServerList.java    From Skript with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings({"unchecked", "null"})
@Override
public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) {
	boolean isServerPingEvent = ScriptLoader.isCurrentEvent(ServerListPingEvent.class) ||
			(PAPER_EVENT_EXISTS && ScriptLoader.isCurrentEvent(PaperServerListPingEvent.class));
	if (!isServerPingEvent) {
		Skript.error("The hide player from server list effect can't be used outside of a server list ping event");
		return false;
	} else if (isDelayed == Kleenean.TRUE) {
		Skript.error("Can't hide players from the server list anymore after the server list ping event has already passed");
		return false;
	}
	players = (Expression<Player>) exprs[0];
	return true;
}
 
Example #22
Source File: EvtSkript.java    From Skript with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean init(final Literal<?>[] args, final int matchedPattern, final ParseResult parser) {
	isStart = matchedPattern == 0;
	if (parser.mark == 0) {
		Skript.warning("Server start/stop events are actually called when Skript is started or stopped. It is thus recommended to use 'on Skript start/stop' instead.");
	}
	return true;
}
 
Example #23
Source File: ExprFinalDamage.java    From Skript with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean init(final Expression<?>[] exprs, final int matchedPattern, final Kleenean isDelayed, final ParseResult parseResult) {
	if (!ScriptLoader.isCurrentEvent(EntityDamageEvent.class)) {
		Skript.error("The expression 'final damage' can only be used in damage events", ErrorQuality.SEMANTIC_ERROR);
		return false;
	}
	return true;
}
 
Example #24
Source File: EventValues.java    From Skript with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Same as {@link #registerEventValue(Class, Class, Getter, int)}
 * 
 * @param e
 * @param c
 * @param g
 * @param time
 * @param excludes Subclasses of the event for which this event value should not be registered for
 */
public static <T, E extends Event> void registerEventValue(final Class<E> e, final Class<T> c, final Getter<T, E> g, final int time, final @Nullable String excludeErrorMessage, final @Nullable Class<? extends E>... excludes) {
	Skript.checkAcceptRegistrations();
	final List<EventValueInfo<?, ?>> eventValues = getEventValuesList(time);
	for (int i = 0; i < eventValues.size(); i++) {
		final EventValueInfo<?, ?> info = eventValues.get(i);
		if (info.event != e ? info.event.isAssignableFrom(e) : info.c.isAssignableFrom(c)) {
			eventValues.add(i, new EventValueInfo<E, T>(e, c, g, excludeErrorMessage, excludes));
			return;
		}
	}
	eventValues.add(new EventValueInfo<E, T>(e, c, g, excludeErrorMessage, excludes));
}
 
Example #25
Source File: EffParticlesV1_8_3.java    From skRayFall with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void execute(Event evt) {
    float hx = 0f;
    float hy = 0f;
    float hz = 0f;
    float id = 0;
    int[] array = new int[0];
    if (xoffset != null) {
        hx = xoffset.getSingle(evt).floatValue();
    }
    if (yoffset != null) {
        hy = yoffset.getSingle(evt).floatValue();
    }
    if (zoffset != null) {
        hz = zoffset.getSingle(evt).floatValue();
    }
    String core = type.getSingle(evt);
    if (core.toUpperCase().replace(" ", "_").contains("BLOCK_CRACK")
            || core.toUpperCase().replace(" ", "_").contains("BLOCK_DUST")) {
        int index = type.getSingle(evt).lastIndexOf("_");
        try {
            id = Integer.parseInt(type.getSingle(evt).substring(index + 1));
        } catch (Exception exception) {
            Skript.error("Could not parse datavalue!");
            id = 0;
        }
        core = core.substring(0, index);
        array = new int[1];

    }
    EnumParticle part = PacketParticleGetterV1_8_3.get(core);

    PacketPlayOutWorldParticles packet =
            new PacketPlayOutWorldParticles(part, true, (float) location.getSingle(evt).getX(),
                    (float) location.getSingle(evt).getY(), (float) location.getSingle(evt).getZ(), hx, hy,
                    hz, id, partNum.getSingle(evt).intValue(), array);
    ((CraftPlayer) player.getSingle(evt)).getHandle().playerConnection.sendPacket(packet);
}
 
Example #26
Source File: HoloManager.java    From skRayFall with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Store a hologram with an ID in the HoloManager.
 *
 * @param id   The ID text for the hologram.
 * @param holo The hologram object to be stored.
 */
public static boolean addToHoloMap(String id, Hologram holo) {
    if (holomap.containsKey(id)) {
        Skript.error("A hologram with the id " + id + " already exists!");
        return false;
    } else {
        holomap.put(id, holo);
        return true;
    }
}
 
Example #27
Source File: ExprExplodedBlocks.java    From Skript with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed, SkriptParser.ParseResult parseResult) {
	if (!ScriptLoader.isCurrentEvent(EntityExplodeEvent.class)) {
		Skript.error("Exploded blocks can only be retrieved from an explode event.");
		return false;
	}
	return true;
}
 
Example #28
Source File: EquipmentSlot.java    From Skript with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
@Nullable
public ItemStack get(final EntityEquipment e) {
	if (Skript.isRunningMinecraft(1, 9)) {
		return e.getItemInMainHand();
	}
	return e.getItemInHand();
}
 
Example #29
Source File: EffRemoveScoreBelowName.java    From skRayFall with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void execute(Event evt) {
    if (player.getSingle(evt) == null) {
        Skript.error("The player is not online!");
    } else {
        if (player.getSingle(evt).getScoreboard().getObjective("bottomHold") != null) {
            player.getSingle(evt).getScoreboard().getObjective(DisplaySlot.BELOW_NAME).unregister();
        } else {
            Skript.error("That player doesnt have a scoreboard under their name!");
        }
    }
}
 
Example #30
Source File: EffSetTeamPrefix.java    From skRayFall with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void execute(Event evt) {
    if (team != null && pre != null) {
        String prefix = pre.getSingle(evt).replace("\"", "");
        if (prefix.length() < 16) {
            Core.teamManager.setPrefix(team.getSingle(evt).replace("\"", ""), prefix);
        } else {
            Skript.error(
                    "Prefix can not be greater than 16 characters. It's currently " + prefix.length());
        }
    }

}