Can scripts listen for mqtt messages?

i hope that listen for mqtt messages from some devices (e.g switch) and run scripts.

because i need to know that Determine if the device is online.

Such as:

device (switch) sends message to the mqtt every minute. Otherwise, prove that the device is offline.

how do i should?

thanks guys