Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // slackbot/api класс для отправки сообщений от ботов - пользователям проекта
- class ApiBot_Messages extends ApiBot_Default {
- // разрешенные методы
- public const ALLOW_METHODS = [
- "addSingle",
- "addGroup",
- ];
- // отправка сообщения пользователю в single диалог с ним
- public function addSingle() {
- Bus::statholder()->inc("bot_conversation", "row20");
- $user_id = $this->post("?i", "user_id");
- $text = $this->post("?s", "text");
- $client_message_id = generateUUID();
- // пробуем получить информацию о пользователе
- $user_info = $this->_tryGetUserInfo($user_id);
- if ($user_info === false) {
- return $this->error(1, "Invalid user_id");
- }
- $text = $this->_filterText($text);
- if (mb_strlen($text) < 1) {
- Bus::statholder()->inc("bot_conversation", "row22");
- return $this->error(2, "Invalid message text");
- }
- // создаем сингл диалог
- $meta_row = Helper_Single::createIfNotExist($user_id, $user_info["user_dpc"], $this->bot_user_id);
- // проверяем, можно ли писать в диалог
- try {
- Helper_Conversations::checkIsAllowed($meta_row["conversation_map"], $meta_row, $user_id);
- } catch (cs_Conversation_IsBlockedByOpponent | cs_Conversation_IsBlockedByMe $e) {
- return $this->error(4, "Conversation is blocked");
- } catch (cs_Conversation_MemberIsDisabled $e) {
- return $this->error(4, "User is disabled");
- }
- // добавляем сообщение локально или сокет запросом
- $message = $this->_makeMessage($this->bot_user_id, $text, $client_message_id);
- $this->_addMessage($this->bot_user_id, $message, $meta_row);
- Bus::statholder()->inc("bot_conversation", "row24");
- return $this->ok();
- }
- // пробуем получить информацию о пользователе
- // @mixed
- protected function _tryGetUserInfo(int $user_id) {
- if ($user_id < 1) {
- Bus::statholder()->inc("bot_conversation", "row21");
- return false;
- }
- try {
- $user_info = Bus::usercache()->getInfo($user_id);
- } catch (cs_UserNotFound $e) {
- Bus::statholder()->inc("bot_conversation", "row23");
- return false;
- }
- return $user_info;
- }
- // отправка сообщения в group диалог
- public function addGroup() {
- Bus::statholder()->inc("bot_conversation", "row40");
- $conversation_map = $this->post("?k", "conversation_key");
- $text = $this->post("?s", "text");
- $client_message_id = generateUUID();
- $text = $this->_filterText($text);
- if (mb_strlen($text) < 1) {
- Bus::statholder()->inc("bot_conversation", "row41");
- return $this->error(2, "Invalid message text");
- }
- // проверяем, что диалог существует
- $meta_row = Type_Conversation_Meta::get($conversation_map);
- if (!isset($meta_row["conversation_map"])) {
- Bus::statholder()->inc("bot_conversation", "row42");
- return $this->error(1, "Conversation is not exist");
- }
- $this->_throwIfConversationIsNotGroup($meta_row);
- // проверяем, что являемся его участником
- if (!Type_Conversation_Users::isMember($this->bot_user_id, $meta_row["users"])) {
- Bus::statholder()->inc("bot_conversation", "row43");
- return $this->error(3, "You're not member of this conversation");
- }
- // формируем сообщение
- $message = $this->_makeMessage($this->bot_user_id, $text, $client_message_id);
- // добавляем сообщение локально или сокет запросом
- $this->_addMessage($this->bot_user_id, $message, $meta_row);
- Bus::statholder()->inc("bot_conversation", "row44");
- return $this->ok();
- }
- // выбрасываем ошибку, если диалог не является групповым
- protected function _throwIfConversationIsNotGroup(array $meta_row):void {
- if ($meta_row["type"] != CONVERSATION_TYPE_GROUP) {
- Bus::statholder()->inc("bot_conversation", "row45");
- throw new paramException("Conversation is not a group");
- }
- }
- // -------------------------------------------------------
- // PROTECTED
- // -------------------------------------------------------
- // фильтруем текст
- protected function _filterText(string $text):string {
- // переводим emoji в :short_name:
- $text = Type_Api_Filter::replaceEmojiWithShortName($text);
- // фильтруем текст сообщения
- $text = Type_Api_Filter::sanitizeMessageText($text);
- return $text;
- }
- // формируем сообщение
- protected function _makeMessage(int $bot_user_id, string $text, string $client_message_id):array {
- return Type_Conversation_Message_Main::getLastVersionHandler()::makeText(
- $bot_user_id,
- $text,
- $client_message_id
- );
- }
- // добавляем сообщение с помощью сокет запроса или локально
- protected function _addMessage(int $bot_user_id, array $message, array $meta_row):void {
- // если диалог находится на другом dpc
- if (CURRENT_DPC != $meta_row["dpc"]) {
- // добавляем сообщение с помощью сокет запроса
- $this->_addMessageOnAnotherDpc($bot_user_id, $message, $meta_row);
- return;
- }
- // отправляем сообщение локально
- try {
- Helper_Conversations::addMessage($meta_row["conversation_map"], $message, $meta_row["users"],
- $meta_row["type"], $meta_row["conversation_name"], $meta_row["extra"]);
- } catch (cs_ConversationIsLocked $e) {
- throw new blockException(__METHOD__ . " conversation is locked");
- }
- }
- // добавляем сообщение с помощью сокет запроса
- protected function _addMessageOnAnotherDpc(int $bot_user_id, array $message, array $meta_row):void {
- // добавляем сообщение на другой dpc через socket запрос
- $ar_post = [
- "conversation_map" => $meta_row["conversation_map"],
- "message" => $message,
- "meta_row" => $meta_row,
- ];
- $response = Type_Socket_Main::init($meta_row["dpc"])->call("conversations.addMessage", $ar_post, $bot_user_id);
- // пришел валидный ответ?
- if ($response["status"] != "ok") {
- // диалог закрыт
- if ($response["response"]["error_code"] == 10018) {
- throw new blockException(__METHOD__ . " conversation is locked");
- }
- throw new returnException(__CLASS__ . ": request return call not 'ok'");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement