1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace FondBot\Foundation\Listeners; |
6
|
|
|
|
7
|
|
|
use FondBot\FondBot; |
8
|
|
|
use FondBot\Conversation\Context; |
9
|
|
|
use FondBot\Events\MessageReceived; |
10
|
|
|
use FondBot\Conversation\ConversationManager; |
11
|
|
|
use Illuminate\Foundation\Bus\DispatchesJobs; |
12
|
|
|
|
13
|
|
|
class HandleConversation |
14
|
|
|
{ |
15
|
|
|
use DispatchesJobs; |
16
|
|
|
|
17
|
|
|
private $kernel; |
18
|
|
|
private $conversationManager; |
19
|
|
|
|
20
|
|
|
public function __construct(FondBot $kernel, ConversationManager $conversationManager) |
21
|
|
|
{ |
22
|
|
|
$this->kernel = $kernel; |
23
|
|
|
$this->conversationManager = $conversationManager; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
public function handle(MessageReceived $messageReceived): void |
27
|
|
|
{ |
28
|
|
|
/** @var Context $context */ |
29
|
|
|
$context = $this->conversationManager->resolveContext( |
30
|
|
|
$this->kernel->getChannel(), |
31
|
|
|
$messageReceived->getChat(), |
32
|
|
|
$messageReceived->getFrom() |
33
|
|
|
); |
34
|
|
|
|
35
|
|
|
// If there is no interaction in session |
36
|
|
|
// Try to match intent and run it |
37
|
|
|
// Otherwise, run interaction |
38
|
|
|
if (!$this->isInConversation($context)) { |
39
|
|
|
$conversable = $this->conversationManager->matchIntent($messageReceived); |
40
|
|
|
} else { |
41
|
|
|
$conversable = $context->getInteraction(); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
$this->conversationManager->setReceivedMessage($messageReceived); |
45
|
|
|
$this->conversationManager->converse($conversable); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* Determine if conversation started. |
50
|
|
|
* |
51
|
|
|
* @param Context $context |
52
|
|
|
* |
53
|
|
|
* @return bool |
54
|
|
|
*/ |
55
|
|
|
private function isInConversation(Context $context): bool |
56
|
|
|
{ |
57
|
|
|
return $context->getInteraction() !== null; |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|