yourtar-cli 2.0.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -16,10 +16,10 @@ DATABASE_HOST=mysql_{{name}}_back
16
16
  CORS_ALLOW_ORIGIN=^https?://(localhost|127\.0\.0\.1)(:[0-9]+)?$
17
17
  ###< nelmio/cors-bundle ###
18
18
 
19
- DEFAULT_URI="http://localhost:8000"
19
+ DEFAULT_URI=http://localhost:8000
20
20
 
21
21
  ###> Bot ###
22
- #TG_TOKEN=475749278:AAGxVLFFGiuymbuQYz-oHF_OoOIZhyxClA4
23
- #VK_TOKEN=475749278:AAGxVLFFGiuymbuQYz-oHF_OoOIZhyxClA4
24
- #MAX_TOKEN=475749278:AAGxVLFFGiuymbuQYz-oHF_OoOIZhyxClA4
22
+ #TG_TOKEN=7590949811:AAEg62uBqmOMaatJXUaQueSnqRLujdokWNE
23
+ #VK_TOKEN=vk1.a.59H83PysK2tYXqAjWD1ZrSAPBht8B4cAiNmYfY_LHPuOgNnmcTBEEz_UHIOKu4k2zESyFHDKGAi4NJQAOztVbU5b3508ytakCGjRiGmpr5dUXrNMbGnSkHZW5uBVfHTGvYBwEjbBMQUP2SJkEXITDpUqluH5FCHCBn_b7DnarRs41QtKA_sEgsWQROJLRoNVZTvxcH4bL48BYkgldQ51lA
24
+ #MAX_TOKEN=f9LHodD0cOKr6uAZuM3uWU41JlGYUiPuRMBhWDYbj_hz_bVxQVCbbgG0vP6p2eeu5OmX7EOYHnFGPCxUaJKz
25
25
  ###< Bot ###
@@ -16,10 +16,10 @@ DATABASE_HOST=mysql_{{name}}_back
16
16
  CORS_ALLOW_ORIGIN=^https?://(localhost|127\.0\.0\.1)(:[0-9]+)?$
17
17
  ###< nelmio/cors-bundle ###
18
18
 
19
- DEFAULT_URI="http://localhost:8000"
19
+ DEFAULT_URI=http://localhost:8000
20
20
 
21
21
  ###> Bot ###
22
- #TG_TOKEN=475749278:AAGxVLFFGiuymbuQYz-oHF_OoOIZhyxClA4
23
- #VK_TOKEN=475749278:AAGxVLFFGiuymbuQYz-oHF_OoOIZhyxClA4
24
- #MAX_TOKEN=475749278:AAGxVLFFGiuymbuQYz-oHF_OoOIZhyxClA4
22
+ #TG_TOKEN=7590949811:AAEg62uBqmOMaatJXUaQueSnqRLujdokWNE
23
+ #VK_TOKEN=vk1.a.59H83PysK2tYXqAjWD1ZrSAPBht8B4cAiNmYfY_LHPuOgNnmcTBEEz_UHIOKu4k2zESyFHDKGAi4NJQAOztVbU5b3508ytakCGjRiGmpr5dUXrNMbGnSkHZW5uBVfHTGvYBwEjbBMQUP2SJkEXITDpUqluH5FCHCBn_b7DnarRs41QtKA_sEgsWQROJLRoNVZTvxcH4bL48BYkgldQ51lA
24
+ #MAX_TOKEN=f9LHodD0cOKr6uAZuM3uWU41JlGYUiPuRMBhWDYbj_hz_bVxQVCbbgG0vP6p2eeu5OmX7EOYHnFGPCxUaJKz
25
25
  ###< Bot ###
@@ -16,10 +16,10 @@ DATABASE_HOST=mysql_{{name}}_back
16
16
  CORS_ALLOW_ORIGIN=^https?://(localhost|127\.0\.0\.1)(:[0-9]+)?$
17
17
  ###< nelmio/cors-bundle ###
18
18
 
19
- DEFAULT_URI="http://localhost:8000"
19
+ DEFAULT_URI=http://localhost:8000
20
20
 
21
21
  ###> Bot ###
22
- #TG_TOKEN=475749278:AAGxVLFFGiuymbuQYz-oHF_OoOIZhyxClA4
23
- #VK_TOKEN=475749278:AAGxVLFFGiuymbuQYz-oHF_OoOIZhyxClA4
24
- #MAX_TOKEN=475749278:AAGxVLFFGiuymbuQYz-oHF_OoOIZhyxClA4
22
+ #TG_TOKEN=7590949811:AAEg62uBqmOMaatJXUaQueSnqRLujdokWNE
23
+ #VK_TOKEN=vk1.a.59H83PysK2tYXqAjWD1ZrSAPBht8B4cAiNmYfY_LHPuOgNnmcTBEEz_UHIOKu4k2zESyFHDKGAi4NJQAOztVbU5b3508ytakCGjRiGmpr5dUXrNMbGnSkHZW5uBVfHTGvYBwEjbBMQUP2SJkEXITDpUqluH5FCHCBn_b7DnarRs41QtKA_sEgsWQROJLRoNVZTvxcH4bL48BYkgldQ51lA
24
+ #MAX_TOKEN=f9LHodD0cOKr6uAZuM3uWU41JlGYUiPuRMBhWDYbj_hz_bVxQVCbbgG0vP6p2eeu5OmX7EOYHnFGPCxUaJKz
25
25
  ###< Bot ###
@@ -42,7 +42,7 @@ commands:
42
42
 
43
43
  webhook:
44
44
  ifndef TG_TOKEN
45
- curl https://api.telegram.org:443/bot$(TG_TOKEN)/setWebhook?url=$(DEFAULT_URI)/api/message/
45
+ curl https://api.telegram.org:443/bot$(TG_TOKEN)/setWebhook?url=$(DEFAULT_URI)/api/message/tg
46
46
  endif
47
47
  ifndef MAX_TOKEN
48
48
  curl -X POST "https://platform-api.max.ru/subscriptions" -H "Authorization: $(MAX_TOKEN)" -H "Content-Type: application/json" -d '{"url": "$(DEFAULT_URI)/api/message/max","update_types": ["message_created", "bot_started", "message_callback"],"secret": "your_secret"}'
@@ -2,19 +2,15 @@
2
2
 
3
3
  namespace App\Controller;
4
4
 
5
- use App\Entity\Chat;
6
- use App\Entity\Lead;
7
- use App\Entity\Token;
8
- use App\Repository\ChatRepository;
9
- use App\Repository\PaymentRepository;
10
- use App\Repository\TokenRepository;
11
5
  use App\Service\MessageProcessService;
12
- use App\Service\TelegramService;
6
+ use App\Service\MessengerService\MaxService;
7
+ use App\Service\MessengerService\TelegramService;
8
+ use App\Service\MessengerService\VkService;
13
9
  use Psr\Log\LoggerInterface;
14
- use Doctrine\ORM\EntityManagerInterface;
15
10
  use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
16
11
  use Symfony\Component\HttpFoundation\JsonResponse;
17
12
  use Symfony\Component\HttpFoundation\Request;
13
+ use Symfony\Component\HttpFoundation\Response;
18
14
  use Symfony\Component\Routing\Attribute\Route;
19
15
 
20
16
  #[Route('/api/message')]
@@ -26,14 +22,81 @@ final class MessageController extends AbstractController
26
22
  {
27
23
  $this->messageService = $messageService;
28
24
  }
29
-
30
- #[Route('/', name: 'app_message_webhook')]
25
+
26
+ #[Route('/tg', name: 'app_message_webhook_tg')]
31
27
  public function index(Request $request): JsonResponse
