#Script API General

1 messages Β· Page 81 of 1

dusky flicker
#

but using bun i dont even need it to run ts

fathom hemlock
#

why is player now wrong: const attacker = event.player;

steady canopy
distant tulip
#

dude use your types completions

#

that is not a thing

fathom hemlock
dusky flicker
#

didn't you install the package?

fathom hemlock
#

I just disable it idk why

#

let me activate it

dusky flicker
fathom hemlock
#

typescript is so broken πŸ’€

#

error on res.selection

#

errror on addTag

dusky flicker
#

probably the error is the type of "attacker"

fathom hemlock
#

nvm

#

but how do I define the entity?

#

in entityHurt

#

I use damage source: const attacker = lol.damageSource

round bone
round bone
fathom hemlock
#

but idk how the define the player

round bone
#

if (attacker instanceof Player)

fathom hemlock
#

ohh

distant tulip
fathom hemlock
#

thank you guys

mighty igloo
#

so when youi setup a playerselector in custom commands how do you get the player that the user selected in the command

fresh current
#

Yo @dusky flicker

mighty igloo
#
system.beforeEvents.startup.subscribe((init: StartupEvent) => {
  init.customCommandRegistry.registerEnum("mcbepm:rankenum", ranks);
  init.customCommandRegistry.registerEnum("mcbepm:addremove", [
    "add",
    "remove",
  ]);
  const rankCommand: CustomCommand = {
    name: "mcbepm:rank",
    description: "Remove or set player ranks.",
    permissionLevel: CommandPermissionLevel.Admin,
    mandatoryParameters: [
      { type: CustomCommandParamType.Enum, name: "mcbepm:addremove" },
      {
        type: CustomCommandParamType.PlayerSelector,
        name: "mcbepm:player_select",
      },
      { type: CustomCommandParamType.Enum, name: "mcbepm:rankenum" },
    ],
  };
  init.customCommandRegistry.registerCommand(rankCommand, changerank);
});

function changerank(origin: CustomCommandOrigin, addremove: any, player_select: Player, rankenum: any): CustomCommandResult {
  (origin.sourceEntity as Player).sendMessage(addremove + player_select.name + rankenum);
  if (addremove === "add")
  {
    player_select.setDynamicProperty("mcbepm_rank", rankenum.toString());
    return { status: CustomCommandStatus.Success };
  } else if (addremove === "remove")
  {
    player_select.setDynamicProperty("mcbepm_rank", ""); 
    return { status: CustomCommandStatus.Success };
  } else {
    return {
      status: CustomCommandStatus.Failure,
      message: `Invalid add/remove option: ${addremove}`,
    };
  }
}
``` this doesnt return the player for some reason but everything else does. the player is as undefined
dusky flicker
midnight crane
cyan basin
#

Nvm, it does return Object

steady canopy
# mighty igloo

PlayerSelector returns Player[] because you can use selectors such as "@a" which is multiple targets and it doesn't matter if in the command you actually used a name or a one-target selector, it will always return an Array of Player instances. So the way you should do this is

player_select.forEach(player => {
  player.setDynamicProperty("mcbepm_rank", rankenum.toString());
})

and the same for the remove function.

#

Also if you are using typescript which is literally to help you with typings, at least put all the typings correctly instead of just doing any for almost all parameters

This should be like this:

function changerank(origin: CustomCommandOrigin, addremove: string, player_select: Player[], rankenum: string){}
cyan basin
#

Yeah, that makes sense looking more into the command

remote oyster
#
import { system, CustomCommand, CustomCommandParameter, CustomCommandParamType, CommandPermissionLevel, CustomCommandOrigin, CustomCommandResult, Player, CustomCommandStatus } from "@minecraft/server";

/**
 * Handles the `/namespace:test <target>` custom command.
 *
 * Sends a test message to all selected target players, indicating the sender's name.
 *
 * @param {CustomCommandOrigin} origin - The origin of the command, which includes the sender information.
 * @param {Player[]} targetPlayers - Array of players selected by the player selector argument.
 * @returns {CustomCommandResult} - The result of the command execution, including message and status.
 */
function handleTestCommand(origin: CustomCommandOrigin, targetPlayers: Player[]): CustomCommandResult {
    const senderName = (origin.sourceEntity as Player)?.name ?? "Unknown";

    for (const player of targetPlayers) {
        player.sendMessage(`[Test] This message was sent to you by ${senderName}`);
    }

    return {
        message: `[Test] Sent message to ${targetPlayers.length} player(s).`,
        status: CustomCommandStatus.Success,
    };
}

system.beforeEvents.startup.subscribe((object) => {
    const slashCommands = object.customCommandRegistry;

    /**
     * Registers the `/namespace:test` command at server startup.
     */
    slashCommands.registerCommand(
        {
            name: "namespace:test",
            description: "An example for making a custom slash command",
            permissionLevel: CommandPermissionLevel.Any,
            mandatoryParameters: [
                {
                    name: "target",
                    type: CustomCommandParamType.PlayerSelector,
                } as CustomCommandParameter,
            ],
            optionalParameters: [],
        } as CustomCommand,

        handleTestCommand
    );
});
leaden elbow
#

how to check if player is op (in 1.21.80)

leaden elbow
#

anyone

thorn flicker
#

only in 2.0.0-beta

leaden elbow
thorn flicker
#

so use player.isOp()

leaden elbow
#

ohh i thought it was removed

remote oyster
# leaden elbow ohh i thought it was removed

It will be in the next release most likely. Be mindful that it doesn't work well on Realms. Which is why they are refactoring it. Too many underlying conflicts of interest between local, BDS, Realms, etc when handling permissions.

leaden elbow
safe stream
#

First time seeing this error

dawn zealot
#

how do i get the direction the player is walking in even if they arent facing it

#

basically wanna get the direction the player is walking

steady canopy
dawn zealot
fresh current
#

yo @steady canopy

#

can you help me fix this script

fresh current
#

import { InputButton, ButtonState, Player, world, system, EntityHealthComponent } from "@minecraft/server";

// Map to track players' blocking and last hit times
const playerStates = new Map();

const BLOCK_WINDOW = 500; // ms window for a parry
const BLOCK_CHECK_INTERVAL = 5; // ticks (0.25s)

world.beforeEvents.entityHurt.subscribe((event) => {
const { hurtEntity, damageSource } = event;

if (!hurtEntity || hurtEntity.typeId !== "minecraft:player") return;

const player = hurtEntity;
const state = playerStates.get(player.id) || {};

const now = Date.now();

if (state.isBlocking) {
// Parry condition: recent block and timing
if (now - state.blockStart <= BLOCK_WINDOW) {
// Cancel damage
event.cancel = true;

  // Optional: push attacker back
  if (damageSource.damagingEntity) {
    const attacker = damageSource.damagingEntity;
    const direction = {
      x: attacker.location.x - player.location.x,
      y: 0,
      z: attacker.location.z - player.location.z,
    };

    const length = Math.hypot(direction.x, direction.z);
    attacker.applyKnockback(direction.x / length, direction.z / length, 1);
  }

  player.runCommandAsync("say Parried!");
} else {
  // Blocking but not timed for parry
  event.damage = event.damage / 2; // Reduce damage
  player.runCommandAsync("say Blocked!");
}

}

// Save the time they were hit
state.lastHitTime = now;
playerStates.set(player.id, state);
});

system.runInterval(() => {
for (const player of world.getPlayers()) {
const state = playerStates.get(player.id) || {};
const isSneaking = player.isSneaking;

// Start or update block
if (isSneaking && !state.isBlocking) {
  state.isBlocking = true;
  state.blockStart = Date.now();
}

// Stop block
if (!isSneaking && state.isBlocking) {
  state.isBlocking = false;
}

playerStates.set(player.id, state);

}
}, BLOCK_CHECK_INTERVAL);

#

sb told me change it to .js

#

and then when i did

#

this is what it send in game

fresh current
mighty igloo
#

so to get the player would I just do ```ts
const player = player_select[0] as Player;

gilded shadow
#

only an after Event

cinder shadow
#

not YET

shy leaf
#

please mojang

#

bless us with beforeEvents entityHurt

woven loom
#

Has anyone used debug shapes in the most recent preview? It does not appear to work for me on Android.

