Minecraft – /tellraw using wrong player when using with command block in nether

minecraft-commandsminecraft-java-edition

[Java Edition 1.15.2]
I have a pressure plate that activates two command blocks in the nether:

  1. execute as @p in minecraft:overworld run tp @p 98 67 101 180 0 which teleports the player from the pressure plate in the nether to a specific location in the overworld facing north.
  2. tellraw @a {"text":"","color":"green","bold":true,"extra":[{"selector":"@p"},{"text":" has teleported to the overworld!"}]} which tells the chat who teleported and to where.

I have the same thing in the overworld going to the nether. This works perfectly fine when going from the overworld to the nether, however, when going from the nether to the overworld the tellraw command block targets my friend in the overworld with @p instead of me.
For example, say I am playerOne and my friend is playerTwo. When I am going from the overworld to the nether is says playerOne has teleported to the nether! which is what is supposed to happen. But, when teleporting from the nether to the overworld, I see playerTwo has teleported to the overworld! which is incorrect.
How can I get this to work so that it is always the nearest player no matter what the dimension? If it makes a difference, playerTwo is always in the overworld while this is happening.

Best Answer

I know this is a tedious solution, but there's a selector @s that is designed to target the executing player, not the nearest player. Because of this, we could bind the two commands using a function:

Create a datapack, for this example, I'll use mydatapack as the name. Inside the datapack create one function that runs your two commands, but slightly modified. Instead of using execute as, just write:

tp @s 98 67 101 180 0
tellraw @a {"text":"","color":"green","bold":true,"extra":[{"selector":"@s"},{"text":" has teleported to the overworld!"}]}

Next, do the same for the nether one. I'll call these functions tpInNether for the example above, and tpInOverworld for the pressure plate to be put in the overworld.

On your pressure plate command block, paste execute as @p in minecraft:overworld run function tpInNether, do the same for the overworld pressure plate