Nov 21, 2015
0
Level 7
[Tip] Fluent Slack Message Builder
Hey,
Just a little class for people who need to send Slack messages from their code:
class SlackMessageBuilder
{
/**
* The message.
*
* @var string
*/
private $message = "";
/**
* The room to post to.
*
* @var string
*/
private $room = "";
/**
* The username to post as.
*
* @var string
*/
private $username = "iDiscuss Bot";
/**
* The emoji to use for the bot.
*
* @var string
*/
private $emoji = ":bell:";
/**
* The endpoint to send requests to.
*
* @var string
*/
private $endpoint = "";
/**
* Set the message.
*
* @param string $message
* @return SlackMessageBuilder
*/
public function setMessage($message)
{
$this->message = $message;
return $this;
}
/**
* Set the room to post to.
*
* @param string $room
* @return SlackMessageBuilder
*/
public function setRoom($room)
{
$this->room = $room;
return $this;
}
/**
* Set the username to post as.
*
* @param string $username
* @return SlackMessageBuilder
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Set the emoji to use for the bot.
*
* @param string $emoji
* @return SlackMessageBuilder
*/
public function setEmoji($emoji)
{
$this->emoji = $emoji;
return $this;
}
/**
* Set the endpoint to send requests to.
*
* @param string $endpoint
* @return SlackMessageBuilder
*/
public function setEndpoint($endpoint)
{
$this->endpoint = $endpoint;
return $this;
}
/**
* Send the message.
*/
public function send()
{
$data = "payload=" . json_encode([
"channel" => "#{$this->room}",
"text" => $this->message,
"icon_emoji" => $this->emoji,
"username" => $this->username
]);
// You can get your webhook endpoint from your Slack settings
$ch = curl_init($this->endpoint);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
}
How it can be used:
$message = new SlackMessageBuilder;
$message->setEmoji(":bell:")
->setEndpoint("WEBHOOK URL")
->setMessage("MESSAGE")
->setRoom("ROOM")
->setUsername("USERNAME")
->send();
You need to add a new Incoming Webhook on your Slack team for this to work. It does work on development environments!
Please or to participate in this conversation.