Search code examples
slackslack-apislack-commands

Slack bot can't send a message to a channel with - or space like "channel-name"


my slack bot can't send a message to a channel with space or - like "channel-name" but works well for a one word channel.

  $curl = curl_init();

  curl_setopt_array($curl, array(
    CURLOPT_URL => "https://slack.com/api/chat.postMessage",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS =>"{ \"channel\": \"channel-withspace\",\"text\": \"hello\"}",
    CURLOPT_HTTPHEADER => array(
      "Content-Type: application/json",
      "Authorization: Bearer <here>"
    ),
  ));

  $response = curl_exec($curl);

  curl_close($curl);
  echo $response;

Here is the error:

{"ok":false,"error":"not_in_channel","warning":"missing_charset","response_metadata":{"warnings":["missing_charset"]}}

Solution

  • Found the answer, turns out I need to invite the bot by typing a message in channel:

    /invite @bot-name
    

    Found the answer here: https://stackoverflow.com/a/61369364/5159914