Is there any way that I can track a villager trade and execute a command when an item is traded

I'm working on a minecraft map and basically what I want is to execute a command when a player trades an item with the villager. (This is a custom villager with custom items not a random villager). I haven't tried anything yet, but what I was thinking of is a scoreboard that counts how many times the trade got used. If someone could help me that would be great!

1 Answer

If you're OK with using command blocks, a quick search online revealed this thread, citing this wiki page; apparently solving your very issue.

Emphasis added:

i want to detect when i do a trade with a villager. there is maybe a way to do it if i use data when i do a trade there is an nbt that change called uses but and i try to write the command it doesn't work any idea's?

Oh, yea, easy peasy… There's an advancement trigger that's made for just this!

{ "criteria": { "requirement": { "trigger": "minecraft:villager_trade", "conditions": { "item": { "item": "minecraft:diamond" } } } }
}

If you're just looking to detect just one villager and run some commands as that villager, (for some custom map NPC or something) it would be very easy to just have:

data modify storage temp NPC_1.uses set value []
data modify storage temp NPC_1.uses append from entity <NPC #1> Offers.Recipes[0].uses
data modify storage temp NPC_1.uses append from entity <NPC #1> Offers.Recipes[1].uses
data modify storage temp NPC_1.uses append from entity <NPC #1> Offers.Recipes[2].uses
... and so on...
execute store success score .changed int run data modify storage map NPC_1.uses set from storage temp NPC_1.uses
execute if score .changed matches 1 run tellraw @a {"text":"NPC #1 was traded with."}
execute if score .changed matches 1 as <NPC #1> run say "It's true, a player traded with me."
1

You Might Also Like