32
28
  {
33
29
  $value = json_decode($request->getContent(), true);
34
30
 
35
- $this->messageService->processMessage($value);
31
+ $result = $this->messageService->processMessage(new TelegramService()->normalizeMessage($value));
32
+ if (!$result) return $this->json(['error' => true], 500);
33
+
34
+ return $this->json(['message' => 'OK',]);
35
+ }
36
+
37
+ // #[Route('/tg/{id}', name: 'app_message_webhook_tg_for_bot')]
38
+ // public function tgWebhookForOrg($id, Request $request): JsonResponse
39
+ // {
40
+ // $value = json_decode($request->getContent(), true);
41
+ //
42
+ // //TODO: доделать для бота
43
+ // $result = $this->messageService->processMessage(new TelegramService()->normalizeMessage($value));
44
+ // if (!$result) return $this->json(['error' => true], 500);
45
+ //
46
+ // return $this->json(['message' => 'OK',]);
47
+ // }
48
+
49
+ #[Route('/vk', name: 'app_message_webhook_vk', methods: 'post')]
50
+ public function vkWebhook(Request $request, LoggerInterface $logger)
51
+ {
52
+ $data = json_decode($request->getContent(), true);
53
+ $logger->error('VK: ' . $request->getContent());
54
+
55
+ if (array_key_exists('type', $data) && ($data['type'] === 'message_new' || $data['type'] === 'message_event')) {
56
+ $result = $this->messageService->processMessage(new VkService()->normalizeMessage($data));
57
+ if (!$result) return $this->json(['error' => true], 500);
58
+ }
59
+
60
+ if ($data['type'] === 'confirmation') return new Response('8e9b12dd');
61
+ return new Response('ok');
62
+ }
63
+
64
+ // #[Route('/vk/{id}', name: 'app_message_webhook_vk_for_bot', methods: 'post')]
65
+ // public function vkWebhookForBot($id, Request $request)
66
+ // {
67
+ // $data = json_decode($request->getContent(), true);
68
+ //
69
+ // //TODO: доделать для бота
70
+ // if (array_key_exists('type', $data) && ($data['type'] === 'message_new' || $data['type'] === 'message_event')) {
71
+ // $result = $this->messageService->processMessage(new VkService()->normalizeMessage($data));
72
+ // if (!$result) return $this->json(['error' => true], 500);
73
+ // }
74
+ //
75
+ // if ($data['type'] === 'confirmation') return new Response('b852d1d2');
76
+ // return new Response('ok');
77
+ // }
78
+
79
+ #[Route('/max', name: 'app_message_webhook_max')]
80
+ public function max(Request $request, LoggerInterface $logger): JsonResponse
81
+ {
82
+ $data = json_decode($request->getContent(), true);
83
+ // $logger->error('LOG MES ' . $request->getContent());
84
+ $data = new MaxService()->normalizeMessage($data);
85
+ $result = $this->messageService->processMessage($data);
86
+ if (!$result) return $this->json(['error' => true], 500);
36
87
 
37
88
  return $this->json(['message' => 'OK',]);
38
89
  }
90
+
91
+ // #[Route('/max', name: 'app_message_webhook_max_for_bot')]
92
+ // public function maxForBot(Request $request): JsonResponse
93
+ // {
94
+ // $data = json_decode($request->getContent(), true);
95
+ // //TODO: доделать для бота
96
+ // $data = new MaxService()->normalizeData($data);
97
+ // $result = $this->messageService->processMessage($data);
98
+ // if (!$result) return $this->json(['error' => true], 500);
99
+ //
100
+ // return $this->json(['message' => 'OK',]);
101
+ // }
39
102
  }
@@ -3,13 +3,18 @@
3
3
  namespace App\Entity;
4
4
 
5
5
  use App\Repository\ChatRepository;
6
+ use App\Service\MessengerService\MaxService;
7
+ use App\Service\MessengerService\TelegramService;
8
+ use App\Service\MessengerService\VkService;
6
9
  use Doctrine\DBAL\Types\Types;
7
10
  use Doctrine\ORM\Mapping as ORM;
8
11
 
9
12
  #[ORM\Entity(repositoryClass: ChatRepository::class)]
10
13
  class Chat
