Perform an action when bluetooth keyboard is connected or disconnected
The app Tooth Fairy ($5.99) should be able to do this. Although it's designed for AirPods, it works just as well with keyboards and other Bluetooth devices. After adding a device, you can set scripts to run upon connect and disconnect, so you can call your own scripts to perform whatever action you'd like to take.