I like @Tobias's solution. I will add that I use third-party package counsel, which overrides M-x with its own
counsel-M-x function, so advising
execute-extended-command would not work for me.
Here's a barely-tested alternative that tests whether the keys reported by
this-command-keys are bound to a given command, where "a given command" is typically the caller itself (i.e.
some-example-command in the example below).
(defun called-via-key-binding (cmd)
"Returns non-nil if `this-command-keys' is bound to CMD."
(eq (key-binding (this-command-keys)) cmd))
(defun some-example-command ()
((not (called-interactively-p 'any))
(message "Not called interactively"))
(message "Called via key binding and not M-x"))
(message "Not called via key binding, so maybe called via M-x"))))
(The call to
called-interactively-p should arguably be moved into