Skip to content

Instantly share code, notes, and snippets.

@tamakiii
Last active August 29, 2015 14:13
Show Gist options
  • Save tamakiii/52740774a76d3433fb32 to your computer and use it in GitHub Desktop.
Save tamakiii/52740774a76d3433fb32 to your computer and use it in GitHub Desktop.
<?php
namespace Acme\Component\Slack\Message;
use Acme\Component\Slack\Message\MessageInterface;
use Acme\Component\Slack\Message\SenderInterface;
use Guzzle\Http\ClientInterface;
use Guzzle\Http\Message\Response;
/**
* Slack message sender.
*/
class Sender implements SenderInterface
{
/**
* @var string
*/
private $url;
/**
* @var ClientInterface
*/
private $client;
/**
* @param string $url
* @param ClientInterface $client
*/
public function __construct($url, ClientInterface $client)
{
$this->url = $url;
$this->client = $client;
}
/**
* @param string $channel
* @param MessageInterface $message
* @return Response
*/
public function send($channel, MessageInterface $message)
{
$request = $this->client->post($this->url, array(), http_build_query(array(
'payload' => json_encode(array(
'channel' => $channel,
'text' => $message->getText(),
'username' => $message->getUserName(),
'icon_emoji' => $message->getIconEmoji(),
'link_names' => $message->getLinkNames(),
))
)));
$request->setHeader('Content-Type', 'application/x-www-form-urlencoded');
$response = $request->send();
if (!$response->isSuccessful()) {
throw new \UnexpectedValueException('Request unsuccessful(status).');
}
return $response;
}
}
@tamakiii
Copy link
Author

3系のGuzzleを使ってSlackにメッセージ送るときのサンプル。

エンコードされたBodyをPOSTで送るのに

$request->setHeader('Content-Type', 'application/x-www-form-urlencoded');

が必要

@tamakiii
Copy link
Author

Sample class how to send payload to slack with Guzzle version 3.x.

Need this line to post encoded body.

$request->setHeader('Content-Type', 'application/x-www-form-urlencoded');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment