#Script API General

1 messages · Page 83 of 1

remote oyster
#

People that obfuscate 🫠

((Ω,𝜃) => (
  Ω[𝜃] = Ω[𝜃] ?? {},
  Ω[𝜃].‎‎🜚 = Ω[𝜃].‎‎🜚 || ((ø, ƒ) => {
    const [π, σ] = [
      x => x.split(":")[1],
      y => y.charAt(0).toUpperCase() + y.slice(1)
    ];

    return e => {
      const m = e[["me", "ss", "age"].join("")],
            s = e[["sen", "der"].join("")];

      const d = σ(π(s[["dimen" + "sion"]["id".length ? "" : ""].id]));

      if (~m.indexOf('!') && !m.indexOf('!')) {
        (ø || Ω).sendMessage(["Hel", "lo "].join("") + d);
        (e.cancel ??= void 0, e.cancel = true);
      }
    };
  })(world)
))(this, "▓");

world.beforeEvents["chat" + "Send"].subscribe(this["▓"].‎‎🜚);
deep quiver
#

I agree here 100% I never uploaded a obfuscated pack ever in my life, except for market place, but thats different, it gets encrypted

tulip osprey
#

thank you so much I was able to find it and remove it

rough jackal
loud frigate
#

How tho? It's not like you can execute arbitrary code in scripting, it's a sandbox

rough jackal
#

dang that's rough

#

thank you

loud frigate
#

I'd say that the core issue is that addon on the marketplace are payed directly. This creates competitions which limits information sharing amongst creators. As opposed to a community where stuff you get for free which creates the opposite scenario where creators want to interact and scare info to improve compatibility as people just install everything so you get points for that

loud frigate
#

Still crazy there isn't something as basic as the age of an entity variable

small cloak
loud frigate
#

Reminds me there once was a mod that would spawn some withers with slur names sneakily after you had been playing with a while

small cloak
#

Even seen packs that look innocent at first, but then they hide code off the screen. That's a common technique for real malware.

loud frigate
#

I wonder if they inspect the code at Mojang QA

woven loom
inland merlin
#

To dynamically set value, I ended up getting all block types and also subtracting those from the list, as well as items with minecraft prefix. After that the value returned was accurate and allow the icons to stay correct no matter how many addons I have added. For chestformdata

#

Works amazing, always appreciate the hekp

mighty igloo
#

so i have a detection for a landclaim to detect if the user is interacting with a block to cancel the event but it detects interactions on all blocks. any way to filter

floral vessel
#

is there a way to run a function on block update?

mighty igloo
#

well when i right click on any block it triggers an interact. even if its not an interactable block like a lever or door

floral vessel
#

literally unusable

#

unless you want to lag the hell out of the game

#

great

shy leaf
mighty igloo
#

yes but i have it to create a message

shy leaf
#

on a related note, does afterEvent for playerInteractWithBlock behave the same?

mighty igloo
#

no

shy leaf
#

then you could make use of that

mighty igloo
#

because you cant cancel the event after the event happens

shy leaf
#

i mean

#

ofc, but im asking if it fires even for blocks with no interaction

#

i forgot if it does or not

mighty igloo
#

is it a good idea to use async in it?

#

the before event

shy leaf
#

proooobably not

mighty igloo
#

thought so

shy leaf
mighty igloo
#

also the interact spams

#

i think player interact block is already asynchronous or something

#

thanks

halcyon phoenix
#

can you trigger a jigsaw block in script?

fallen cape
prisma shard
#

what.... setRotation() exist

prisma shard
prisma shard
prisma shard
fallen cape
#

Some math can do that already tho

woven loom
#

I have been telling people how to do that for years now.

#

just search fro a message "toAngle" by me

loud frigate
#

Why are some events called multiple times?

#

Click on block fires multiple times but just when clicking on the side

prisma shard
#

damn i miss coddy @dim tusk where are you

loud frigate
#

I know that's how to stop it but why is it even doing that. What's the use case. Params are the same anyways and it fires inconsistently

distant tulip
#

they are not called multiple times, that count as multiple interactions, each interaction trigger one

ivory bough
#

How to spawn an entity near the player in a valid position like spawn rules?

prisma shard
#

hmm

#

After stopping walking, The velocity keeps for a while

#

how can i fix that

#

It doesnt trigger anything immediately after stopping walking since it takes some time for getVelocity() to be 0 after stopping waling

#

@shy leaf help maybe?

shy leaf
#

shrug

loud frigate
#

its like when you click on the side of a block it siulayes player click on all neighboring sides, a hacky way to get torch placement going

#

thats what i would think but the face passed is the same

prisma shard
#

ask mojang

loud frigate
#

i will

prisma shard
#

xd

prisma shard
#

what is the best storage database

warm mason
prisma shard
#

xd

#

Actually, you're right

#

i will make my one tbh

#

But i need ideas how they work

#

Can you link me some storage database script-resources?

warm mason
prisma shard
#

thanks

#

does it have limit

random flint
warm mason
prisma shard
#

so it splits dynamic properties

#

because dynamic properties have a character limit

warm mason
warm mason
random flint
warm mason
ivory bough
#
system.afterEvents.scriptEventReceive.subscribe((event) => {
    if (event.id === "space:event28") {
      const source = event.sourceEntity;
      const rotation = {
        x: 0,
        y: 5,
      }
      const currentRot = source.getRotation();
      const runInt = system.runInterval(() => {
        if (source.getRotation != currentRot) {
          source.teleport(source.location, {
             rotation: rotation
           });
           clear()
        }
      }, 10);
      function clear() {
        system.clearRun(runInt);
      }
    }
});

why doesn't it rotate the camera back after I rotate my camera?

warm mason
#
if (source.getRotation().x != currentRot.x || source.getRotation().y != currentRot.y) {
ivory bough
warm mason
#

I also don't see the point in the clear function.

ivory bough
warm mason
warm mason
ivory bough
warm mason
cyan basin
#

With custom commands in preview, why is the prefix still shown along side showing them without it?

#

It just makes it look super messy

inland merlin
cyan basin
#

I'm sure it'll be a super long time before it happens

inland merlin
#

There was a simialr question a while back

cyan basin
#

How come internally the game supports it but they can't expose that to the api?

inland merlin
#

Good question lol

cyan basin
#

I understand it's not as simple as that but I'm quite curious :P

inland merlin
#

Maybe they will surprise us

#

Lol

wary edge
#

Everything is hardcoded vs making things data driven so creators can use them.

inland merlin
#

I think one of the biggest things which would be helpful to me rn is block dynamic properties

remote oyster
#

Wish I had my computer by me. I feel like you can do subcommands with it. Strategically of course, but I honestly can't confirm right now.

loud frigate
# warm mason

how does that work? probabl a dumb JS question but how are you adding that arbitrary filesMap object to an ItemStack object? If i write that in TS it errors

warm mason
#

By the way, with ItemStack this may not work exactly as intended, but it doesn't matter....

warm mason
#

a class object is essentially just an object that is made according to a template

loud frigate
warm mason
#

And that's why I don't use TS

loud frigate
#

feature is so cursed im glad it doesnt allow it 💀

round bone
wary edge
loud frigate
#

well good to know, another odd javascript feature

warm mason
round bone
#

TypeScript is a bit harder than JavaScript, but it makes DX much better

wary edge
#

Laziness creates messy code which creates hard times.

#

Especially if you're sharing code.

round bone
loud frigate
leaden glade
#

orangutan?

loud frigate
round bone
loud frigate
#

i started fro python ages ago and now i hate it lol

warm mason
# wary edge Especially if you're sharing code.

Well, I write this code alone, so everything is fine. + the difference in my skills makes itself felt. When I wrote some features, I might not have known about other ways to solve it. Of course, I update the old code, but this part suits me quite well

round bone
loud frigate
# round bone typed Python is not that bad

never tried tbh. maybe should give a shot. still there the annoyng bit is all the libraries that seem simple to use and are for simple stuff but as soon as you got an issue you got to delve into their code and its madness

round bone
#

my favorite language is TypeScript currently

#

it has everything what I need, and is used in a lot of technologies

loud frigate
warm mason
#

Although I haven't heard anything about min either

loud frigate
#

hm that seems quite cunter intuitive

#

i just tried and that doesnt seem to do much for me. for my stuff i use anoter way to keep entities alive from kill (cloning, not perfect as some properties might get lost)

#

actaully Items are one of those... thats an issue, the minecraft:transformation component i was using does have a preserve equipment but that doesnt seem to copy inventories

random flint
buoyant canopy
#

how to listen for placement of block placer item events?

#

custom component don't trigger if a block was placed by a block placer item

ivory bough
#
const difficulty = world.getDifficulty();
  if (difficulty == "Peacful") {
    world.setDifficulty("Easy");
  }

Why doesn't this work?

#

This is in a runInterval BTW

buoyant canopy
#

never mind

ivory bough
wary edge
buoyant canopy
ivory bough
buoyant canopy
ivory bough
#
const difficulty = world.getDifficulty();
  if (difficulty == "Peacful") {
    world.setDifficulty("Easy");
  }

Also, can anyone help with this?

ivory bough
prisma shard
#

ops

#

1 sec

prisma shard
#

try this

ivory bough
prisma shard
ivory bough
warm mason
valid ice
#

Using the enum for difficulty would avoid spelling mistakes 🙂

prisma shard
#

I always use enums so

warm mason
prisma shard
#

Xd

valid ice
#

Well then git gud

wary edge
#

Please stop.

warm mason
valid ice
#

You'd have to change it regardless of using string or enum, I really don't see the problem

warm mason
prisma shard
#

smokey as always becoming strict like The === strict operator

warm mason
prisma shard
deep quiver
warm mason
#
  • saving 4 seconds of life, which can be spent on self-development :D
deep quiver
#

I mean on the code side

#

Runtime

warm mason
deep quiver
#

Importing an enum doesn’t take long, especially with tools that do the import for you automatically (vscode)

round bone
warm mason
round bone
#

you know what does it mean?

#

I am not sure

#

it does not mean that I am wrong

warm mason
round bone
#

no problem, just don't argue over some scripting my friend

mighty igloo
#

how do you modify a variable within another file

#

another ts file or js

#

it doesnt let me import a let

round bone
#

you can use a class provider

warm mason
round bone
#

or a singleton pattern

mighty igloo
#

this doesnt work: export const data = {
players: Players = [];
};

#

i need it to be a "players" type. which is a type i created

#

its an array type

wary edge
#

just export const players = []? Then you can push/pop it?

mighty igloo
#

alr 👍

#

thx

#

any alternative for this

warm mason
wary edge
#

const does not allow for reassignment.

mighty igloo
#

oh

#

well i know that

#

but i didnt know you did it like that

#

basically my goal here is to instead store player data within a world dynamic property because if I store it on the player I cannot modify it while they are offline

#

i also want to be able to modify the value across all files

#

but i dont know how

wary edge
mighty igloo
wary edge
#

In another file I just did export default.

mighty igloo
#

yeah but when i use that then I cannot import it

#

its a lowecase p and the "Players" there is a type not the let

#

oh i see

#

let me try

#

still nothin

wary edge
mighty igloo
#

i did

#

thats like the first thing i did

round bone
#

Wrong type

mighty igloo
#

I ended up just deciding to use getdynamic properties and set dynamic properties and just set and get from there. I guess that way it can all work together and if you leave when it sets it then its already saved

#

idk if its efficient but it works

round bone
#

Not efficient

#

Just make a class with 2 static methods

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

class WorldPlayers {
    private constructor() {}
    private players: Player[] = []

    public static getPlayers(): Player[] {
        return this.players
    }

    public setPlayers(players: Player[]): void {
        this.players = players
    }
}

export { WorldPlayers }
wary edge
#

Ehhh.

mighty igloo
#

no

wary edge
#

Tbh you could do away with just the array, no class needed.

mighty igloo
#

players is a variable I made

wary edge
#

Not everything needs to be OOP.

mighty igloo
#

it doesnt use Player from server

#

its not meant to

#

thats what makes it work offline

#

plus i'd be using the varible for every stored player value

#

so its not too bad

#

universal

buoyant canopy
round bone
#

OOP is a bit easier codebase to deal with.

#

That's why I like it.

loud frigate
full idol
#

Is there an easy way to allow spectators to open chests?

random flint
loud frigate
echo tinsel
#

is it possible that i can set it up instead of

    form.button("§8⬅ Back");
    form.button("§c⤴ Home");

its jump for back and sneak for home?

gilded shadow
echo tinsel
echo tinsel
#

i was assuming you were saying it cant detect the player jumped if the menu is opened because the player didnt jump. i was asking if there is anyway it can just detect that the button that is normally used for jump was pressed

echo tinsel
#

alright thank you

dawn zealot
#

i wish i could too

echo tinsel
#

ive already split the menu once so theres less on one page. that would be so much better if you could just back out anywhere rather then having to scroll all the way down

dawn zealot
#

just use chest ui

echo tinsel
#

what?

dawn zealot
echo tinsel
#

hmm, im honestly conflicted on that

#

i dont know if i like it

#

does that have a chance with conflicting with other things?

dawn zealot
#

no

#

well depends if u have custom ui

loud frigate
echo tinsel
#

ive been using script for everything.
looks like this currently

dawn zealot
#

would look alot better with chest ui

echo tinsel
#

i kinda disagree as that would require you to hover over the item and i feel like youd spend longer in the menu if you didnt know the icons

#

i find chest ui incredibly annoying when i use it on java servers so idk.
it would fit alot more on the same screen though

dawn zealot
#

okay bro im just giving u ideas holy

cyan basin
#

the steve head looking creepy af

echo tinsel
echo tinsel
#

he dont even look like that. he has eyes on the actual head lol

random flint
ruby plover
#

yo does anyone know how to solve this issue? i decided to try to make my own js code for the first time using similar code to create this, but i got this error

[Scripting][error]-TypeError: Native type conversion failed. Function argument [1] expected type: EntityDataDrivenTriggerEventOptions | undefined at <anonymous> (milk.js:189)

const EventDetector = {
  "eventName": {
  }
}

world.afterEvents.dataDrivenEntityTrigger.subscribe((data => {
        world.afterEvents.dataDrivenEntityTrigger.subscribe((event) => {
            let entity = event.source;
            if (EventDetector[data.eventId] != undefined, entity != undefined) {
                system.runTimeout(() => {
                    entity.runCommand("playsound supernova.spawn @a");
                    entity.runCommand("particle moo:stars1");
                    entity.runCommand("particle moo:stars2");
                    entity.runCommand("particle moo:stars3");
                    entity.runCommand("particle moo:stars4");
                    entity.runCommand("particle moo:large-void");
                    entity.runCommand("particle moo:fog");
                    entity.runCommand("particle moo:fog2");
                    entity.runCommand("particle moo:black-hole");
                    entity.runCommand("particle moo:black-hole-dust");
                })}}, 0);
            }
));```
#

the error is present here })}}, 0);

loud frigate
random flint
#

Is this custom or vanilla entity you're trying to edit

loud frigate
#

custom

#

just has these relevant components. maybe something with a scripting event could be donebut i tried in the past and it wasnt that easy due to when stuff was fired

loud frigate
#

I made a new entity and it magically works. Probably another component interfering or something. Anyways thanks it works now

prisma shard
knotty plaza
#

What options or what preset can I use in camera.setCamera() to just change the location of your perspective?

#

I tried with minecraft:free, but that makes me be able to see myself

wary edge
knotty plaza
wary edge
#

They did discuss this in the Creator Camp but nothing that I can recall.

stuck ibex
floral vessel
#

what are all events which are associated with a block update?

knotty plaza
#

Is there a way to allow the player to go back to first person after I set their camera to a custom position?

#

Without using .clear()

worldly heath
#

can I heal an entity by a specific amount ?

#

/effect regeneration isn't always accurate

shy leaf
worldly heath
#

is setHealth a thing ?

#

like player.setHealth(..) ?

knotty plaza
#

No wait

#

You said specific amount right?

worldly heath
#

yeh not to full health

knotty plaza
#
const health = player.getComponent('health');
health.setCurrentValue(health.currentValue + 2);
worldly heath
#

gonna try if it works

#

Thanks! this actually works

wary edge
gilded shadow
#

How to trigger hit effect on entities without actually hitting them or damaging them

gilded shadow
#

any workarounds?

#

like animation or render controller?

shy leaf
#

triggering hit effect without hitting them hmmm

#

thats like

#

trying to eat soup with fork i need a better comparison

warm mason
gilded shadow
#

oh BTW by hit effect I meant when the entity glows red

shy leaf
#

oh wait you mean the iframes effect

#

oh

#

theres

warm mason
#

What's the problem with applying damage?

shy leaf
#

ONE way, and it involves a command

gilded shadow
shy leaf
#

what about making sure that it doesnt die?

gilded shadow
#

too much work

shy leaf
#

like setting the health before applying damage

warm mason
shy leaf
#

its... two more lines

#

yk

safe stream
ivory bough
#

[Scripting][error]-ReferenceError: Native function [Dimension::getWeather] does not have required privileges. at <anonymous> (run.js:78)

const overworld = world.getDimension("overworld");
const weather = overworld.getWeather();

"const weather = overworld.getWeather();" is line 78

warm mason
#

Mojang finally added applyImpuse for players. Now this day is a holiday

ivory bough
distant tulip
warm mason
distant tulip
#

yeah

ivory bough
distant tulip
#

even modify it

warm mason
# ivory bough [Scripting][error]-ReferenceError: Native function [Dimension::getWeather] does ...
class Weather {
  static #weatherMap = new WeakMap();
  constructor(dimension) {
    this.#dimension = dimension
  }
  #dimension

  /** @type {import('@minecraft/server').WeatherType} */
  get id() { return world.getDynamicProperty('weather:' + this.dimension.id) || 'Clear' }

  /** @type {Dimension} */
  get dimension() { return this.#dimension }

  /**
   * @param {Dimension}
   * @returns {Weather}
   */
  static get(dimension) {
    return this.#weatherMap.get(dimension) || (this.#weatherMap.set(dimension, new Weather(dimension))).get(dimension)
  }

  static isRaining() {
    return ['Rain','Thunder'].includes(Weather.get(world.getDimension('overworld')).id)
  }
}
world.afterEvents.weatherChange.subscribe(data => {
  world.setDynamicProperty('weather:' + world.getDimension(data.dimension).id, data.newWeather)
})

My weather class. You can use it.

ivory bough
north frigate
#

Hey can anyone who's familiar with Acode editor tell me what plugins to use for coding

mighty igloo
#

why is the play sound not working

sharp elbow
#

Try setting the location to the player's location.

mighty igloo
#

i did

#

i tried that

warm mason
mighty igloo
#

yes

#

it works in game with commands

#

but not in code

round bone
#

doesn't it require a privilege?

mighty igloo
#

no i didnt make it do that

round bone
#

system.run(() => {

})

mighty igloo
#

yeah did that

round bone
#

and inside playSound

#

hmm

#

pretty weird

mighty igloo
#

its almost like ui cuts it off

warped blaze
#

Added totalArmor and totalToughness read only properties to EntityEquippableComponent

Enabled Player.applyImpulse and Player.clearVelocity in beta, which no longer throw errors```
finally
elder zenith
#

guys, is there a way to spawn an item with a pickup delay?

thorn flicker
#

you can use the loot table command.

elder zenith
#

whats the command to call that from script api?

#

@thorn flicker

#

I can't find it

elder zenith
elder zenith
#

how do i insert a variable into a command being run?

#

"command "${variable}" do stuff" isn't working for me

thorn flicker
elder zenith
elder zenith
thorn flicker
elder zenith
#

yeah

thorn flicker
#

"subfolder/your_file_name"

elder zenith
#

ok

#

do I include the .json?

thorn flicker
#

I forgot if you need to include loot_tables/at the beginning or not

thorn flicker
elder zenith
#

ok

thorn flicker
elder zenith
#

wait, should it be in quotes?

thorn flicker
#

yes.

elder zenith
#

neither one worked

thorn flicker
#

show me your code.

elder zenith
#

dimension.runCommand(`loot spawn ${block.location.x+0.5} ${block.location.y+1} ${block.location.z+0.5} loot "loot_tables/blocks/tomato_plant_harvest"`)

thorn flicker
#

it should work.

elder zenith
#

maybe my loot table file is wrong?

#
{
    "pools": [
        {
            "rolls": 1,
            "entries": [
                {
                    "type": "item",
                    "name": "toes:tomato",
                    "functions": [
                        {
                            "function": "set_count",
                            "count": { "min": 1, "max": 4 }
                        }
                    ]
                }
            ]
        }
    ]
}```
thorn flicker
#

looks fine.

elder zenith
#

hmmmmm

#

lemme make sure its not like at spawn or smth

thorn flicker
#

remove loot_tables/

elder zenith
thorn flicker
#

I told you to try without it as well

#

lol

elder zenith
#

lol I tried /blocks but with the /

thorn flicker
#

ah, I see

elder zenith
#

ok well thanks for bearing with me lol

thorn flicker
elder zenith
#

ah ok

thorn flicker
elder zenith
#

there's no pickup delay ._.

#

also it's flooring the position to the nearest block

shy leaf
#

since hunger/saturation/exhaustion components are out (in preview), what will you guys do with them?

dawn zealot
#

probably fuck all 😭

floral vessel
#

Who do I have to ask to get an onUpdate event for custom block components? There is no viable workaround afaik for running a script on block update.

prime zenith
#

anyone on to help me figure out why the loot command isnt finding my loot table

prisma shard
#

Cat_Hi 🥀 💔

prime zenith
#

i posted my code in a post

prime zenith
#

Anyone please helps me i cry now

north frigate
#

Can I use assembly to code script files

unique acorn
#

why

#

just why would you use assembly

#

but no you can't

north frigate
round bone
stuck ibex
#

This means it's allowed now?

shy leaf
shut citrus
#

What dif between require and import?

halcyon phoenix
#

hey people
does getEntities returns {entity},{entity} or {entity,entity}?

warm mason
#

Functions always return one value

halcyon phoenix
inland oracle
#

Hi am i trying to use block tick am i using it wrong

    "components": {
      "minecraft:tick": {
        "interval_range": [10, 20],
        "looping": true
      },

then in my custom block component i try use onTick but doesnt seem to work my player interact works wich tells me the block component is working on the block


  onPlayerInteract(event: BlockComponentPlayerInteractEvent, params: CustomComponentParameters) {
    if (event.player === undefined) {
      return;
    }

    console.info("Interact on Lava detect");
  }

  onTick(event: BlockComponentTickEvent, customParameters: CustomComponentParameters) {
    console.info("Lava Detection Tick");
  }
prisma shard
prisma shard
prisma shard
shy leaf
#

it doesnt work as intended

#

for now

#

it has rubberbanding issues

deep quiver
granite badger
#

I don't have time to test the player.applyImpulse thing. Can someone help me validate if this workaround is still valid? If it works I'd assume they didn't change the behavior of the method yet.

inland oracle
#

Example: I had minecraft:liquid_detection defined in the base components, and it was working across all permutations. When I added my custom component using Scripting v2-beta and Block Components v2, I also added it in the base — but it was being overridden when changing the crop growth stages.

Turns out, the Minecraft component doesn't need to be re-added in each permutation, but custom components do. All this just to make my crops break when lava touches them. They really need to add a lava option to liquid_detection, lol.

rose light
#

Is there a way for me to identify if the item is a block?

wary edge
halcyon phoenix
#

I tried getting the tags of an entity from a structure I generated but I cannot get it,
I tried teleporting all entities with that tag but the original ones only teleported not the structure generated ones. do strcuture blocks not include entity tags?

inland oracle
#

CustomComponent parameters 💜

prisma shard
#

Umm, what's the setVelocity for and how do i replace it to test?

shy leaf
#

it does work, but too much rubberbandings

prisma shard
#
Player.prototype.applyImpulse = function (vector) {
  this.applyKnockback(
    { x: vector.x, z: vector.z },
    vector.y < 0.0 ? 0.5 * vector.y : vector.y
  );
};```
#

meanwhile we can use it

warm mason
prisma shard
warm mason
prisma shard
warm mason
simple zodiac
#

a knockback is affected by knockback resistance. Such as just wearing netherite armor...

distant tulip
#

Even when ignoring that, knockback does not translate to velocity that simple

gaunt salmonBOT
ivory bough
#
world.beforeEvents.playerInteractWithBlock.subscribe((event) => {
      const block = event.block;
      if (block.typeId.includes("bed")) {
        const time = world.getTimeOfDay();
        system.run(() => {
          weather = overworld.getWeather();
        });
        const player = event.player;
        if (time >= 12542 && time <= 23459 && weather === "Clear" || time >= 12010 && time <= 23991 && weather === "Rain" || weather === "Thunder") {
        const detectNul = overworld.getEntities({ location: player.location, maxDistance: 4000, type: "space:null" });
     const detectNo_Texture = overworld.getEntities({ location: player.location, maxDistance: 4000, type: "space:no_texture" });
     const detectR2 = overworld.getEntities({ location: player.location, maxDistance: 4000, type: "space:r2" });
     const detectBroken_End = overworld.getEntities({ location: player.location, maxDistance: 4000, type: "space:the_broken_end" });
     const moonPhase = world.getMoonPhase();
     if (detectNul.length > 0) {
       system.run(() => {
       player.runCommand(`title @s actionbar err.null`);
       });
       event.cancel = true;
     } else if (detectNo_Texture.length > 0) {
       system.run(() => {
       player.runCommand(`title @s actionbar err.texture`);
       });
       event.cancel = true;
     } else if (detectR2.length > 0) {
       system.run(() => {
       player.runCommand(`title @s actionbar err.soul`);
       });
       event.cancel = true;
     } else if (detectBroken_End.length > 0) {
       system.run(() => {
       player.runCommand(`title @s actionbar err.theendisnear`);
       });
       event.cancel = true;
     } else if (moonPhase === 5 || moonPhase === 6 || moonPhase === 7 || moonPhase === 4) {
       system.run(() => {
       player.runCommand(`title @s actionbar err.themoon`);
       });
       event.cancel = true;
          }
       }
    }
});

For some reason this only works after the player interacts with a bed atleast 1 time

prisma shard
#

jsut do js const weather = overworld.getWeather();

prisma shard
fast lark
#

hi

#

someone can help?

#

world.afterEvents.playerBreakBlock.subscribe(({ dimension, itemStackBeforeBreak, itemStackAfterBreak, player, brokenBlockPermutation, block }) => {
if (itemStackBeforeBreak === "shinki:damethyst_drill"){
console.warn(${player.name} broke a block of type ${brokenBlockPermutation.type.id} at ${JSON.stringify(block.location)} in the dimension ${dimension.id}. They were holding ${itemStackBeforeBreak?.typeId || "nothing"} before breaking the block and now hold ${itemStackAfterBreak?.typeId || "nothing"});
player.playSound('random.explode', {pitch:0.6, location: player.location, volume: 1}); //Sound effect
let blockCount = 0;
for (let dx = -1; dx <= 1; dx++) {
for (let dy = -1; dy <= 1; dy++) {
for (let dz = -1; dz <= 1; dz++) {
if (dx === 0 && dy === 0 && dz === 0) continue;

                        const neighbor = block.offset({ x: dx, y: dy, z: dz });
                        if (unbreakableBlocks.has(neighbor.typeId)) continue;
                        blockCount = blockCount + 1; 
                        player.runCommand(`execute as @s run loot spawn ${neighbor.location.x} ${neighbor.location.y} ${neighbor.location.z} mine ${neighbor.location.x} ${neighbor.location.y} ${neighbor.location.z} mainhand`);
                        neighbor.setType('air');
                    }
                }
            }
            damageItem(itemStack, source, blockCount); 
        }
    })
#

it dosent show any error and it dosent do anything+

warm mason
# fast lark world.afterEvents.playerBreakBlock.subscribe(({ dimension, itemStackBeforeBreak,...
world.afterEvents.playerBreakBlock.subscribe(({ dimension, itemStackBeforeBreak, itemStackAfterBreak, player, brokenBlockPermutation, block }) => {
  if (itemStackBeforeBreak?.typeId != 'shinki:damethyst_drill') return;

    console.warn(`${player.name} broke a block of type ${brokenBlockPermutation.type.id} at ${JSON.stringify(block.location)} in the dimension ${dimension.id}. They were holding ${itemStackBeforeBreak?.typeId || "nothing"} before breaking the block and now hold ${itemStackAfterBreak?.typeId || "nothing"}`);
    player.playSound('random.explode', {pitch:0.6, location: player.location, volume: 1}); 

    let blockCount = 0;
    for (let dx = -1; dx <= 1; dx++) {
      for (let dy = -1; dy <= 1; dy++) {
        for (let dz = -1; dz <= 1; dz++) {
          if (dx === 0 && dy === 0 && dz === 0) continue; 
                
          const neighbor = block.offset({ x: dx, y: dy, z: dz });
          if (unbreakableBlocks.has(neighbor.typeId)) continue;
          blockCount++

          player.runCommand(`execute as @s run loot spawn ${neighbor.location.x} ${neighbor.location.y} ${neighbor.location.z} mine ${neighbor.location.x} ${neighbor.location.y} ${neighbor.location.z} mainhand`);
          neighbor.setType('air');
      }
    }
  }

  damageItem(itemStackBeforeBreak, source, blockCount); 
})
#

The ItemStack object is not a string, and you compared it to a string, that's why it didn't work

#

I also recommend using custom components.

static wedge
#

what is the maximum size of dynamic property bytes that the world and entities/items can contain

warm mason
jolly citrus
#
hit.applyKnockback(plr.getViewDirection().x, plr.getViewDirection().z, zKb, verticalKnockback);

how would i go about converting this to match the new signature of .applyKnockback() in 2.0.0-beta?

warm mason
jolly citrus
#

thankyouu

static wedge
# jolly citrus 32767

I’m trying to understand the storage limits of dynamic properties. I know that a single string property can hold up to 32,767 bytes, but I’m asking about the total storage limit for all dynamic properties combined on the world

ruby plover
remote oyster
patent tapir
#

It's || for or and && for and

ruby plover
#

oo

#

oo means "oh" lol

patent tapir
ruby plover
patent tapir
#

which line is line 189

#

the line that the error points to is important

ruby plover
#

the error is present here })}}, 0);