ivory bough
#

How to change the player's camera direction to the opposite of the current direction?

woven loom
#

invert the direction vector

#

faceAt( location-directionVector )

prisma shard
#

teleport the player to the opposite of view direction

#

ig

ivory bough
#

How to set player on fire without player.json?

ivory bough
woven loom
#

seton fire or something

ivory bough
ivory bough
#

Hey am I insane or why does getBlocks not have a location parameter?

remote oyster
random flint
#

It takes BlockVolume now

ivory bough
random flint
# ivory bough Can you give an example? Like I want it to detect at a player's location

The long solution:

import { BlockVolume } from "@minecraft/server";

function getBlockAroundPlayer(player,blockId,size=10) {
    const loc = player.location;
    const searchVolume = new BlockVolume({
        x: loc.x - size / 2,
        y: loc.y - size / 2,
        z: loc.z - size / 2
    },{
        x: loc.x + size / 2,
        y: loc.y + size / 2,
        z: loc.z + size / 2
    })
    return player.dimension.getBlocks(searchVolume,{
        includeTypes: [ blockId ]
    })
}

The short solution:

const blockBelowPlayer = player.dimension.getBlock(player.location).below()
ivory bough
#

ty

prisma shard
ivory bough
fresh current
#

yo @prisma shard

#

or @random flint

#

can one of you help me fix this

#

the parry doesnt cancel damage
and blocking doesnt stop players m1 or dmg once they are holding block and it doesnt stop players from hitting them

gaunt salmonBOT
random flint
# fresh current

Is this AI? 😐

You can't cancel damage only with ScriptAPI

#

I wish we could tho πŸ™πŸ˜­

sharp elbow
#

You will need the "minecraft:damage_sensor" component on the player (or other actors) to disable the damage.

fresh current
fresh current
sharp elbow
#

Yes, I do, and logically this looks like it would do what you want. To double-check with you: You are receiving the "Parried!" message when you parry an attack, right? It's just not cancelling damage

fresh current
#

yep

#

and im recieving the block message as well

#

the only thing it does other than them messages is knock up the attacker

#

which i also dont like

sharp elbow
#

If you don't want the attacker to receive knockback, then remove the attacker.applyKnockback call in your parry logic

#

As for cancelling the damage, it's a tad trickier. Prefacing with this: The best way is to modify the player's behavior. Does your project's goal support that?

fresh current
#

wait what do you mean by that

#

ok i just took this out

#

const attacker = event.damageSource?.damagingEntity;
if (attacker) {
const knockback = getKnockbackDirection(player, attacker);
attacker.applyKnockback({x: knockback.x, z: knockback.z}, 1.0);
}

#

was this what you were saying?

sharp elbow
#

I mean editing the player's definition so that we can cancel damage. Some creators don't like doing this, because it makes their behavior pack incompatible with other packs that also modify the player's definition; Minecraft can only apply one definition to an entity.

fresh current
#

well im using a addon

#

one piece asa

#

idk if they aer using it how to check it?

sharp elbow
#

In the behavior pack, look in the "entities" folder and see if they have a file named "player", or something along those lines.

#

(The file name does not guarantee this though, best way is to open every one and see if any definitions use the "minecraft:player" identifier)

fresh current
#

this one

#

i went to entities in bp

#

and found this

#

its the only player one

sharp elbow
#

That's the one. You can use that as a base, then

#

Seems kinda big though, haha, let's see what we're working with

#

Oof, five thousand lines

shy leaf
#

five thousand? holy

sharp elbow
#

Bad news, what I was about to suggest is not super compatible with this player definition. There are 61 damage sensors in this file already; in whatever way the author set up the different variants, they are more like micro-states on the player

fresh current
#

hmm

sharp elbow
#

Still possible technically, just really tedious to go edit

fresh current
#

so this blocking/parry system wont work basically

sharp elbow
#

You might be able to append the logic I was about to suggest onto each damage sensor, but there's no telling if that would bust the other logic that's in there (since damage sensors can only trigger one event per tick)

#

It would require a much finer understanding of how this add-on is set up to do correctly

fresh current
#

so theres no other way?

sharp elbow
#

There are the less pretty options.

  • You could give the player Resistance V when they activate a sneak, but of course that's heavily abusable.
  • You could try healing the player back for the damage they were dealt, but of course the player could die in that strike.
  • You could try placing another entity on top of the player when they sneak, so any attacker hits that instead. Probably would not work too well while moving.
#

I'm trying to think of some others

mighty igloo
#

Or you could just hide the effects with json ui

#

Edit the hud_screen.json

fresh current
#

THE MASSAHEX

mighty igloo
#

As well as the effects screen.

fresh current
#

AHHHHHHHHHHHHHHHHHHHHHHHH

mighty igloo
#

Oh well I can't exactly help you right now

#

I'm at church

#

But

fresh current
#

bet

#

u got a idea tho?

mighty igloo
#

Yes

#

Search #1067869374410657962 for something related to modifying the display of effects on the hud screen

#

Ofc you coul always just turn the resistance ui element into a shield icon in the middle to represent blocking

#

It'd be cool

sharp elbow
#

I'm not certain that this is relevant to their question, though. They need a way to prevent the player from being hurt when a parry activates

mighty igloo
#

But I also know his problem

#

I've been helping him

fresh current
#

mhm

mighty igloo
#

He doesn't like the way that the resistance looks

#

Like the ui

fresh current
#

basically i want it so if you crouch like a mili sec becfore they hit u its a parry which deflects all dmg

#

and if your holding block it makes u unable to hit and make it so you deflects dmg as well

#

but also like a block bar so if you holding it it can be broken

mighty igloo
fresh current
#

im fine with anything as long as it works

mighty igloo
#

Alr

fallow minnow
#

is there a way to grab which language the player has selected through script api

wary edge
#

No.

fallow minnow
fresh current
#

yo @sharp elbow

sharp elbow
#

🫑 What's up

fresh current
#

this is my leveling system would this be correct?

#

cause its not working

distant tulip
#

that is outdated code

#

with a lot of incorrect functions

fresh current
#

whats outdated about it?

distant tulip
#

Dynamic properties

#

we don't need to register them anymore

fresh current
#

how abt this one

#

oh nvm

#

its also outdated

#

export const quests = [
{
id: "pirate_slayer",
name: "Pirate Slayer",
description: "Kill 5 Pirates.",
entityType: "op_asa:kaizoku",
killGoal: 5,
rewardXP: 100
},
{
id: "pirate_hunter",
name: "Pirate Hunter",
description: "Kill Pirate Bandit.",
entityType: "op_asa:kaizoku4",
killGoal: 1,
rewardXP: 150
}
];

distant tulip
dawn zealot
#

Is their anyway i can detect a headshot?

fresh current
#

hmm

fresh current
#

since the npcs

#

are not available rn

#

zombie_slayer

#

???

mighty igloo
#

Is the profanity filter global?

#

Does it filter all text?

#

Even server messages?

#

Like world.sendmessage

shy leaf
#

i dont remember exactly though

mighty igloo
#

Ok if so then good because I want people have the option to have it on or off. I know in settings there is a setting to turn off the profanity filter as far as I know.

shy leaf
#

yeah there is

#

as a toggle in settings

mighty igloo
#

It seems to filter cuss words in the chat menu but not the chat display in the hud screen.

#

It could be because I'm using a custom json ui for the hud_screen for the chat

fallow minnow
#

if youd like to force it you can edit some json ui

#

i think its like

#

"profanity_filter": boolean

#

something like that

#

on a label

fresh current
#

yo @mighty igloo

#

quick question

past coyote
#

I’m gonna ask the lovely community of amazing developers.

I tried to make a block logging script that records every block, broken or replaced and then admin can go to an area and roll back those changes
(the commands for this or in a separate file)

However, this script absolutely murders the world dynamic properties string length, and I’m not sure of a more optimized way to handle this

gilded shadow
past coyote
#

its only saving player break and place

#

so its as low level as I can get it

gilded shadow
#

so youre saving everything in one dynamic property ?

fast lark
#

Where i can find people who want to make commissions

distant tulip
#

-# not here
read the rules

round bone
lyric kestrel
rugged tinsel
#

