title: How to post a message in an existing DM as a Slack Bot
body: <p>My understanding of the <a href="https://api.slack.com/methods/chat.postMessage" rel="nofollow noreferrer">chat.postMessage</a> method of the Slack Web API is that you can, as a bot with a bot token, post messaged to public channels. However, if you want to post to DMs - you would need to request a user token and then post on behalf of the user</p>
  <p>However, I've used a few apps that are able to post into DMs as an app (and therefore, I assume, are using a bot token). To me this is ideal, so you're not bugging every person in the Slack workspace to get their user token</p>
  <p>Can anyone tell me how this is done?</p>
  <p>For reference, here is the code I use to post a message as a bot. It does not work for DMs or for private channels the bot has not been invited to. Would love to fix that. Thanks</p>
  <pre><code>function getQueryString(data = {}) {
          return Object.entries(data)
            .map(([key, value]) =&gt; `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
            .join('&amp;');
    }
  
  function postMessageInSlack(bot_token, channelID, userID, message, send_blocks, endpoint) {
          const options = {
              headers: {'Content-Type': 'application/x-www-form-urlencoded'}
          };
          const data = {
              token: bot_token,
              channel: channelID,
              text: `${message} from &lt;@${userID}&gt;`,
              blocks: JSON.stringify(send_blocks),
          }
          delete axios.defaults.headers.common[&quot;Content-Type&quot;];
          axios.post(endpoint,
              data, {
              options,
              transformRequest: getQueryString}
          )
          .then(res =&gt; console.log(&quot;result is &quot;, res))
          .catch(err =&gt; console.log(&quot;the error is &quot;, err))
  }
  </code></pre>