#

thats line 189

patent tapir
#

ok hold on

ruby plover
#

aight

patent tapir
#

found it

#

you had your parenthesis all scrambled

#

you were trying to apply the timeout in ticks to the afterEvents method

#

not the system.runTimeout method

#

this is what your code looks like formatted

ruby plover
#

ohhhh

patent tapir
#
world.afterEvents.dataDrivenEntityTrigger.subscribe((data => {
    world.afterEvents.dataDrivenEntityTrigger.subscribe((event) => {
        let entity = event.source;
        if (EventDetector[data.eventId] != undefined, entity != undefined) {
            system.runTimeout(() => {
                entity.runCommand("playsound supernova.spawn @a");
                entity.runCommand("particle moo:stars1");
                entity.runCommand("particle moo:stars2");
                entity.runCommand("particle moo:stars3");
                entity.runCommand("particle moo:stars4");
                entity.runCommand("particle moo:large-void");
                entity.runCommand("particle moo:fog");
                entity.runCommand("particle moo:fog2");
                entity.runCommand("particle moo:black-hole");
                entity.runCommand("particle moo:black-hole-dust");
            })
        }
    }, 0);
}
));```
#

makes sense?

ruby plover
#

yea yea i get it

#

Tysm

patent tapir
#

mhm

dawn zealot
patent tapir
dawn zealot
#

why not just make them into 1 particle?

#

instead of having tons of them

#

😭

ruby plover
#

probably will optimize it later, but just wanted to get it working as an entity event before making everything

fresh current
#

question

#

what if your trying to edit a file that the owner got view only on anyway to by pass that?

fallow carbon
fresh current
#

nvm i fixed it

#

yo fetchbot

#

{
"pools": [
{
"conditions": [
{
"condition": "random_chance",
"chance": 0.25
}
],
"rolls": 1,
"entries": [
{
"type": "item",
"name": "op_asa:akumanomi_betabeta",
"weight": 1
}
]
},
{
"conditions": [
{
"condition": "killed_by_player_or_pets"
}
],
"rolls": 1,
"entries": [
{
"type": "item",
"name": "op_asa:bounty_trebol",
"weight": 1
}
}
]
}
]
}
]
}

#

is this correct?

fallow carbon
fresh current
#

wdym?

fallow carbon
#

this is the Script API General, thats a loot table

fresh current
#

which channel

#

should i go into

fallow carbon
#

perhaps make a post in #1067869659757543555 or #1067869022273667152, I'm not sure what the right category is.

prime zenith
#

Whats the loot table for vault and ominous vault if running command

fresh current
#

yo @fallow carbon

#

come back rq

tender pier
#

Does anyone know how to spawn a particle when you place a block?

#

I want to spawn a specific particles each time i place that block, but I have no idea how to do that

wary edge
tender pier
wary edge
patent tapir
#

why is Intl not defined?

#

I try to use it in a simple relative date script but whenever I use const relativeDate = new Intl.DateTimeFormat() it gives an Intl is not defined error

fresh current
#

yo its showing weird letters

remote oyster
# static wedge are you sure about that ?

Yes, dynamic properties are written to the world data file and at the moment they do not restrict the size, that I'm aware of. It's purely based on how large your hard drive is. The size of the strings is where they restrict you. So others just break them down into chunks.

fresh current
#

@fallow carbon

#

its showing up weird letters

#

PK

#

like this

remote oyster
#

Not sure why. I presume the devs pulled it out?

#

But your guess is as good as mine lol.

tender pier
wary edge
fresh current
#

this is weird

#

can someone help me

fallow carbon
frozen vine
#

How do I detect when an entity is in coordinated uka and therefore executes a command?

fallow carbon
patent tapir
#

I also didn't know it was quickjs

#

I don't know anything about the source alright

#

how do I import it then

fallow carbon
patent tapir
#

I'm using the bedrock scripting api

#

not whatever that is

fallow carbon
#

the bedrock scripting api runs on top of a modified version of quickjs afaik

fallow carbon
wary edge
#

You can of course just recreate Intl.RelativeTimeFormat.

patent tapir
#

I created a forum post for such a purpose already

patent tapir
fallow carbon
fresh current
#

yo @fallow carbon

fallow carbon
#

that is ofcourse assuming that it does not depend on api's minecraft does not include

fresh current
#

can you help me fix it right quick please?

fallow carbon
patent tapir
#

And Smokey already gave me a link to a nice function recreation of what I'm looking for

fallow carbon
#

hmm, I must have missed that. I don't see it in the chat here

patent tapir
halcyon phoenix
#

is it possible to change an entity nameTag?

patent tapir
#

just do entity.nameTag = "name"

#

it even works on players, which is really useful

inland oracle
#

Anyone know if im doing this wrong(good possibility) or a bug in scripting api v2

When i try check player gamemode towards the Gamemode Enum it doesnt work the print shows the enum as undefined

console.log(player.getGameMode());
console.log(GameMode.Creative);

      if (player.getGameMode() === GameMode.Creative) {
        // Grow crop fully
        block.setPermutation(block.permutation.withState("crs_green:crop_age" as any, params.max_age - 1));
      } else {

but if i do a string check i get the right outcome

console.log(player.getGameMode());
console.log(GameMode.Creative);

      if (player.getGameMode().toString() === "creative") {
        // Grow crop fully
        block.setPermutation(block.permutation.withState("crs_green:crop_age" as any, params.max_age - 1));
      } else {
patent tapir
#

it should look like this
```js
code
```

#

much better

#

alright

patent tapir
#

it's just GameMode.creative

inland oracle
#

but it is in v2 for some reason i know its not in v1

patent tapir
#

it's GameMode.creative not GameMode.Creative

#

trust me

inland oracle
#
/**
 * Represents a game mode for the current world experience.
 */
export enum GameMode {
    /**
     * @rc
     * @remarks
     * World is in a more locked-down experience, where blocks may
     * not be manipulated.
     *
     */
    Adventure = 'Adventure',
    /**
     * @rc
     * @remarks
     * World is in a full creative mode. In creative mode, the
     * player has all the resources available in the item selection
     * tabs and the survival selection tab. They can also destroy
     * blocks instantly including those which would normally be
     * indestructible. Command and structure blocks can also be
     * used in creative mode. Items also do not lose durability or
     * disappear.
     *
     */
    Creative = 'Creative',
    /**
     * @rc
     * @remarks
     * World is in spectator mode. In spectator mode, spectators
     * are always flying and cannot become grounded. Spectators can
     * pass through solid blocks and entities without any
     * collisions, and cannot use items or interact with blocks or
     * mobs. Spectators cannot be seen by mobs or other players,
     * except for other spectators; spectators appear as a
     * transparent floating head.
     *
     */
    Spectator = 'Spectator',
    /**
     * @rc
     * @remarks
     * World is in a survival mode, where players can take damage
     * and entities may not be peaceful. Survival mode is where the
     * player must collect resources, build structures while
     * surviving in their generated world. Activities can, over
     * time, chip away at player health and hunger bar.
     *
     */
    Survival = 'Survival',
}

patent tapir
inland oracle
#

i shall try dont worry lol ill be damned

patent tapir
inland oracle
patent tapir
#

make sure you're importing GameMode

inland oracle
#

oh acctually my typscript failed to compile due to the lower case

patent tapir
#

it's basically the same but whatever

inland oracle
#

but it still wont work because in @minecraft/server its upper case in v2.0.0-Beta

patent tapir
#

for future reference

patent tapir
#

I gotta go for dinner

#

see ya and I hope you get the help you need

ivory bough
inland oracle
#

the v2 with custom components with parameters opens up alot

tender pier
#

can i get some help with this? I'm trying to make this script work with tags but honestly idk what i'm doing rn

inland oracle
tender pier
#

I get this error

shy leaf
#

are you using outdated module?

#

oh

#

you missed an s in afterEvent

#

its .afterEvents

inland oracle
shy leaf
#

kinda ironic cuz i overslept today...

#

but yeah

inland oracle
#

im the oposite i should go sleep lol

shy leaf
inland oracle
#

and typescript can be a huge help for catching things early

#

i didnt notice the missing s as i just quickly typed what you was doing but due to autocomplete i didnt get the error

tender pier
#

Thank y'all really

inland oracle
tender pier
shy leaf
shy leaf
inland oracle
#

provides autocomplete also shows alot of documentation so you can pick apart find new things

#

i stumble accross things by accident all the time thanks to npm and typescript

shy leaf
#

when i tested hotbar change event with oldschool method using .selectedSlotIndex and the native method, the former fires first

#

its around... 1~3ms late

#

but sometimes it also fires at the same time

inland oracle
#

hmm maybe a bug in preview

shy leaf
#

might open a bug report

inland oracle
#

i think i found a bug in v2 scripting api not sure where the reporting is for bedrock im coming from java modding lol

shy leaf
#

its on the same place you report bugs for java edition

#

in mojira

inland oracle
#

the only bugs ive ever reported have been related to forge modding api

#

is it possible to detect the light level of a block example crops grow under certain light conditions

shy leaf
#

i might be wrong cuz i barely touched anything block related

inland oracle
#

it doesnt seem like you can i tried to go through world and dimension unfortunate

#

like i could go the route of detecting if blocktype matching a light source is around a certain distance and if has a visable path e.g air but that seems like alot of calculation for a basic crop for now lol

#

i did something similar in my custom lava_detection component to destroy crops when lava flows into them

remote oyster
#

Because it is a enum, you must import it from @minecraft/server or it will be undefined.

inland oracle
dusky flicker
sour sedge
halcyon phoenix
#

GUYS I FREAKING DID IT

#

MY OWN MAZE GENERATION

#

3 days of work and 187 lines of code

warm mason
#

Although it's still cool, I guess

halcyon phoenix
#

it's so amazing to look at after 3 days of despair

#

I did this cause I can't get jigsaw block to work :>

warm mason
halcyon phoenix
#

YEAH

#

LOL

warm mason
halcyon phoenix
#

Nice, I'm not alone

halcyon phoenix
warm mason
# warm mason

This is a single storey version, although it supports multiple storeys.

halcyon phoenix
#

also the math.random is kinda predictable sometimes I get like a straight line

#

any suggestions to prevent that?

#

I have an array that stores all the structures and I do structures[getRandomInt(structure.length)]

#

to get a random structure

halcyon phoenix
warm mason
halcyon phoenix
#

I can't wrap my head around the grid....

#

to the point where I don't even know what im coding

warm mason
halcyon phoenix
#

I'll try making a true maze generator next time :<

#

is it fine if I as for yours as a reference?

warm mason
#

This is essentially just a screenshot.

granite cape
#

p

#

p

warm mason
granite cape
#

new pp for new player

remote oyster
halcyon phoenix
#

I had this issue where the player coordinates are so exact and I need to match it with others however the rest of the other coordinates are armor stand and are perfectly placed there how do I turn my coordinate into the same? what other methods are there?

copper egret
#

use ```
Math.round(entity.location x)

