Physical access to a USB port means you're pretty much screwed.
HID (ie, keyboard) emulation is only one thing that a USB device can do. It can also pretend to be an ethernet interface, or a modem, and offer "network access" to the PC. If the OS helpfully autoconfigures it, and decides to use it, then the device will be able to sniff the network traffic, spoof DNS queries, etc.
More details here.
Now, if you're only interested in stopping this and not the other attacks, you can stop it with software that will detect an excessive typing speed. That won't stop a slow rubber ducky of course. You could check the USB VID/PID of the keyboard, but a USB device can easily spoof these.
Really, USB is physical access, it's insecure.