11
14
  {
12
-
15
+ public const TYPE_TG = 'telegram';
16
+ public const TYPE_VK = 'vkontakte';
17
+ public const TYPE_MAX = 'max';
13
18
  public const ROLE_ADMIN = 'admin';
14
19
 
15
20
  #[ORM\Id]
@@ -20,18 +25,22 @@ class Chat
20
25
  #[ORM\Column(length: 255)]
21
26
  private ?string $chatId = null;
22
27
 
23
- #[ORM\Column(length: 255)]
28
+ #[ORM\Column(name: 'messenger_user_id', length: 255)]
24
29
  private ?string $userId = null;
25
30
 
26
- #[ORM\Column(length: 255, nullable: true)]
27
- private ?string $role = null;
28
-
29
31
  #[ORM\Column(length: 255, nullable: true)]
30
32
  private ?string $username = null;
31
33
 
32
34
  #[ORM\Column(length: 255, nullable: true)]
33
35
  private ?string $phone = null;
34
36
 
37
+ #[ORM\Column(length: 255)]
38
+ private ?string $type = null;
39
+
40
+ #[ORM\ManyToOne(inversedBy: 'chats')]
41
+ #[ORM\JoinColumn(nullable: false)]
42
+ private ?User $user = null;
43
+
35
44
  public function getId(): ?int
36
45
  {
37
46
  return $this->id;
@@ -61,51 +70,56 @@ class Chat
61
70
  return $this;
62
71
  }
63
72
 
64
- public function getRole(): ?string
73
+ public function getUsername(): ?string
65
74
  {
66
- return $this->role;
75
+ return $this->username;
67
76
  }
68
77
 
69
- public function getRoleName(): ?string
78
+ public function setUsername(?string $username): static
70
79
  {
71
- $role = 'Роль отсутствует!';
80
+ $this->username = $username;
72
81
 
73
- switch ($this->role) {
74
- case self::ROLE_ADMIN:
75
- $role = 'Администратор (может все)';
76
- break;
77
- }
82
+ return $this;
83
+ }
78
84
 
79
- return $role;
85
+ public function getPhone(): ?string
86
+ {
87
+ return $this->phone;
80
88
  }
81
89
 
82
- public function setRole(?string $role): static
90
+ public function setPhone(?string $phone): static
83
91
  {
84
- $this->role = $role;
92
+ $this->phone = $phone;
85
93
 
86
94
  return $this;
87
95
  }
88
96
 
89
- public function getUsername(): ?string
97
+ public function getMessenger() {
98
+ if ($this->type === self::TYPE_MAX) return new MaxService($this);
99
+ if ($this->type === self::TYPE_VK) return new VkService($this);
100
+ if ($this->type === self::TYPE_TG) return new TelegramService($this);
101
+ }
102
+
103
+ public function getType(): ?string
90
104
  {
91
- return $this->username;
105
+ return $this->type;
92
106
  }
93
107
 
94
- public function setUsername(?string $username): static
108
+ public function setType(string $type): static
95
109
  {
96
- $this->username = $username;
110
+ $this->type = $type;
97
111
 
98
112
  return $this;
99
113
  }
100
114
 
101
- public function getPhone(): ?string
115
+ public function getUser(): ?User
102
116
  {
103
- return $this->phone;
117
+ return $this->user;
104
118
  }
105
119
 
106
- public function setPhone(?string $phone): static
120
+ public function setUser(?User $user): static
107
121
  {
108
- $this->phone = $phone;
122
+ $this->user = $user;
109
123
 
110
124
  return $this;
111
125
  }
@@ -18,7 +18,7 @@ class DialogContext
18
18
  #[ORM\JoinColumn(nullable: false)]
19
19
  private ?Chat $chat = null;
20
20
 
21
- #[ORM\Column(type: Types::SIMPLE_ARRAY)]
21
+ #[ORM\Column(type: Types::JSON)]
22
22
  private array $context = [];
23
23
 
24
24
  public function getId(): ?int
@@ -49,35 +49,4 @@ class DialogContext
49
49
 
50
50
  return $this;
51
51
  }
52
-
53
- public function getNextMessage($order = null):array
54
- {
55
- $result = array('message' => '', 'buttons' => array());
56
-
57
- switch ($this->context['data'][0]) {
58
- case 'name':
59
- $result['message'] = "Материал №" . $this->context['id'] . "\r\n\r\nВведите, пожалуйста, название материала:";
60
- break;
61
- case 'description':
62
- $result['message'] = "Материал №" . $this->context['id'] . "\r\n\r\nВведите, пожалуйста, описание материала:";
63
- break;
64
- case 'price':
65
- $result['message'] = "Материал №" . $this->context['id'] . "\r\n\r\nВведите, пожалуйста, стоимость заказа (введите 0 для бесплатных материалов)";
66
- break;
67
- case 'file':
68
- $result['message'] = "Материал №" . $this->context['id'] . "\r\n\r\nПрикрепите, пожалуйста, файл, который будет продаваться";
69
- break;
70
- case 'photo':
71
- $result['message'] = "Материал №" . $this->context['id'] . "\r\n\r\nПрикрепите, пожалуйста, изображение, которое будет показываться на экране с подробностями о материале";
72
- break;
73
- case 'materialDelete':
74
- $result['message'] = "Материал №" . $this->context['id'] . "\r\n\r\nВы точно хотите его удалить?";
75
- $result['buttons'] = [
76
- [['text' => "Да", 'callback_data' => json_encode(array('command' => 'materialDeleteConfirm', 'id' => $this->context['id']))], ['text' => "Нет", 'callback_data' => json_encode(array('command' => 'materialDeleteCancel', 'id' => $this->context['id']))]]
77
- ];
78
- break;
79
- }
80
-
81
- return $result;
82
- }
83
52
  }