#

so uh, good day.
Is there a way to make the player forcely open an inventory UI once he rides the horse

cerulean cliff
#

The ago old question of... is there a way to cancel the death of entities?

#

Of any entity... ignoring our lovely damage sensor

distant tulip
#

unless you know when the damage is happening, no

halcyon phoenix
distant tulip
#

it is possible

halcyon phoenix
#

what method?

warm mason
distant tulip
#

and getRiders()[0]

cerulean cliff
warm mason
halcyon phoenix
cerulean cliff
warm mason
warped kelp
#

Can I use scripts to detect entity health? Like, a specific entity's health to run functions or run entity events?

warped kelp
#

Nice

warm mason
warped kelp
#

Thank you

violet harbor
#

Hellooo. Could someone tell me how to create a blacklist for blocks that fences should not connect to, in this script here? I'm new to this stuff so I need help.


const fenceTag = 'custom:fence'

export class fence_Manager {
    static update_Fence_States(Fence) {
        let north = undefined;
        try {
            north = Fence.north(1);
        } catch { }
        let south = undefined;
        try {
            south = Fence.south(1);
        } catch { }
        let east = undefined;
        try {
            east = Fence.east(1);
        } catch { }
        let west = undefined;
        try {
            west = Fence.west(1);
        } catch { }
        const blocks = [
            { block: north, side: "north" },
            { block: south, side: "south" },
            { block: east, side: "east" },
            { block: west, side: "west" },
        ];
        for (const blockData of blocks) {
            if (blockData.block != undefined) {
                if (!(blockData.block.isLiquid || blockData.block.isAir)) {
                    Fence.setPermutation(Fence.permutation.withState("custom:" + blockData.side, true));
                } else {
                    Fence.setPermutation(Fence.permutation.withState("custom:" + blockData.side, false));
                }
            } else {
                Fence.setPermutation(Fence.permutation.withState("custom:" + blockData.side, false));
            }
        }
    }
    static updateFencesAround(Block) {
        let north = undefined;
        try {
            north = Block.north(1);
        } catch { }
        let south = undefined;
        try {
            south = Block.south(1);
        } catch { }
        let east = undefined;
        try {
            east = Block.east(1);
        } catch { }
        let west = undefined;
        try {
            west = Block.west(1);
        } catch { }
        const blocks = [Block, north, south, east, west];
        for (const block of blocks) {
            if (block != undefined) {
                if (block.hasTag(fenceTag)) this.update_Fence_States(block);
            }
        }
    }
}```
dusky flicker
dusky flicker
warm mason
dusky flicker
warm mason
warm mason
dusky flicker
#

i really dont understand minecraft community

wary edge
#

Bedrock community try not to gatekeep, difficulty impossible.

distant tulip
#

his addon is wip

#

huh

#

whats with the emojis

dusky flicker
#

bros probably ashamed

warm mason
wary edge
warm mason
distant tulip
warm mason
distant tulip
#

anyway, how is the work on it coming along?

#

oh

#

your github?

warm mason
warm mason
distant tulip
#

alr, good luck with it and your exams

warm mason
cold shoal
#

Will I need to make many changes if I convert my scripts to the v2 API?

distant tulip
#

depend

prime zenith
#

Internally is it wheat_seed seed seeds or wheat_seeds

#

Nvm bridge just told me lol

prisma shard
prisma shard
#

what,, seemed like my messages got deleted idk

misty dagger
#

I noticed that the worldInitialize before and after events are getting deprecated in 2.0.0. What is the proper way to access the BlockComponentRegistry class without using those events?

wary edge
wary edge
proud saddle
#

how can i optimize code with using runJob?

woven loom
#

Depends

warm mason
proud saddle
#

okay
with other side
what yield in generator functions actually does?

warm mason
woven loom
#

Pause

warm mason
#

Analogous to await system.waitTicks(1)

woven loom
#

Yield does not break to next tick tho

warm mason
warped kelp
#

Helloo, there appears to be a problem, the script does not seem to work despite not showing any warning in the console?

{
    const array = [
        "dud_1_donuthin",
        "dud_2_donuthin",
        "dud_3_donuthin",
        "dud_4_donuthin",
        "chunk_take_1",
        "chunk_take_2"
    ];

    world.beforeEvents.worldInitialize.subscribe(({ itemComponentRegistry }) => {
        itemComponentRegistry.registerCustomComponent("og_cleaver_1:trigger", {
            onHitEntity(event) {
                const player = event.attackingEntity;
                player.runCommand(`function ${array[Math.floor(Math.random() * array.length)]}`);
            }
        });
    });
}
warm mason
woven loom
warped kelp
warm mason
warped kelp
#

What

warm mason
#

This file might simply not launch.

woven loom
warm mason
#

Show manifest

warm mason
warped kelp
# warm mason Show manifest

Me?

{
  "format_version": 2,
  "header": {
    "description": "Adds the very dangerous meat lover! by §dDistortionist",
    "name": "Meat Lover <3 1",
    "uuid": "138e28b2-40a1-439a-8833-247f01880841",
    "version": [
      0,
      0,
      1
    ],
    "min_engine_version": [
      1,
      19,
      70
    ]
  },
  "modules": [
    {
      "description": "Adds the very dangerous meat lover! by §dDistortionist",
      "type": "data",
      "uuid": "6cf21ffa-55da-4055-abd1-42abf5b72a41",
      "version": [
        0,
        0,
        1
      ]
    },
    {
      "type": "script",
      "uuid": "ac2da102-999e-4f81-9217-a6b3bf314bf6",
      "version": [
        0,
        0,
        1
      ],
      "entry": "scripts/main.js",
      "language": "javascript"
    }
  ],
  "dependencies": [
    {
      "uuid": "d5e3ec19-7c2f-47e6-9b21-e8f71b976e4c",
      "version": [
        0,
        0,
        1
      ]
    },
    {
      "version": "1.17.0",
      "module_name": "@minecraft/server"
    },
    {
      "version": "1.3.0",
      "module_name": "@minecraft/server-ui"
    },
    {
      "version": "1.2.0",
      "module_name": "@minecraft/common"
    }
  ],
  "capabilities": [
    "script_eval"
  ]
}
warm mason
warm mason
woven loom
#

Nope, its hardcoded

warm mason
woven loom
#

Mojang dev told me that, but I am forgetting.

warped kelp
warped kelp
#

import "./custom/detect_hwalth_meat";
import "./custom/on_hit_cleaverr";
import "./item_trigger";

warm mason
#

Maybe it's because of the extra scope?...

warped kelp
#

It was import { world, system } from "@minecraft/server"; before

prisma shard
# proud saddle how can i optimize code with using runJob?

really depends. Such as when using fillBlocks and setType, runJob is must.

And asking about yield, Yield basically pauses the code for next tick,

You could better understand runJob and yield by this example:

system.runJob(function* () {
  yield dimension.setType(`stone`);
}())
prisma shard
proud saddle
warped kelp
prisma shard
woven loom
#

Anyone got a ts template for script api project?

prisma shard
warped kelp
wary edge
woven loom
#

Uh

prisma shard
warm mason
#

Actually, this is far from the first time

prisma shard
warped kelp
#

Nvm just needed to remake it for some reason

wary edge
jolly citrus
#

Are slash commands available only on servers

#

Or can addons also access them

#

Hopefully I don’t sound crazy but I swear i heard about a slash command builder being added to beta APIs a few updates back

warm mason
full idol
#

Are dynamic properties readable by players on realms? For example through hacks, could they read their own/the world dynamic properties?

simple zodiac
jolly citrus
#

I don’t think Script API stores any sort of data locally on players

#

Only on the server

#

It’s unlikely that anybody would be able to hack the server that their game is being hosted on to access that kind of data

full idol
#

Ah alrighty, thank you!

jolly citrus
#

Can I somehow stop totems from functioning on a specific player(s) under specific conditions

jolly citrus
#

what parameters does callback on customcommand pass

#

nvm

winged gull
#

which is stored inside of the world's .ldb files.

#

in the db folder

fresh current
#

@fallow carbon can you help me rq now?

inland oracle
jolly citrus
#

why's this throwing me an error

customCommandRegistry.registerCommand({
    name: "getuserlogs",
    description: "Get logs for a username and group",
    permissionLevel: 0,
    mandatoryParameters: [
      { name: "username", type: Str },
      { name: "group", type: Str }
    ],
    optionalParameters: [
      { name: "page", type: Int }
    ]
  }, (origin, args) => {
    const sender = origin.sourceEntity;
    try {
      if (!args[0] || !args[1]) return sender.sendMessage("§cUsername and group required.");
      const page = args[2] && args[2] > 0 ? args[2] : 1;

      sender.sendMessage("§0");
      let id = world.getDynamicPropertyIds().filter((dpid) => dpid.startsWith("data:"))
        .map(dpid => {
          let data = JSON.parse(world.getDynamicProperty(dpid));
          if (data?.lastKnownUsername === args[0]) return dpid.split(":")[1];
        })
        .find(Boolean);

      if (!id) return sender.sendMessage("§cNo logs found for this player.");

      const logs = DataUtils.getLogsByGroup(id, args[1]);
      if (!logs.length) return sender.sendMessage("§cNo logs found for this group/player.");

      const LOGS_PER_PAGE = 10;
      const totalPages = Math.ceil(logs.length / LOGS_PER_PAGE);
      const start = (page - 1) * LOGS_PER_PAGE;
      const end = start + LOGS_PER_PAGE;

      if (page > totalPages || page < 1) {
        return sender.sendMessage(`§cInvalid page. Please enter 1 - ${totalPages}`);
      }

      sender.sendMessage(`§aLoading ${args[0]}'s ${args[1]} logs...`);
      logs.slice(start, end).forEach((log, i) => {
        const index = start + i + 1;
        const format = formatUnixTime(log?.date);
        const logLocation = log?.location ? Object.values(log.location).join(", ") : "N/A";
        const claim = log?.claim ?? "None";
        const name = args[0];
        if (args[1] === "fence") {
          sender.sendMessage(`§d${format}§7 [${index}] - §d${name} §eopened fence gate at §d${logLocation} §ein claim §d${claim}`);
        } else if (args[1] === "pearl") {
          const from = log?.fromLocation ? Object.values(log.fromLocation).join(", ") : "???";
          const to = log?.toLocation ? Object.values(log.toLocation).join(", ") : "???";
          sender.sendMessage(`§d${format}§7 [${index}] - §d${name} §ethrew pearl from §d${from} §eto §d${to} §ein claim §d${claim}`);
        }
      });

      sender.sendMessage(`§aPage ${page} of ${totalPages}.`);
      sender.sendMessage("§0");

    } catch (e) {
      sender.sendMessage(`§c${e} ${e.stack}`);
    }
  });
