The right answer: enable the online/offline detection in zigbee2mqtt. I forget the name of the setting though (edit: it's called availability). This might increase power consumption on some battery devices. You can then check if devices are available in your scripts and ignore their state if not.
It has a delay until offline state is detected, the delay can be tweaked as far as I know, but is a tradeoff with battery powered devices consumption.