From what I could make out from the documentation; Discord wants the bot to get logged into the Discord Server and show its presence there first. Only then will Discord allow the Bot to send messages using its API, into the same server.
The documentation is not very clear -- It looks to me that a Bot cannot conventionally login into a Server. This is because a Bot does not have an email address. It is only given a special token.
I guess one of the built in libraries that Discord provides should be able to do this. Whatever I could make out, your bot needs to find out the Websocket gateway it has to connect to first.
This API call works and it does provide you the gateway end point https://discord.com/api/v6/gateway
But I am not good at websocket connection (wss:// protocol) so I skipped that step and moreover, I was impatient.
Luckily I got one route to solve the problem. That was to download the Electron based Windows executable called "LiveBot" from here: https://github.com/SebOuellette/LiveBot
Warning: Thats a very large ZIP file there as Electron based executables usually are. Just start LiveBot on a Windows machine; and provide your Bot token there.
That will make the Bot behave like a regular user on your server. Once Discord comes to know that your Bot was able to connect to the server it is attached to; then after that point it will allow messages to be sent.
My experience states that if your Bot has NOT been able to connect to your server at least once, you will always get a 40001 error code. Just the way you described.
This is not a programmatic approach but it worked for me. Since only one connection was needed, that is all I did. After that I was able to use the REST API using plain old Curl to send out direct messages; instead of one of the Discord libraries.
Hope this works for you too.