#

Str and Int are defined elsewhere ^

remote oyster
inland oracle
# remote oyster That would be helpful. I'm slightly preoccupied at the moment but I could snoop ...

https://github.com/CodeRandomMC/crs_green-1.21.80-beta/blob/main/scripts/crop_block_component.ts

so the issue i was having as stated earlier when using the Gamemode enum inport i get a undefined error on the enum when checking it towards a players gamemode (clarify yes the enum is undefined not the player) i can check players gamemode agaisnt a string "creative" and works fine, i am using the latest stable BETA apis on stable version of bedrock with v2 experiments turned on

GitHub

Contribute to CodeRandomMC/crs_green-1.21.80-beta development by creating an account on GitHub.

#

just a simple crop component using the new custom block components, anyone feel free to look as its just me testing things with the beta api

#

beware its just me testing the new api's so not the cleanest of work XD

inland oracle
wary edge
jolly citrus
#

Hst’s as specific as it gets

#

Comes up on command initialization not when it’s ran

#

It just says getuserlogs encountered an error and points me to line 74 which is just some closing brackets

jolly citrus
wary edge
#

Post your code, errors there.

remote oyster
true isle
#

Is it possible to itterate blocks placed by script across a dimension? Like scatter feature almost

short iron
#

Ok quick question, the "realms" servers are currently using API 1.18.0 correct?

