Compare commits

..

No commits in common. "master" and "1.1.1" have entirely different histories.

70 changed files with 836 additions and 1140 deletions

View File

@ -4,7 +4,6 @@ namespace Slack;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Slack\Blockkit\Modal;
@ -20,7 +19,7 @@ use Slack\Exceptions\{SlackAlreadyPinnedException,
SlackNotInChannelException,
SlackThreadNotFoundException,
SlackTokenScopeException};
use Slack\Models\{Team,Token,User};
use Slack\Models\{Team,User};
use Slack\Response\ChannelList;
use Slack\Response\Generic;
use Slack\Response\User as ResponseUser;
@ -34,7 +33,6 @@ final class API
private const scopes = [
'auth.test'=>'', // No scope required
'chat.delete'=>'chat:write',
'chat.postEphemeral'=>'chat:write',
'chat.postMessage'=>'chat:write',
'chat.update'=>'chat:write',
'conversations.history'=>'channels:history', // Also need groups:history for Private Channels and im:history for messages to the bot.
@ -56,7 +54,7 @@ final class API
];
// Our slack token to use
private Token $_token;
private $_token;
public function __construct(Team $o)
{
@ -75,61 +73,46 @@ final class API
/**
* Delete a message in a channel
*
* @param string $channel
* @param string $timestamp
* @param $channel
* @param $timestamp
* @return Generic
* @throws SlackException
* @throws \Exception
*/
public function deleteChat(string $channel,string $timestamp): Generic
public function deleteChat($channel,$timestamp): Generic
{
Log::debug(sprintf('%s:Delete Message [%s] in [%s]',static::LOGKEY,$timestamp,$channel),['m'=>__METHOD__]);
return new Generic($this->execute('chat.delete',['channel'=>$channel,'ts'=>$timestamp]));
}
/**
* Open a dialogue with the user
*
* @param string $trigger
* @param string $dialog
* @return Generic
* @throws SlackException
*/
public function dialogOpen(string $trigger,string $dialog): Generic
{
Log::debug(sprintf('%s:Open a Dialog',static::LOGKEY),['m'=>__METHOD__,'d'=>$dialog,'t'=>$trigger]);
return new Generic($this->execute('dialog.open',['dialog'=>$dialog,'trigger_id'=>$trigger]));
}
/**
* Get Messages on a channel from a specific timestamp
*
* @param string $channel
* @param string $timestamp
* @param $channel
* @param $timestamp
* @param int $limit
* @return Generic
* @throws SlackException
* @throws \Exception
*/
public function getChannelHistory(string $channel,string $timestamp,int $limit=20): Generic
public function getChannelHistory($channel,$timestamp,$limit=20): Generic
{
Log::debug(sprintf('%s:Message History for Channel [%s] from Timestamp [%s]',static::LOGKEY,$channel,$timestamp),['m'=>__METHOD__]);
return new Generic($this->execute('conversations.history',['channel'=>$channel,'oldest'=>$timestamp,'limit'=>$limit],TRUE));
return new Generic($this->execute('conversations.history',['channel'=>$channel,'oldest'=>$timestamp,'limit'=>$limit]));
}
/**
* Get information on a channel.
*
* @param string $channel
* @param $channel
* @return Generic
* @throws SlackException
* @throws \Exception
*/
public function getChannelInfo(string $channel): Generic
public function getChannelInfo($channel): Generic
{
Log::debug(sprintf('%s:Channel Information [%s]',static::LOGKEY,$channel),['m'=>__METHOD__]);
return new Generic($this->execute('conversations.info',['channel'=>$channel],TRUE));
return new Generic($this->execute('conversations.info',['channel'=>$channel]));
}
/**
@ -137,13 +120,13 @@ final class API
*
* @param int $limit
* @return Generic
* @throws SlackException
* @throws \Exception
*/
public function getChannelList(int $limit=100): Generic
{
Log::debug(sprintf('%s:Channel List',static::LOGKEY),['m'=>__METHOD__]);
return new Generic($this->execute('conversations.list',['limit'=>$limit],TRUE));
return new Generic($this->execute('conversations.list',['limit'=>$limit]));
}
/**
@ -152,13 +135,13 @@ final class API
* @param string $channel
* @param string $thread_ts
* @return Chat
* @throws SlackException
* @throws \Exception
*/
public function getMessageHistory(string $channel,string $thread_ts): Chat
{
Log::debug(sprintf('%s:Get Message Threads for Message [%s] on Channel [%s]',static::LOGKEY,$thread_ts,$channel),['m'=>__METHOD__]);
return new Chat($this->execute('conversations.replies',['channel'=>$channel,'ts'=>$thread_ts],TRUE));
return new Chat($this->execute('conversations.replies',['channel'=>$channel,'ts'=>$thread_ts]));
}
/**
@ -166,37 +149,152 @@ final class API
*
* @param string $team_id
* @return ResponseTeam
* @throws SlackException
* @throws \Exception
*/
public function getTeam(string $team_id): ResponseTeam
{
Log::debug(sprintf('%s:Team Info [%s]',static::LOGKEY,$team_id),['m'=>__METHOD__]);
return new ResponseTeam($this->execute('team.info',['team'=>$team_id],TRUE));
return new ResponseTeam($this->execute('team.info',['team'=>$team_id]));
}
/**
* Get information on a user
*
* @param string $user_id
* @param $user_id
* @return ResponseUser
* @throws SlackException
* @throws \Exception
*/
public function getUser(string $user_id): ResponseUser
public function getUser($user_id): ResponseUser
{
Log::debug(sprintf('%s:User Info [%s]',static::LOGKEY,$user_id),['m'=>__METHOD__]);
return new ResponseUser($this->execute('users.info',['user'=>$user_id],TRUE));
return new ResponseUser($this->execute('users.info',['user'=>$user_id]));
}
/**
* Open a dialogue with the user
*
* @param string $trigger
* @param string $dialog
* @return Generic
* @throws \Exception
*/
public function dialogOpen(string $trigger,string $dialog): Generic
{
Log::debug(sprintf('%s:Open a Dialog',static::LOGKEY),['m'=>__METHOD__,'d'=>$dialog,'t'=>$trigger]);
return new Generic($this->execute('dialog.open',json_encode(['dialog'=>$dialog,'trigger_id'=>$trigger])));
}
/**
* Migrate users to Enterprise IDs
*
* @param array $users
* @return Generic
* @throws \Exception
*/
public function migrationExchange(array $users): Generic
{
Log::debug(sprintf('%s:Migrate Exchange [%s] users',static::LOGKEY,count($users)),['m'=>__METHOD__]);
return new Generic($this->execute('migration.exchange',['users'=>join(',',$users)]));
}
/**
* Pin a message in a channel
*
* @param $channel
* @param $timestamp
* @return Generic
* @throws \Exception
*/
public function pinMessage(string $channel,string $timestamp): Generic
{
Log::debug(sprintf('%s:Pin Message [%s|%s]',static::LOGKEY,$channel,$timestamp),['m'=>__METHOD__]);
return new Generic($this->execute('pins.add',json_encode(['channel'=>$channel,'timestamp'=>$timestamp])));
}
/**
* Post a Slack Message
*
* @param Message $request
* @return Generic
* @throws \Exception
*/
public function postMessage(Message $request): Generic
{
Log::debug(sprintf('%s:Post a Slack Message',static::LOGKEY),['m'=>__METHOD__,'r'=>$request]);
return new Generic($this->execute('chat.postMessage',json_encode($request)));
}
/**
* Schedule a slack message
*
* @param Message $request
* @return Generic
* @throws \Exception
*/
public function scheduleMessage(Message $request): Generic
{
Log::debug(sprintf('%s:Scheduling a Slack Message',static::LOGKEY),['m'=>__METHOD__,'r'=>$request]);
return new Generic($this->execute('chat.scheduleMessage',json_encode($request)));
}
/**
* Get the scheduled messages
*
* @param Message $request
* @return Generic
* @throws \Exception
*/
public function scheduleMessagesList(string $request=NULL): Generic
{
Log::debug(sprintf('%s:Get the Scheduled Messages in Slack',static::LOGKEY),['m'=>__METHOD__,'r'=>$request]);
return new Generic($this->execute('chat.scheduledMessages.list',$request ? ['channel'=>$request] : []));
}
/**
* Remove a Pin from a message
*
* @param $channel
* @param $timestamp
* @return Generic
* @throws \Exception
*/
public function unpinMessage($channel,$timestamp): Generic
{
Log::debug(sprintf('%s:Remove Pin from Message [%s|%s]',static::LOGKEY,$channel,$timestamp),['m'=>__METHOD__]);
return new Generic($this->execute('pins.remove',json_encode(['channel'=>$channel,'timestamp'=>$timestamp])));
}
/**
* Update a Slack Message
*
* @param Message $request
* @return Generic
* @throws \Exception
*/
public function updateMessage(Message $request): Generic
{
Log::debug(sprintf('%s:Update a Slack Message',static::LOGKEY),['m'=>__METHOD__,'r'=>$request]);
return new Generic($this->execute('chat.update',json_encode($request)));
}
/**
* Get the list of channels for a user (the bot normally)
*
* @param User $uo
* @param int $limit
* @param User $uo
* @param int $limit
* @param string|null $cursor
* @return ChannelList
* @throws SlackException
* @throws \Exception
*/
public function getUserChannels(User $uo,int $limit=100,string $cursor=NULL): ChannelList
{
@ -212,205 +310,105 @@ final class API
if ($cursor)
$args->put('cursor',$cursor);
return new ChannelList($this->execute('users.conversations',$args->toArray(),TRUE));
}
/**
* Migrate users to Enterprise IDs
*
* @param array $users
* @return Generic
* @throws SlackException
*/
public function migrationExchange(array $users): Generic
{
Log::debug(sprintf('%s:Migrate Exchange [%s] users',static::LOGKEY,count($users)),['m'=>__METHOD__]);
return new Generic($this->execute('migration.exchange',['users'=>join(',',$users)],TRUE));
}
/**
* Pin a message in a channel
*
* @param string $channel
* @param string $timestamp
* @return Generic
* @throws SlackException
*/
public function pinMessage(string $channel,string $timestamp): Generic
{
Log::debug(sprintf('%s:Pin Message [%s|%s]',static::LOGKEY,$channel,$timestamp),['m'=>__METHOD__]);
return new Generic($this->execute('pins.add',['channel'=>$channel,'timestamp'=>$timestamp]));
}
/**
* Post a Slack Message to a user as an ephemeral message
*
* @param Message $request
* @return Generic
* @throws SlackException
*/
public function postEphemeral(Message $request): Generic
{
Log::debug(sprintf('%s:Post a Slack Ephemeral Message',static::LOGKEY),['m'=>__METHOD__,'r'=>$request]);
return new Generic($this->execute('chat.postEphemeral',$request));
}
/**
* Post a Slack Message
*
* @param Message $request
* @return Generic
* @throws SlackException
*/
public function postMessage(Message $request): Generic
{
Log::debug(sprintf('%s:Post a Slack Message',static::LOGKEY),['m'=>__METHOD__,'r'=>$request]);
return new Generic($this->execute('chat.postMessage',$request));
}
/**
* Schedule a slack message
*
* @param Message $request
* @return Generic
* @throws SlackException
*/
public function scheduleMessage(Message $request): Generic
{
Log::debug(sprintf('%s:Scheduling a Slack Message',static::LOGKEY),['m'=>__METHOD__,'r'=>$request]);
return new Generic($this->execute('chat.scheduleMessage',$request));
}
/**
* Get the scheduled messages
*
* @param string|null $request
* @return Generic
* @throws SlackException
*/
public function scheduleMessagesList(string $request=NULL): Generic
{
Log::debug(sprintf('%s:Get the Scheduled Messages in Slack',static::LOGKEY),['m'=>__METHOD__,'r'=>$request]);
return new Generic($this->execute('chat.scheduledMessages.list',$request ? ['channel'=>$request] : []));
}
/**
* Remove a Pin from a message
*
* @param string $channel
* @param string $timestamp
* @return Generic
* @throws SlackException
*/
public function unpinMessage(string $channel,string $timestamp): Generic
{
Log::debug(sprintf('%s:Remove Pin from Message [%s|%s]',static::LOGKEY,$channel,$timestamp),['m'=>__METHOD__]);
return new Generic($this->execute('pins.remove',['channel'=>$channel,'timestamp'=>$timestamp]));
}
/**
* Update a Slack Message
*
* @param Message $request
* @return Generic
* @throws SlackException
*/
public function updateMessage(Message $request): Generic
{
Log::debug(sprintf('%s:Update a Slack Message',static::LOGKEY),['m'=>__METHOD__,'r'=>$request]);
return new Generic($this->execute('chat.update',$request));
return new ChannelList($this->execute('users.conversations',$args->toArray()));
}
public function viewOpen(string $trigger,Modal $view): Generic
{
Log::debug(sprintf('%s:Open a view',static::LOGKEY),['m'=>__METHOD__,'t'=>$trigger]);
return new Generic($this->execute('views.open',['trigger_id'=>$trigger,'view'=>$view]));
return new Generic($this->execute('views.open',json_encode(['trigger_id'=>$trigger,'view'=>$view])));
}
/**
* Publish a view
*
* @param string $user
* @param Modal $view
* @param string $view
* @param string $hash
* @return Generic
* @throws SlackException
* @throws \Exception
* @todo Add some smarts to detect if the new view is the same as the current view, and thus no need to post.
*/
public function viewPublish(string $user,Modal $view,string $hash=''): Generic
{
Log::debug(sprintf('%s:Publish a view',static::LOGKEY),['m'=>__METHOD__,'u'=>$user,'h'=>$hash]);
return new Generic($this->execute('views.publish',$hash ? ['user_id'=>$user,'view'=>$view,'hash'=>$hash] : ['user_id'=>$user,'view'=>$view]));
return new Generic($this->execute('views.publish',json_encode($hash ? ['user_id'=>$user,'view'=>$view,'hash'=>$hash] : ['user_id'=>$user,'view'=>$view])));
}
public function viewPush(string $trigger,Modal $view): Generic
{
Log::debug(sprintf('%s:Push a view',static::LOGKEY),['m'=>__METHOD__,'t'=>$trigger]);
return new Generic($this->execute('views.push',['trigger_id'=>$trigger,'view'=>$view]));
return new Generic($this->execute('views.push',json_encode(['trigger_id'=>$trigger,'view'=>$view])));
}
public function viewUpdate(string $view_id,Modal $view): Generic
{
Log::debug(sprintf('%s:Update a view',static::LOGKEY),['m'=>__METHOD__,'id'=>$view_id]);
return new Generic($this->execute('views.update',['view_id'=>$view_id,'view'=>$view]));
return new Generic($this->execute('views.update',json_encode(['view_id'=>$view_id,'view'=>$view])));
}
/**
* Call the Slack API
*
* @param string $method
* @param mixed $parameters
* @param bool $asForm
* @param null $parameters
* @return object
* @throws \Exception
* @throws SlackException
*/
private function execute(string $method,mixed $parameters,bool $asForm=FALSE): object
private function execute(string $method,$parameters = NULL): object
{
switch (config('app.env')) {
case 'steno': $url = 'http://steno:3000';
case 'dev': $url = 'http://steno:3000';
break;
case 'replay': $url = 'http://steno_replay:3000';
case 'testing': $url = 'http://localhost:3000';
break;
case 'testing-l': $url = 'http://steno_replay:3000';
break;
default:
$url = 'https://slack.com';
}
$url .= '/api/'.$method;
// If we dont have a scope definition, or if the scope definition is not in the token
if (is_null($x=Arr::get(self::scopes,$method)) OR (($x !== '') AND ! $this->_token->hasScope($x))) {
throw new SlackTokenScopeException(sprintf('Token [%d:%s] doesnt have the required scope: [%s] for [%s]',$this->_token->id,$this->_token->token_hidden,serialize($x),$method));
}
$http = Http::baseUrl($url);
$http
->withToken($this->_token->token)
->acceptJson();
// If we are passed an array, we'll do a normal post.
if (is_array($parameters)) {
$parameters['token'] = $this->_token->token;
$request = $this->prepareRequest(
$url,
$parameters
);
if ($asForm) {
if (! is_array($parameters))
throw new SlackException('Parameters are not an array for a form submission');
// If we are json, then we'll do an application/json post
} elseif (is_json($parameters)) {
$request = $this->prepareRequest(
$url,
$parameters,
[
'Content-Type: application/json; charset=utf-8',
'Content-Length: '.strlen($parameters),
'Authorization: Bearer '.$this->_token->token,
]
);
$http->asForm();
} elseif ($parameters) {
$http->withBody((is_array($parameters) || ($parameters instanceof BlockKit)) ? json_encode($parameters) : $parameters,'application/json');
} else {
throw new \Exception('Parameters unknown');
}
try {
$request = $http->post(sprintf('/api/%s',$method),$asForm ? $parameters : NULL)->throw();
$response = $request->object();
$response = curl_exec($request);
if (! $response)
throw new \Exception('CURL exec returned an empty response: '.serialize(curl_getinfo($request)));
$result = json_decode($response);
} catch (\Exception $e) {
Log::error(sprintf('%s:Got an error while posting to [%s] (%s)',static::LOGKEY,$url,$e->getMessage()),['m'=>__METHOD__]);
@ -418,49 +416,73 @@ final class API
throw new \Exception($e->getMessage());
}
if ($response->ok)
return $response;
else
switch ($response->error) {
if (! $result) {
Log::error(sprintf('%s:Our result shouldnt be empty',static::LOGKEY),['m'=>__METHOD__,'r'=>$request,'R'=>$response]);
throw new SlackException('Slack Result is Empty');
}
if (! $result->ok) {
switch ($result->error) {
case 'already_pinned':
throw new SlackAlreadyPinnedException('Already Pinned',$request->status());
case 'channel_not_found':
throw new SlackChannelNotFoundException('Channel Not Found',$request->status());
case 'hash_conflict':
if (App::environment() == 'local')
file_put_contents('/tmp/hash_conflict.'.$method,print_r($response,TRUE));
throw new SlackHashConflictException('Hash Conflict',$request->status());
case 'invalid_auth':
throw new SlackNoAuthException('Invalid Auth Token',$request->status());
case 'message_not_found':
throw new SlackMessageNotFoundException('Message Not Found',$request->status());
case 'no_pin':
throw new SlackNoPinException('No Pin',$request->status());
throw new SlackAlreadyPinnedException('Already Pinned',curl_getinfo($request,CURLINFO_HTTP_CODE));
case 'not_authed':
throw new SlackNoAuthException('No Auth Token',$request->status());
throw new SlackNoAuthException('No Auth Token',curl_getinfo($request,CURLINFO_HTTP_CODE));
case 'not_found':
file_put_contents('/tmp/method.'.$method,print_r(['request'=>is_json($parameters) ? json_decode($parameters,TRUE) : $parameters,'response'=>$response],TRUE));
throw new SlackNotFoundException('Not Found',$request->status());
case 'channel_not_found':
throw new SlackChannelNotFoundException('Channel Not Found',curl_getinfo($request,CURLINFO_HTTP_CODE));
case 'hash_conflict':
if (App::environment() == 'dev')
file_put_contents('/tmp/hash_conflict.'.$method,print_r(json_decode(json_decode($parameters)->view),TRUE));
throw new SlackHashConflictException('Hash Conflict',curl_getinfo($request,CURLINFO_HTTP_CODE));
case 'message_not_found':
throw new SlackMessageNotFoundException('Message Not Found',curl_getinfo($request,CURLINFO_HTTP_CODE));
case 'no_pin':
throw new SlackNoPinException('No Pin',curl_getinfo($request,CURLINFO_HTTP_CODE));
case 'not_in_channel':
throw new SlackNotInChannelException('Not In Channel',$request->status());
throw new SlackNotInChannelException('Not In Channel',curl_getinfo($request,CURLINFO_HTTP_CODE));
case 'not_found':
file_put_contents('/tmp/method.'.$method,print_r(['request'=>is_json($parameters) ? json_decode($parameters,TRUE) : $parameters,'response'=>$result],TRUE));
throw new SlackNotFoundException('Not Found',curl_getinfo($request,CURLINFO_HTTP_CODE));
case 'thread_not_found':
throw new SlackThreadNotFoundException('Thread Not Found',$request->status());
throw new SlackThreadNotFoundException('Thread Not Found',curl_getinfo($request,CURLINFO_HTTP_CODE));
case 'account_inactive':
// @todo Mark the token/team as inactive
default:
Log::error(sprintf('%s:Generic Error',static::LOGKEY),['m'=>__METHOD__,'t'=>$this->_token->team_id,'r'=>$response]);
throw new SlackException($response->error,$request->status());
Log::error(sprintf('%s:Generic Error',static::LOGKEY),['m'=>__METHOD__,'t'=>$this->_token->team_id,'r'=>$result]);
throw new SlackException($result->error,curl_getinfo($request,CURLINFO_HTTP_CODE));
}
}
curl_close($request);
return $result;
}
/**
* Setup the API call
*
* @param $url
* @param string $parameters
* @param array $headers
* @return resource
*/
private function prepareRequest($url,$parameters='',$headers = [])
{
$request = curl_init();
curl_setopt($request,CURLOPT_URL,$url);
curl_setopt($request,CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($request,CURLOPT_HTTPHEADER,$headers);
curl_setopt($request,CURLINFO_HEADER_OUT,TRUE);
curl_setopt($request,CURLOPT_SSL_VERIFYPEER,FALSE);
curl_setopt($request,CURLOPT_POSTFIELDS,$parameters);
return $request;
}
}

View File

@ -44,7 +44,6 @@ abstract class Base
*
* @param bool $create
* @return Channel|null
* @todo Enable simulating an existing channel, using FALSE (dont create), 0 (create dont save), 1 (create and save)
*/
final public function channel(bool $create=FALSE): ?Channel
{
@ -64,44 +63,6 @@ abstract class Base
return $o->exists ? $o : NULL;
}
/**
* Separate out a callback command to the id that the command relates to
*
* @param string $key
* @param string|null $item
* @return string|null
* @throws \Exception
*/
final protected function keyitem(string $key,string $item=NULL): ?string
{
if (! $item)
return $item;
$regex = '/^([a-z_]+)\|([0-9]+)$/';
$id = NULL;
$value = NULL;
if (preg_match($regex,$item)) {
$id = preg_replace($regex,'$1',$item);
$value = preg_replace($regex,'$2',$item);
}
switch ($key) {
case 'id':
return $id ?: $item;
case 'value':
return $value;
default:
throw new \Exception('Unknown key: '.$key);
}
}
/**
* Return the Eneterprise object that a Response is related to
*
* @return Enterprise
*/
final public function enterprise(): Enterprise
{
$class = class_exists(AppEnterprise::class) ? AppEnterprise::class : Enterprise::class;
@ -152,7 +113,7 @@ abstract class Base
if (! $o->exists) {
$o->team_id = $this->enterprise_id ? NULL : $this->team()->id;
$o->enterprise_id = ($x=$this->enterprise())->exists ? $x->id : NULL;
$o->active = FALSE;
$o->active = TRUE;
$o->save();
Log::debug(sprintf('%s: User Created in DB [%s] (%s)',self::LOGKEY,$this->user_id,$o->id));

View File

@ -5,24 +5,12 @@ namespace Slack;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Slack\Exceptions\SlackSyntaxException;
/**
* Class BlockKit - Slack Blockit Objects
*
* @notes
* + callback_id is used to identify the source of any action (modal). (Message blocks do not have a callback_id, accept in legacy attachments).
* eg: hometab, add_product, ask_modal
* + block_id is used to identify the sub action(s) of any action (modal). (Messages with blocks can have a block_id, we need to use this to determine what to do.)
* eg: multiple blocks (list of something)
* + action_id is used to identify the action that was initiated
* eg: view, edit, review
* + value is the value of the action_id
* eg: 5 (question #), yes, no, skip, abort
*
* @package Slack
*/
abstract class BlockKit implements \JsonSerializable,\Countable
abstract class BlockKit implements \JsonSerializable
{
protected Collection $_data;
@ -52,7 +40,7 @@ abstract class BlockKit implements \JsonSerializable,\Countable
protected function validate(string $key,$value)
{
if (Arr::get(static::LIMITS,$key) && (strlen($value) > static::LIMITS[$key]))
throw new SlackSyntaxException(sprintf('%s must be %d chars or less for buttons %s',$key,static::LIMITS[$key],get_class($this)));
throw new Exception(sprintf('%s must be %d chars or less for buttons %s',$key,self::LIMITS[$key],get_class($this)));
return $value;
}

View File

@ -2,26 +2,26 @@
namespace Slack\Blockkit\Blocks\Accessories;
use \Exception;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Slack\Blockkit\Blocks\Elements\{Confirm,Text};
use Slack\Blockkit\Element;
use Slack\Exceptions\SlackSyntaxException;
final class Overflow extends Element
{
public const LIMITS = [
protected const LIMITS = [
'action_id' => 255,
];
public const MIN_OPTIONS = 1;
public const MAX_OPTIONS = 5;
private const MIN_OPTIONS = 1;
private const MAX_OPTIONS = 5;
/**
* @param string $action_id
* @param Collection $options
* @throws SlackSyntaxException
* @throws Exception
* @todo We dont handle option_groups yet.
*/
public function __construct(string $action_id,Collection $options)
@ -34,10 +34,10 @@ final class Overflow extends Element
$this->action_id = $this->validate('action_id',$action_id);
if (count($options) < self::MIN_OPTIONS)
throw new SlackSyntaxException(sprintf('Must have atleast %d options',self::MIN_OPTIONS));
throw new Exception(sprintf('Must have atleast %d options',self::MIN_OPTIONS));
if (count($options) > self::MAX_OPTIONS)
throw new SlackSyntaxException(sprintf('Can only have maximum %d options',self::MAX_OPTIONS));
throw new Exception(sprintf('Can only have maximum %d options',self::MAX_OPTIONS));
$this->options = $options->transform(function($item) {
return ['text'=>Text::item(Arr::get($item,'name'),'plain_text'),'value'=>(string)Arr::get($item,'id')];

View File

@ -2,21 +2,21 @@
namespace Slack\Blockkit\Blocks;
use \Exception;
use Illuminate\Support\Collection;
use Slack\Blockkit\Blocks;
use Slack\Blockkit\Blocks\Elements\{Button,MultiStaticSelect};
use Slack\Exceptions\SlackSyntaxException;
final class Actions extends Blocks
{
public const LIMITS = [
protected const LIMITS = [
'block_id' => 255, // @todo Should be unique for each message
];
public const MAX_ELEMENTS = 5;
private const MAX_ELEMENTS = 5;
public const VALID_ELEMENTS = [
private const VALID_ELEMENTS = [
Button::class,
MultiStaticSelect::class,
Blocks\Accessories\Overflow::class,
@ -38,7 +38,7 @@ final class Actions extends Blocks
public function jsonSerialize()
{
if (! $this->elements)
throw new SlackSyntaxException('Must define at least 1 element');
throw new Exception('Must define at least 1 element');
return parent::jsonSerialize();
}
@ -55,7 +55,7 @@ final class Actions extends Blocks
public function elements(Collection $collection): self
{
if (count($collection) > self::MAX_ELEMENTS)
throw new SlackSyntaxException(sprintf('Can only have maximum %d elements',self::MAX_ELEMENTS));
throw new Exception(sprintf('Can only have maximum %d elements',self::MAX_ELEMENTS));
// @todo Check that a valid element is added. https://api.slack.com/reference/block-kit/blocks#actions

View File

@ -2,22 +2,22 @@
namespace Slack\Blockkit\Blocks;
use \Exception;
use Illuminate\Support\Collection;
use Slack\Blockkit\Blocks;
use Slack\Exceptions\SlackSyntaxException;
final class Context extends Blocks
{
public const LIMITS = [
protected const LIMITS = [
'block_id' => 255, // @todo Should be unique for each message
];
public const MAX_ELEMENTS = 10;
private const MAX_ELEMENTS = 10;
/**
* @param Collection $collection
* @throws SlackSyntaxException
* @throws Exception
* @todo Collection can only be image or text elements
*/
public function __construct(Collection $collection)
@ -28,7 +28,7 @@ final class Context extends Blocks
$this->type = 'context';
if (count($collection) > self::MAX_ELEMENTS)
throw new SlackSyntaxException(sprintf('Can only have maximum %d elements',self::MAX_ELEMENTS));
throw new Exception(sprintf('Can only have maximum %d elements',self::MAX_ELEMENTS));
$this->elements = $collection;
}

View File

@ -2,8 +2,9 @@
namespace Slack\Blockkit\Blocks\Elements;
use \Exception;
use Slack\Blockkit\Element;
use Slack\Exceptions\SlackSyntaxException;
final class Button extends Element
{
@ -15,25 +16,39 @@ final class Button extends Element
'value' => 2000,
];
public function __construct(string $text,string $value,string $action_id)
public function __construct(Text $text,string $value,string $action_id)
{
parent::__construct();
// Defaults
$this->type = 'button';
$this->text = Text::item($this->validate('text',$text),'plain_text');
if ($text->type != 'plain_text')
throw new Exception(sprintf('Text must be plain_text not %s',$text->type));
if (strlen($text->text) > self::LIMITS['text'])
throw new Exception(sprintf('Text must be %d chars or less',self::LIMITS['text']));
$this->text = $text;
$this->value = $this->validate('value',$value);
$this->action_id = $this->validate('action_id',$action_id);
}
public static function item(string $text,string $value,string $action_id): self
public static function item(Text $text,string $value,string $action_id): self
{
return new self($text,$value,$action_id);
}
/* OPTIONAL ITEMS */
public function callback_id(string $string): self
{
$this->callback_id = $string;
return $this;
}
public function confirm(Confirm $confirm): self
{
$this->confirm = $confirm;
@ -44,7 +59,7 @@ final class Button extends Element
public function style(string $string): self
{
if (! in_array($string,['default','primary','danger']))
throw new SlackSyntaxException(sprintf('Unknown style %s',$string));
throw new Exception(sprintf('Unknown style %s',$string));
$this->style = $string;

View File

@ -3,39 +3,18 @@
namespace Slack\Blockkit\Blocks\Elements;
use Slack\Blockkit\Element;
use Slack\Exceptions\SlackSyntaxException;
final class Confirm extends Element
{
protected const LIMITS = [
'title' => 100,
'text' => 300,
'confirm' => 30,
'deny' => 30,
];
public function __construct(string $title,Text $text,string $confirm,string $deny)
public function __construct()
{
parent::__construct();
$this->title = Text::item($this->validate('title',$title),'plain_text');
$this->text = $this->validate('text',$text->text) ? $text : NULL;
$this->confirm = Text::item($this->validate('confirm',$confirm),'plain_text');
$this->deny = Text::item($this->validate('deny',$deny),'plain_text');
abort(500,'Not Implememted');
}
public static function item(string $title,Text $text,string $confirm,string $deny): self
public static function item(): self
{
return new self($title,$text,$confirm,$deny);
}
public function style(string $string): self
{
if (! in_array($string,['default','primary','danger']))
throw new SlackSyntaxException(sprintf('Unknown style %s',$string));
$this->style = $string;
return $this;
return new self();
}
}

View File

@ -1,69 +0,0 @@
<?php
namespace Slack\Blockkit\Blocks\Elements;
use Slack\Blockkit\Element;
use Slack\Exceptions\SlackSyntaxException;
final class ExternalSelect extends Element
{
protected const LIMITS = [
'action_id' => 255,
'placeholder' => 150,
];
/**
* @param string $placeholder
* @param string $action_id
* @throws SlackSyntaxException
*/
public function __construct(string $placeholder,string $action_id)
{
parent::__construct();
// Defaults
$this->type = 'external_select';
$this->placeholder = Text::item($this->validate('placeholder',$placeholder),'plain_text');
$this->action_id = $this->validate('action_id',$action_id);
}
public static function item(string $placeholder,string $action_id): self
{
return new self($placeholder,$action_id);
}
/* OPTIONAL ITEMS */
public function confirm(Confirm $confirm): self
{
$this->confirm = $confirm;
return $this;
}
// @note only 1 element in a view can have this set to true
public function focus_on_load(bool $bool): self
{
$this->focus_on_load = $bool;
return $this;
}
public function initial_option(string $option): self
{
$this->initial_option = $option;
return $this;
}
public function min_query_length(int $int): self
{
if ($int < 1)
throw new SlackSyntaxException('Minimum 1 options must be configured');
$this->min_query_length = $int;
return $this;
}
}

View File

@ -1,85 +0,0 @@
<?php
namespace Slack\Blockkit\Blocks\Elements;
use Illuminate\Support\Collection;
use Slack\Blockkit\Element;
use Slack\Exceptions\SlackSyntaxException;
final class MultiExternalSelect extends Element
{
public const LIMITS = [
'action_id' => 255,
'placeholder' => 150,
];
public const MAX_OPTIONS = 100;
// @todo option_group? (double check it is applicable to this item)
/**
* @param string $placeholder
* @param string $action_id
* @throws SlackSyntaxException
*/
public function __construct(string $placeholder,string $action_id)
{
parent::__construct();
// Defaults
$this->type = 'multi_external_select';
$this->placeholder = Text::item($this->validate('placeholder',$placeholder),'plain_text');
$this->action_id = $this->validate('action_id',$action_id);
}
public static function item(string $placeholder,string $action_id): self
{
return new self($placeholder,$action_id);
}
/* OPTIONAL ITEMS */
public function confirm(Confirm $confirm): self
{
$this->confirm = $confirm;
return $this;
}
// @note only 1 element in a view can have this set to true
public function focus_on_load(bool $bool): self
{
$this->focus_on_load = $bool;
return $this;
}
public function initial_options(Collection $array=NULL): self
{
$this->initial_options = $array->map(function($item) { return ['text'=>['type'=>'plain_text','text'=>$item->name],'value'=>(string)$item->value]; });
return $this;
}
public function min_query_length(int $int): self
{
if ($int < 1)
throw new SlackSyntaxException('Minimum 1 options must be configured');
$this->min_query_length = $int;
return $this;
}
public function max_selected_items(int $int): self
{
if ($int < 1)
throw new SlackSyntaxException('Minimum 1 options must be configured');
$this->max_selected_items = $int;
return $this;
}
}

View File

@ -2,51 +2,58 @@
namespace Slack\Blockkit\Blocks\Elements;
use \Exception;
use Illuminate\Support\Collection;
use Slack\Blockkit\Element;
use Slack\Exceptions\SlackSyntaxException;
final class MultiStaticSelect extends Element
{
public const LIMITS = [
protected const LIMITS = [
'action_id' => 255,
'placeholder' => 150,
];
public const MAX_OPTIONS = 100;
private const MAX_OPTIONS = 100;
// @todo option_group? (double check it is applicable to this item)
/**
* @param string $placeholder
* @param Text $placeholder
* @param string $action_id
* @param Collection $options
* @throws SlackSyntaxException
* @throws Exception
* @todo We dont handle option_groups yet.
*/
public function __construct(string $placeholder,string $action_id,Collection $options)
public function __construct(Text $placeholder,string $action_id,Collection $options)
{
parent::__construct();
// Defaults
$this->type = 'multi_static_select';
$this->placeholder = Text::item($this->validate('placeholder',$placeholder),'plain_text');
if ($placeholder->type != 'plain_text')
throw new Exception(sprintf('Text must be plain_text not %s',$placeholder->type));
if (strlen($placeholder->text) > self::LIMITS['placeholder'])
throw new Exception(sprintf('Text must be %d chars or less',self::LIMITS['placeholder']));
$this->placeholder = $placeholder;
$this->action_id = $this->validate('action_id',$action_id);
if (! $options->count())
throw new SlackSyntaxException('There are no options?');
throw new Exception('There are no options?');
if ($options->count() > self::MAX_OPTIONS)
throw new SlackSyntaxException(sprintf('Can only have maximum %d options',self::MAX_OPTIONS));
throw new Exception(sprintf('Can only have maximum %d options',self::MAX_OPTIONS));
$this->options = $options->transform(function($item) {
return ['text'=>Text::item($item->name,'plain_text'),'value'=>(string)$item->value];
});
}
public static function item(string $placeholder,string $action_id,Collection $options): self
public static function item(Text $placeholder,string $action_id,Collection $options): self
{
return new self($placeholder,$action_id,$options);
}
@ -67,17 +74,17 @@ final class MultiStaticSelect extends Element
return $this;
}
public function initial_options(Collection $initial=NULL): self
public function initial_options(array $initial=NULL): self
{
// No initial options.
if (count($initial)) {
if (! $this->options)
throw new SlackSyntaxException('Cannot set an initial value without options defined first');
throw new Exception('Cannot set an initial value without options defined first');
if (count($initial) > self::MAX_OPTIONS)
throw new SlackSyntaxException(sprintf('Can only have maximum %d options',self::MAX_OPTIONS));
throw new Exception(sprintf('Can only have maximum %d options',self::MAX_OPTIONS));
$this->initial_options = $this->options->filter(function($item) use ($initial) { return $initial->contains($item['value']); });
$this->initial_options = $this->options->filter(function($item) use ($initial) { return in_array($item['value'],$initial); });
}
return $this;
@ -86,7 +93,7 @@ final class MultiStaticSelect extends Element
public function max_selected_items(int $int): self
{
if ($int < 1)
throw new SlackSyntaxException('Minimum 1 options must be configured');
throw new Exception('Minimum 1 options must be configured');
$this->max_selected_items = $int;

View File

@ -2,8 +2,9 @@
namespace Slack\Blockkit\Blocks\Elements;
use \Exception;
use Slack\Blockkit\Element;
use Slack\Exceptions\SlackSyntaxException;
/**
* @note Overflow, select, and multi-select menus can only use plain_text objects,
@ -23,7 +24,7 @@ final class Options extends Element
parent::__construct();
if (strlen($text->text) > self::LIMITS['text'])
throw new SlackSyntaxException(sprintf('Text must be %d chars or less',self::LIMITS['text']));
throw new Exception(sprintf('Text must be %d chars or less',self::LIMITS['text']));
$this->text = $text;
$this->value = $this->validate('value',$value);
@ -36,9 +37,15 @@ final class Options extends Element
/* OPTIONAL ITEMS */
public function description(string $text): self
public function description(Text $text): self
{
$this->description = Text::item($this->validate('description',$text),'plain_text');
if ($text->type != 'plain_text')
throw new Exception(sprintf('Text must be plain_text not %s',$text->type));
if (strlen($text->text) > self::LIMITS['description'])
throw new Exception(sprintf('Text must be %d chars or less',self::LIMITS['description']));
$this->description = $text;
return $this;
}

View File

@ -3,19 +3,18 @@
namespace Slack\Blockkit\Blocks\Elements;
use Slack\Blockkit\Element;
use Slack\Exceptions\SlackSyntaxException;
/**
* This is an element of an input dialog
*/
final class PlainTextInput extends Element
final class PlaintTextInput extends Element
{
public const LIMITS = [
protected const LIMITS = [
'action_id' => 255, // @todo Should be unique for each message
'placeholder' => 150,
];
public const MAX_MIN_LENGTH = 3000;
private const MAX_MIN_LENGTH = 3000;
// @todo dispatch_action_config
// @todo focus_on_load
@ -46,7 +45,7 @@ final class PlainTextInput extends Element
public function min_length(int $int): self
{
if ($int > self::MAX_MIN_LENGTH)
throw new SlackSyntaxException(sprintf('min_length must be less than %d',self::MAX_MIN_LENGTH));
throw new Exception(sprintf('min_length must be less than %d',self::MAX_MIN_LENGTH));
$this->min_length = $int;
@ -56,7 +55,7 @@ final class PlainTextInput extends Element
public function max_length(int $int): self
{
if ($this->min_length && ($int < $this->min_length))
throw new SlackSyntaxException('max_length must be greater than min_length');
throw new Exception('max_length must be greater than min_length');
$this->max_length = $int;
@ -73,7 +72,7 @@ final class PlainTextInput extends Element
public function placeholder(Text $text): self
{
if (strlen($text->text) > self::LIMITS['placeholder'])
throw new SlackSyntaxException(sprintf('Text must be %d chars or less',self::LIMITS['placeholder']));
throw new Exception(sprintf('Text must be %d chars or less',self::LIMITS['placeholder']));
$this->placeholder = $text;

View File

@ -2,51 +2,58 @@
namespace Slack\Blockkit\Blocks\Elements;
use \Exception;
use Illuminate\Support\Collection;
use Slack\Blockkit\Element;
use Slack\Exceptions\SlackSyntaxException;
final class StaticSelect extends Element
{
public const LIMITS = [
protected const LIMITS = [
'action_id' => 255,
'placeholder' => 150,
];
public const MAX_OPTIONS = 100;
private const MAX_OPTIONS = 100;
// @todo option_group
/**
* @param string $placeholder
* @param Text $placeholder
* @param string $action_id
* @param Collection $options
* @throws SlackSyntaxException
* @throws Exception
* @todo We dont handle option_groups yet.
*/
public function __construct(string $placeholder,string $action_id,Collection $options)
public function __construct(Text $placeholder,string $action_id,Collection $options)
{
parent::__construct();
// Defaults
$this->type = 'static_select';
$this->placeholder = Text::item($this->validate('placeholder',$placeholder),'plain_text');
if ($placeholder->type != 'plain_text')
throw new Exception(sprintf('Text must be plain_text not %s',$placeholder->type));
if (strlen($placeholder->text) > self::LIMITS['placeholder'])
throw new Exception(sprintf('Text must be %d chars or less',self::LIMITS['placeholder']));
$this->placeholder = $placeholder;
$this->action_id = $this->validate('action_id',$action_id);
if (! $options->count())
throw new SlackSyntaxException('There are no options?');
throw new Exception('There are no options?');
if ($options->count() > self::MAX_OPTIONS)
throw new SlackSyntaxException(sprintf('Can only have maximum %d options',self::MAX_OPTIONS));
throw new Exception(sprintf('Can only have maximum %d options',self::MAX_OPTIONS));
$this->options = $options->transform(function($item) {
return ['text'=>Text::item($item->name,'plain_text'),'value'=>(string)$item->value];
});
}
public static function item(string $placeholder,string $action_id,Collection $options): self
public static function item(Text $placeholder,string $action_id,Collection $options): self
{
return new self($placeholder,$action_id,$options);
}
@ -70,7 +77,7 @@ final class StaticSelect extends Element
public function initial_option(string $string=NULL): self
{
if (! $this->options)
throw new SlackSyntaxException('Cannot set an initial value without options defined first');
throw new Exception('Cannot set an initial value without options defined first');
if ($string)
$this->initial_option = $this->options->first(function($item) use ($string) { return $item['value'] == $string; });

View File

@ -2,22 +2,23 @@
namespace Slack\Blockkit\Blocks\Elements;
use \Exception;
use Slack\Blockkit\Element;
use Slack\Exceptions\SlackSyntaxException;
final class Text extends Element
{
public const TYPES = ['mrkdwn','plain_text'];
private const TYPES = ['mrkdwn','plain_text'];
public function __construct(string $text,string $type)
{
parent::__construct();
if (! in_array($type,self::TYPES))
throw new SlackSyntaxException(sprintf('Type [%s] not valid',$type));
throw new Exception(sprintf('Type [%s] not valid',$type));
$this->text = $text;
$this->type = $type;
$this->text = $text;
}
public static function item(string $text,string $type='mrkdwn'): self
@ -29,8 +30,8 @@ final class Text extends Element
public function emoji(bool $bool): self
{
if ($this->type != 'plain_text')
throw new SlackSyntaxException(sprintf('Cannnot use emoji when type is [%s]',$this->type));
if ($x=$this->type != 'plain_text')
throw new Exception(sprintf('Cannnot use emoji when type is [%s]',$x));
$this->emoji = $bool;

View File

@ -2,9 +2,10 @@
namespace Slack\Blockkit\Blocks;
use \Exception;
use Slack\Blockkit\Blocks;
use Slack\Blockkit\Blocks\Elements\Text;
use Slack\Exceptions\SlackSyntaxException;
final class Header extends Blocks
{
@ -14,20 +15,26 @@ final class Header extends Blocks
];
/**
* @param string $text
* @throws SlackSyntaxException
* @param Text $text
* @throws Exception
*/
public function __construct(string $text)
public function __construct(Text $text)
{
parent::__construct();
// Defaults
$this->type = 'header';
$this->text = Text::item($this->validate('text',$text),'plain_text');
if ($text->type != 'plain_text')
throw new Exception(sprintf('Text must be plain_text not %s',$text->type));
if (strlen($text->text) > self::LIMITS['text'])
throw new Exception(sprintf('Text must be %d chars or less',self::LIMITS['text']));
$this->text = $text;
}
public static function item(string $text): self
public static function item(Text $text): self
{
return new self($text);
}

View File

@ -2,39 +2,46 @@
namespace Slack\Blockkit\Blocks;
use Slack\Blockkit\{Blocks,Blocks\Elements\Text,Element};
use Slack\Exceptions\SlackSyntaxException;
use \Exception;
use Slack\Blockkit\{Blocks,Element};
final class Input extends Blocks
{
public const LIMITS = [
protected const LIMITS = [
'block_id' => 255, // @todo Should be unique for each message
'hint' => 2000,
'label' => 2000,
];
public const VALID_ELEMENTS = [
Elements\PlainTextInput::class,
private const VALID_ELEMENTS = [
Elements\PlaintTextInput::class,
Elements\MultiStaticSelect::class
];
// @todo dispatch_action
/**
* @param string|null $label
* @throws SlackSyntaxException
* @param Elements\Text|null $label
* @throws Exception
*/
public function __construct(string $label=NULL)
public function __construct(Elements\Text $label=NULL)
{
parent::__construct();
if ($label->type != 'plain_text')
throw new Exception(sprintf('Text must be plain_text not %s',$label->type));
// Defaults
$this->type = 'input';
$this->label = Text::item($this->validate('label',$label),'plain_text');
if (strlen($label->text) > self::LIMITS['label'])
throw new Exception(sprintf('Text must be %d chars or less',self::LIMITS['label']));
$this->label = $label;
}
public static function item(string $label=NULL): self
public static function item(Elements\Text $label=NULL): self
{
return new self($label);
}
@ -42,7 +49,7 @@ final class Input extends Blocks
public function jsonSerialize()
{
if (! $this->element)
throw new SlackSyntaxException('Must define an element');
throw new Exception('Must define an element');
return parent::jsonSerialize();
}
@ -59,7 +66,7 @@ final class Input extends Blocks
public function element(Element $object): self
{
if (! in_array(get_class($object),self::VALID_ELEMENTS))
throw new SlackSyntaxException(sprintf('Invalid element [%s] added to input',get_class($object)));
throw new Exception(sprintf('Invalid element [%s] added to input',get_class($object)));
$this->element = $object;
@ -69,7 +76,7 @@ final class Input extends Blocks
public function hint(Elements\Text $text): self
{
if (strlen($text->text) > self::LIMITS['hint'])
throw new SlackSyntaxException(sprintf('Text must be %d chars or less',self::LIMITS['hint']));
throw new Exception(sprintf('Text must be %d chars or less',self::LIMITS['hint']));
$this->hint = $text;

View File

@ -2,25 +2,25 @@
namespace Slack\Blockkit\Blocks;
use \Exception;
use Illuminate\Support\Collection;
use Slack\Blockkit\{Blocks,Element};
use Slack\BLockKit\Blocks\Elements\Text;
use Slack\Exceptions\SlackSyntaxException;
final class Section extends Blocks
{
public const LIMITS = [
protected const LIMITS = [
'block_id' => 255, // @todo Should be unique for each message
'text' => 3000,
];
public const MAX_FIELDS = 10;
public const MAX_FIELDS_TEXT = 2000;
private const MAX_FIELDS = 10;
private const MAX_FIELDS_TEXT = 2000;
/**
* @param Text|NULL $text not required if fields is provided
* @throws SlackSyntaxException
* @throws Exception
*/
public function __construct(Text $text=NULL)
{
@ -31,7 +31,7 @@ final class Section extends Blocks
if ($text) {
if (strlen($text->text) > self::LIMITS['text'])
throw new SlackSyntaxException(sprintf('Text must be %d chars or less',self::LIMITS['text']));
throw new Exception(sprintf('Text must be %d chars or less',self::LIMITS['text']));
$this->text = $text;
}
@ -45,7 +45,7 @@ final class Section extends Blocks
public function jsonSerialize()
{
if (! $this->text && ! $this->fields && ! $this->accessory)
throw new SlackSyntaxException('Must define text, accessory or fields');
throw new Exception('Must define text, accessory or fields');
return parent::jsonSerialize();
}
@ -69,10 +69,10 @@ final class Section extends Blocks
public function fields(Collection $collection): self
{
if (count($collection) > self::MAX_FIELDS)
throw new SlackSyntaxException(sprintf('Can only have maximum %d fields',self::MAX_FIELDS));
throw new Exception(sprintf('Can only have maximum %d fields',self::MAX_FIELDS));
if (($x=$collection->map(function($item) { return strlen($item->text); })->max()) > self::MAX_FIELDS_TEXT)
throw new SlackSyntaxException(sprintf('The maximum size of the text in a field is %d (%d)',self::MAX_FIELDS_TEXT,$x));
throw new Exception(sprintf('The maximum size of the text in a field is %d (%d)',self::MAX_FIELDS_TEXT,$x));
$this->fields = $collection;

View File

@ -2,44 +2,52 @@
namespace Slack\Blockkit;
use \Exception;
use Slack\BlockKit;
use Slack\Blockkit\Blocks\Divider;
use Slack\Blockkit\Blocks\Elements\Text;
use Slack\Blockkit\Blocks\Section;
use Slack\Exceptions\SlackSyntaxException;
/**
* This class creates a slack Modal Response
*/
final class Modal extends BlockKit
{
public const LIMITS = [
protected const LIMITS = [
'callback_id' => 255,
'close' => 24,
'private_metadata' => 3000,
'submit' => 24,
'title' => 24,
'text' => 24,
];
public const MAX_BLOCKS = 100;
private const MAX_BLOCKS = 100;
private $action = NULL;
public function __construct(string $title=NULL,string $type='modal')
public function __construct(Text $title=NULL,string $type='modal')
{
parent::__construct();
if (! in_array($type,['modal','home']))
throw new SlackSyntaxException(sprintf('Unknown type %s',$type));
throw new Exception(sprintf('Unknown type %s',$type));
if ($type != 'modal' && $title)
throw new Exception(sprintf('Titles are not required for %s',$type));
if ($title) {
if ($type != 'modal')
throw new SlackSyntaxException(sprintf('Titles are not required for %s',$type));
if ($title->type != 'plain_text')
throw new Exception(sprintf('Text must be plain_text not %s',$title->type));
$this->title = Text::item($this->validate('title',$title),'plain_text');
if (strlen($title->text) > self::LIMITS['text'])
throw new Exception(sprintf('Text must be %d chars or less',self::LIMITS['text']));
$this->title = $title;
}
$this->type = $type;
$this->blocks = collect();
}
@ -48,14 +56,14 @@ final class Modal extends BlockKit
*
* @param Blocks $block
* @return $this
* @throws SlackSyntaxException
* @throws Exception
*/
public function addBlock(Blocks $block): self
{
$this->blocks->push($block);
if ($this->blocks->count() > self::MAX_BLOCKS)
throw new SlackSyntaxException(sprintf('Modal can only have %d blocks',self::MAX_BLOCKS));
if ($x=$this->blocks->count() > self::MAX_BLOCKS)
throw new Exception(sprintf('Modal can only have %d blocks',self::MAX_BLOCKS));
return $this;
}
@ -82,17 +90,17 @@ final class Modal extends BlockKit
public function action(string $string)
{
if (! in_array($string,['clear','update']))
throw new SlackSyntaxException(sprintf('Unknown action %s',$string));
throw new Exception(sprintf('Unknown action %s',$string));
$this->action = $string;
return $this;
}
public function clear_on_close(bool $bool=TRUE): self
public function clear_on_close(bool $bool): self
{
if ($this->type != 'modal')
throw new SlackSyntaxException(sprintf('clear_on_close is not required for %s',$this->type));
throw new Exception(sprintf('clear_on_close is not required for %s',$type));
$this->clear_on_close = $bool;
@ -106,12 +114,18 @@ final class Modal extends BlockKit
return $this;
}
public function close(string $text): self
public function close(Text $text): self
{
if ($this->type != 'modal')
throw new SlackSyntaxException(sprintf('Close is not required for %s',$this->type));
throw new Exception(sprintf('Close is not required for %s',$type));
$this->close = Text::item($this->validate('close',$text),'plain_text');
if ($text->type != 'plain_text')
throw new Exception(sprintf('Text must be plain_text not %s',$text->type));
if (strlen($text->text) > self::LIMITS['close'])
throw new Exception(sprintf('Text must be %d chars or less',self::LIMITS['close']));
$this->close = $text;
return $this;
}
@ -136,10 +150,10 @@ final class Modal extends BlockKit
return $this;
}
public function notify_on_close(bool $bool=TRUE): self
public function notify_on_close(bool $bool): self
{
if ($this->type != 'modal')
throw new SlackSyntaxException(sprintf('notify_on_close is not required for %s',$this->type));
throw new Exception(sprintf('notify_on_close is not required for %s',$type));
$this->notify_on_close = $bool;
@ -161,12 +175,18 @@ final class Modal extends BlockKit
return $this;
}
public function submit(string $text): self
public function submit(Text $text): self
{
if ($this->type != 'modal')
throw new SlackSyntaxException(sprintf('Submit is not required for %s',$this->type));
throw new Exception(sprintf('Submit is not required for %s',$type));
$this->submit = Text::item($this->validate('submit',$text),'plain_text');
if ($text->type != 'plain_text')
throw new Exception(sprintf('Text must be plain_text not %s',$text->type));
if (strlen($text->text) > self::LIMITS['submit'])
throw new Exception(sprintf('Text must be %d chars or less',self::LIMITS['submit']));
$this->submit = $text;
return $this;
}
@ -174,10 +194,24 @@ final class Modal extends BlockKit
public function submit_disabled(bool $bool): self
{
if ($this->type != 'modal')
throw new SlackSyntaxException(sprintf('submit_disabled is not required for %s',$this->type));
throw new Exception(sprintf('submit_disabled is not required for %s',$type));
$this->submit_disabled = $bool;
return $this;
}
/**
* Add a block to the modal
*
* @param Blocks $blocks
* @return $this
* @deprecated use addBlock() instead
*/
public function setBlocks(Blocks $blocks): self
{
$this->_data->put('blocks',$blocks);
return $this;
}
}

View File

@ -9,7 +9,6 @@ use React\EventLoop\Loop;
use Slack\Client\SocketMode;
use Slack\Command\Factory as SlackCommandFactory;
use Slack\Event\Factory as SlackEventFactory;
use Slack\Exceptions\SlackException;
use Slack\Interactive\Factory as SlackInteractiveFactory;
class SlackSocketClient extends Command
@ -34,13 +33,13 @@ class SlackSocketClient extends Command
* Execute the console command.
*
* @return void
* @throws SlackException
* @throws \Exception
*/
public function handle()
{
// Make sure our socket_token is defined
if (! config('slack.socket_token'))
throw new SlackException('SocketMode Client Token not defined.');
throw new \Exception('SocketMode Client Token not defined.');
$loop = Loop::get();

View File

@ -1,7 +0,0 @@
<?php
namespace Slack\Exceptions;
class SlackSyntaxException extends SlackException
{
}

View File

@ -9,7 +9,7 @@ use App\Http\Controllers\Controller;
use Slack\Client\Payload;
use Slack\Event\Factory as SlackEventFactory;
final class EventsController extends Controller
class EventsController extends Controller
{
private const LOGKEY = 'CEC';

View File

@ -10,7 +10,7 @@ use Slack\Client\Payload;
use Slack\Message;
use Slack\Interactive\Factory as InteractiveMessageFactory;
final class InteractiveMessageController extends Controller
class InteractiveMessageController extends Controller
{
private const LOGKEY = 'CIM';

View File

@ -9,7 +9,7 @@ use App\Http\Controllers\Controller;
use Slack\Client\Payload;
use Slack\Options\Factory as SlackOptionsFactory;
final class InteractiveOptionsController extends Controller
class InteractiveOptionsController extends Controller
{
private const LOGKEY = 'CIO';
@ -18,6 +18,7 @@ final class InteractiveOptionsController extends Controller
*
* @param Request $request
* @return \Illuminate\Http\Response|\Laravel\Lumen\Http\ResponseFactory
* @throws \Exception
*/
public function fire(Request $request)
{

View File

@ -12,7 +12,7 @@ use Slack\Command\Factory;
use Slack\Message;
use Slack\Message\Attachment;
final class SlashCommandController extends Controller
class SlashCommandController extends Controller
{
private const LOGKEY = 'CSC';

View File

@ -11,7 +11,7 @@ use Slack\Event\Factory as EventFactory;
use Slack\Interactive\Factory as InteractiveFactory;
use Slack\Options\Factory as OptionsFactory;
final class CheckRequest
class CheckRequest
{
private const LOGKEY = 'MCR';
@ -73,7 +73,7 @@ final class CheckRequest
return response('',200);
} else {
Log::debug(sprintf('%s:Incoming Request Allowed [%s/%s]',static::LOGKEY,$event->enterprise_id,$event->team_id),['m'=>__METHOD__]);
Log::debug(sprintf('%s:Incoming Request Allowed',static::LOGKEY),['m'=>__METHOD__,'e'=>$event->enterprise_id,'t'=>$event->team_id,'eo'=>$event->enterprise()->id,'to'=>$event->team()]);
return $next($request);
}

View File

@ -9,7 +9,7 @@ use Illuminate\Support\Facades\Log;
use Slack\Base;
final class CheckSignature
class CheckSignature
{
private const LOGKEY = 'MCS';

View File

@ -35,7 +35,6 @@ abstract class Base extends SlackBase
* + user_id
* @param string $key
* @return mixed|object
* @throws \Exception
*/
public function __get(string $key)
{
@ -47,12 +46,6 @@ abstract class Base extends SlackBase
case 'user_id':
return object_get($this->_data,'user.id');
case 'callback_key':
return $this->keyitem('id',$this->callback_id);
case 'callback_value':
return $this->keyitem('value',$this->callback_id);
case 'callback_id':
case 'trigger_id':
case 'type':

View File

@ -5,6 +5,7 @@ namespace Slack\Interactive;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Slack\Exceptions\SlackException;
use Slack\Models\Channel;
/**
@ -54,7 +55,7 @@ use Slack\Models\Channel;
* )
* )
*/
final class BlockActions extends Base
class BlockActions extends Base
{
private const LOGKEY = 'IBA';
@ -64,25 +65,19 @@ final class BlockActions extends Base
case 'action':
return Arr::get(object_get($this->_data,'actions'),$this->index);
case 'action_id':
return object_get(Arr::get($this->actions,$this->index),$key);
// An event can have more than 1 action, each action can have 1 value.
case 'action_key':
return $this->keyitem('id',$this->action_id);
return $this->action('action');
case 'action_value':
return $this->keyitem('value',$this->action_id);
// Interactive Messages have a block_id.
case 'block_key':
return $this->keyitem('id',$this->block_id);
case 'block_value':
return $this->keyitem('value',$this->block_id);
return $this->action('value');
case 'actions':
case 'response_url':
return object_get($this->_data,$key);
case 'action_id':
case 'block_id':
return object_get($this->action,$key);
@ -92,33 +87,23 @@ final class BlockActions extends Base
// For app hometab, the callback is in the view->callback_id array.
return object_get($this->_data,sprintf('%s.%s',$this->container_type,$key));
case 'message':
case 'message_attachment':
return NULL;
default:
throw new \Exception('Unknown container type: '.$this->container_type);
throw new SlackException('Unknown container type: '.$this->container_type);
}
// @todo See if all responses have a container.type, and if so, put this in base.
case 'container_type':
return object_get($this->_data,'container.type');
case 'channel_id':
return object_get($this->_data,'channel.id') ?: Channel::findOrFail($this->keyitem('value',object_get($this->action,'action_id')))->channel_id;
return object_get($this->_data,'channel.id') ?: Channel::findOrFail($this->action('value'))->channel_id;
case 'keys':
return collect(object_get($this->_data,'view.blocks'))->pluck('accessory.action_id');
// For Block Actions that are messages
case 'message_ts':
switch ($this->container_type) {
// Ephemeral messages
case 'message':
return object_get($this->_data,'container.message_ts');
default:
return object_get($this->_data,'message.ts');
}
return object_get($this->_data,'message.ts');
case 'team_id': // view.team_id represent workspace publishing view
return object_get($this->_data,'user.team_id');
@ -134,8 +119,6 @@ final class BlockActions extends Base
return object_get($this->action,'selected_option.value');
case 'multi_static_select':
return object_get($this->action,'selected_options.value');
case 'button':
default:
return object_get($this->action,$key);
}
@ -147,7 +130,7 @@ final class BlockActions extends Base
// @todo To Check
case 'overflow':
// @todo To Check
throw new \Exception('To be implemented: ',$x);
throw new SlackException('To be implemented: ',$x);
case 'static_select':
return count(object_get($this->action,'selected_option'));
case 'multi_static_select':
@ -161,6 +144,38 @@ final class BlockActions extends Base
}
}
/**
* Separate out an action command to the id that the command relates to
*
* @param string $key
* @return string
* @throws SlackException
*/
private function action(string $key): ?string
{
$regex = '/^([a-z_]+)\|([0-9]+)$/';
$action = NULL;
$value = NULL;
// We only take the action up to the pipe symbol
$action_key = object_get($this->action,'action_id');
if (preg_match($regex,$action_key)) {
$action = preg_replace($regex,'$1',$action_key);
$value = preg_replace($regex,'$2',$action_key);
}
switch ($key) {
case 'action':
return $action ?: $action_key;
case 'value':
return $value;
default:
throw new SlackException('Unknown key: '.$key);
}
}
/**
* Some block actions are triggered by messages, and thus dont have a callback_id
*

View File

@ -2,24 +2,24 @@
namespace Slack\Interactive;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Log;
use Slack\Client\Payload;
class Factory {
protected const LOGKEY = 'SIF';
private const LOGKEY = 'SIF';
/**
* @var array event type to event class mapping
*/
public const map = [
'block_actions' => BlockActions::class,
'interactive_message' => InteractiveMessage::class,
//'interactive_message' => InteractiveMessage::class,
'shortcut' => Shortcut::class,
'view_closed' => ViewClosed::class,
'view_submission' => ViewSubmission::class,
//'view_submission' => ViewSubmission::class,
];
/**

View File

@ -99,8 +99,26 @@ class InteractiveMessage extends Base
public function respond(): Message
{
Log::info(sprintf('%s:Interactive Message - Callback [%s] Name [%s] Type [%s]',static::LOGKEY,$this->callback_id,$this->name,$this->type),['m'=>__METHOD__]);
Log::notice(sprintf('%s:Unhandled action [%s]',static::LOGKEY,$this->callback_id),['m'=>__METHOD__]);
return (new Message)->text('That didnt work, I didnt know what to do with your button - you might like to tell '.$this->team()->owner->slack_user);
$action = NULL;
$id = NULL;
if (preg_match('/^(.*)\|([0-9]+)/',$this->callback_id)) {
[$action,$id] = explode('|',$this->callback_id,2);
} elseif (preg_match('/^[a-z_]+$/',$this->callback_id)) {
$id = $this->name;
$action = $this->callback_id;
} else {
// If we get here, its an action that we dont know about.
Log::notice(sprintf('%s:Unhandled CALLBACK [%s]',static::LOGKEY,$this->callback_id),['m'=>__METHOD__]);
}
switch ($action) {
default:
Log::notice(sprintf('%s:Unhandled ACTION [%s]',static::LOGKEY,$action),['m'=>__METHOD__]);
return (new Message)->text('That didnt work, I didnt know what to do with your button - you might like to tell '.$this->team()->owner->slack_user);
}
}
}

View File

@ -9,7 +9,7 @@ use Illuminate\Support\Facades\Log;
*
* @package Slack\Interactive
*/
final class Unknown extends Base
class Unknown extends Base
{
public function __construct(array $request)
{

View File

@ -65,7 +65,7 @@ use Illuminate\Support\Arr;
*/
class ViewClosed extends Base
{
protected const LOGKEY = 'IVC';
private const LOGKEY = 'IVC';
public function __get($key)
{

View File

@ -2,9 +2,12 @@
namespace Slack\Interactive;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Slack\Blockkit\Modal;
use Slack\Models\Team;
/**
* Incoming modal view submission event.
@ -21,24 +24,12 @@ class ViewSubmission extends Base
public function __get($key)
{
switch ($key) {
case 'blocks':
return collect(object_get($this->_data,'view.'.$key));
case 'callback_id':
return object_get($this->_data,'view.callback_id');
case 'callback_key':
return $this->keyitem('id',$this->callback_id);
case 'callback_value':
return $this->keyitem('value',$this->callback_id);
return object_get($this->_data,'view.'.$key);
case 'meta':
return object_get($this->_data,'view.private_metadata');
case 'state':
return collect(object_get($this->_data,'view.'.$key.'.values'));
case 'view_id':
return object_get($this->_data,'view.id');
@ -51,25 +42,59 @@ class ViewSubmission extends Base
* This method should be overridden by a local implementation
*
* @return Modal
* @throws \Exception
*/
public function respond(): Modal
{
// Do some magic with event data
Log::info(sprintf('%s:View Submission for Callback [%s] User [%s] in [%s]',self::LOGKEY,$this->callback_id,$this->user_id,$this->team_id),['m'=>__METHOD__]);
Log::notice(sprintf('%s:Unhandled action [%s]',self::LOGKEY,$this->callback_key),['m'=>__METHOD__]);
return new Modal;
}
$action = NULL;
$id = NULL;
public function value(string $block_id,string $action_id=NULL): ?string
{
// If there is no state we need to search out blocks for the block_id
if (! $this->state->count()) {
$block = $this->blocks->search(function($item) use ($block_id) { return $item->block_id == $block_id; });
return $block !== FALSE ? object_get($this->blocks->get($block),$action_id) : NULL;
if (preg_match('/^(.*)\|([0-9]+)/',$this->callback_id)) {
[$action,$cid] = explode('|',$this->callback_id,2);
} elseif (preg_match('/^[a-z_]+$/',$this->callback_id)) {
$action = $this->callback_id;
} else {
return object_get($this->state->get($block_id),$action_id.'.value');
// If we get here, its an action that we dont know about.
Log::notice(sprintf('%s:Unhandled CALLBACK [%s]',static::LOGKEY,$this->callback_id),['m'=>__METHOD__]);
}
switch ($action) {
default:
Log::notice(sprintf('%s:Unhandled ACTION [%s]',self::LOGKEY,$action),['m'=>__METHOD__]);
}
return new Modal(new Team);
}
protected function blocks(): Collection
{
$result = collect();
foreach (object_get($this->_data,'view.blocks',[]) as $id=>$block) {
switch (object_get($block,'type')) {
case 'input':
$result->put($block->element->action_id,$block->block_id);
break;
case 'section':
$result->put($block->block_id,$id);
break;
}
}
return $result;
}
public function value(string $block_id): ?string
{
$key = Arr::get($this->blocks(),$block_id);
// Return the state value, or the original block value
return object_get($this->_data,'view.state.values.'.$key.'.'.$block_id.'.value') ?: object_get(Arr::get(object_get($this->_data,'view.blocks'),$key),'text.text','');
}
}

View File

@ -8,7 +8,7 @@ use Illuminate\Support\Facades\Log;
use Slack\Models\{Channel,User};
use Slack\Exceptions\SlackException;
final class DeleteChat extends Job
class DeleteChat extends Job
{
private const LOGKEY = 'JDC';
@ -22,16 +22,16 @@ final class DeleteChat extends Job
public function __construct(Model $o,string $ts)
{
if ($o instanceof Channel) {
$this->cid = $o->channel_id;
$this->_data['cid'] = $o->channel_id;
} elseif ($o instanceof User) {
$this->cid = $o->user_id;
$this->_data['cid'] = $o->user_id;
} else
throw new \Exception('Invalid Model: '.get_class($o));
$this->to = $o->team;
$this->ts = $ts;
$this->_data['to'] = $o->team;
$this->_data['ts'] = $ts;
}
/**

View File

@ -1,46 +0,0 @@
<?php
namespace Slack\Jobs;
use Illuminate\Support\Facades\Log;
use Slack\Exceptions\SlackException;
use Slack\Message;
final class DeleteResponse extends Job
{
private const LOGKEY = 'JDC';
/**
* Create a new job instance.
*
* @param string $url
*/
public function __construct(string $url)
{
$this->url = $url;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
Log::info(sprintf('%s:Start - Delete Response [%s]',static::LOGKEY,$this->url),['m'=>__METHOD__]);
$o = new Message;
$o->text('')
->delete_original();
try {
$o->respond($this->url);
Log::debug(sprintf('%s:Deleted Slack Message: %s',static::LOGKEY,$this->url),['m'=>__METHOD__]);
} catch (SlackException $e) {
Log::error(sprintf('%s:Failed to delete slack message [%s] [%s]',static::LOGKEY,$this->url,$e->getMessage()),['m'=>__METHOD__]);
}
}
}

View File

@ -7,7 +7,6 @@ use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
abstract class Job implements ShouldQueue
{
@ -24,20 +23,10 @@ abstract class Job implements ShouldQueue
use InteractsWithQueue, Queueable, SerializesModels;
protected Collection $_data;
protected $_data = [];
public function __get($key)
{
if (! isset($this->_data))
$this->_data = collect();
return Arr::get($this->_data,$key);
}
public function __set(string $key,$value) {
if (! isset($this->_data))
$this->_data = collect();
return $this->_data->put($key,$value);
}
}

View File

@ -9,7 +9,7 @@ use Slack\Models\Team;
class TeamUpdate extends Job
{
protected const LOGKEY = 'JTU';
private const LOGKEY = 'JTU';
/**
* Create a new job instance.
@ -18,7 +18,7 @@ class TeamUpdate extends Job
*/
public function __construct(Team $to)
{
$this->to = $to;
$this->_data['to'] = $to;
}
public function handle()

View File

@ -12,7 +12,7 @@ class AppHomeOpenedListener implements ShouldQueue
{
protected const LOGKEY = 'LAH';
public $queue = 'slack';
public $queue = 'high';
/**
* Handle the event.
@ -20,11 +20,11 @@ class AppHomeOpenedListener implements ShouldQueue
* @param AppHomeOpened $event
* @return void
*/
public function handle(AppHomeOpened $event): void
public function handle(AppHomeOpened $event)
{
// Do some magic with event data
Log::info(sprintf('%s:App Home Page open for [%s] in team [%s]',self::LOGKEY,$event->user_id,$event->team_id),['m'=>__METHOD__]);
dispatch((new SlackHomeTabUpdate($event->user(),$event->team(TRUE),$event->tab,$event->view))->onQueue('slack'));
dispatch((new SlackHomeTabUpdate($event->user(),$event->team(TRUE),$event->tab,$event->view))->onQueue('high'));
}
}

View File

@ -2,7 +2,6 @@
namespace Slack\Listeners;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;
use Slack\Jobs\DeleteChat;
@ -11,16 +10,13 @@ use Slack\Interactive\BlockActions;
/**
* This class handles BlockActions events.
* It's expected that the local application would implement this class completely, rather than using this
* module's implementation.
*
* @note Since block actions contain a trigger_id, we shouldnt queue this as the trigger_id may have expired by the time
* the queue runs the job. (trigger_id's only last 3 seconds)
* modules implementation.
*/
class BlockActionListener //implements ShouldQueue
abstract class BlockActionListener
{
protected const LOGKEY = 'LBA';
// public $queue = 'slack';
public $queue = 'slack';
/**
* Handle the event.
@ -64,7 +60,7 @@ class BlockActionListener //implements ShouldQueue
switch ($event->action_id) {
case 'self_destruct':
// Queue the delete of the message
dispatch((new DeleteChat($event->user(),$event->message_ts))->onQueue('slack'));
dispatch((new DeleteChat($event->user(),$event->message_ts))->onQueue('low'));
// @todo If this message is on integrations messages channel, which is not the user_id() - need to use the user's integration direct channel ID
break;

View File

@ -1,30 +0,0 @@
<?php
namespace Slack\Listeners;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;
use Slack\Options\BlockSuggestion;
class BlockSuggestionListener implements ShouldQueue
{
private const LOGKEY = 'LBS';
public $queue = 'slack';
/**
* Handle the event.
*
* @note Since BlockSuggestions are interactive, it is unlikely that this is needed.
* @param BlockSuggestion $event
* @return void
* @throws \Exception
*/
public function handle(BlockSuggestion $event): void
{
// Do some magic with event data
Log::info(sprintf('%s:Block Suggestion Callback [%s] User [%s] in [%s]',self::LOGKEY,$event->callback_id,$event->user_id,$event->team_id),['e'=>$event]);
Log::notice(sprintf('%s:Ignoring Block Suggestion [%s]',static::LOGKEY,$event->callback_id),['m'=>__METHOD__]);
}
}

View File

@ -11,7 +11,7 @@ class ChannelJoinListener implements ShouldQueue
{
protected const LOGKEY = 'LCJ';
public $queue = 'slack';
public $queue = 'high';
/**
* Handle the event.
@ -19,7 +19,7 @@ class ChannelJoinListener implements ShouldQueue
* @param MemberJoinedChannel $event
* @return void
*/
public function handle(MemberJoinedChannel $event): void
public function handle(MemberJoinedChannel $event)
{
// Do some magic with event data
Log::info(sprintf('%s:User [%s] joined Channel [%s]',self::LOGKEY,$event->invited,$event->channel_id),['m'=>__METHOD__]);

View File

@ -11,7 +11,7 @@ class ChannelLeftListener implements ShouldQueue
{
protected const LOGKEY = 'LCL';
public $queue = 'slack';
public $queue = 'high';
/**
* Handle the event.
@ -19,7 +19,7 @@ class ChannelLeftListener implements ShouldQueue
* @param Base $event
* @return void
*/
public function handle(Base $event): void
public function handle(Base $event)
{
if (! $event instanceof ChannelLeft AND ! $event instanceof GroupLeft)
abort(500,'Wrong class calling this listener? '.get_class($event));

View File

@ -11,7 +11,7 @@ class InteractiveMessageListener implements ShouldQueue
{
protected const LOGKEY = 'LIM';
public $queue = 'slack';
public $queue = 'high';
/**
* Handle the event.
@ -19,10 +19,14 @@ class InteractiveMessageListener implements ShouldQueue
* @param InteractiveMessage $event
* @return void
*/
public function handle(InteractiveMessage $event): void
public function handle(InteractiveMessage $event)
{
// Do some magic with event data
Log::info(sprintf('%s:Interactive Message Callback [%s] User [%s] in [%s]',self::LOGKEY,$event->callback_id,$event->user_id,$event->team_id),['m'=>__METHOD__]);
Log::notice(sprintf('%s:Ignoring Interactive Message [%s]',static::LOGKEY,$event->callback_id),['m'=>__METHOD__]);
Log::info(sprintf('%s:Interactive Message for Callback [%s] User [%s] in [%s]',self::LOGKEY,$event->callback_id,$event->user_id,$event->team_id),['m'=>__METHOD__]);
switch ($event->callback_id) {
default:
Log::notice(sprintf('%s:Unhandled CALLBACK [%s]',self::LOGKEY,$event->callback_id),['m'=>__METHOD__]);
}
}
}

View File

@ -11,7 +11,7 @@ class MessageListener implements ShouldQueue
{
protected const LOGKEY = 'LM-';
public $queue = 'slack';
public $queue = 'high';
/**
* Handle the event.
@ -19,7 +19,7 @@ class MessageListener implements ShouldQueue
* @param Message $event
* @return void
*/
public function handle(Message $event): void
public function handle(Message $event)
{
// Do some magic with event data
Log::info(sprintf('%s:Message event [%s] - subtype [%s]',self::LOGKEY,$event->ts,$event->type),['m'=>__METHOD__]);

View File

@ -11,7 +11,7 @@ class PinAddedListener implements ShouldQueue
{
protected const LOGKEY = 'LPA';
public $queue = 'slack';
public $queue = 'high';
/**
* Handle the event.
@ -19,7 +19,7 @@ class PinAddedListener implements ShouldQueue
* @param PinAdded $event
* @return void
*/
public function handle(PinAdded $event): void
public function handle(PinAdded $event)
{
// Do some magic with event data
Log::info(sprintf('%s:Pin Added to message [%s] in [%s]',self::LOGKEY,$event->ts,$event->channel_id),['m'=>__METHOD__]);

View File

@ -11,7 +11,7 @@ class PinRemovedListener implements ShouldQueue
{
protected const LOGKEY = 'LPR';
public $queue = 'slack';
public $queue = 'high';
/**
* Handle the event.
@ -19,7 +19,7 @@ class PinRemovedListener implements ShouldQueue
* @param PinRemoved $event
* @return void
*/
public function handle(PinRemoved $event): void
public function handle(PinRemoved $event)
{
// Do some magic with event data
Log::info(sprintf('%s:Pin Removed from message [%s] in [%s]',self::LOGKEY,$event->ts,$event->channel_id),['m'=>__METHOD__]);

View File

@ -11,7 +11,7 @@ class ReactionAddedListener implements ShouldQueue
{
protected const LOGKEY = 'LRA';
public $queue = 'slack';
public $queue = 'high';
/**
* Handle the event.
@ -19,10 +19,11 @@ class ReactionAddedListener implements ShouldQueue
* @param ReactionAdded $event
* @return void
*/
public function handle(ReactionAdded $event): void
public function handle(ReactionAdded $event)
{
// Do some magic with event data
Log::info(sprintf('%s:Reaction [%s] added to message in [%s]',self::LOGKEY,$event->reaction,$event->team_id),['m'=>__METHOD__]);
Log::notice(sprintf('%s:Ignoring Reaction Add [%s] on [%s]',static::LOGKEY,$event->reaction,$event->ts),['m'=>__METHOD__]);
Log::debug(sprintf('%s:Ignoring Reaction Add [%s] on [%s]',static::LOGKEY,$event->reaction,$event->ts),['m'=>__METHOD__]);
}
}

View File

@ -2,46 +2,57 @@
namespace Slack\Listeners;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;
use Slack\Blockkit\Blocks\Elements\Text;
use Slack\Blockkit\Blocks\{Header,Section};
use Slack\Blockkit\Modal;
use Slack\Interactive\Shortcut;
use Slack\Message;
class ShortcutListener //implements ShouldQueue
{
protected const LOGKEY = 'LSC';
public $queue = 'slack';
// Block actions arent queued, since slack expects a response to the request
//public $queue = 'high';
/**
* Handle the event.
*
* @param Shortcut $event
* @return void
* @return Message|null
* @throws \Exception
* @todo To Test
*/
public function handle(Shortcut $event): void
public function handle(Shortcut $event): ?Message
{
if (! $event->channel() || ! $event->channel()->active) {
$modal = new Modal(config('app.name'));
$modal = new Modal(Text::item(config('app.name'),'plain_text'));
$modal->addBlock(Header::item(':robot_face: Bot not in this channel'))
->addBlock(Section::item(Text::item('Please add the BOT to this channel and try this again.')));
$modal->addBlock(
Header::item(Text::item(':robot_face: Bot not in this channel','plain_text'))
)
->addBlock(
Section::item(Text::item('Please add the BOT to this channel and try this again.'))
);
try {
$event->team()->slackAPI()->viewOpen($event->trigger_id,$modal);
$event->team()->slackAPI()->viewOpen($event->trigger_id,json_encode($modal));
} catch (\Exception $e) {
Log::error(sprintf('%s:Got an error posting view to slack: %s',static::LOGKEY,$e->getMessage()),['m'=>__METHOD__]);
}
return (new Message)->blank();
}
// Do some magic with event data
Log::info(sprintf('%s:Shortcut [%s] triggered for: [%s]',self::LOGKEY,$event->callback_id,$event->team_id),['m'=>__METHOD__]);
Log::notice(sprintf('%s:Ignoring Shortcut [%s] in team [%s]',static::LOGKEY,$event->callback_id,$event->team_id),['m'=>__METHOD__]);
switch ($event->callback_id) {
default:
Log::notice(sprintf('%s:Unhandled CALLBACK [%s]',self::LOGKEY,$event->callback_id),['m'=>__METHOD__]);
}
}
}

View File

@ -11,7 +11,7 @@ class ViewClosedListener implements ShouldQueue
{
protected const LOGKEY = 'LVC';
public $queue = 'slack';
public $queue = 'high';
/**
* Handle the event.
@ -19,10 +19,14 @@ class ViewClosedListener implements ShouldQueue
* @param ViewClosed $event
* @return void
*/
public function handle(ViewClosed $event): void
public function handle(ViewClosed $event)
{
// Do some magic with event data
Log::info(sprintf('%s:View Closed Callback [%s] User [%s] in [%s]',self::LOGKEY,$event->callback_id,$event->user_id,$event->team_id),['m'=>__METHOD__]);
Log::notice(sprintf('%s:Ignoring View Closed [%s]',static::LOGKEY,$event->callback_id),['m'=>__METHOD__]);
Log::info(sprintf('%s:Block Action for Callback [%s] User [%s] in [%s]',self::LOGKEY,$event->callback_id,$event->user_id,$event->team_id),['m'=>__METHOD__]);
switch ($event->callback_id) {
default:
Log::notice(sprintf('%s:Unhandled CALLBACK [%s]',self::LOGKEY,$event->callback_id),['m'=>__METHOD__]);
}
}
}

View File

@ -11,7 +11,7 @@ class ViewSubmissionListener implements ShouldQueue
{
protected const LOGKEY = 'LVC';
public $queue = 'slack';
public $queue = 'high';
/**
* Handle the event.
@ -19,10 +19,14 @@ class ViewSubmissionListener implements ShouldQueue
* @param ViewSubmission $event
* @return void
*/
public function handle(ViewSubmission $event): void
public function handle(ViewSubmission $event)
{
// Do some magic with event data
Log::info(sprintf('%s:View Submission Callback [%s] User [%s] in [%s]',self::LOGKEY,$event->callback_id,$event->user_id,$event->team_id),['m'=>__METHOD__]);
Log::notice(sprintf('%s:Ignoring View Closed [%s]',static::LOGKEY,$event->callback_id),['m'=>__METHOD__]);
Log::info(sprintf('%s:View Submission for Callback [%s] User [%s] in [%s]',self::LOGKEY,$event->callback_id,$event->user_id,$event->team_id),['m'=>__METHOD__]);
switch ($event->callback_id) {
default:
Log::notice(sprintf('%s:Unhandled CALLBACK [%s]',self::LOGKEY,$event->callback_id),['m'=>__METHOD__]);
}
}
}

View File

@ -7,14 +7,13 @@ use Carbon\CarbonInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Slack\Blockkit\Blocks;
use Slack\Blockkit\Blocks\{Context,Divider,Section};
use Slack\Blockkit\Blocks\Context;
use Slack\Blockkit\Blocks\Elements\Text;
use Slack\Exceptions\{SlackException,SlackSyntaxException};
use Slack\Jobs\{DeleteChat,DeleteResponse};
use Slack\Exceptions\SlackException;
use Slack\Jobs\DeleteChat;
use Slack\Message\Attachment;
use Slack\Models\{Channel,User};
use Slack\Response\Generic;
@ -24,10 +23,9 @@ use Slack\Response\Generic;
*/
final class Message extends BlockKit
{
private const LOGKEY = 'SM-';
protected const LOGKEY = 'SM-';
public const MAX_ATTACHMENTS = 20;
public const MAX_BLOCKS = 50;
private const MAX_ATTACHMENTS = 20;
private Model $o;
private ?Carbon $selfdestruct = NULL;
@ -36,7 +34,7 @@ final class Message extends BlockKit
* Message constructor.
*
* @param Model|null $o Who the message will be to - Channel or User
* @throws \Exception
* @throws SlackException
*/
public function __construct(Model $o=NULL)
{
@ -52,7 +50,7 @@ final class Message extends BlockKit
$this->setUser($o);
} else {
throw new \Exception('Model not handled: '.get_class($o));
throw new SlackException('Model not handled: '.get_class($o));
}
$this->o = $o;
@ -74,9 +72,9 @@ final class Message extends BlockKit
/**
* Add a block to the message
*
* @param Attachment $attachment
* @param Blocks $blocks
* @return Message
* @throws SlackSyntaxException
* @todo to test
*/
public function addAttachment(Attachment $attachment): self
{
@ -86,7 +84,7 @@ final class Message extends BlockKit
$this->attachments->push($attachment);
if (count($this->attachments) > self::MAX_ATTACHMENTS)
throw new SlackSyntaxException(sprintf('Messages should not have more than %d attachments',self::MAX_ATTACHMENTS));
throw new Exception(sprintf('Messages should not have more than %d attachments',self::MAX_ATTACHMENTS));
return $this;
}
@ -98,9 +96,6 @@ final class Message extends BlockKit
$this->blocks->push($block);
if (count($this->blocks) > self::MAX_BLOCKS)
throw new SlackSyntaxException(sprintf('Messages should not have more than %d blocks',self::MAX_BLOCKS));
return $this;
}
@ -111,27 +106,6 @@ final class Message extends BlockKit
return $this;
}
/**
* For messages that we interact with via a response_url
*
* @param bool $bool
* @return Message
*/
public function delete_original(bool $bool=TRUE): self
{
$this->delete_original = $bool;
return $this;
}
// This is a helper method
public function divider(): self
{
$this->blocks->push(Divider::item());
return $this;
}
public function forgetTS(): self
{
$this->_data->forget('ts');
@ -146,7 +120,7 @@ final class Message extends BlockKit
*/
public function isEmpty(): bool
{
return ! $this->jsonSerialize();
return $this->jsonSerialize() ? FALSE : TRUE;
}
/**
@ -155,7 +129,7 @@ final class Message extends BlockKit
public function jsonSerialize()
{
// For interactive messages that generate a dialog, we need to return NULL
return count($this) ? parent::jsonSerialize() : NULL;
return $this->_data->count() ? parent::jsonSerialize() : NULL;
}
/**
@ -170,31 +144,20 @@ final class Message extends BlockKit
if (! $delete && $this->selfdestruct)
$delete = $this->selfdestruct;
if ((! isset($this->o)) || ((! $this->o->team) && (! $this->o->user_team)))
throw new SlackSyntaxException('Message needs to have a user or a channel to work out the team.');
if ($this->_data->has('ephemeral'))
abort('500','Cannot post ephemeral messages.');
$api = $this->o->team ? $this->o->team->slackAPI() : $this->o->user_team->slackAPI();
if ($this->_data->get('blocks') && $this->_data->get('attachments'))
throw new SlackException('Message cannot have blocks and attachments.');
if ($this->ephemeral) {
$response = $api->postEphemeral($this);
} else {
$response = $this->_data->has('ts') ? $api->updateMessage($this) : $api->postMessage($this);
}
$api = $this->o->team->slackAPI();
$response = $this->_data->has('ts') ? $api->updateMessage($this) : $api->postMessage($this);
if ($delete) {
Log::debug(sprintf('%s:Scheduling Delete of [%s:%s] on [%s]',static::LOGKEY,object_get($this->o,'channel_id',$this->o->id),$response->ts,$delete->format('Y-m-d H:i')),['m'=>__METHOD__,'r'=>$response,'message_ts'=>$response->ts]);
Log::debug(sprintf('%s:Scheduling Delete of [%s:%s] on [%s]',static::LOGKEY,object_get($this->o,'channel_id',$this->o->id),$response->ts,$delete->format('Y-m-d')),['m'=>__METHOD__]);
if ($this->o instanceof User) {
Log::error(sprintf('%s:Cannot schedule delete of [%s:%s] on user channels [%s]',static::LOGKEY,object_get($this->o,'channel_id',$this->o->id),$response->ts,$this->o->user_id),['m'=>__METHOD__]);
} elseif ($this->ephemeral) {
Log::error(sprintf('%s:Ignoring delete of [%s:%s] on ephemeral messages',static::LOGKEY,object_get($this->o,'channel_id',$this->o->id),$response->ts),['m'=>__METHOD__]);
} else {
// Queue the delete of the message if requested
dispatch((new DeleteChat($this->o,$response->ts))->onQueue('slack')->delay($delete));
}
// Queue the delete of the message if requested
dispatch((new DeleteChat($this->o,$response->ts))->onQueue('low')->delay($delete));
}
return $response;
@ -205,21 +168,24 @@ final class Message extends BlockKit
*
* @note This URL can only be used 5 times in 30 minutes
* @param string $url
* @param Carbon|null $delete
* @return object
* @return string
* @throws SlackException
*/
public function respond(string $url,Carbon $delete=NULL): object
public function respond(string $url)
{
if (! $delete && $this->selfdestruct)
$delete = $this->selfdestruct;
$request = curl_init();
$http = Http::acceptJson();
$http->withBody(json_encode($this),'application/json');
curl_setopt($request,CURLOPT_URL,$url);
curl_setopt($request,CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($request,CURLINFO_HEADER_OUT,TRUE);
curl_setopt($request,CURLOPT_HTTPHEADER,['Content-Type: application/json; charset=utf-8']);
curl_setopt($request,CURLOPT_SSL_VERIFYPEER,FALSE);
curl_setopt($request,CURLOPT_POSTFIELDS,json_encode($this));
try {
$request = $http->post($url)->throw();
$response = $request->object();
$result = curl_exec($request);
if (! $result)
throw new \Exception('CURL exec returned an empty response: '.serialize(curl_getinfo($request)));
} catch (\Exception $e) {
Log::error(sprintf('%s:Got an error while posting to [%s] (%s)',static::LOGKEY,$url,$e->getMessage()),['m'=>__METHOD__]);
@ -227,19 +193,16 @@ final class Message extends BlockKit
throw new \Exception($e->getMessage());
}
if (! $response->ok) {
Log::critical(sprintf('%s:Generic Error',static::LOGKEY),['m'=>__METHOD__,'r'=>$response]);
throw new SlackException(serialize($response),$request->status());
if ($result !== 'ok') {
switch ($result) {
default:
Log::critical(sprintf('%s:Generic Error',static::LOGKEY),['m'=>__METHOD__,'r'=>$result]);
throw new SlackException($result,curl_getinfo($request,CURLINFO_HTTP_CODE));
}
}
if ($delete) {
Log::debug(sprintf('%s:Scheduling Delete of [%s:%s] on [%s]',static::LOGKEY,object_get($this->o,'channel_id',$this->o->id),$url,$delete->format('Y-m-d')),['m'=>__METHOD__]);
// Queue the delete of the response if requested
dispatch((new DeleteResponse($url))->onQueue('slack')->delay($delete));
}
return $response;
curl_close($request);
return $result;
}
/**
@ -263,7 +226,6 @@ final class Message extends BlockKit
*
* @param Carbon $time
* @return Message
* @throws SlackSyntaxException
*/
public function selfdestruct(Carbon $time): self
{
@ -274,7 +236,6 @@ final class Message extends BlockKit
);
$this->selfdestruct = $time;
return $this;
}
@ -306,18 +267,11 @@ final class Message extends BlockKit
return $this;
}
// This is a helper method
public function spacer(): self
{
$this->blocks->push(Section::item(Text::item(' ')));
return $this;
}
/* CONFIGURATION METHODS */
/**
* @return Message
* @todo - Check this is a valid option
*/
public function ephemeral(): self
{
@ -354,10 +308,8 @@ final class Message extends BlockKit
}
/**
* Replace the original message
*
* @param bool $bool
* @return Message
* @todo - Check this is a valid option
*/
public function replace_original(bool $bool=TRUE): self
{
@ -418,29 +370,84 @@ final class Message extends BlockKit
return $this;
}
/**
* Post the message to user
*
* @param string $user
* @return $this
*/
public function user(string $user): self
{
$this->user = $user;
return $this;
}
/**
* Set bot username (used with as_user)
*
* @param string $user
* @return $this
*/
public function username(string $user): self
{
$this->username = $user;
return $this;
}
/**
* Add an attachment to a message
*
* @param Attachment $attachments
* @return Message
* @deprecated use addAttachment()
*/
public function setAttachments(Attachment $attachments): self
{
$this->_data->put('attachments',[$attachments]);
return $this;
}
/**
* Add blocks to the message
*
* @param Blocks $blocks
* @return Message
* @throws \Exception
* @deprecated use addBlocks()
*/
public function setBlocks(Blocks $blocks): self
{
if ($this->blocks->count())
throw new \Exception('Blocks already defined');
$this->blocks = $blocks;
return $this;
}
/**
* Message text
*
* @param string $string
* @return Message
* @deprecated use text()
*/
public function setText(string $string): self
{
$this->text = $string;
return $this;
}
/**
* Set the timestamp, used when replacing messages
*
* @param string $string
* @return Message
* @deprecated use ts()
*/
public function setTS(string $string): self
{
$this->_data->put('ts',$string);
return $this;
}
/**
* Set the thread timestamp, used when adding a threaded response
*
* @param string $string
* @return Message
* @deprecated use thead_ts()
*/
public function setThreadTS(string $string): self
{
$this->_data->put('thread_ts',$string);
return $this;
}
}

View File

@ -2,6 +2,7 @@
namespace Slack\Message;
use \Exception;
use Illuminate\Support\Arr;
use Slack\BlockKit;
@ -9,7 +10,7 @@ use Slack\Blockkit\Blocks;
final class Attachment extends BlockKit
{
public const LIMITS = [
protected const LIMITS = [
'footer' => 300,
];

View File

@ -4,11 +4,10 @@ namespace Slack\Message;
use Slack\BlockKit;
use Slack\Blockkit\Blocks\Elements\Text;
use Slack\Exceptions\SlackSyntaxException;
/**
* Class MessageAttachmentAction - Slack Message Attachments Actions
* Represents a Single Action for a Slack Message Attachment
* Represents an Single Action for a Slack Message Attachment
*
* @package App\Slack\Message
* @note These are now legacy - use blocks instead
@ -16,14 +15,14 @@ use Slack\Exceptions\SlackSyntaxException;
*/
final class AttachmentAction extends BlockKit
{
public const LIMITS = [
protected const LIMITS = [
'text' => 30,
'value' => 2000,
];
public const DATA_SOURCES = ['static','users','channels','conversastions','external'];
public const STYLES = ['default','danger','primary'];
public const TYPES = ['button','select'];
private const DATA_SOURCES = ['static','users','channels','conversastions','external'];
private const STYLES = ['default','danger','primary'];
private const TYPES = ['button','select'];
// @todo options
// @todo option_groups
@ -34,7 +33,7 @@ final class AttachmentAction extends BlockKit
parent::__construct();
if (! in_array($type,self::TYPES))
throw new SlackSyntaxException(sprintf('Type [%s] not valid',$type));
throw new Exception(sprintf('Type [%s] not valid',$type));
$this->type = $type;
switch ($type) {
@ -81,7 +80,7 @@ final class AttachmentAction extends BlockKit
public function data_source(string $string): self
{
if (! in_array($string,self::DATA_SOURCES))
throw new SlackSyntaxException(sprintf('Type [%s] not valid',$string));
throw new Exception(sprintf('Type [%s] not valid',$string));
$this->data_source = $string;
@ -98,14 +97,13 @@ final class AttachmentAction extends BlockKit
/**
* Set the text displayed in the action
*
* @param string $string
* @param string $type
* @return $this
* @throws SlackSyntaxException
*/
public function style(string $string): self
{
if (! in_array($string,self::STYLES))
throw new SlackSyntaxException(sprintf('Type [%s] not valid',$string));
throw new Exception(sprintf('Type [%s] not valid',$string));
$this->style = $string;
@ -117,7 +115,6 @@ final class AttachmentAction extends BlockKit
*
* @param string $string
* @return $this
* @throws SlackSyntaxException
*/
public function value(string $string): self
{

View File

@ -4,9 +4,9 @@ namespace Slack\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Slack\Traits\ScopeActive;
use App\Models\Slack\Team as AppTeam;
use Slack\Traits\ScopeActive;
class Channel extends Model
{

View File

@ -14,7 +14,7 @@ class Team extends Model
{
use ScopeActive;
protected $fillable = ['team_id','active'];
protected $fillable = ['team_id'];
protected $table = 'slack_teams';
/* RELATIONS */

View File

@ -61,6 +61,8 @@ class User extends Model
*/
public function getUserTeamAttribute(): ?Team
{
Log::debug(sprintf('%s:User [%s], Team [%s], Enterprise [%s]',self::LOGKEY,$this->id,$this->team_id,$this->enterprise_id),['m'=>__METHOD__]);
return $this->team_id ? $this->team : (($x=$this->enterprise->teams) ? $x->first() : NULL);
}

View File

@ -2,24 +2,20 @@
namespace Slack\Options;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Slack\Base as SlackBase;
use Slack\Exceptions\SlackException;
use Slack\Message;
abstract class Base extends SlackBase
{
private const LOGKEY = 'SOb';
// Does the event respond with a reply to the HTTP request, or via a post with a trigger
// Child class should have a respond() function.
// (There should be a local implementation of the child class should respondNow = TRUE)
public $respondNow = FALSE;
public $respondNow = TRUE;
public function __construct(array $request)
{
Log::info(sprintf('%s:Slack INTERACTIVE MESSAGE Initialised [%s]',self::LOGKEY,get_class($this)),['m'=>__METHOD__]);
Log::info(sprintf('SOb:Slack INTERACTIVE MESSAGE Initialised [%s]',get_class($this)),['m'=>__METHOD__]);
// Our data is in a payload value
parent::__construct($request);
@ -36,42 +32,22 @@ abstract class Base extends SlackBase
* + user_id
* @param string $key
* @return mixed|object
* @throws \Exception
*/
public function __get(string $key)
{
switch ($key) {
case 'channel_id':
return object_get($this->_data,'channel.id');
case 'enterprise_id':
return object_get($this->_data,'team.'.$key);
case 'team_id':
return object_get($this->_data,'team.id');
case 'channel_id':
return object_get($this->_data,'channel.id');
case 'user_id':
return object_get($this->_data,'user.id');
case 'callback_key':
return $this->keyitem('id',$this->callback_id);
case 'callback_value':
return $this->keyitem('value',$this->callback_id);
case 'callback_id':
//case 'action_ts':
//case 'message_ts':
case 'type':
return object_get($this->_data,$key);
default:
throw new SlackException('Unknown key: '.$key);
}
}
/**
* Interactive messages can return their output in the incoming HTTP post.
* This function should be overwritten in the parent class, and finish by calling return Message::blank();
*
* @return Message
*/
abstract public function respond(): Message;
}

View File

@ -1,147 +0,0 @@
<?php
namespace Slack\Options;
use Illuminate\Support\Facades\Log;
use Slack\Message;
/**
* Class BlockSuggestion
(
[type] => block_suggestion
[user] => stdClass Object
(
[id] => U01QF1B0Y6B
[username] => deon
[name] => deon
[team_id] => T01QF14NSQP
)
[container] => stdClass Object
(
[type] => view
[view_id] => V034715K8GP
)
[api_app_id] => A4TCZ007N
[token] => Oow8S2EFvrZoS9z8N4nwf9Jo
[action_id] => system_include_brand
[block_id] => YME
[value] => abcdde
[team] => stdClass Object
(
[id] => T01QF14NSQP
[domain] => els953a-1
[enterprise_id] => E01R1P48JCU
[enterprise_name] => Leenooks Enteprise A
)
[enterprise] => stdClass Object
(
[id] => E01R1P48JCU
[name] => Leenooks Enteprise A
)
[is_enterprise_install] =>
[view] => stdClass Object
(
[id] => V034715K8GP
[team_id] => T01QF14NSQP
[type] => modal
[blocks] => Array
(
[0] => stdClass Object
(
[type] => section
[block_id] => YME
[text] => stdClass Object
(
[type] => mrkdwn
[text] => Select Brands:
[verbatim] =>
)
[accessory] => stdClass Object
(
[type] => multi_external_select
[action_id] => system_include_brand
[initial_options] => Array
(
)
[placeholder] => stdClass Object
(
[type] => plain_text
[text] => select...
[emoji] => 1
)
)
)
)
[private_metadata] =>
[callback_id] =>
[state] => stdClass Object
(
[values] => stdClass Object
(
[YME] => stdClass Object
(
[system_include_brand] => stdClass Object
(
[type] => multi_external_select
[selected_options] => Array
(
)
)
)
)
)
[hash] => 1645768594.IO10vEq1
[title] => stdClass Object
(
[type] => plain_text
[text] => Configure brands
[emoji] => 1
)
[clear_on_close] =>
[notify_on_close] =>
[close] =>
[submit] =>
[previous_view_id] =>
[root_view_id] => V034715K8GP
[app_id] => A4TCZ007N
[external_id] =>
[app_installed_team_id] => T01QF14NSQP
[bot_id] => B01RKPRAT0Q
)
)
*/
abstract class BlockSuggestion extends Base
{
protected const LOGKEY = 'OIM';
public function __get($key)
{
switch ($key) {
case 'action_id':
case 'value':
return object_get($this->_data,$key);
case 'callback_id':
return object_get($this->_data,'view.'.$key);
default:
return parent::__get($key);
}
}
}

View File

@ -2,39 +2,37 @@
namespace Slack\Options;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Log;
use Slack\Client\Payload;
use Slack\Interactive\Unknown;
class Factory {
protected const LOGKEY = 'SOf';
private const LOGKEY = 'SOf';
/**
* @var array event type to event class mapping
*/
public const map = [
'block_suggestion' => BlockSuggestion::class,
'interactive_message' => InteractiveMessage::class,
//'interactive_message' => InteractiveMessage::class,
];
/**
* Returns new event instance
*
* @param string $type
* @param array $request
* @param string $type
* @param Request $request
* @return Base
* @note Options classes must be defined in the calling application and extend these self::map abstract classes
* otherwise errors will be thrown
*/
public static function create(string $type,array $request)
{
$class = Arr::get(config('slack.options',self::map),$type,Unknown::class);
Log::debug(sprintf('%s:Working out Interactive Options Event Class for [%s] as [%s]',static::LOGKEY,$type,$class),['m'=>__METHOD__]);
if (App::environment() == 'local')
file_put_contents('/tmp/option.'.$type,print_r($request,TRUE));
if (App::environment() == 'dev')
file_put_contents('/tmp/option.'.$type,print_r(json_decode($request->input('payload')),TRUE));
return new $class($request);
}

View File

@ -33,7 +33,7 @@ use Slack\Message;
* [attachment_id] => 3
* [token] => Oow8S2EFvrZoS9z8N4nwf9Jo
*/
abstract class InteractiveMessage extends Base
class InteractiveMessage extends Base
{
protected const LOGKEY = 'OIM';
@ -49,4 +49,25 @@ abstract class InteractiveMessage extends Base
return parent::__get($key);
}
}
/**
* Interactive messages can return their output in the incoming HTTP post
*
* @return Message
* @throws \Exception
*/
public function respond(): Message
{
Log::info(sprintf('%s:Interactive Option - Callback [%s] Name [%s] Value [%s]',static::LOGKEY,$this->callback_id,$this->name,$this->value),['m'=>__METHOD__]);
if (preg_match('/^(.*)\|([0-9]+)/',$this->callback_id)) {
[$action,$id] = explode('|',$this->callback_id,2);
} else {
// If we get here, its an action that we dont know about.
Log::notice(sprintf('%s:Unhandled CALLBACK [%s]',static::LOGKEY,$this->callback_id),['m'=>__METHOD__]);
}
return (new Message)->blank();
}
}

View File

@ -4,35 +4,17 @@ namespace Slack\Options;
use Illuminate\Support\Facades\Log;
use Slack\Message;
/**
* Catch all unknown slack event that we havent specifically programmed for.
*
* @package Slack\Options
*/
final class Unknown extends Base
class Unknown extends Base
{
protected const LOGKEY = 'OU-';
public function __construct(array $request)
{
Log::notice(sprintf('SOU:UNKNOWN Slack Interaction Option received [%s]',get_class($this)),['m'=>__METHOD__]);
parent::__construct($request);
}
/**
* Interactive messages can return their output in the incoming HTTP post
*
* @return Message
*/
public function respond(): Message
{
Log::info(sprintf('%s:Unknown Option - Callback [%s] Name [%s] Value [%s]',static::LOGKEY,$this->callback_id,$this->name,$this->value),['m'=>__METHOD__]);
Log::notice(sprintf('%s:Unhandled CALLBACK [%s]',static::LOGKEY,$this->callback_id),['m'=>__METHOD__]);
return Message::blank();
}
}

View File

@ -10,6 +10,9 @@ use Slack\API;
use Slack\Channels\SlackBotChannel;
use Slack\Console\Commands\SlackSocketClient;
/**
* @todo For Lumen installs, this service provider is not required?
*/
class SlackServiceProvider extends ServiceProvider
{
/**

View File

@ -12,9 +12,9 @@ use Slack\Base as SlackBase;
*
* @note: This class is used for events not specifically created.
*/
abstract class Base extends SlackBase implements \JsonSerializable
class Base extends SlackBase implements \JsonSerializable
{
private const LOGKEY = 'RB-';
protected const LOGKEY = 'RB-';
/**
* Default Constructor Setup
@ -29,7 +29,7 @@ abstract class Base extends SlackBase implements \JsonSerializable
if (get_class($this) == Base::class) {
Log::debug(sprintf('%s:Slack RESPONSE Initialised [%s]',static::LOGKEY,get_class($this)),['m'=>__METHOD__]);
if (App::environment() == 'local')
if (App::environment() == 'dev')
file_put_contents('/tmp/response',print_r($this,TRUE),FILE_APPEND);
}
}
@ -55,9 +55,8 @@ abstract class Base extends SlackBase implements \JsonSerializable
case 'scheduled_messages': // Used by scheduledMessagesList()
return collect(object_get($this->_data,$key));
case 'ts':
return object_get($this->_data,$key) ?: object_get($this->_data,'message_ts');
case 'team_id':
case 'ts':
case 'user_id':
case 'type': // Needed by URL verification
return object_get($this->_data,$key);

View File

@ -4,7 +4,7 @@ namespace Slack\Response;
final class ChannelList extends Base
{
private const LOGKEY = 'RCL';
protected const LOGKEY = 'RCL';
/**
* Enable getting values for keys in the response

View File

@ -8,9 +8,9 @@ use Illuminate\Support\Collection;
/**
* This is a Slack Response from a GetHistory API call which is a message Chat
*/
final class Chat extends Base
class Chat extends Base
{
private const LOGKEY = 'RC-';
protected const LOGKEY = 'RC-';
/**
* Enable getting values for keys in the response

View File

@ -5,9 +5,9 @@ namespace Slack\Response;
/**
* This is a Generic Slack Response to API calls
*/
final class Generic extends Base
class Generic extends Base
{
private const LOGKEY = 'RGE';
protected const LOGKEY = 'RGE';
/**
* Enable getting values for keys in the response

View File

@ -9,7 +9,7 @@ namespace Slack\Response;
*/
final class Team extends Base
{
private const LOGKEY = 'RT_';
protected const LOGKEY = 'RT_';
/**
* Enable getting values for keys in the response

View File

@ -5,9 +5,9 @@ namespace Slack\Response;
/**
* This is the Slack Response to an Auth Test API call
*/
final class Test extends Base
class Test extends Base
{
private const LOGKEY = 'RTE';
protected const LOGKEY = 'RTE';
/**
* Enable getting values for keys in the response

View File

@ -9,7 +9,7 @@ namespace Slack\Response;
*/
final class User extends Base
{
private const LOGKEY = 'RU_';
protected const LOGKEY = 'RU_';
/**
* Enable getting values for keys in the response