Another optimization would be not using JSON.stringify, custom serialization and deserialization would be more efficient on space

remote oyster
# past coyote I’m gonna ask the lovely community of amazing developers. I tried to make a b...

Based on what you are doing, and the large amount of data that will be involved, I can suggest the following:

[STORE DATA]
   |
[CHUNK JSON] β†’ Split into 30KB parts
   |
[SET EACH CHUNK] β†’ myDB/key/0, myDB/key/1, ...
   |
[UPDATE POINTERS] β†’ Track chunk keys
[GET DATA]
   |
[LOAD CHUNKS] β†’ myDB/key/0 ... N
   |
[REASSEMBLE JSON]
   |
[PARSE VALUE]
[DELETE DATA]
   |
[FIND CHUNKS VIA POINTER]
   |
[DELETE CHUNKS]
   |
[REMOVE POINTER]
past coyote
#

Something called Superbase

#

Still though the data is super large, in like a few minutes with 20 players it hit 200kb

#

Maybe like 10 minutes

#

I have it auto delete logs older than 48 hours

#

I don’t want to do that but it’s whatever

remote oyster
#

Yea, the data you are recording is very large. You are very limited on that aspect. Using an external database is probably your best bet. Pretty certain my suggestion would suffice too, but the world size would grow large very quickly lol.

past coyote
#

Yeahhhh

#

The system is needed though, it’s for a Minecraft 1.7.3 beta recreation server

#

Feel free to join and gawk at at haha

#

play.betafied .net

#

@remote oyster

fallow minnow
past coyote
fallow minnow
#

bahaha

#

its very nice tbf

#

very easy to use

#

and

#

its free 500,000,000 character storage

past coyote
#

Yeah dude I love it

fallow minnow
#

200kb is like 200,000 storage i think?

#

so you have plenty of reem

#

room

past coyote
#

I only need it for that anyways everything else is is on the world

fallow minnow
#

and use a discord bot to add to it

#

and use the new asyncBeforePlayerJoin event

remote oyster
fallow minnow
distant tulip
fallow minnow
#

its quite nice

remote oyster
#

Ah, thanks

fallow minnow
#

you can fetch their data

#

make them wait

fallow minnow
#

and then deny access

#

it doesn't send the join packet or leave packet

remote oyster
#

I'm curious, does it work on Realms? I know they have that module enabled in Realms.

remote oyster
#

πŸ‘€

fallow minnow
#

well it should

#

transferPlayer works on realms so

#

but yeah pretty much you can make them wait

remote oyster
#

Yea that works but the others don't. So its hit and miss.

fallow minnow
#

it waits until whatever you need is fetched

distant tulip
#

it should work one singleplayer too

remote oyster
#

This event is fired before a player joins the world. Unlike other before events, this event is a before event that you can delay several ticks by not resolving the promise returned in the subscribe function. If the promise is rejected, the client is rejected.

#

That's very nice!

midnight crane
#

If I am on specific slot and I have a specific tag how do I make it so it does a command

mighty igloo
#

how do you clear all dynamic properties anywhere?

#

including offline players

#

is it even possible?

shy leaf
remote oyster
# mighty igloo including offline players

If they are set to a player object then you can't remove it unless they rejoin. Otherwise, the only other way would be to modify the world data file.

Or make the code backward compatible so that when they join again you automatically handle it as needed.

For your World itself you can use getDynamicPropertyIds which will return an array of dynamic property identifiers. From there, just loop through them and set them to undefined to clear them.

#

Actually no, even better you can use clearDynamicProperties for the World which will loop through the dynamic property identifiers and clear them for you with no extra code needed.

#

It only impacts those made by the behavior pack.

twilit sky
# past coyote I’m gonna ask the lovely community of amazing developers. I tried to make a b...

That is, quite literally, what I have been working on for the past week.

Yes, you will indeed have to make a custom serialisation method. If you use an external database, it'll still mean that data grows to be quite large.

Here's my serialisation function:

/**
* Serialises the key for the block event.
* @param time The unix time of the block event.
* @param blockLocation The location of the block.
* @returns The key in string form.
*/
private serialiseKey(time: number, blockLocation: DimensionLocation): string {

    const base64Time = Utility.compressNumber(time)
    const blockX = Utility.compressNumber(blockLocation.x)
    const blockY = Utility.compressNumber(blockLocation.y)
    const blockZ = Utility.compressNumber(blockLocation.z)
    const blockDimension = Utility.compressDimension(blockLocation.dimension.id)

    if (
        BLOCK_EVENT_PREFIX.includes(".") ||
        base64Time.toString().includes(".") ||
        blockX.toString().includes(".") ||
        blockY.toString().includes(".") ||
        blockZ.toString().includes(".") ||
        blockDimension.toString().includes(".")
    ) {
        system.run(() => world.sendMessage("Areas: Something has gone very wrong with the database, please notify the developer. Full stop found."))
        throw new DatabaseInvalidCharacterError('Invalid character "." found in key.')
    }

    // console.log("Compressed " + base64Time + " original: " + time )

    // Must all be strings
    const key = `${BLOCK_EVENT_PREFIX}.${base64Time}.${blockX}.${blockY}.${blockZ}.${blockDimension}`
    return key
}
#

I managed to get the records to be around 50 - 100 bytes, so 1MB should be able to store around 10 000 records.

shy leaf
#

ive been wondering, does entityExplosion damage type cause more durability damage than other types on shields?

#

its quite unknowable since explosions can damage shields in 1.21.80, but entityExplosion damage type was always able to damage shields durability before the change

dawn zealot
#

what do i use instead of playerSpawn in 2.0.0-beta?

twilit sky
# dawn zealot what do i use instead of playerSpawn in 2.0.0-beta?

world.afterEvents.playerSpawn.subscribe should still work. That's what my experimental addon is using.

Straight from my addon:

// Grabs a player's name when they spawn in
world.afterEvents.playerSpawn.subscribe(event => {
    Areas.Database.Names.savePlayerRecord(event.player)
})
dawn zealot
twilit sky
#

It's from a class:

/**
 * Saves a players name and id for viewing later.
 * @param player The player to save.
 */
public savePlayerRecord(player: Player) {
    const playerId = player.id
    const playerName = player.name

    const key = `nameRecord.${playerId}`
    world.setDynamicProperty(key, playerName)

    const idKey = `nameRecordId.${playerName}`
    world.setDynamicProperty(idKey, playerId)
}
dawn zealot
#

also do u not see this

twilit sky
#

It's that I bit at the start, that's what was removed.

dawn zealot
#

oh im so lost man

#

all im tryna do is define player bro 😭

#

why they changing all ts

twilit sky
#

IPlayerSpawnAfterEventSignal got removed, but that's a different class to PlayerSpawnAfterEventSignal

dawn zealot
#

world.afterEvents.playerSpawn.subscribe(data => {
const player = Areas.Database.Names.savePlayerRecord(data.player)

#

so what am i doing wrong

#

i dont understand the new shit

remote oyster
#

playerSpawn hasn't changed.... Must be an issue with your database.

dawn zealot
#

dont have a database

remote oyster
#

Your line of code above insinuates you use one.

rugged tinsel
#

what's the issue you're dealing with and what's leading you to believe it's playerSpawn that's causing it?

dawn zealot
twilit sky
#

I probably shouldn't have shown you the code from my addon, that's my custom class.

Areas.Database.Names is completely custom.

You can do

world.afterEvents.playerSpawn.subscribe(event => {
    savePlayerRecord(event.player)
})

function savePlayerRecord(player: Player) {
    const playerId = player.id
    const playerName = player.name

    const key = `nameRecord.${playerId}`
    world.setDynamicProperty(key, playerName)

    const idKey = `nameRecordId.${playerName}`
    world.setDynamicProperty(idKey, playerId)
}
dawn zealot
#

leaving

remote oyster
#

Show your code

rugged tinsel
dawn zealot
#

js

#
import { world } from "@minecraft/server";
import { getScore } from "./config";

world.afterEvents.playerSpawn.subscribe((data) => {
    const player = data.player
    console.warn("text")

    player.runCommand(`scoreboard players add @s season_one 0`)

    if (getScore(player, "season_one") === 0) {
        world.scoreboard.getObjective("season_one").setScore(player, 1);

        world.scoreboard.getObjective("superj_ticks").setScore(player, 0);
        world.scoreboard.getObjective("dash_ticks").setScore(player, 0);
        world.scoreboard.getObjective("shoot_ticks").setScore(player, 0);

        player.runCommand(`say joined first time test`)
    }
})
#

i used this before

#

now it no longer works

rugged tinsel
#

is "text" getting printed?

dawn zealot
#

nope

#

thats why im so confused

#

omfg

#

wait

#

LMAO

#

im not running the file in my main file

#

i might be stupid

rugged tinsel
#

welp, that would probably do it

dawn zealot
#

😭 πŸ™

twilit sky
#

Forgetting the import? That's a classic, I do that all the time πŸ˜† .

dawn zealot
#

i was so confused

round bone
twilit sky
shell sigil
granite cape
#

someone wanna try this?,

#1370349334016561253 message

true isle
#

That reminds me i need to to make 2.0 components

true isle
fathom hemlock
#

why is first line wrong? ``` form.show(player).then(res => {
if (res.canceled) return;

  const [text, action, deleteBtn] = res.formValues;

  if (!isNew && deleteBtn) {
    ui.buttons.splice(index, 1);
    player.sendMessage(`Β§cButton ${index + 1} deleted.`);
  } else {
    if (!text) return player.sendMessage("Β§cButton text is required.");
    const newBtn = { text, action };
    if (isNew) ui.buttons.push(newBtn);
    else ui.buttons[index] = newBtn;
    player.sendMessage(`Β§aButton ${isNew ? "added" : "updated"}!`);
  }

  saveAllUIs();
  editButtonList(player, name);
});```
lyric kestrel
#

omg, I fixed a major issue in my code just by moving something from an independent system.run into my main function that also runs in a system.run, but the first one ran before the function's system.run

twilit sky
fathom hemlock
#

I don't want to fix 126 files each over 500 lines of code 😭

lyric kestrel
halcyon phoenix
#

can we read the inside of the bundles now?

thorn flicker
#

yes.

gilded shadow
#

is there an event for when an entity gets loaded and unloaded?

gilded shadow
#

ill check it

round bone
#

EntityRemove

glacial widget
#

how do i make a line break on /kick

remote oyster
untold garnet
#

/n lol

#

Dude put /n

distant tulip
#

common mistake

glacial widget
#

doesnt*

glacial widget
distant tulip
#

Try `line 1
Line 2`

remote oyster
# glacial widget

Show your code. You are doing something that is causing it to not interpret the string the way you want it to.

fathom hemlock
#

can I do smth like this in with custom libaries?

fathom hemlock
#

"metadata": {
"exports": {
"@easy": "scripts/extension/gravel.js"
}
}

#

right?

#

and in my tsconfigs

fathom hemlock
round bone
glacial widget
#

no runCommand

round bone
#

And combine it with enters instead \n

remote oyster
simple zodiac
dawn zealot
#

if i do this:
const item = new ItemStack('osuea:rod_tier_two', 1)
how do i add lock in inventory keep on death etc?

patent tapir
#

yall am I doing this right (apparently not, but I should have fixed it) ```js
import { system, world, CommandPermissionLevel, CustomCommandParamType } from "@minecraft/server"

system.beforeEvents.startup.subscribe(({ customCommandRegistry }) => {
customCommandRegistry.registerCommand({
name: "dev:test",
permissionLevel: CommandPermissionLevel.Any,
mandatoryParameters: [{ name: "target", type: CustomCommandParamType.PlayerSelector }]
}, ({ sourceType, sourceEntity, sourceBlock }) => {
target.sendMessage(Success!)
})
})```

#

using @minecraft/server 2.0.0-beta

#

or do I have to use the alpha (fixed, yes I do)

patent tapir
#

hold on let me set my manifest to use an absurd script version so it yells at me and tells me what the right alpha is

patent tapir
#

I did NOT think that custom commands were moved to the base game already

#

but it seems to work to an extent

#

this will be very useful for me bao_icon_entities

#

alright how do I put a defined parameter into the command callback

patent tapir
#

WHY IS MY CROSSHAIR A SPLASH POTION OF POISON NOW??????

true isle
#

thats pretty neat btw

thorn flicker
#

-# which should've been fixed in preview

patent tapir
#

I made an rp and then like 50% of all the button textures were shifted (I think) and I didn't change any of them

patent tapir
#

this is what I have now but target isnt defined for some reason js customCommandRegistry.registerCommand({ name: `dev:test`, description: `Tests if this is working!`, cheatsRequired: false, permissionLevel: CommandPermissionLevel.Any, mandatoryParameters: [{ name: `dev:target`, type: CustomCommandParamType.PlayerSelector }] }, ({ sourceType, sourceEntity, sourceBlock }) => { target.sendMessage(`Success!`) })

dawn zealot
#

is their a way i can detect if a player preses a button like f on their keyboard?

patent tapir
#

I'm just shit at js

#

please

#

just tell me how to use the parameter in my function

granite cape
#

but why you add cheatsRequired, if you not using ai?

patent tapir
granite cape
#

bruh

patent tapir
#

and minecraft doesnt yell at me

granite cape
#

just add args

patent tapir
#

how do I do that in js

granite cape
#

this is what I have now but target isnt defined for some reason js customCommandRegistry.registerCommand({ name: `dev:test`, description: `Tests if this is working!`, permissionLevel: CommandPermissionLevel.Any, mandatoryParameters: [{ name: `target`, type: CustomCommandParamType.PlayerSelector }] }, ({ sourceType, sourceEntity, sourceBlock },target) => { target.sendMessage(`Success!`) })

patent tapir
#

but it isnt in the destructuring

#

how does that wor- whatever

#

I'll try it

#

this is what I have now js import { system, world, CommandPermissionLevel, CustomCommandParamType } from "@minecraft/server" system.beforeEvents.startup.subscribe(({ customCommandRegistry }) => { customCommandRegistry.registerCommand({ name: `dev:test`, description: `Tests if this is working!`, cheatsRequired: false, permissionLevel: CommandPermissionLevel.Any, mandatoryParameters: [{ name: `target`, type: CustomCommandParamType.PlayerSelector }] }, ({ sourceType, sourceEntity, sourceBlock, initiator }, target) => { target.sendMessage(`Success!`) }) })

patent tapir
#

what did I do this time

granite cape
#

nothing

#

you can try this thoo,
#1370349334016561253 message

#

i give example on commands.js

patent tapir
granite cape
#

send main.js

patent tapir
#

your "add an argument" thing didnt work

#
import { system, world, CommandPermissionLevel, CustomCommandParamType } from "@minecraft/server"
system.beforeEvents.startup.subscribe(({ customCommandRegistry }) => {
    customCommandRegistry.registerCommand({
        name: `dev:test`,
        description: `Tests if this is working!`,
        cheatsRequired: false,
        permissionLevel: CommandPermissionLevel.Any,
        mandatoryParameters: [{ name: `target`, type: CustomCommandParamType.PlayerSelector }]
    }, ({ sourceType, sourceEntity, sourceBlock, initiator }, target) => {
        target.sendMessage(`Success!`)
    })
})```
#

thats it

#

on 3.0.0-alpha

granite cape
#

why you use alpha version?

patent tapir
wary edge
#

Then you messed up.

patent tapir
#

maybe I tried importing an invalid package due to bridge's autocompletions but damn

#

I'll try the beta again

granite cape
patent tapir
#

ok it does work on the current beta

granite cape
patent tapir
#

but I still have the issue of not being able to use the parameters in the callbackfn

patent tapir
wary edge
#

Don't use alpha...please

#

Especially if you dont know what youre doing.

patent tapir
#

i went back to beta

#

how do I use the custom command parameters in the callbackfn

#

please

#

it's all I want to know

granite cape
wary edge
#

Idk.

wary edge
patent tapir
wary edge
#

Ok and?

#

Just convert the TS to JS?

patent tapir
wary edge
patent tapir
wary edge
#

Yeah you can.

patent tapir
#

I was trying so hard to not get mad but now I'm getting mad again because all you can tell me is to "use ts or convert it" and I can't do either. It's truly not that simple. I'm an incompetent idiot who can't goddamn convert two languages because I don't remotely know how one of them works. Is it really too hard to ask just to give me direct js instructions???

granite cape
patent tapir
wary edge
#

But you literally can convert it...

wary edge
#

You can literally just...remove the types.

#

Typescript is just JS...with types.

#

Or just learn TS.

granite cape
patent tapir
#

._.

patent tapir
#

that barely makes sense to me

#

and I want my command to be in all one nice function, like I have been doing, instead of other object consts

#

which right now- js system.beforeEvents.startup.subscribe(({ customCommandRegistry }) => { customCommandRegistry.registerCommand({ name: `dev:test`, description: `Tests if this is working!`, cheatsRequired: false, permissionLevel: CommandPermissionLevel.Any, mandatoryParameters: [{ name: `target`, type: CustomCommandParamType.PlayerSelector }], }, ({ sourceType, sourceEntity, sourceBlock, initiator }, target) => { target.sendMessage(`Success!`) }) })Looks like this. How is it so hard to get help here?

#

I very simply can't figure out how to use the custom command paramater "target" in the callbackfn.

#

that's all I want to know at this moment.

#

Thank you.

wary edge
patent tapir
#

like five times

#

still can't figure it out

warped blaze
wary edge
patent tapir
warped blaze
wary edge
#

Why are you so allergic to multiple objects? Especially when you yourself do not understand the basics of JS you cannot be complaining.

#

Learn the basics, then read the docs.

patent tapir
warped blaze
remote oyster
wary edge
#

You cannot be holding yourself to this standard when you do not even understand or grasp the concept. It's like a student trying to simplify a matrix equation when they don't even know how to add or multiply them.

patent tapir
patent tapir
ruby haven
#

Does apply knockback work on other entities

patent tapir
ruby haven
#

How can I create a dash skill of my entity using the dataDrinvenEntity?

wary edge
ruby haven
patent tapir
#

it's basically identical to knockback

ruby haven
patent tapir
#

I still get target is not defined!!!!!!!!! HOW. DO. I. DEFINE. THE target PARAMETER. AS. A. VARIABLE. I. CAN. USE. ```js
function test(target) {
system.run(() => {
target.sendMessage(Success!)
})
}

customCommandRegistry.registerCommand({
    name: `dev:test`,
    description: `Tests if this is working!`,
    cheatsRequired: false,
    permissionLevel: CommandPermissionLevel.Any,
    mandatoryParameters: [{ name: `target`, type: CustomCommandParamType.PlayerSelector }],
}, test(target))```
remote oyster
remote oyster
patent tapir
#

I did my best to do what I count as "converting" some typescript to javascript but they look like they do the exact same thing and the js doesn't work.

remote oyster
#

Then you implemented that code incorrectly because it's already been tested on my end and confirmed working.

patent tapir
#

where does it even pick up "targetPlayers"

remote oyster
#

You really don't know JavaScript do you?

patent tapir
patent tapir
remote oyster
patent tapir
remote oyster
patent tapir
#

so what I learned is that I need to have the origin parameter included as the first parameter in the function, it must be a seperate function, every parameter in the custom command probably has to be in order in the function args and don't need their name to match, and the namespaces must all be the same throughout the entire behavior pack, selector arguments must be iterated through.............................................. ok.

#

now I know.

#

Now I can continue what I wanted to do for this whole entire day. Which is make very simple custom commands instead of using a message prefix based system.

patent tapir
remote oyster
#

Doesn't have to be a function, but I find that it helps to keep it cleaner looking. That's mostly personal preference.

#

I still prefer using prefix messages over registerCommands. At least until they do something with namespaces.

wary edge
#

Which they have.

remote oyster
#

In preview

#

πŸ™‚

mighty igloo
remote oyster
# mighty igloo it doesnt clear player properties though

No, only for world. Can't clear them from a player unless the player is online. Only other option is to edit the saved world file using an NBT editor of your choice and manually removing them. Otherwise, don't store on players and do so in the world using player id as the key for the value(s).

mighty igloo
#

alr

shy leaf
#

speaking of DPs, what is the good way to cache them into memory?

remote oyster
shy leaf
remote oyster
#

My use case isn't large but it can get large if I wanted it to. Just haven't had the need to and in either case, I wouldn't want to impose on memory since it's limited.

shy leaf
#

i see, thanks

#

might have to start caching DPs into memory for performance since the current one uses world.getDynamicProperty() in runInterval

sweet seal
#

How to make someone stuck in first-person with only script API?

dawn zealot
#

how do i stop people from opening chests, barrels, flipping trap doors etc

#

2.0.0-beta

#

nvm figured it out

patent tapir
#

Hey is there some way to have a branching command (like /fill) so I can make a setDynamicProperty command and let it set all 3 types of dynamic property seamlessly

#

or do I just have to put in a dreadful amount of logic like I do with message prefix based "commands" ._.

#

...or just make 3 different commands

#

after finally learning how to get them to run I'm on a roll with them but this gives me pause

#

-# I already tried registering an Enum with the different parameter types but that went about as well as you'd probably expect

#

For now I'll just make 3 different commands until I get an answer that would change it

ivory bough
#

Is there any way to kick the owner without bds with custom message?

twilit sky
fathom hemlock
#
  "compilerOptions": {
    "module": "ES2020",
    "target": "ES2021",
    "moduleResolution": "Node",
    "allowSyntheticDefaultImports": true,
    "baseUrl": "./scripts",
    "rootDir": "./scripts",
    "outDir": "./scripts",
    "preserveConstEnums": true,
    "experimentalDecorators": true,
    "paths": {
      "@easy": ["./scripts/extensions/gravel.js"]
    }
  },
  "exclude": ["node_modules"],
  "include": ["scripts"]
}
#

my file has a ts and a d.ts file

round bone
#

hmm

#

prettty weird

shy leaf
#

wait a god damn minute.

#

why does effectType from EffectAddBeforeEvent give translated strings as effectType

#

uhhhh????????

past coyote
#

So my script can't run /allowlist on BDS, this is due to the permission level I am sure... so how do I make it so the command is run from the console permission level?

shy leaf
past coyote
#

You can supposedly elevate the script to be able to use those

#

op-permission-level = 4

shy leaf
#

hmmmm never tried scripting in BDS before, so im honestly not sure

prisma shard
#

will this be fine?

#

try catch try catch

#

well how about this

#

1000 ms Hang lmao im gonna kill my pc

round bone
#
while (true) {
    try {
        system.runJob()        
        break
    } catch {}
}
prisma shard
#

uh

#

while true isnt it dangerous

round bone
#

you can add a limit

prisma shard
#

like i mean, i never used while (true ) so

round bone
round bone
prisma shard
# round bone you can add a limit

bascialy im loading the chunk , but sometime it say error not loaded chunk, so when you fillBlocks again, it works the second time, and if it doesnt, again dooing works on the third time

round bone
#

this while loop is doing the same thing, but it'll stop checking for it when the function will be run successfully

#

if you would like to rate limit it, you can use:

const MAX_ITERATIONS = 3
for (let i = 0; i < MAX_ITERATIONS; i++) {
    try {
        system.runJob(fillBlocks(player, chunks, blockId, {}, count))
        break
    } catch {}
}
prisma shard
#

ohoo

#

okay i'll be doing this

prisma shard
#

like waitTicks on each iteration

halcyon phoenix
round bone
#

i is a number of current attempt

round bone
round bone
distant tulip
#

yep

#

cubecraft was using it at some point in there ban system, you can bypass that, not sure if they still using it

round bone
#

😭

remote oyster
round bone
#

she is using it for some DB as a PK afaik

oak lynx
fathom hemlock
#

is this good?

#


uiBuilder.register.actionformdata("main", "menu", (player, form) => {
  form.title("Menu").body("lol why do u read this?")
    .button("Test")
    .button("Close");

  return async (response) => {
    switch (response.selection) {
      case 0:
        runCommand(player, "say lol");
        break;
      case 1:
        player.sendMessage("BYE!");
        break;
    }
  };
});
midnight crane
#

So someone sent me a script to set a scoreboard depending on what slot you are on here it is ```js
import { world, system } from "@minecraft/server";

const slotObjective = world.scoreboard.getObjective("slotValue") ?? world.scoreboard.addObjective("slotValue", "slotValue");

system.runInterval(() => {
for (const player of world.getPlayers()) {

    const currentSlot = player.selectedSlotIndex;
    const lastSlot = player.getDynamicProperty("lastSelectedSlot")

    if (lastSlot !== undefined && currentSlot !== lastSlot) {
        const score = slotObjective.getScore(player) ?? 0;
        const d = currentSlot > lastSlot ? 1 : -1;
        slotObjective.setScore(player, score + d);
    }

    player.setDynamicProperty("lastSelectedSlot", currentSlot);
}

});

unique acorn
#

if you are 100% sure the objective will exist then you can remove ?? world.scoreboard.addObjective("slotValue", "slotValue"); if you don't want to cause confusion

midnight crane
unique acorn
thorn flicker
#

ItemInventoryComponent

#

I cant find a doc on it rn

halcyon phoenix
thorn flicker
#

it got added last preview.

halcyon phoenix
#

how do you use this?

#

it's been a while since I scripted

thorn flicker
#

like how you get any component on an item

halcyon phoenix
#

I forgot :<

thorn flicker
#

look around.

halcyon phoenix
#

slot.getItem().getComponent("itemInventory");

#

like this?

thorn flicker
#

its should be just inventory

halcyon phoenix
#

ohhh

#

thanks

#

it's not on the docs where did oyu find it?

thorn flicker
#

in the changelog.

halcyon phoenix
#

dang, thanks VoidCell

thorn flicker
bold bison
# thorn flicker

Is it possible to make me a script to increase the percentage of monsters’ respawn?

bold bison
round bone
#

or spawning another one after death?

coral ermine
#

is there a method to execute

/event command

distant tulip
#

triggerEvent()?

round bone
#

Do you need docs?

prisma shard
#

oh my god scripting is so weird

#

can you check if the error is a unloadedChunkError

#
catch (error) {
typeof error === UnloadedChunksError 
}```
that?
prisma shard
#

oh okay

#

pfft lol it spammed my chat

#

    try {
      player.dimension.fillBlocks(blockVolume, block, blockFillOptions)

    } catch {
      try {

        for (let i = 0; i < 3; i++) {
          if (i > 0) system.waitTicks(1)
          player.dimension.fillBlocks(blockVolume, block, blockFillOptions)
          break;
        }

      } catch (e) {
        if (e instanceof UnloadedChunksError) {
          world.sendMessage(`[WorldEdit] Failed to fill blocks for now, Chunks have been loaded now, Please try the same command again. For some reason, If it fails, It works the second time.`)
        }
      }

    }
#

this is my try{} catch{} try{} catch{} spagghetti code

#

😭 i wanna run that sendMessage only 1 time

#

i think its for the iteration

copper egret
#

I thought they added damage cancelation vai script apijoedead

midnight crane
#

How would I make it so if I'm on a specific slot it constantly does a command

distant tulip
oak lynx
#

moving from ! to slash commands is crazy

#

cuz now i have so much more boilerplate 😭

patent tapir
patent tapir
#

It'll take a while, sure, but it's much better (and can also be used in /execute afaik)

oak lynx
#

it took me like an hour or two to migrate

patent tapir
# oak lynx it took me like an hour or two to migrate

And I'm terrible at js but good thing most I need to do it copy-paste the callbackfn into the new custom command, link all the parameters, set up success/fail and returning messages, then remove the now unneeded error handling... still a lot but whatever

#

A worthy sacrifice to make

oak lynx
#

i mean most of my commands are admin only

patent tapir
#

But otherwise I'm not sure what makes that different

oak lynx
#

i actually did the commit without checking if it works πŸ’€

#

time to open the server

patent tapir
oak lynx
#

nuh uh i am a peak dev

patent tapir
#

Hopefully you fully know how they work then

#

πŸ‘

oak lynx
#

yeah no errors

#

only slowdowns i get cuz i load a lot of data on startup

patent tapir
#

That was my big mistake yesterday

oak lynx
#

i know

patent tapir
#

And nobody told me that was the issue I was having ._.

oak lynx
#

docs on this are kinda eh rn

patent tapir
oak lynx
#

now i just need a decent version of getBlocks()

patent tapir
#

Or changed?

#

I don't quite remember that method anyway

#

Hold on going afk Minato can probably help

oak lynx
#

nah it just returns positions of blocks instead of blocks

distant tulip
oak lynx
#

i use jayly docs

distant tulip
#

cool

oak lynx
#

getting a script to run bds in terminal was peak πŸ™

#

wait how does the operator permission work?

#

i have operator and i cant use commands with CommandPermissionLevel.Admin

patent tapir
oak lynx
#

docs say "Any operator can run this command, but NOT command blocks."

patent tapir
oak lynx
#

nah the commands just dont show up

patent tapir
oak lynx
#

commands with any permissions show up

patent tapir
#

Until Mojang fixes Admin

#

I guess

oak lynx
#

yeah changed it

patent tapir
#

Aight

oak lynx
#

i mean i have command blocks disabled so it doesnt really matter

oak lynx
#

yeah they work now

#

love it when docs have fake info 🀯

remote oyster
#

Which one?

remote oyster
# oak lynx .

That looks like it may be related, for BDS that is, the configuration in server.properties when setting op-permission-level either 0 to 4 or simply not defining it at all. Try setting it between 2-4 and see if that resolves it.

#

This issue with permissions between BDS, Realms, etc, is partly why I believe they are removing isOp() and taking a different approach.

Operator Permission Levels (op-permission-level) – Minecraft Bedrock Dedicated Server

The op-permission-level setting in server.properties determines the default permission level assigned to players when using the /op command. This affects which commands they can use unless explicitly set in ops.json.


Level 1 – Basic Commands

Allows only non-destructive, informational, and communication-related commands. Ideal for minimal permissions.


Level 2 – Game Management Commands

Adds access to gameplay-related commands such as gamemode changes, teleporting, and giving items. Suitable for creative players or minor helpers.


Level 3 – Moderation Commands

Grants access to moderation tools like kicking and banning players. Useful for server moderators or staff.


Level 4 – Full Administrative Access

Provides full access to all server and management commands. Intended only for server owners or trusted administrators.

granite badger
#

time to copy paste this to my docs if that's ok (with credits ofc)

oak lynx
#

hmm time to figure out if loading all the auctions to ram is better or calling the api

sweet seal
#

world.beforeEvents.playerInteractWithBlock.subscribe((event) => {
    const player = event.player;
    const block = event.block;

    if (block.typeId !== "minecraft:frame") return;

    const inventory = player.getComponent("inventory")?.container;
    if (!inventory) return;

    system.run(() => {
    inventory.addItem(new ItemStack("minecraft:emerald", 1));
    block.setType("minecraft:air");
    })
});

How to get the item inside of the item frame?

sterile epoch
# oak lynx .

I had this problem and fixed it by doing .setOp(true)

shy leaf
#

can cauldron's content be edited?

#

i remember seeing a block component of it

shy leaf
# sweet seal ^

im not sure if theres any component related with item frames

#

i might be wrong though

sweet seal
#

Any other way to do it?

sweet seal
shy leaf
#

yeah im not sure either, sorry

sweet seal
#

Alright.

fallow carbon
deep yew
#

Not sure if it's been answered, but how do I spawn custom entities in the latest beta2.0 1.21.80 stable version?

fallow carbon
#

I don't think the Dimension.spawnEntity function has changes between 1.0 and 2.0

deep yew
#

it has between 1.21.70 and 1.21.80

#

Argument of type '"floating:text"' is not assignable to parameter of type 'VanillaEntityIdentifier'.

fallow carbon
#

is that a type error?

deep yew
#

I might've just accidentally discovered a fix but not sure yet as it's not showing a syntax error. The issue is custom entities aren't in VanillaEntityIdentifier because they're not vanilla

shy leaf
#

kinda odd

fallow carbon
#

what version of the npm package are you using?

deep yew
#

I changed it to {id:"floating:text"} so I'll test

#

latest stable beta

fallow carbon
#

so 2.1.0-beta.1.21.90-preview.25?

deep yew
#

stable not preview

shy leaf
#

wth.

#

i cant tell if thats a jank or not

fallow carbon
#

so the solution here is this, ```ts
(some_variable as Dimension).spawnEntity<"my:custom_entity">("my:custom_entity", { x: 0, y: 0, z: 0 });

#

cc @deep yew and @shy leaf

deep yew
#

hmm

shy leaf
deep yew
#

huh?

fallow carbon
#

well, assuming your using typescript

deep yew
#

-# it works....

#

at least for syntax

#

that's new to me

fallow carbon
deep yew
#

I just don't understand it yet

shy leaf
#

me neither

#

i mean i do get whats happening here

#

but idk why

deep yew
#

exactly. I just don't see why this simple function needs it and not just keep the old logic

#

but maybe it's a pre-fix for something later

shy leaf
#

it could be an oversight from devs

fallow carbon
#

the reason its like that is for the completions here.

deep yew
#

yes see I understand why I need to put the type parameter, because of syntax error. It's not a vanilla entity. I just don't understand the need for it in general

fallow carbon
#

better dx

#

though 90% of the time it seems to me its more likely your spawning a custom entity

gilded shadow
#

looks more neat

fallow carbon
#

you could also just use <string> as the type parameter which would be looser I suppose.

fresh current
#

yo @fallow carbon can you help me

gilded shadow
#

if you state your problem instead of asking people to help you

fresh current
#

basically im trying to make a leveling system that connects to different npcs for questlines and quest for players im making one piece and trying to do different quest for islands

#

this the script i have so far but nothing works

fallow carbon
fresh current
#

when rightclicking on the npd

#

npc

gilded shadow
#

so we are supposed blindly fix it? without knowing the problem ?

#

if you can provide the error

#

it would help

fallow carbon
#

also the stack trace would be helpful

fresh current
#

didnt i just say the error

#

idk even know what that is

remote oyster
gilded shadow
#
world.afterEvents.playerInteractWithEntity.subscribe(event => {
    const player = event.player;
    const npc = event.target;

    if (!npc.hasTag("quest_giver")) return;

    const state = getPlayerState(player);
    if (state.quest) {
        player.runCommand(`say Β§cYou are already on a quest.`);
        return;
    }

    // Find available quests for player's level
    const availableQuests = quests.filter(q => q.minLevel <= state.level);
    if (availableQuests.length === 0) {
        player.runCommand(`say Β§eNo quests available at your level.`);
        return;
    }

    const quest = availableQuests[Math.floor(Math.random() * availableQuests.length)];
    state.quest = quest;
    state.kills = 0;

    player.runCommand(`say Β§bQuest Accepted: ${quest.name} - ${quest.description}`);
});
#

there nothing related to typeId

fresh current
#

hmm

gilded shadow
#

either the error is somewhere else

fresh current
#

so what is the problem

gilded shadow
fallow carbon
#

do you know how to see your content log @fresh current?

fresh current
#

on minecraft?

fallow carbon
#

yes

gilded shadow
#

yea

fresh current
#

wanna join vc

fallow carbon
#

no

fresh current
#

and ill share my screen

#

ooff

gilded shadow
#

no

fresh current
#

oof

#

welp

gilded shadow
#

so when you open the game go in settings > creator > and enable content log gui

#

also put log level to info

fresh current
#

mhm

#

thats the thing

#

that says

#

typeId when i try interacting with the npc

#

but

#

im doing homework rn so

#

thanks for your unaccommodating

gilded shadow
#

you cant expect anyone to spoon feed you without even knowing where your mouth is

fresh current
#

not spoon

fallow carbon
# fresh current thanks for your unaccommodating

just because we are unavailable to join a voice channel does not mean we aren't trying to assist you, its sometime a challenge but the process of gathering information and using that to form an answer is sometimes required (like in this case) and is not something we can do without your assistance, please keep in mind we have no obligation to assist you but are doing so anyways.

fresh current
#

1 sec

#

this is also with the ui im making

#

an dthis happens when i right click the npc

gilded shadow
#

and the file that you sent only has 94 lines

fresh current
#

index is my other file

gilded shadow
#

yeah so if you read the error it explains where the error is coming from

fresh current
gilded shadow
safe stream
#

Is there a method to check if the held item (itemStack) is a block?

fresh current
#

this is line 144

#

.getEquipment(EquipmentSlot.Mainhand).typeId == "op_asa:cola") {

untold garnet
untold garnet
#

Make a function with all minecraft block id and return if given id is in the list

#

This will be a huge library

remote oyster
safe stream
fresh current
#

thats a whole another script

safe stream
fresh current
#

the thing is

#

thats not what im trying to fix

#

thats a whole other system script

#

the script im trying to fix is the leveling system

safe stream
#

then why did you send it 😭

fresh current
#

because

#

he tlaking abt line 44

#

144

#

but that ha nothing to do with what im trying to fix

fallow carbon
safe stream
#

your content log error says index.js:144

gilded shadow
#

you have an error in your code

gilded shadow
# fresh current 144
if (event.player
        .getComponent(EntityComponentTypes.Equippable)
        .getEquipment(EquipmentSlot.Mainhand)?.typeId == "op_asa:cola") {

put this in your line 144 and see if it fixes

fresh current
#

bet

#

@gilded zephyr

#

wya pussy

safe stream
#

interesting

safe stream
fallow carbon
safe stream
#

oh will do

remote oyster
fallow carbon
#

(untested)

frozen vine
#

Is it possible for me to change the state of my block when hit by a wind charge like it happens with vanilla doors?

#

Not exactly because of the wind charge but also because of its explosion

prisma shard
#

this is where ternery operator ? is much helpful

prisma shard
fallow carbon
#

that effectively does the same thing but requires a try catch?

#

not sure what your wanting me to see @prisma shard

prisma shard
#

hm?

#

like i mean

#

that also works

fallow carbon
#

yes, it does, but it does make use of try-catch which may not be desirable

prisma shard
#

oh okay

#

Let me test both of our functions

#

in game

fallow carbon
#

ok πŸ™‚

prisma shard
#

both works

#

and it just seems to be an error on yours

#

when there is no item in mainhand

#

hmmm ? doesnt fix it

fallow carbon
fallow carbon
# prisma shard and it just seems to be an error on yours

ok, here is my test and its results.



function a_isItemStackABlock(itemStack: ItemStack): boolean {
    return BlockTypes.get(itemStack.typeId) !== undefined;
}

function b_isItemStackABlock(itemStack) {
    try {
        BlockPermutation.resolve(itemStack.typeId);
        return true;
    } catch {}
    return false;
}

system.afterEvents.scriptEventReceive.subscribe((e) => {
    if (e.id !== "f:test") return;
    const items = ItemTypes.getAll().map((item) => new ItemStack(item, 1));
    let s1 = Date.now();
    let blockCount = 0;
    let itemCount = 0;
    for (const item of items) {
        if (a_isItemStackABlock(item)) {
            blockCount++;
        } else {
            itemCount++;
        }
    }
    let e1 = Date.now();
    let s2 = Date.now();
    let blockCount2 = 0;
    let itemCount2 = 0;
    for (const item of items) {
        if (b_isItemStackABlock(item)) {
            blockCount2++;
        } else {
            itemCount2++;
        }
    }
    let e2 = Date.now();
    world.sendMessage(`a: ${e1 - s1}ms, b: ${e2 - s2}ms`);
    world.sendMessage(`blocks: ${blockCount}, items: ${itemCount}`);
    world.sendMessage(`blocks2: ${blockCount2}, items2: ${itemCount2}`);
});
prisma shard
#
function isBlock(itemStack) {
    try {
        BlockTypes?.get(itemStack?.typeId) !== undefined;
    }
    catch {
        return false;
    }
}```
try catch fixes it
#

system.runInterval(() => {
    for (const player of world.getAllPlayers()) {
        const a = player.getComponent(EntityComponentTypes.Equippable).getEquipment(EquipmentSlot.Mainhand)
        console.warn(`fetchbot: ${isItemStackABlock(a)}`)
        console.warn(`mine: ${isBlock(a)}`)
    }
}, 20)


function isItemStackABlock(itemStack) {
    try {
        BlockPermutation.resolve(itemStack.typeId)
        return true;
    } catch { }
    return false
}

function isBlock(itemStack) {
    try {
        BlockTypes?.get(itemStack?.typeId) !== undefined;
    }
    catch {
        return false;
    }
}```
heree's mine tested code
#

eh yours is better method

#

i'll replace your func with mine is it okay lol

fallow carbon
prisma shard
#

heh i add try catch it just works

#

bruh if it works it works

fallow carbon
#

I don't like it when things break and start working and I don't understand why.

prisma shard
#

lol

shy leaf
#

uh

#

whats up with the try catches

fallow carbon
#

in the function with BlockPermutation its because the resolve method will throw if it fails and in the isBlock i'm not sure since I haven't seen any errors on my end.

prisma shard
#

i need some real help in json ui :c

#

already asked in json ui channel, no help, so depres πŸ’” πŸ₯€

fallow carbon
# prisma shard already asked in json ui channel, no help, so depres πŸ’” πŸ₯€

please have patience, you asked just a few minutes ago and it seems like the json-ui channel is less active than this one (json-ui is perhaps more niche). it might be better form if you try and work it out on your own for a while, look at some tutorial, the bedrock.dev wiki, etc. and document what you have managed to work out and ask for guidance from there πŸ™‚

prisma shard
#
function isUnderground(player) {
  if (player.dimension.heightRange.min > player.location.y) return true;
  if (player.dimension.heightRange.max < player.location.y) return false;

  let block = player.dimension.getTopmostBlock(player.location)
  if (player.location.y >= block.y) return false
  while (!block.isSolid && block.y > player.dimension.heightRange.min) {
    if (player.location.y >= block.y) return false
    block = block.below()
  }
  return true
}```
can anyone fix this function, It return error cannot read property 'y' of undefined, when going down the  void
fallow carbon
prisma shard
#
function isUnderground(player) {
    try {
        if (player.location.y < player.dimension.heightRange.min) return false;
  if (player.location.y > player.dimension.heightRange.max) return false;

  let block = player.dimension.getTopmostBlock({x: player.location.x, z: player.location.z });
  
  if (!block) return false;
  
  if (player.location.y >= block.y) return false;
  
  while (!block.isSolid && block.y > player.dimension.heightRange.min) {
    if (player.location.y >= block.y) return false;
    block = block.below();
    if (!block) return false;
  }
  return true;
    }
  catch {
    return false
  }
}```
I dont know but i am in love with try catch lmfao
remote oyster
fallow carbon
prisma shard
#

okay i am trying
-# jk with the trycatch

remote oyster
#

Yea, don't put a bandaid on it. That bandaid will eventually fall off πŸ™ƒ

shy leaf
#

this is like

#

holding two metal pipes together with a tape

fallow carbon
#

there is a hole in the wall, lets paint over it πŸ™‚

shy leaf
#

well that one is valid if its a drywall

fallow carbon
#

I mean, you should prob fix the hole first though πŸ™‚

prisma shard
#

i fixed it

#

but it now returns trying to acces location faile

#

when going void

fallow carbon
#

it sounds like your bounds check is perhaps not correct then

shy leaf
remote oyster
#

Validate the object before accessing the properties or methods in the object.

shy leaf
#

im going to crashout if i see another try catch

valid ice
#

try {
crashout;
} catch {
discord.delete();
}

shy leaf
#

herobrine

prisma shard
#

funni how i realized it was a different code causing the error

final ocean
#

Help me what is the name of the event player break block

frozen vine
#

Is it possible for me to change the state of my block when hit by a wind charge like it happens with vanilla doors?

prisma shard
copper egret
#

.isOp() isn't working in a dedicated server?

unique acorn
prisma shard
#

oo

#

cennac

#

you're alive

copper egret
#

it's a bedrock edition or bds

round bone
#

it'll be removed soon

#

I think it's already deprecated

copper egret
#

I know it will be changed into something like player.PerrmissionLevel. However, I am lazy to change it into admin tag method for temporary

#

Additionally, the op level permission in custom slash command is also not working. It doesn't detect operators

halcyon phoenix
#

what's the coordinate to make a pseudo dimension?

#

in end?

final ocean
#

How to make real time system also date month year

north frigate
#

Jokes on you I'm coding using termux >:)

night loom
# final ocean How to make real time system also date month year
world.beforeEvents.chatSend.subscribe((event) => {
  const { sender, message } = event;

  if (message === "!data") {
    const now = new Date(Date.now());
    const day = now.getDate();
    const month = now.getMonth() + 1;
    const year = now.getFullYear();

    sender.sendMessage(`${day}.${month}.${year}`);
  }
});

is that what you meant?

round bone
#
const isAdmin = (/** @type {import("@minecraft/server").Player} */player) => {
    return player.isOp()
}
round bone
round bone
#

use a tag or wait for new permission system

copper egret
#

normally in the client world, we could use the reload command. However, we couldn't execute it and it said it doesn't meet the permission level to run it

round bone
#

you have to use reload via server's process (terminal)

#

at this point, you should use some tag to recognize an permitted user

copper egret
#

rip

round bone
#

or you can always wait for new permission system

copper egret
#

is there any way to change the permission level of an op in bds though?

round bone
#

but I don't know if you would like to wait for it

round bone
#

highest value is 4

copper egret
#

or should I put it myself?

round bone
#

it does exist, documentation does not include this

round bone
#

it'll work

copper egret
#

oh nice it works

#

thanks

round bone
#

no problem

fiery solar
halcyon phoenix
#

do you put it below the normal Y level? like the level the endsgone platform spawns

halcyon phoenix
north frigate
#

What's the beta version of server ui in Minecraft 1.21.80

final ocean
#

Help me fix code

shy leaf
final ocean
remote oyster
# final ocean Help me fix code

Open a forum in #1067535382285135923 where you can share your code and explain what the issues are. Then wait and see if anyone responds.

final ocean
#

I posted it now can anyone help me

half socket
#

Is chatSend still beta?

shy leaf
half socket
unique acorn
fathom hemlock
#

how do I change the name of a player?

thorn flicker
fathom hemlock
#

or?

thorn flicker
round bone
#

cancel event and send new one

#
import { world } from "@minecraft/server"

world.beforeEvents.chatSend.subscribe((eventData) => {
    eventData.cancel = true
    world.sendMessage(`${player.name}: ${message}`)
})
thorn flicker
#

but yeah, that's how you do it

tight bloom
#
import { world, system, BlockPermutation, EntityDamageCause, EffectTypes, ItemStack, Component } from "@minecraft/server";
import { MinecraftEffectTypes } from './vanilla-data.js';
import { Perlin } from './perlin.js';
//FADED BUD: BEGIN
world.afterEvents.worldLoad.subscribe((initEvent) => {
    initEvent.blockComponentRegistry.registerCustomComponent('deep_end:on_fall_on_faded_bud', {
        onEntityFallOn(arg) {
            if (arg.fallDistance >= 1) {
                arg.entity.addEffect(MinecraftEffectTypes.Levitation, 9, {
                    amplifier: 50
                });
                arg.entity.addEffect(MinecraftEffectTypes.SlowFalling, 140, {
                    amplifier: 1
                });
            }
        }
    });
});```
#

[Scripting][error]-TypeError: cannot read property 'subscribe' of undefined at <anonymous> (deep_end_custom_block_components.js:5)[Scripting][warning]-Component 'deep_end:on_fall_on_faded_bud' was not registered in script but used on a block

#

So, apparently worldInitialize was deprecated

#

but I get these errors trying to update to worldLoad

thorn flicker
#

what version are you using?

tight bloom
#

My @minecraft-server in the manifest is 1.19.0 and I'm on stable 1.21.80

thorn flicker
#

there's no worldLoad in 1.19.0

#

you can still use worldInitialize

#

just not in v2

tight bloom
#

what do I use for v2 components?

wary edge
tight bloom
#

It seems that custom components v2 are only functional on preview?

wary edge
tight bloom
#

Wait, really?

#

is there something new to put in the manifest? i can't find it in the docs page

wary edge
tight bloom
#

I have that on the world

#

but the custom v2 component returns
| deep_end:faded_bud | components | deep_end:on_fall_on_faded_bud | child 'deep_end:on_fall_on_faded_bud' not valid here.

wary edge
tight bloom
#

will do

round bone