deep quiver
thorn flicker
#

the latest for server is 1.19.0

short iron
#

Eh, thought they can't use beta API?

thorn flicker
#

they can.

short iron
#

😭 when that change lol

thorn flicker
#

I never heard that you couldn't

short iron
#

Weird always had issues with it poor coding on my part I'm sure. Reason I ask is it says it uses .beforeChat etc but it doesn't and I don't see any documentation that says otherwise. Or I'm looking at the wrong thing

valid ice
#

You have to turn on beta APIs before uploading the world to the realm, but yes, they do work on the realm

short iron
#

dead thanks lol... But to confirm they did remove the chat events from stable to experimental APIs right?

tender pier
#

hello

#

can someone help me fix my code?

wary edge
#

Please open a post.

tender pier
#

okay

remote oyster
#

I attempted to build your addon and test but I got a lot of errors when loading it in the world for testing. Wasn't trying to debug all of those issues just to confirm what I mentioned above. I don't have enough free time for it.

ivory bough
#
system.beforeEvents.startup.subscribe((e) => {
  e.blockComponentRegistry.registerCustomComponent("space:physicaltrack", {
        onTick:(event) => {
          let block = event.block;
          let loc = block.location
          physicalStacktraceTick(block.location, overworld);
        }
    })
    const vhsCommand = {
    name: "remove:vhs",
    description: "null",
    permissionLevel: 0
  };
  e.customCommandRegistry.registerCommand(vhsCommand, Command);
});

