It's generally not possible, or at least not advisable, to try to detect which input devices are attached. In particular the fact an input device is available does not mean the user necessarily wants to use it.
If you ask "does the user have a keyboard?" then does an on-screen keyboard count? What about a foldable tablet with one side of the display showing a keyboard? What if the tablet has a keyboard attachment but the user prefers to use touch input?
The best thing to do is wait and see which input the user actually uses, and respond according to that.