@@ -0,0 +1,93 @@
1
+ <?php
2
+
3
+ namespace App\Entity;
4
+
5
+ use App\Repository\UserRepository;
6
+ use Doctrine\Common\Collections\ArrayCollection;
7
+ use Doctrine\Common\Collections\Collection;
8
+ use Doctrine\ORM\Mapping as ORM;
9
+
10
+ #[ORM\Entity(repositoryClass: UserRepository::class)]
11
+ class User
12
+ {
13
+ #[ORM\Id]
14
+ #[ORM\GeneratedValue]
15
+ #[ORM\Column]
16
+ private ?int $id = null;
17
+
18
+ #[ORM\Column(length: 255, nullable: true)]
19
+ private ?string $phone = null;
20
+
21
+ /**
22
+ * @var Collection<int, Chat>
23
+ */
24
+ #[ORM\OneToMany(targetEntity: Chat::class, mappedBy: 'user', orphanRemoval: true)]
25
+ private Collection $chats;
26
+
27
+ #[ORM\Column(length: 255, nullable: true)]
28
+ private ?string $role = null;
29
+
30
+ public function __construct()
31
+ {
32
+ $this->chats = new ArrayCollection();
33
+ }
34
+
35
+ public function getId(): ?int
36
+ {
37
+ return $this->id;
38
+ }
39
+
40
+ public function getPhone(): ?string
41
+ {
42
+ return $this->phone;
43
+ }
44
+
45
+ public function setPhone(?string $phone): static
46
+ {
47
+ $this->phone = $phone;
48
+
49
+ return $this;
50
+ }
51
+
52
+ /**
53
+ * @return Collection<int, Chat>
54
+ */
55
+ public function getChats(): Collection
56
+ {
57
+ return $this->chats;
58
+ }
59
+
60
+ public function addChat(Chat $chat): static
61
+ {
62
+ if (!$this->chats->contains($chat)) {
63
+ $this->chats->add($chat);
64
+ $chat->setUser($this);
65
+ }
66
+
67
+ return $this;
68
+ }
69
+
70
+ public function removeChat(Chat $chat): static
71
+ {
72
+ if ($this->chats->removeElement($chat)) {
73
+ // set the owning side to null (unless already changed)
74
+ if ($chat->getUser() === $this) {
75
+ $chat->setUser(null);
76
+ }
77
+ }
78
+
79
+ return $this;
80
+ }
81
+
82
+ public function getRole(): ?string
83
+ {
84
+ return $this->role;
85
+ }
86
+
87
+ public function setRole(?string $role): static
88
+ {
89
+ $this->role = $role;
90
+
91
+ return $this;
92
+ }
93
+ }
@@ -0,0 +1,43 @@
1
+ <?php
2
+
3
+ namespace App\Repository;
4
+
5
+ use App\Entity\User;
6
+ use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
7
+ use Doctrine\Persistence\ManagerRegistry;
8
+
9
+ /**
10
+ * @extends ServiceEntityRepository<User>
11
+ */
12
+ class UserRepository extends ServiceEntityRepository
13
+ {
14
+ public function __construct(ManagerRegistry $registry)
15
+ {
16
+ parent::__construct($registry, User::class);
17
+ }
18
+
19
+ // /**
20
+ // * @return User[] Returns an array of User objects
21
+ // */
22
+ // public function findByExampleField($value): array
23
+ // {
24
+ // return $this->createQueryBuilder('u')
25
+ // ->andWhere('u.exampleField = :val')
26
+ // ->setParameter('val', $value)
27
+ // ->orderBy('u.id', 'ASC')
28
+ // ->setMaxResults(10)
29
+ // ->getQuery()
30
+ // ->getResult()
31
+ // ;
32
+ // }
33
+
34
+ // public function findOneBySomeField($value): ?User
35
+ // {
36
+ // return $this->createQueryBuilder('u')
37
+ // ->andWhere('u.exampleField = :val')
38
+ // ->setParameter('val', $value)
39
+ // ->getQuery()
40
+ // ->getOneOrNullResult()
41
+ // ;
42
+ // }
43
+ }
@@ -0,0 +1,34 @@
1
+ <?php
2
+
3
+ namespace App\Service;
4
+
5
+ use App\Entity\Chat;
6
+ use App\Entity\DialogContext;
7
+ use App\Service\MessageThemeService\CustomMessageService;
8
+ use Doctrine\ORM\EntityManagerInterface;
9
+ use Psr\Log\LoggerInterface;
10
+
11
+ class MessageProcessService
12
+ {
13
+ private ?EntityManagerInterface $em = null;
14
+ private ?LoggerInterface $logger;
15
+
16
+ public function __construct(EntityManagerInterface $em, LoggerInterface $logger)
17
+ {
18
+ $this->em = $em;
19
+ $this->logger = $logger;
20
+ }
21
+
22
+ public function processMessage(array $message): bool
23
+ {
24
+ $this->logger->error('msg '. json_encode($message));
25
+
26
+ $messageIsProcessed = false;
27
+ // add Message services
28
+ if (!$messageIsProcessed) $messageIsProcessed = new CustomMessageService($this->em, $this->logger)->processMessage($message);
29
+ /* ADD Service */
30
+
31
+ return $messageIsProcessed;
32
+ }
33
+
34
+ }
@@ -0,0 +1,164 @@
1
+ <?php
2
+
3
+ namespace App\Service\MessageThemeService;
4
+
5
+ use App\Entity\Chat;
6
+ use App\Entity\DialogContext;
7
+ use App\Entity\User;
8
+ use App\Service\MessengerService\VkService;
9
+ use Doctrine\ORM\EntityManagerInterface;
10
+ use Psr\Log\LoggerInterface;
11
+
12
+ class CustomMessageService implements MessageThemeInterface
13
+ {
14
+ private ?EntityManagerInterface $em = null;
15
+
16
+ private ?LoggerInterface $logger;
17
+
18
+ private $paginationCount = 3;
19
+ private $comission = 10;
20
+
21
+ public function __construct(EntityManagerInterface $em, LoggerInterface $logger)
22
+ {
23
+ $this->em = $em;
24
+ $this->logger = $logger;
25
+ }
26
+
27
+ public function processMessage($message): bool
28
+ {
29
+ $this->logger->debug('Processing message', ['message' => $message]);
30
+ $isProcessed = true;
31
+
32
+ $chat = $this->em->getRepository(Chat::class)->findOneBy(array('chatId' => $message['from']), array('id' => 'desc'));
33
+ $context = $this->em->getRepository(DialogContext::class)->findOneBy(['chat' => $chat]);
34
+ if (array_key_exists('message', $message)) {
35
+ $arr = explode(' ', $message['message']);
36
+
37
+ //Comment: Это свитч для работы с командами и ручным вводом
38
+ switch (strtolower($arr[0])) {
39
+ case '/start':
40
+ $isInit = false;
41
+ if (!$chat instanceof Chat) {
42
+ $chat = new Chat();
43
+ if (array_key_exists('username', $message)) $chat->setUsername($message['username']);
44
+ if (array_key_exists('userId', $message)) $chat->setUserId($message['userId']);
45
+ $chat->setChatId($message['from']);
46
+ $chat->setType(match ($message['type']) {
47
+ 'MAX' => Chat::TYPE_MAX,
48
+ 'TG' => Chat::TYPE_TG,
49
+ 'VK' => Chat::TYPE_VK,
50
+ });
51
+
52
+ $user = new User();
53
+ $this->em->persist($user);
54
+ $chat->setUser($user);
55
+
56
+ $this->em->persist($chat);
57
+ $this->em->flush();
58
+ $isInit = true;
59
+ }
60
+
61
+ $responseText = "";
62
+
63
+ if ($isInit) $responseText = "Добрый день! Вы попали в чат-бота!";
64
+
65
+ if (strlen($responseText) > 0) $resp = $chat->getMessenger()->sendMessage($responseText);
66
+
67
+ if (is_null($chat->getPhone())) {
68
+ $resp = $chat->getMessenger()->sendKeyboardMessage("Поделитесь, пожалуйста, номером телефона", [
69
+ [['text' => 'Поделиться номером телефона', 'request_contact' => true]]
70
+ ]);
71
+ $this->logger->error('resp', $resp);
72
+ }
73
+ if ($chat->getMessenger() instanceof VkService) $chat->getMessenger()->sendKeyboardMessage("Воспользуйтесь меню для работы с ботом", [
74
+ [['text' => 'Меню'],],
75
+ ]);
76
+ break;
77
+ case '/example':
78
+ // $context = new DialogContext();
79
+ // $context->setChat($chat);
80
+ // $context->setContext(['data' => ['files'],]);
81
+ // $this->dialogRepo->add($context, true);
82
+ //
83
+ // $buttons = [];
84
+ // $responseText = "В данном разделе Вы можете заказать и оплатить услуги печати из Библиотеки ТУСУР с доставкой в корпус или общежитие\r\n\r\n" .
85
+ // "Прикрепите, пожалуйста, файлы для печати";
86
+ //
87
+ // $messenger->sendMessage($responseText, $from, $buttons);
88
+ break;
89
+ case '/help':
90
+ case '?':
91
+ $buttons = [];
92
+ if ($chat->getUser()->getRole() === Chat::ROLE_ADMIN) {
93
+ $responseText = "Приветствую! Я Вас узнал) Вы из администрации бота\r\n" .
94
+ "Что желаете сделать?\r\n\r\n" .
95
+ "P.S.: бот с любовью и заботой разработан командой @yourtar";
96
+ $buttons[] = [['text' => 'Админ. панель', 'callback_data' => json_encode(array('command' => 'adminMenu',)),]];
97
+ $buttons[] = [['text' => 'Статистика', 'callback_data' => json_encode(array('command' => 'stats',)),]];
98
+ } else {
99
+ $responseText = "Добро пожаловать в чат-бота !\r\n\r\n" .
100
+ "P.S.: бот с любовью и заботой разработан командой @yourtar!";
101
+ }
102
+
103
+ $chat->getMessenger()->sendMessage($responseText, $buttons);
104
+ break;
105
+ default:
106
+ if ($context instanceof DialogContext) {
107
+ //Comment: Это свитч для работы с контектом ввода (когда вводят ответ на вопрос бота)
108
+ switch ($context->getContext()['data'][0]) {
109
+ case 'example':
110
+
111
+ break;
112
+ default:
113
+ $isProcessed = false;
114
+ break;
115
+ }
116
+ }
117
+ // else if (array_key_exists('photo', $message['message']) && count($message['message']['photo']) > 1 && array_key_exists('media_group_id', $message)) {
118
+ // $ms = $this->em->getRepository(MessageSending::class)->findOneBy(array('photoMediaGroupId' => $message['media_group_id']));
119
+
120
+ // if ($ms instanceof MessageSending) {
121
+ // $file = $messenger->getFile(end($message['message']['photo'])['file_id']);
122
+
123
+ // $files = $ms->getImage();
124
+ // $files[] = $file;
125
+ // $ms->setImage($files);
126
+ // $this->em->flush();
127
+ // }
128
+ // }
129
+ else $isProcessed = false;
130
+ break;
131
+ }
132
+ }
133
+ else if (array_key_exists('data', $message)) {
134
+ $arr = json_decode($message['data'], true);
135
+
136
+ //Comment: Это свитч для работы с командами и ручным вводом
137
+ switch ($arr['command']) {
138
+ case 'adminMenu':
139
+ $chat->getMessenger()->deleteMessage($message['message_id']);
140
+ $chat->getMessenger()->sendMessage("Чем хотите управлять?", [
141
+ [['text' => 'Адреса', 'callback_data' => json_encode(array('command' => 'branchList',)),]],
142
+ [['text' => 'Услуги', 'callback_data' => json_encode(array('command' => 'serviceList',)),]],
143
+ [['text' => 'Пользоваатели', 'callback_data' => json_encode(array('command' => 'users',)),]],
144
+ ]);
145
+ break;
146
+ default:
147
+ $isProcessed = false;
148
+ break;
149
+ }
150
+ }
151
+
152
+ if (array_key_exists('phone', $message) && $chat) {
153
+ $phone = preg_replace('/[^0-9+]/', '', $chat->getPhone());
154
+ $phone = substr($phone, -10);
155
+ $chat->setPhone($phone);
156
+ if (is_null($chat->getUser()->getPhone())) $chat->getUser()->setPhone($phone);
157
+ $chat->getMessenger()->sendMessage("Спасибо, что поделились номером!");
158
+
159
+ $this->em->flush();
160
+ }
161
+
162
+ return $isProcessed;
163
+ }
164
+ }