I genuinely don't know why this doesn't work. This doesn't even return an explanation for why it doesn't work. My block says that space:physicaltrack doesn't work exist even though it does. And there's no other errors. And it's not about the functions either

#

I am using 2.0.0-beta

shy leaf
#

give me a second

shy leaf
#

that too

worn sphinx
#

How to fix this error?
[Scripting][error]-Unhandled promise rejection: TypeError: Native type conversion failed. Function argument [2] expected type: ModalFormDataTextFieldOptions | undefined at show (CustomFrom/ModalFormCustom/index.js:67)

shy leaf
worn sphinx
shy leaf
worn sphinx
# shy leaf can you show your current code

I just tested this code but when I open the gui it gives me an error
Code:

world.beforeEvents.itemUse.subscribe((event) => {
  const player = event.source;

  showBasicModalForm(player);
})


function showBasicModalForm(player) {
  const players = world.getPlayers();

  const modalForm = new ModalFormData().title("Example Modal Controls for §o§7ModalFormData§r");

  modalForm.textField("Input w/ default", "type text here", "this is default");

  modalForm
    .show(players[0])
    .then((formData) => {
        
    })
}
leaden elbow
shy leaf
#

that

worn sphinx
#

Tks

inland oracle
# remote oyster Yea, looking at your code, and reviewing the dependencies you are requesting, it...

interesting was you using beta apis andv2 components with 1.21.82 stable as the code has no errors but the undefined enum, i understand that its lowercase in the older versions but in the beta api the import its capitalized in the the code, also the code is typescript not java script so you'd have to build the java script first, the only time i get errors is using th enum import Gamemode otherwise no errors and i can check players gamemode towards a string and the addon works fine without any errors

#

shouldnt get any errors

#

and as i said earlier latest stable 2.0.0-beta the import is capitalized im looking at the imports code

#

but player.getGamemode() still returns lowercase when testing against a string, so even if the enum worked it wouldnt test right now its capitalized

remote oyster
inland oracle
#

ah yes i fell in love with custom components v2 lol

#

easily sending parameters through block components opens up for easily building all sorts of blocks

distant tulip
#

My eyes hurt

remote oyster
# inland oracle and as i said earlier latest stable 2.0.0-beta the import is capitalized im look...

It's not capitalized. I already verified. The issue is that your dependencies are being overwritten when importing because you use ^ before the version in package.json. Another issue is that when pulling in sub-dependencies (like when a package depends on @minecraft/server), they might request a different version than the one you're using, especially if they're using ^ too. That’s where overrides comes in: it forces all packages to use the exact version you specify, preventing mismatches and making sure everything stays consistent.

What is happening in your environment, from what I could verify, is that it were trying to pull in preview API's and in preview they are capitalized.

inland oracle
remote oyster
# inland oracle so will it not just stick to the latest 2.0.0-beta-stable or does it force a pri...
{
  "name": "crs_greenstead",
  "version": "0.1.0",
  "productName": "Minecraft TypeScript Starter Project",
  "description": "TypeScript Starter",
  "private": true,
  "devDependencies": {
    "@minecraft/core-build-tasks": "5.0.0",
    "eslint-plugin-minecraft-linting": "2.0.4",
    "source-map": "0.7.4",
    "ts-node": "10.9.2",
    "typescript": "5.8.3"
  },
  "scripts": {
    "lint": "just-scripts lint",
    "build": "just-scripts build",
    "clean": "just-scripts clean",
    "local-deploy": "just-scripts local-deploy",
    "mcaddon": "just-scripts mcaddon",
    "enablemcloopback": "CheckNetIsolation.exe LoopbackExempt -a -p=S-1-15-2-1958404141-86561845-1752920682-3514627264-368642714-62675701-733520436",
    "enablemcpreviewloopback": "CheckNetIsolation.exe LoopbackExempt -a -p=S-1-15-2-424268864-5579737-879501358-346833251-474568803-887069379-4040235476"
  },
  "dependencies": {
    "@minecraft/math": "2.2.4",
    "@minecraft/server": "2.0.0-beta.1.21.82-stable",
    "@minecraft/server-ui": "2.0.0-beta.1.21.82-stable",
    "@minecraft/vanilla-data": "1.21.81"
  },
  "overrides": {
    "@minecraft/math": {
      "@minecraft/server": "2.0.0-beta.1.21.82-stable"
    },
    "@minecraft/server-ui": {
      "@minecraft/server": "2.0.0-beta.1.21.82-stable"
    }
  }
}
#

This will override math and server-ui preventing them from trying to install their own dependency version for server.

#

You will need to probably delete node_modules in the root directory of your project to clean up. Then execute npm i again.

inland oracle
remote oyster
# inland oracle okay thanks much appreciated ill try that

Because of how their versioning works, using ^ is not ideal. It's recommended to target the explicit version you require and update manually when needed. Some packages, such as @minecraft/math and @minecraft/server-ui, internally reference different versions of @minecraft/server. For example, even the Beta Stable versions may try to resolve dependencies against the Stable channel.

To prevent this, the overrides field is used to enforce the version you explicitly declared. This ensures consistency across packages and avoids subtle bugs or mismatches caused by mixed API versions.

inland oracle
remote oyster
#

Honest mistake. Most don't realize that some of their packages will internally reference another version and try to use that instead of what you actually asked for. Thankfully they have the feature to override in those edge cases lol.

inland oracle
#

i think its because i was using preview the other day, changed a few things to get on stable also im just getting into bedrock development from forge dev, obviously the wrong way XD

remote oyster
inland oracle
#

the guys not using npm and typescript i'll give it to them if it wasn't for intellisense and strict type checking this learning process would be much slower lol

remote oyster
inland oracle
# remote oyster I started out not using Typescript for Bedrock. Was definitely a slower learning...

As a Java developer, I find TypeScript feels much closer to a Java environment than plain JavaScript. I always encourage using TypeScript for Bedrock scripting—it’s a game-changer! The type safety catching errors early in the IDE, especially with new APIs. Instead of stumbling across issues at runtime, you can fix them upfront, turning days of debugging into hours. Highly recommend to anyone and its not that much different or hard to learn

#

Microsoft’s heavy use of TypeScript really sold me on it for Bedrock scripting their videos on the minecraft creator YouTube channel were super helpful when I was deciding whether to switch from Java-injected mods to the official Bedrock APIs. At first, I was hesitant, but after checking out the v2 APIs and custom block components v2, I was hooked! I made the switch right away and haven’t looked back so now just seeing what can be done and building things from my java mods in bedrock.

#

I’ve been part of the Minecraft scene since the early alpha days, when it was just a creative sandbox building game. Like many Java/Forge developers, I was hesitant to switch to Bedrock Edition because the early scripting APIs were pretty limited. A lot of us didn’t look back after that. I hadn’t developed Java mods in years, but recently, I started playing Bedrock with my wife and fell in love with the game again. I decided to explore the modern APIs, and I’m blown away. I’m hooked on Bedrock scripting now 😄

#

anyway has anyone discovered if you can get light level of block, not light emission but the light level like a crop does for determining if should grow I've discovered growing, lava break, farmland moisture i need to crack light levels lol withing a block component would be nice rather than external checks

ivory bough
inland oracle
ivory bough
# distant tulip What is the exact error

The only errors:
[Scripting][warning]-Component 'space:physicaltrack' was not registered in script but used on a block

[Geometry][error]-models/blocks/physical_stacktrace.json | Required child geometry.[a-zA-Z0-9_.'-:]+ not found

[Geometry][error]-models/blocks/physical_stacktrace.json | geometry file didn't validate

ivory bough
distant tulip
#

you are not updating your script file

ivory bough
inland oracle
ivory bough
inland oracle
inland oracle
inland oracle
# ivory bough Yeah.

Seems to works as intended as host you are op to begin with i then remove the op, print to log, add it back, print again

player.setOp(false);
console.log(player.isOp());
player.setOp(true);
console.log(player.isOp());
ivory bough
inland oracle
#

make sure beta api's and in experiments you have the beta api turned on

jolly citrus
#

anyone know what the issue is

system.beforeEvents.startup.subscribe(({ customCommandRegistry }) => {
  const { String: Str, Integer: Int, PlayerSelector: Player } = CustomCommandParamType;

  try {
    customCommandRegistry.registerCommand({
        name: "hi",
        description: "Says hi back to you",
        permissionLevel: 0,
        mandatoryParameters: [],
        optionalParameters: []
      }, (origin) => {
        const sender = origin.sourceEntity;
        try {
          sender.sendMessage(`§aHello ${sender.name}!`);
        } catch (e) {
          sender.sendMessage(`§c${e} ${e.stack}`);
        }
      });
  } catch (e) {
    system.run(() => {
    world.sendMessage(`§cError registering command: ${e} ${e.stack}`);
    })
  }
});
#

this is line 61

#

right i need a namespace

#

smh

jolly citrus
granite cape
#

umm

granite cape
jolly citrus
#

that won't change anything

#

the issue was that i didn't have a namespace for the command name

granite cape
#

yea i know

jolly citrus
#

scriptstarter module is just a library built on top of vanilla commandbuilder to make it easier for some people to add commands or multiple of them

#

it still works the same way

#

Do all of my commands have to use the same namespace

#

if they're from the same pack

inland oracle
jolly citrus
#

For some my commands beyond registering ones with the namespace c dont register

#

It just stops at the first one that uses t

inland oracle
#

have you tried to use the same namespace just to see if that is the cause

jolly citrus
#

No And i wont because I ragequit vsc

#

Never touching minecraft again

distant tulip
#

lol

ivory bough
full idol
#

Is it bad to have just a ton of imports for different modules and functions in the main file that loads when the world starts?

inland oracle
jolly citrus
#

Maybe it does slow things down but I doubt the difference is noticeable compared to what it'd be like if you just shoved everything into your main script

#

Been scripting since 2021 and I haven't noticed any lag from setting up large systems broken down into multiple scripts and folders

jolly citrus
#

I've asked for feedback & help with script and add-on optimization before and nobody's mentioned anything about refraining from using lots of scripts, only that you should simplify the logic & reduce the actual amount of operations that are done

full idol
#

Interesting! I see, I wasn't sure as it currently spikes for 250ms, which isn't really bad during world load I guess, but if that's not a major issue for realms, it should be fine. Thanks!

#

Oh, also, is it possible to get the world seed with the scripting API?

jolly citrus
#

Mine takes 157ms but it's unlikely any meaningful part of that comes from module loading

amber granite
#

How to make system where it detects player's temperature?

#
  • is there a way to detect how much time since an item has been crafted
inland oracle
# amber granite How to make system where it detects player's temperature?

there would be loads of different ways set as a dynamic property on the player, manipulate it through events i dont know of the top of my head checking biome and change the value depending on these conditions can add other conditions like take into account what the player is wearing and react to these conditions

amber granite
#

Nice

#

What bout the second one

full idol
#

Is there a really low stack size or something?

distant tulip
inland oracle
gilded shadow
#

can i change what an entity is holding like making a skeleton switch from bow to sword?

inland oracle
distant tulip
#

equipable component don't work on none player entities

gilded shadow