The error "This command must be called from a menu or a tool bar" comes from kill-this-buffer. The docstring of kill-this-buffer
kill-this-buffer is an interactive byte-code-function in ‘menu-bar.el’.
It can be invoked from the menu: File → Close.
(kill-this-buffer)
Kill the current buffer.
When called in the minibuffer, get out of the minibuffer
using ‘abort-recursive-edit’.
This command can be invoked only from a menu or a tool bar. If you want
to invoke a similar command with ‘M-x’, use ‘kill-current-buffer’.
suggests to use kill-current-buffer instead.