Advertisement
Higan

Untitled

Feb 12th, 2020
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 6.69 KB | None | 0 0
  1. <?php
  2.  
  3. // slackbot/api класс для отправки сообщений от ботов - пользователям проекта
  4. class ApiBot_Messages extends ApiBot_Default {
  5.  
  6.     // разрешенные методы
  7.     public const ALLOW_METHODS = [
  8.         "addSingle",
  9.         "addGroup",
  10.     ];
  11.  
  12.     // отправка сообщения пользователю в single диалог с ним
  13.     public function addSingle() {
  14.  
  15.         Bus::statholder()->inc("bot_conversation", "row20");
  16.  
  17.         $user_id           = $this->post("?i", "user_id");
  18.         $text              = $this->post("?s", "text");
  19.         $client_message_id = generateUUID();
  20.  
  21.         // пробуем получить информацию о пользователе
  22.         $user_info = $this->_tryGetUserInfo($user_id);
  23.         if ($user_info === false) {
  24.  
  25.             return $this->error(1, "Invalid user_id");
  26.         }
  27.  
  28.         $text = $this->_filterText($text);
  29.         if (mb_strlen($text) < 1) {
  30.  
  31.             Bus::statholder()->inc("bot_conversation", "row22");
  32.             return $this->error(2, "Invalid message text");
  33.         }
  34.  
  35.         // создаем сингл диалог
  36.         $meta_row = Helper_Single::createIfNotExist($user_id, $user_info["user_dpc"], $this->bot_user_id);
  37.  
  38.         // проверяем, можно ли писать в диалог
  39.         try {
  40.             Helper_Conversations::checkIsAllowed($meta_row["conversation_map"], $meta_row, $user_id);
  41.         } catch (cs_Conversation_IsBlockedByOpponent | cs_Conversation_IsBlockedByMe $e) {
  42.             return $this->error(4, "Conversation is blocked");
  43.         } catch (cs_Conversation_MemberIsDisabled $e) {
  44.             return $this->error(4, "User is disabled");
  45.         }
  46.  
  47.         // добавляем сообщение локально или сокет запросом
  48.         $message = $this->_makeMessage($this->bot_user_id, $text, $client_message_id);
  49.         $this->_addMessage($this->bot_user_id, $message, $meta_row);
  50.  
  51.         Bus::statholder()->inc("bot_conversation", "row24");
  52.         return $this->ok();
  53.     }
  54.  
  55.     // пробуем получить информацию о пользователе
  56.     // @mixed
  57.     protected function _tryGetUserInfo(int $user_id) {
  58.  
  59.         if ($user_id < 1) {
  60.  
  61.             Bus::statholder()->inc("bot_conversation", "row21");
  62.             return false;
  63.         }
  64.  
  65.         try {
  66.             $user_info = Bus::usercache()->getInfo($user_id);
  67.         } catch (cs_UserNotFound $e) {
  68.  
  69.             Bus::statholder()->inc("bot_conversation", "row23");
  70.             return false;
  71.         }
  72.  
  73.         return $user_info;
  74.     }
  75.  
  76.     // отправка сообщения в group диалог
  77.     public function addGroup() {
  78.  
  79.         Bus::statholder()->inc("bot_conversation", "row40");
  80.  
  81.         $conversation_map  = $this->post("?k", "conversation_key");
  82.         $text              = $this->post("?s", "text");
  83.         $client_message_id = generateUUID();
  84.  
  85.         $text = $this->_filterText($text);
  86.         if (mb_strlen($text) < 1) {
  87.  
  88.             Bus::statholder()->inc("bot_conversation", "row41");
  89.             return $this->error(2, "Invalid message text");
  90.         }
  91.  
  92.         // проверяем, что диалог существует
  93.         $meta_row = Type_Conversation_Meta::get($conversation_map);
  94.         if (!isset($meta_row["conversation_map"])) {
  95.  
  96.             Bus::statholder()->inc("bot_conversation", "row42");
  97.             return $this->error(1, "Conversation is not exist");
  98.         }
  99.  
  100.         $this->_throwIfConversationIsNotGroup($meta_row);
  101.  
  102.         // проверяем, что являемся его участником
  103.         if (!Type_Conversation_Users::isMember($this->bot_user_id, $meta_row["users"])) {
  104.  
  105.             Bus::statholder()->inc("bot_conversation", "row43");
  106.             return $this->error(3, "You're not member of this conversation");
  107.         }
  108.  
  109.         // формируем сообщение
  110.         $message = $this->_makeMessage($this->bot_user_id, $text, $client_message_id);
  111.  
  112.         // добавляем сообщение локально или сокет запросом
  113.         $this->_addMessage($this->bot_user_id, $message, $meta_row);
  114.  
  115.         Bus::statholder()->inc("bot_conversation", "row44");
  116.         return $this->ok();
  117.     }
  118.  
  119.     // выбрасываем ошибку, если диалог не является групповым
  120.     protected function _throwIfConversationIsNotGroup(array $meta_row):void {
  121.  
  122.         if ($meta_row["type"] != CONVERSATION_TYPE_GROUP) {
  123.  
  124.             Bus::statholder()->inc("bot_conversation", "row45");
  125.             throw new paramException("Conversation is not a group");
  126.         }
  127.     }
  128.  
  129.     // -------------------------------------------------------
  130.     // PROTECTED
  131.     // -------------------------------------------------------
  132.  
  133.     // фильтруем текст
  134.     protected function _filterText(string $text):string {
  135.  
  136.         // переводим emoji в :short_name:
  137.         $text = Type_Api_Filter::replaceEmojiWithShortName($text);
  138.  
  139.         // фильтруем текст сообщения
  140.         $text = Type_Api_Filter::sanitizeMessageText($text);
  141.  
  142.         return $text;
  143.     }
  144.  
  145.     // формируем сообщение
  146.     protected function _makeMessage(int $bot_user_id, string $text, string $client_message_id):array {
  147.  
  148.         return Type_Conversation_Message_Main::getLastVersionHandler()::makeText(
  149.             $bot_user_id,
  150.             $text,
  151.             $client_message_id
  152.         );
  153.     }
  154.  
  155.     // добавляем сообщение с помощью сокет запроса или локально
  156.     protected function _addMessage(int $bot_user_id, array $message, array $meta_row):void {
  157.  
  158.         // если диалог находится на другом dpc
  159.         if (CURRENT_DPC != $meta_row["dpc"]) {
  160.  
  161.             // добавляем сообщение с помощью сокет запроса
  162.             $this->_addMessageOnAnotherDpc($bot_user_id, $message, $meta_row);
  163.             return;
  164.         }
  165.  
  166.         // отправляем сообщение локально
  167.         try {
  168.  
  169.             Helper_Conversations::addMessage($meta_row["conversation_map"], $message, $meta_row["users"],
  170.                 $meta_row["type"], $meta_row["conversation_name"], $meta_row["extra"]);
  171.         } catch (cs_ConversationIsLocked $e) {
  172.  
  173.             throw new blockException(__METHOD__ . " conversation is locked");
  174.         }
  175.     }
  176.  
  177.     // добавляем сообщение с помощью сокет запроса
  178.     protected function _addMessageOnAnotherDpc(int $bot_user_id, array $message, array $meta_row):void {
  179.  
  180.         // добавляем сообщение на другой dpc через socket запрос
  181.         $ar_post  = [
  182.             "conversation_map" => $meta_row["conversation_map"],
  183.             "message"          => $message,
  184.             "meta_row"         => $meta_row,
  185.         ];
  186.         $response = Type_Socket_Main::init($meta_row["dpc"])->call("conversations.addMessage", $ar_post, $bot_user_id);
  187.  
  188.         // пришел валидный ответ?
  189.         if ($response["status"] != "ok") {
  190.  
  191.             // диалог закрыт
  192.             if ($response["response"]["error_code"] == 10018) {
  193.                 throw new blockException(__METHOD__ . " conversation is locked");
  194.             }
  195.  
  196.             throw new returnException(__CLASS__ . ": request return call not 'ok'");
  197.         }
  198.     }
  199. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement