├── Commands ├── MessagesController.php ├── SystemCommands │ ├── CallbackqueryCommand.php │ └── GenericmessageCommand.php ├── UserCommands │ ├── CallbackqueryCommand.php │ ├── CancelCommand.php │ ├── DateCommand.php │ ├── EchoCommand.php │ ├── GenericmessageCommand.php │ ├── HelpCommand.php │ ├── Leave_dialogCommand.php │ ├── LeavedialogCommand.php │ ├── LoginCommand.php │ ├── LogoutCommand.php │ ├── SlapCommand.php │ ├── SurveyCommand.php │ ├── WeatherCommand.php │ └── WhoamiCommand.php └── YiiChatCommand.php ├── LICENSE ├── Module.php ├── README.md ├── Telegram.php ├── TelegramAsset.php ├── assets ├── css │ ├── telegram.css │ ├── telegram.css.map │ └── telegram.scss └── js │ ├── jquery.nicescroll.min.js │ └── telegram.js ├── composer.json ├── controllers ├── ChatController.php └── DefaultController.php ├── messages ├── es │ └── tlgrm.php └── ru │ └── tlgrm.php ├── migrations ├── m160808_112253_onmotion_yii2_telegram.php └── m161122_112253_onmotion_yii2_telegram.php ├── models ├── Actions.php ├── AuthorizedManagerChat.php ├── Message.php └── Usernames.php └── views └── default ├── button.php └── chat.php /Commands/MessagesController.php: -------------------------------------------------------------------------------- 1 | db; 17 | $db->createCommand()->delete('tlgrm_messages', 'time < \'' . date("Y-m-d H:i:s", time() - (3600 * 24 * $keep)) . '\'')->execute(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Commands/SystemCommands/CallbackqueryCommand.php: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | 11 | namespace Longman\TelegramBot\Commands\SystemCommands; 12 | 13 | use onmotion\telegram\models\AuthorizedManagerChat; 14 | use onmotion\telegram\models\Usernames; 15 | use Longman\TelegramBot\Commands\SystemCommand; 16 | use Longman\TelegramBot\Request; 17 | use Yii; 18 | 19 | /** 20 | * Callback query command 21 | */ 22 | class CallbackqueryCommand extends SystemCommand 23 | { 24 | /**#@+ 25 | * {@inheritdoc} 26 | */ 27 | protected $name = 'callbackquery'; 28 | protected $description = 'Reply to callback query'; 29 | protected $version = '1.0.0'; 30 | /**#@-*/ 31 | 32 | /** 33 | * {@inheritdoc} 34 | */ 35 | public function execute() 36 | { 37 | //Do nothing, just for rewriting default Longman command 38 | return Request::emptyResponse(); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Commands/SystemCommands/GenericmessageCommand.php: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | 11 | namespace Longman\TelegramBot\Commands\SystemCommands; 12 | 13 | use onmotion\telegram\models\Actions; 14 | use onmotion\telegram\models\AuthorizedChat; 15 | use onmotion\telegram\models\AuthorizedManagerChat; 16 | use onmotion\telegram\models\AuthorizedUsers; 17 | use onmotion\telegram\models\Message; 18 | use onmotion\telegram\models\Usernames; 19 | use onmotion\telegram\TelegramVars; 20 | use Longman\TelegramBot\Conversation; 21 | use Longman\TelegramBot\Entities\ServerResponse; 22 | use Longman\TelegramBot\Request; 23 | use Longman\TelegramBot\Commands\SystemCommand; 24 | use Yii; 25 | use yii\helpers\ArrayHelper; 26 | 27 | /** 28 | * Generic message command 29 | */ 30 | class GenericmessageCommand extends SystemCommand 31 | { 32 | /**#@+ 33 | * {@inheritdoc} 34 | */ 35 | protected $name = 'Genericmessage'; 36 | protected $description = 'Handle generic message'; 37 | protected $version = '1.0.2'; 38 | protected $need_mysql = false; 39 | /**#@-*/ 40 | 41 | /** 42 | * Execution if MySQL is required but not available 43 | * 44 | * @return boolean 45 | */ 46 | public function executeNoDb() 47 | { 48 | //Do nothing 49 | return Request::emptyResponse(); 50 | } 51 | 52 | 53 | /** 54 | * Execute command 55 | * 56 | * @return boolean 57 | */ 58 | public function execute() 59 | { 60 | //Do nothing, just for rewriting default Longman command 61 | return Request::emptyResponse(); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Commands/UserCommands/CallbackqueryCommand.php: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | 11 | namespace Longman\TelegramBot\Commands\SystemCommands; 12 | 13 | use onmotion\telegram\models\AuthorizedManagerChat; 14 | use onmotion\telegram\models\Usernames; 15 | use Longman\TelegramBot\Commands\SystemCommand; 16 | use Longman\TelegramBot\Request; 17 | use Yii; 18 | 19 | /** 20 | * Callback query command 21 | */ 22 | class CallbackqueryCommand extends SystemCommand 23 | { 24 | /**#@+ 25 | * {@inheritdoc} 26 | */ 27 | protected $name = 'callbackquery'; 28 | protected $description = 'Reply to callback query'; 29 | protected $version = '1.0.0'; 30 | /**#@-*/ 31 | 32 | /** 33 | * {@inheritdoc} 34 | */ 35 | public function execute() 36 | { 37 | $update = $this->getUpdate(); 38 | 39 | $callback_query = $update->getCallbackQuery(); 40 | $chatId = $callback_query->getMessage()->getChat()->getId(); 41 | $callback_query_id = $callback_query->getId(); 42 | $callback_data = $callback_query->getData(); 43 | 44 | $data['callback_query_id'] = $callback_query_id; 45 | $callbackDataArr = explode(' ', $callback_data); 46 | 47 | if ($callbackDataArr[0] == 'client_chat_id') { 48 | 49 | $data['show_alert'] = true; 50 | //Закрепляем чат за авторизованным менеджером 51 | $authChat = AuthorizedManagerChat::findOne(intval($chatId)); 52 | $authChat->client_chat_id = $callbackDataArr[1]; 53 | if ($authChat->validate() && $authChat->save()){ 54 | $data['text'] = Yii::t('tlgrm', 'Start conversation with chat ') . $callbackDataArr[1]; 55 | Request::answerCallbackQuery($data); 56 | unset($data['show_alert'], $data['callback_query_id']); 57 | $data['chat_id'] = $chatId; 58 | return Request::sendMessage($data); 59 | }else{ 60 | try { 61 | $authChat = AuthorizedManagerChat::find()->where(['client_chat_id' => $callbackDataArr[1]])->one(); 62 | $manager = Usernames::find()->where(['chat_id' => $authChat->chat_id])->one(); 63 | $data['text'] = Yii::t('tlgrm', 'Conversation already in progress in this chat. Responsible: ') . ($manager->username ? $manager->username : "not_found"); 64 | } catch (\Exception $e){ 65 | $data['text'] = Yii::t('tlgrm', 'Seems conversation already in progress in this chat.'); 66 | } 67 | unset($data['show_alert'], $data['callback_query_id']); 68 | $data['chat_id'] = $chatId; 69 | 70 | return Request::sendMessage($data); 71 | } 72 | } else { 73 | $data['text'] = Yii::t('tlgrm', 'Unknown command.'); 74 | $data['show_alert'] = false; 75 | return Request::answerCallbackQuery($data); 76 | } 77 | 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /Commands/UserCommands/CancelCommand.php: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | 11 | namespace Longman\TelegramBot\Commands\UserCommands; 12 | 13 | use Longman\TelegramBot\Commands\UserCommand; 14 | use Longman\TelegramBot\Conversation; 15 | use Longman\TelegramBot\Entities\ReplyKeyboardHide; 16 | use Longman\TelegramBot\Request; 17 | 18 | /** 19 | * User "/cancel" command 20 | * 21 | * This command cancels the currently active conversation and 22 | * returns a message to let the user know which conversation it was. 23 | * If no conversation is active, the returned message says so. 24 | */ 25 | class CancelCommand extends UserCommand 26 | { 27 | /**#@+ 28 | * {@inheritdoc} 29 | */ 30 | protected $name = 'cancel'; 31 | protected $description = 'Cancel the currently active conversation'; 32 | protected $usage = '/cancel'; 33 | protected $version = '0.1.1'; 34 | protected $need_mysql = true; 35 | public $enabled = false; 36 | 37 | /**#@-*/ 38 | 39 | /** 40 | * {@inheritdoc} 41 | */ 42 | public function execute() 43 | { 44 | $text = 'No active conversation!'; 45 | 46 | //Cancel current conversation if any 47 | $conversation = new Conversation( 48 | $this->getMessage()->getFrom()->getId(), 49 | $this->getMessage()->getChat()->getId() 50 | ); 51 | 52 | if ($conversation_command = $conversation->getCommand()) { 53 | $conversation->cancel(); 54 | $text = 'Conversation "' . $conversation_command . '" cancelled!'; 55 | } 56 | 57 | return $this->hideKeyboard($text); 58 | } 59 | 60 | /** 61 | * {@inheritdoc} 62 | */ 63 | public function executeNoDb() 64 | { 65 | return $this->hideKeyboard('Nothing to cancel.'); 66 | } 67 | 68 | /** 69 | * Hide the keyboard and output a text 70 | * 71 | * @param string $text 72 | * 73 | * @return \Longman\TelegramBot\Entities\ServerResponse 74 | */ 75 | private function hideKeyboard($text) 76 | { 77 | return Request::sendMessage([ 78 | 'reply_markup' => new ReplyKeyboardHide(['selective' => true]), 79 | 'chat_id' => $this->getMessage()->getChat()->getId(), 80 | 'text' => $text, 81 | ]); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /Commands/UserCommands/DateCommand.php: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | 11 | namespace Longman\TelegramBot\Commands\UserCommands; 12 | 13 | use GuzzleHttp\Client; 14 | use GuzzleHttp\Exception\RequestException; 15 | use Longman\TelegramBot\Commands\UserCommand; 16 | use Longman\TelegramBot\Exception\TelegramException; 17 | use Longman\TelegramBot\Request; 18 | 19 | /** 20 | * User "/date" command 21 | */ 22 | class DateCommand extends UserCommand 23 | { 24 | /**#@+ 25 | * {@inheritdoc} 26 | */ 27 | protected $name = 'date'; 28 | protected $description = 'Show date/time by location'; 29 | protected $usage = '/date '; 30 | protected $version = '1.3.0'; 31 | public $enabled = false; 32 | /**#@-*/ 33 | 34 | /** 35 | * Guzzle Client object 36 | * 37 | * @var \GuzzleHttp\Client 38 | */ 39 | private $client; 40 | 41 | /** 42 | * Base URI for Google Maps API 43 | * 44 | * @var string 45 | */ 46 | private $google_api_base_uri = 'https://maps.googleapis.com/maps/api/'; 47 | 48 | /** 49 | * The Google API Key from the command config 50 | * 51 | * @var string 52 | */ 53 | private $google_api_key; 54 | 55 | /** 56 | * Date format 57 | * 58 | * @var string 59 | */ 60 | private $date_format = 'd-m-Y H:i:s'; 61 | 62 | /** 63 | * Get coordinates 64 | * 65 | * @param string $location 66 | * 67 | * @return array|boolean 68 | */ 69 | private function getCoordinates($location) 70 | { 71 | $path = 'geocode/json'; 72 | $query = ['address' => urlencode($location)]; 73 | 74 | if ($this->google_api_key !== null) { 75 | $query['key'] = $this->google_api_key; 76 | } 77 | 78 | try { 79 | $response = $this->client->get($path, ['query' => $query]); 80 | } catch (RequestException $e) { 81 | throw new TelegramException($e->getMessage()); 82 | } 83 | 84 | if (!($result = $this->validateResponseData($response->getBody()))) { 85 | return false; 86 | } 87 | 88 | $result = $result['results'][0]; 89 | $lat = $result['geometry']['location']['lat']; 90 | $lng = $result['geometry']['location']['lng']; 91 | $acc = $result['geometry']['location_type']; 92 | $types = $result['types']; 93 | 94 | return [$lat, $lng, $acc, $types]; 95 | } 96 | 97 | /** 98 | * Get date 99 | * 100 | * @param string $lat 101 | * @param string $lng 102 | * 103 | * @return array|boolean 104 | */ 105 | private function getDate($lat, $lng) 106 | { 107 | $path = 'timezone/json'; 108 | 109 | $date_utc = new \DateTime(null, new \DateTimeZone('UTC')); 110 | $timestamp = $date_utc->format('U'); 111 | 112 | $query = [ 113 | 'location' => urlencode($lat) . ',' . urlencode($lng), 114 | 'timestamp' => urlencode($timestamp) 115 | ]; 116 | 117 | if ($this->google_api_key !== null) { 118 | $query['key'] = $this->google_api_key; 119 | } 120 | 121 | try { 122 | $response = $this->client->get($path, ['query' => $query]); 123 | } catch (RequestException $e) { 124 | throw new TelegramException($e->getMessage()); 125 | } 126 | 127 | if (!($result = $this->validateResponseData($response->getBody()))) { 128 | return false; 129 | } 130 | 131 | $local_time = $timestamp + $result['rawOffset'] + $result['dstOffset']; 132 | 133 | return [$local_time, $result['timeZoneId']]; 134 | } 135 | 136 | /** 137 | * Evaluate the response data and see if the request was successful 138 | * 139 | * @param string $data 140 | * 141 | * @return bool|array 142 | */ 143 | private function validateResponseData($data) 144 | { 145 | if (empty($data)) { 146 | return false; 147 | } 148 | 149 | $data = json_decode($data, true); 150 | if (empty($data)) { 151 | return false; 152 | } 153 | 154 | if (isset($data['status']) && $data['status'] !== 'OK') { 155 | return false; 156 | } 157 | 158 | return $data; 159 | } 160 | 161 | /** 162 | * Get formatted date 163 | * 164 | * @param string $location 165 | * 166 | * @return string 167 | */ 168 | private function getFormattedDate($location) 169 | { 170 | if (empty($location)) { 171 | return 'The time in nowhere is never'; 172 | } 173 | 174 | list($lat, $lng, $acc, $types) = $this->getCoordinates($location); 175 | 176 | if (empty($lat) || empty($lng)) { 177 | return 'It seems that in "' . $location . '" they do not have a concept of time.'; 178 | } 179 | 180 | list($local_time, $timezone_id) = $this->getDate($lat, $lng); 181 | 182 | $date_utc = new \DateTime(gmdate('Y-m-d H:i:s', $local_time), new \DateTimeZone($timezone_id)); 183 | 184 | return 'The local time in ' . $timezone_id . ' is: ' . $date_utc->format($this->date_format); 185 | } 186 | 187 | /** 188 | * {@inheritdoc} 189 | */ 190 | public function execute() 191 | { 192 | //First we set up the necessary member variables. 193 | $this->client = new Client(['base_uri' => $this->google_api_base_uri]); 194 | if (($this->google_api_key = trim($this->getConfig('google_api_key'))) === '') { 195 | $this->google_api_key = null; 196 | } 197 | 198 | $message = $this->getMessage(); 199 | 200 | $chat_id = $message->getChat()->getId(); 201 | $location = $message->getText(true); 202 | 203 | if (empty($location)) { 204 | $text = 'You must specify location in format: /date '; 205 | } else { 206 | $text = $this->getFormattedDate($location); 207 | } 208 | 209 | $data = [ 210 | 'chat_id' => $chat_id, 211 | 'text' => $text, 212 | ]; 213 | 214 | return Request::sendMessage($data); 215 | } 216 | } 217 | -------------------------------------------------------------------------------- /Commands/UserCommands/EchoCommand.php: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | 11 | namespace Longman\TelegramBot\Commands\UserCommands; 12 | 13 | use Longman\TelegramBot\Commands\UserCommand; 14 | use Longman\TelegramBot\Request; 15 | 16 | /** 17 | * User "/echo" command 18 | */ 19 | class EchoCommand extends UserCommand 20 | { 21 | /**#@+ 22 | * {@inheritdoc} 23 | */ 24 | protected $name = 'echo'; 25 | protected $description = 'Show text'; 26 | protected $usage = '/echo '; 27 | protected $version = '1.0.1'; 28 | public $enabled = false; 29 | /**#@-*/ 30 | 31 | /** 32 | * {@inheritdoc} 33 | */ 34 | public function execute() 35 | { 36 | $message = $this->getMessage(); 37 | $chat_id = $message->getChat()->getId(); 38 | $text = trim($message->getText(true)); 39 | 40 | if ($text === '') { 41 | $text = 'Command usage: ' . $this->getUsage(); 42 | } 43 | 44 | $data = [ 45 | 'chat_id' => $chat_id, 46 | 'text' => $text, 47 | ]; 48 | 49 | return Request::sendMessage($data); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Commands/UserCommands/GenericmessageCommand.php: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | 11 | namespace Longman\TelegramBot\Commands\SystemCommands; 12 | 13 | use onmotion\telegram\models\Actions; 14 | use onmotion\telegram\models\AuthorizedChat; 15 | use onmotion\telegram\models\AuthorizedManagerChat; 16 | use onmotion\telegram\models\AuthorizedUsers; 17 | use onmotion\telegram\models\Message; 18 | use onmotion\telegram\models\Usernames; 19 | use onmotion\telegram\TelegramVars; 20 | use Longman\TelegramBot\Conversation; 21 | use Longman\TelegramBot\Entities\ServerResponse; 22 | use Longman\TelegramBot\Request; 23 | use Longman\TelegramBot\Commands\SystemCommand; 24 | use Yii; 25 | use yii\helpers\ArrayHelper; 26 | 27 | /** 28 | * Generic message command 29 | */ 30 | class GenericmessageCommand extends SystemCommand 31 | { 32 | /**#@+ 33 | * {@inheritdoc} 34 | */ 35 | protected $name = 'Genericmessage'; 36 | protected $description = 'Handle generic message'; 37 | protected $version = '1.0.2'; 38 | protected $need_mysql = false; 39 | /**#@-*/ 40 | 41 | /** 42 | * Execution if MySQL is required but not available 43 | * 44 | * @return boolean 45 | */ 46 | public function executeNoDb() 47 | { 48 | //Do nothing 49 | return Request::emptyResponse(); 50 | } 51 | 52 | /** 53 | * Execute command 54 | * 55 | * @return boolean 56 | */ 57 | public function execute() 58 | { 59 | 60 | //If a conversation is busy, execute the conversation command after handling the message 61 | $userId = $this->getMessage()->getFrom()->getId(); 62 | $chat = $this->getMessage()->getChat(); 63 | $chatId = $chat->getId(); 64 | $username = $chat->getFirstName() . ' ' . $chat->getLastName() . ' (@' . $chat->getUsername() . ')'; 65 | $conversation = new Conversation( 66 | $userId, 67 | $chatId 68 | ); 69 | //Fetch conversation command if it exists and execute it 70 | if ($conversation->exists() && ($command = $conversation->getCommand())) { 71 | return $this->telegram->executeCommand($command, $this->update); 72 | } 73 | 74 | $authChat = AuthorizedManagerChat::find()->where(['chat_id' => $chatId])->andWhere(['not', ['client_chat_id' => null]])->one(); 75 | if ($authChat){ 76 | //менеджер уже ведет чат 77 | $message = new Message(); 78 | $message->client_chat_id = $authChat->client_chat_id; 79 | $message->message = trim($this->getMessage()->getText(true)); 80 | $message->direction = 1; 81 | $message->time = date("Y-m-d H:i:s"); 82 | $message->save(); 83 | return Request::emptyResponse(); 84 | } 85 | 86 | $dbUser = Actions::findOne($chatId); 87 | $text = trim($this->getMessage()->getText(true)); 88 | if ($dbUser && $dbUser->action == 'login') { 89 | if ($text == PASSPHRASE) { 90 | $_authChat = AuthorizedManagerChat::findOne($chatId); 91 | if ($_authChat == null){ 92 | $_authChat = new AuthorizedManagerChat(); 93 | $_authChat->chat_id = $chatId; 94 | $_authChat->save(); 95 | $data = [ 96 | 'chat_id' => $chatId, 97 | 'text' => Yii::t('tlgrm', "Passphrase is correct, now you'll get the messages."), 98 | ]; 99 | //связь пользователя с чатом 100 | $dbUserneme = new Usernames(); 101 | $dbUserneme->chat_id = $chatId; 102 | $dbUserneme->user_id = $userId; 103 | $dbUserneme->username = $username; 104 | $dbUserneme->save(); 105 | }else{ 106 | $data = [ 107 | 'chat_id' => $chatId, 108 | 'text' => Yii::t('tlgrm', "You are already subscribed to receive messages."), 109 | ]; 110 | } 111 | }else{ 112 | $data = [ 113 | 'chat_id' => $chatId, 114 | 'text' => Yii::t('tlgrm', 'Incorrect passphrase.'), 115 | ]; 116 | } 117 | $dbUser->action = null; 118 | $dbUser->save(); 119 | } else { 120 | $data = [ 121 | 'chat_id' => $chatId, 122 | 'text' => Yii::t('tlgrm', 'Try to enter the command, such as /help'), 123 | ]; 124 | } 125 | 126 | return Request::sendMessage($data); 127 | // return Request::emptyResponse(); 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /Commands/UserCommands/HelpCommand.php: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | 11 | namespace Longman\TelegramBot\Commands\UserCommands; 12 | 13 | use Longman\TelegramBot\Commands\UserCommand; 14 | use Longman\TelegramBot\Request; 15 | use Yii; 16 | 17 | /** 18 | * User "/help" command 19 | */ 20 | class HelpCommand extends UserCommand 21 | { 22 | /**#@+ 23 | * {@inheritdoc} 24 | */ 25 | protected $name = 'help'; 26 | protected $description = ''; 27 | protected $usage = '/help or /help '; 28 | protected $version = '1.0.1'; 29 | /**#@-*/ 30 | 31 | public function __construct($telegram, $update = NULL) 32 | { 33 | $this->description = \Yii::t('tlgrm', 'Show bot commands help'); 34 | parent::__construct($telegram, $update); 35 | } 36 | 37 | /** 38 | * {@inheritdoc} 39 | */ 40 | public function execute() 41 | { 42 | $message = $this->getMessage(); 43 | $chat_id = $message->getChat()->getId(); 44 | 45 | $message_id = $message->getMessageId(); 46 | $command = trim($message->getText(true)); 47 | 48 | //Only get enabled Admin and User commands 49 | $commands = array_filter($this->telegram->getCommandsList(), function ($command) { 50 | return (!$command->isSystemCommand() && $command->isEnabled()); 51 | }); 52 | 53 | //If no command parameter is passed, show the list 54 | if ($command === '') { 55 | $text = $this->telegram->getBotName() . ' v. ' . $this->telegram->getVersion() . "\n\n"; 56 | $text .= 'Commands List:' . "\n"; 57 | foreach ($commands as $command) { 58 | $text .= '/' . $command->getName() . ' - ' . $command->getDescription() . "\n"; 59 | } 60 | 61 | $text .= "\n" . 'For exact command help type: /help '; 62 | } else { 63 | $command = str_replace('/', '', $command); 64 | if (isset($commands[$command])) { 65 | $command = $commands[$command]; 66 | $text = 'Command: ' . $command->getName() . ' v' . $command->getVersion() . "\n"; 67 | $text .= 'Description: ' . $command->getDescription() . "\n"; 68 | $text .= 'Usage: ' . $command->getUsage(); 69 | } else { 70 | $text = 'No help available: Command /' . $command . ' not found.'; 71 | } 72 | } 73 | 74 | $data = [ 75 | 'chat_id' => $chat_id, 76 | 'reply_to_message_id' => $message_id, 77 | 'text' => $text, 78 | ]; 79 | 80 | return Request::sendMessage($data); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /Commands/UserCommands/Leave_dialogCommand.php: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | 11 | namespace Longman\TelegramBot\Commands\UserCommands; 12 | 13 | use onmotion\telegram\models\AuthorizedManagerChat; 14 | use Longman\TelegramBot\Commands\UserCommand; 15 | use Longman\TelegramBot\Request; 16 | 17 | /** 18 | * User "/echo" command 19 | */ 20 | class Leave_dialogCommand extends UserCommand 21 | { 22 | /**#@+ 23 | * {@inheritdoc} 24 | */ 25 | protected $name = 'leave_dialog'; 26 | protected $description = 'Закончить текущий активный диалог и перейти в режим ожидания'; 27 | protected $usage = '/leave_dialog'; 28 | protected $version = '1.0.0'; 29 | /**#@-*/ 30 | 31 | /** 32 | * {@inheritdoc} 33 | */ 34 | public function execute() 35 | { 36 | $message = $this->getMessage(); 37 | $chat_id = $message->getChat()->getId(); 38 | 39 | $data = [ 40 | 'chat_id' => $chat_id, 41 | ]; 42 | $authChat = AuthorizedManagerChat::findOne($chat_id); 43 | if (!$authChat){ 44 | $data['text'] = 'Вы не авторизовались!'; 45 | }else { 46 | $currantChat = $authChat->client_chat_id; 47 | if ($currantChat) { 48 | $data['text'] = 'Завершен диалог в чате ' . $currantChat; 49 | $authChat->client_chat_id = null; 50 | $authChat->save(); 51 | } else { 52 | $data['text'] = 'У вас нет активных диалогов.'; 53 | } 54 | } 55 | return Request::sendMessage($data); 56 | 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Commands/UserCommands/LeavedialogCommand.php: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | 11 | namespace Longman\TelegramBot\Commands\UserCommands; 12 | 13 | use onmotion\telegram\models\AuthorizedManagerChat; 14 | use Longman\TelegramBot\Commands\UserCommand; 15 | use Longman\TelegramBot\Request; 16 | use Yii; 17 | 18 | /** 19 | * User "/leavedialog" command 20 | */ 21 | class LeavedialogCommand extends UserCommand 22 | { 23 | /**#@+ 24 | * {@inheritdoc} 25 | */ 26 | protected $name = 'leavedialog'; 27 | protected $description = ''; 28 | protected $usage = '/leavedialog'; 29 | protected $version = '1.0.0'; 30 | /**#@-*/ 31 | 32 | public function __construct($telegram, $update = NULL) 33 | { 34 | $this->description = Yii::t('tlgrm', 'End the currently active conversation and switch to standby mode.'); 35 | parent::__construct($telegram, $update); 36 | } 37 | 38 | /** 39 | * {@inheritdoc} 40 | */ 41 | public function execute() 42 | { 43 | $message = $this->getMessage(); 44 | $chat_id = $message->getChat()->getId(); 45 | 46 | $data = [ 47 | 'chat_id' => $chat_id, 48 | ]; 49 | $authChat = AuthorizedManagerChat::findOne($chat_id); 50 | if (!$authChat){ 51 | $data['text'] = Yii::t('tlgrm', 'You are not authorized!'); 52 | }else { 53 | $currantChat = $authChat->client_chat_id; 54 | if ($currantChat) { 55 | $data['text'] = Yii::t('tlgrm', 'Completed conversation in chat ') . $currantChat; 56 | $authChat->client_chat_id = null; 57 | $authChat->save(); 58 | } else { 59 | $data['text'] = Yii::t('tlgrm', 'You have no active conversations.'); 60 | } 61 | } 62 | return Request::sendMessage($data); 63 | 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /Commands/UserCommands/LoginCommand.php: -------------------------------------------------------------------------------- 1 | description = \Yii::t('tlgrm', 'Login to the support system'); 29 | parent::__construct($telegram, $update); 30 | } 31 | 32 | /** 33 | * {@inheritdoc} 34 | */ 35 | public function execute() 36 | { 37 | $message = $this->getMessage(); 38 | $chat = $message->getChat(); 39 | $username = $chat->getFirstName() . ' ' . $chat->getLastName() . ' (@' . $chat->getUsername() . ')'; 40 | $chat_id = $chat->getId(); 41 | $text = Yii::t('tlgrm', 'Enter passphrase:'); 42 | $userId = $message->getFrom()->getId(); 43 | $authChat = AuthorizedManagerChat::findOne($chat_id); 44 | if ($authChat) { 45 | $data = [ 46 | 'chat_id' => $chat_id, 47 | 'text' => Yii::t('tlgrm', 'You are already logged in as ') . $username, 48 | ]; 49 | return Request::sendMessage($data); 50 | } else { 51 | $dbUser = Actions::findOne($chat_id); 52 | if ($dbUser) { 53 | $dbUser->action = 'login'; 54 | } else { 55 | $dbUser = new Actions(); 56 | $dbUser->chat_id = $chat_id; 57 | $dbUser->action = 'login'; 58 | } 59 | $dbUser->save(); 60 | $data = [ 61 | 'chat_id' => $chat_id, 62 | 'text' => $text, 63 | ]; 64 | 65 | return Request::sendMessage($data); 66 | 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /Commands/UserCommands/LogoutCommand.php: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | 11 | 12 | namespace Longman\TelegramBot\Commands\UserCommands; 13 | 14 | use onmotion\telegram\models\Actions; 15 | use onmotion\telegram\models\AuthorizedChat; 16 | use onmotion\telegram\models\AuthorizedManagerChat; 17 | use onmotion\telegram\models\Usernames; 18 | use onmotion\telegram\TelegramVars; 19 | use Longman\TelegramBot\Commands\UserCommand; 20 | use Longman\TelegramBot\Request; 21 | use Yii; 22 | 23 | /** 24 | * User "/logout" command 25 | */ 26 | class LogoutCommand extends UserCommand 27 | { 28 | /**#@+ 29 | * {@inheritdoc} 30 | */ 31 | protected $name = 'logout'; 32 | protected $description = ''; 33 | protected $usage = '/logout'; 34 | protected $version = '1.0.0'; 35 | 36 | /**#@-*/ 37 | 38 | public function __construct($telegram, $update = NULL) 39 | { 40 | $this->description = \Yii::t('tlgrm', 'Logout from the support system.'); 41 | parent::__construct($telegram, $update); 42 | } 43 | 44 | /** 45 | * {@inheritdoc} 46 | */ 47 | public function execute() 48 | { 49 | $message = $this->getMessage(); 50 | $chat_id = $message->getChat()->getId(); 51 | $userId = $message->getFrom()->getId(); 52 | 53 | $authChat = AuthorizedManagerChat::findOne($chat_id); 54 | if (!$authChat){ 55 | $data = [ 56 | 'chat_id' => $chat_id, 57 | 'text' => Yii::t('tlgrm', 'You are not logged in.'), 58 | ]; 59 | }else{ 60 | $authChat->delete(); 61 | $dbUsername = Usernames::find()->where(['chat_id' => $chat_id])->one(); 62 | if ($dbUsername) $dbUsername->delete(); 63 | $data = [ 64 | 'chat_id' => $chat_id, 65 | 'text' => Yii::t('tlgrm', 'You will no longer receive messages.'), 66 | ]; 67 | } 68 | 69 | return Request::sendMessage($data); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /Commands/UserCommands/SlapCommand.php: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | 11 | namespace Longman\TelegramBot\Commands\UserCommands; 12 | 13 | use Longman\TelegramBot\Commands\UserCommand; 14 | use Longman\TelegramBot\Request; 15 | 16 | /** 17 | * User "/slap" command 18 | */ 19 | class SlapCommand extends UserCommand 20 | { 21 | /**#@+ 22 | * {@inheritdoc} 23 | */ 24 | protected $name = 'slap'; 25 | protected $description = 'Slap someone with their username'; 26 | protected $usage = '/slap <@user>'; 27 | protected $version = '1.0.1'; 28 | public $enabled = false; 29 | /**#@-*/ 30 | 31 | /** 32 | * {@inheritdoc} 33 | */ 34 | public function execute() 35 | { 36 | $message = $this->getMessage(); 37 | 38 | $chat_id = $message->getChat()->getId(); 39 | $message_id = $message->getMessageId(); 40 | $text = $message->getText(true); 41 | 42 | $sender = '@' . $message->getFrom()->getUsername(); 43 | 44 | //username validation 45 | $test = preg_match('/@[\w_]{5,}/', $text); 46 | if ($test === 0) { 47 | $text = $sender . ' sorry no one to slap around..'; 48 | } else { 49 | $text = $sender . ' slaps ' . $text . ' around a bit with a large trout'; 50 | } 51 | 52 | $data = [ 53 | 'chat_id' => $chat_id, 54 | 'text' => $text, 55 | ]; 56 | 57 | return Request::sendMessage($data); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /Commands/UserCommands/SurveyCommand.php: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | 11 | namespace Longman\TelegramBot\Commands\UserCommands; 12 | 13 | use Longman\TelegramBot\Request; 14 | use Longman\TelegramBot\Conversation; 15 | use Longman\TelegramBot\Commands\UserCommand; 16 | use Longman\TelegramBot\Entities\ForceReply; 17 | use Longman\TelegramBot\Entities\ReplyKeyboardHide; 18 | use Longman\TelegramBot\Entities\ReplyKeyboardMarkup; 19 | 20 | /** 21 | * User "/survery" command 22 | */ 23 | class SurveyCommand extends UserCommand 24 | { 25 | /**#@+ 26 | * {@inheritdoc} 27 | */ 28 | protected $name = 'survey'; 29 | protected $description = 'Survery for bot users'; 30 | protected $usage = '/survey'; 31 | protected $version = '0.2.0'; 32 | protected $need_mysql = true; 33 | public $enabled = false; 34 | /**#@-*/ 35 | 36 | /** 37 | * Conversation Object 38 | * 39 | * @var \Longman\TelegramBot\Conversation 40 | */ 41 | protected $conversation; 42 | 43 | /** 44 | * {@inheritdoc} 45 | */ 46 | public function execute() 47 | { 48 | $message = $this->getMessage(); 49 | 50 | $chat = $message->getChat(); 51 | $user = $message->getFrom(); 52 | $text = $message->getText(true); 53 | 54 | $chat_id = $chat->getId(); 55 | $user_id = $user->getId(); 56 | 57 | //Preparing Respose 58 | $data = []; 59 | if ($chat->isGroupChat() || $chat->isSuperGroup()) { 60 | //reply to message id is applied by default 61 | //Force reply is applied by default to so can work with privacy on 62 | $data['reply_markup'] = new ForceReply([ 'selective' => true]); 63 | } 64 | $data['chat_id'] = $chat_id; 65 | 66 | //Conversation start 67 | $this->conversation = new Conversation($user_id, $chat_id, $this->getName()); 68 | 69 | //cache data from the tracking session if any 70 | if (!isset($this->conversation->notes['state'])) { 71 | $state = '0'; 72 | } else { 73 | $state = $this->conversation->notes['state']; 74 | } 75 | 76 | //state machine 77 | //entrypoint of the machine state if given by the track 78 | //Every time the step is achived the track is updated 79 | switch ($state) { 80 | case 0: 81 | if (empty($text)) { 82 | $this->conversation->notes['state'] = 0; 83 | $this->conversation->update(); 84 | 85 | $data['text'] = 'Type your name:'; 86 | $data['reply_markup'] = new ReplyKeyBoardHide(['selective' => true]); 87 | $result = Request::sendMessage($data); 88 | break; 89 | } 90 | $this->conversation->notes['name'] = $text; 91 | $text = ''; 92 | // no break 93 | case 1: 94 | if (empty($text)) { 95 | $this->conversation->notes['state'] = 1; 96 | $this->conversation->update(); 97 | 98 | $data['text'] = 'Type your surname:'; 99 | $result = Request::sendMessage($data); 100 | break; 101 | } 102 | $this->conversation->notes['surname'] = $text; 103 | ++$state; 104 | $text = ''; 105 | 106 | // no break 107 | case 2: 108 | if (empty($text) || !is_numeric($text)) { 109 | $this->conversation->notes['state'] = 2; 110 | $this->conversation->update(); 111 | 112 | $data['text'] = 'Type your age:'; 113 | if (!empty($text) && !is_numeric($text)) { 114 | $data['text'] = 'Type your age, must be a number'; 115 | } 116 | $result = Request::sendMessage($data); 117 | break; 118 | } 119 | $this->conversation->notes['age'] = $text; 120 | $text = ''; 121 | 122 | // no break 123 | case 3: 124 | if (empty($text) || !($text == 'M' || $text == 'F')) { 125 | $this->conversation->notes['state'] = 3; 126 | $this->conversation->update(); 127 | 128 | $keyboard = [['M','F']]; 129 | $reply_keyboard_markup = new ReplyKeyboardMarkup( 130 | [ 131 | 'keyboard' => $keyboard , 132 | 'resize_keyboard' => true, 133 | 'one_time_keyboard' => true, 134 | 'selective' => true 135 | ] 136 | ); 137 | $data['reply_markup'] = $reply_keyboard_markup; 138 | $data['text'] = 'Select your gender:'; 139 | if (!empty($text) && !($text == 'M' || $text == 'F')) { 140 | $data['text'] = 'Select your gender, choose a keyboard option:'; 141 | } 142 | $result = Request::sendMessage($data); 143 | break; 144 | } 145 | $this->conversation->notes['gender'] = $text; 146 | $text = ''; 147 | 148 | // no break 149 | case 4: 150 | if (is_null($message->getLocation())) { 151 | $this->conversation->notes['state'] = 4; 152 | $this->conversation->update(); 153 | $data['reply_markup'] = new ReplyKeyboardMarkup([ 154 | 'keyboard' => [[ 155 | [ 'text' => 'Share Location', 'request_location' => true ], 156 | ]], 157 | 'resize_keyboard' => true, 158 | 'one_time_keyboard' => true, 159 | 'selective' => true, 160 | ]); 161 | $data['text'] = 'Share your location:'; 162 | $result = Request::sendMessage($data); 163 | break; 164 | } 165 | 166 | $this->conversation->notes['longitude'] = $message->getLocation()->getLongitude(); 167 | $this->conversation->notes['latitude'] = $message->getLocation()->getLatitude(); 168 | 169 | // no break 170 | case 5: 171 | if (is_null($message->getPhoto())) { 172 | $this->conversation->notes['state'] = 5; 173 | $this->conversation->update(); 174 | 175 | $data['text'] = 'Insert your picture:'; 176 | $data['reply_markup'] = new ReplyKeyBoardHide(['selective' => true]); 177 | $result = Request::sendMessage($data); 178 | break; 179 | } 180 | $this->conversation->notes['photo_id'] = $message->getPhoto()[0]->getFileId(); 181 | 182 | // no break 183 | case 6: 184 | if (is_null($message->getContact())) { 185 | $this->conversation->notes['state'] = 6; 186 | $this->conversation->update(); 187 | 188 | $data['text'] = 'Share your contact information:'; 189 | $data['reply_markup'] = new ReplyKeyboardMarkup([ 190 | 'keyboard' => [[ 191 | [ 'text' => 'Share Contact', 'request_contact' => true ], 192 | ]], 193 | 'resize_keyboard' => true, 194 | 'one_time_keyboard' => true, 195 | 'selective' => true, 196 | ]); 197 | $result = Request::sendMessage($data); 198 | break; 199 | } 200 | $this->conversation->notes['phone_number'] = $message->getContact()->getPhoneNumber(); 201 | 202 | // no break 203 | case 7: 204 | $this->conversation->update(); 205 | $out_text = '/Survey result:' . "\n"; 206 | unset($this->conversation->notes['state']); 207 | foreach ($this->conversation->notes as $k => $v) { 208 | $out_text .= "\n" . ucfirst($k).': ' . $v; 209 | } 210 | 211 | $data['photo'] = $this->conversation->notes['photo_id']; 212 | $data['reply_markup'] = new ReplyKeyBoardHide(['selective' => true]); 213 | $data['caption'] = $out_text; 214 | $this->conversation->stop(); 215 | $result = Request::sendPhoto($data); 216 | break; 217 | } 218 | return $result; 219 | } 220 | } 221 | -------------------------------------------------------------------------------- /Commands/UserCommands/WeatherCommand.php: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | 11 | namespace Longman\TelegramBot\Commands\UserCommands; 12 | 13 | use GuzzleHttp\Client; 14 | use GuzzleHttp\Exception\RequestException; 15 | use Longman\TelegramBot\Commands\UserCommand; 16 | use Longman\TelegramBot\Exception\TelegramException; 17 | use Longman\TelegramBot\Request; 18 | 19 | /** 20 | * User "/weather" command 21 | */ 22 | class WeatherCommand extends UserCommand 23 | { 24 | /**#@+ 25 | * {@inheritdoc} 26 | */ 27 | protected $name = 'weather'; 28 | protected $description = 'Show weather by location'; 29 | protected $usage = '/weather '; 30 | protected $version = '1.1.0'; 31 | public $enabled = false; 32 | /**#@-*/ 33 | 34 | /** 35 | * Base URI for OpenWeatherMap API 36 | * 37 | * @var string 38 | */ 39 | private $owm_api_base_uri = 'http://api.openweathermap.org/data/2.5/'; 40 | 41 | /** 42 | * Get weather data using HTTP request 43 | * 44 | * @param string $location 45 | * 46 | * @return string 47 | */ 48 | private function getWeatherData($location) 49 | { 50 | $client = new Client(['base_uri' => $this->owm_api_base_uri]); 51 | $path = 'weather'; 52 | $query = [ 53 | 'q' => $location, 54 | 'units' => 'metric', 55 | 'APPID' => trim($this->getConfig('owm_api_key')), 56 | ]; 57 | 58 | try { 59 | $response = $client->get($path, ['query' => $query]); 60 | } catch (RequestException $e) { 61 | throw new TelegramException($e->getMessage()); 62 | } 63 | 64 | return (string)$response->getBody(); 65 | } 66 | 67 | /** 68 | * Get weather string from weather data 69 | * 70 | * @param array $data 71 | * 72 | * @return bool|string 73 | */ 74 | private function getWeatherString(array $data) 75 | { 76 | try { 77 | if (empty($data) || $data['cod'] !== 200) { 78 | return false; 79 | } 80 | 81 | //http://openweathermap.org/weather-conditions 82 | $conditions = [ 83 | 'clear' => ' ☀️', 84 | 'clouds' => ' ☁️', 85 | 'rain' => ' ☔', 86 | 'drizzle' => ' ☔', 87 | 'thunderstorm' => ' ⚡️', 88 | 'snow' => ' ❄️', 89 | ]; 90 | $conditions_now = strtolower($data['weather'][0]['main']); 91 | 92 | return sprintf( 93 | 'The temperature in %1$s (%2$s) is %3$s°C' . "\n" . 94 | 'Current conditions are: %4$s%5$s', 95 | $data['name'], //city 96 | $data['sys']['country'], //country 97 | $data['main']['temp'], //temperature 98 | $data['weather'][0]['description'], //description of weather 99 | (isset($conditions[$conditions_now])) ? $conditions[$conditions_now] : '' 100 | ); 101 | } catch (\Exception $e) { 102 | return false; 103 | } 104 | } 105 | 106 | /** 107 | * {@inheritdoc} 108 | */ 109 | public function execute() 110 | { 111 | $message = $this->getMessage(); 112 | $chat_id = $message->getChat()->getId(); 113 | $text = ''; 114 | 115 | if (trim($this->getConfig('owm_api_key'))) { 116 | if ($location = trim($message->getText(true))) { 117 | if ($weather_data = json_decode($this->getWeatherData($location), true)) { 118 | $text = $this->getWeatherString($weather_data); 119 | } 120 | if (!$text) { 121 | $text = 'Cannot find weather for location: ' . $location; 122 | } 123 | } else { 124 | $text = 'You must specify location in format: /weather '; 125 | } 126 | } else { 127 | $text = 'OpenWeatherMap API key not defined.'; 128 | } 129 | 130 | $data = [ 131 | 'chat_id' => $chat_id, 132 | 'text' => $text, 133 | ]; 134 | 135 | return Request::sendMessage($data); 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /Commands/UserCommands/WhoamiCommand.php: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | * 10 | * Written by Marco Boretto 11 | */ 12 | 13 | namespace Longman\TelegramBot\Commands\UserCommands; 14 | 15 | use Longman\TelegramBot\Commands\UserCommand; 16 | use Longman\TelegramBot\Entities\File; 17 | use Longman\TelegramBot\Request; 18 | 19 | /** 20 | * User "/whoami" command 21 | */ 22 | class WhoamiCommand extends UserCommand 23 | { 24 | /**#@+ 25 | * {@inheritdoc} 26 | */ 27 | protected $name = 'whoami'; 28 | protected $description = 'Show your id, name and username'; 29 | protected $usage = '/whoami'; 30 | protected $version = '1.0.1'; 31 | protected $public = true; 32 | public $enabled = false; 33 | /**#@-*/ 34 | 35 | /** 36 | * {@inheritdoc} 37 | */ 38 | public function execute() 39 | { 40 | $message = $this->getMessage(); 41 | 42 | $user_id = $message->getFrom()->getId(); 43 | $chat_id = $message->getChat()->getId(); 44 | $message_id = $message->getMessageId(); 45 | $text = $message->getText(true); 46 | 47 | //Send chat action 48 | Request::sendChatAction(['chat_id' => $chat_id, 'action' => 'typing']); 49 | 50 | $caption = 'Your Id: ' . $user_id . "\n"; 51 | $caption .= 'Name: ' . $message->getFrom()->getFirstName() 52 | . ' ' . $message->getFrom()->getLastName() . "\n"; 53 | $caption .= 'Username: ' . $message->getFrom()->getUsername(); 54 | 55 | //Fetch user profile photo 56 | $limit = 10; 57 | $offset = null; 58 | $ServerResponse = Request::getUserProfilePhotos([ 59 | 'user_id' => $user_id , 60 | 'limit' => $limit, 61 | 'offset' => $offset, 62 | ]); 63 | 64 | //Check if the request isOK 65 | if ($ServerResponse->isOk()) { 66 | $UserProfilePhoto = $ServerResponse->getResult(); 67 | $totalcount = $UserProfilePhoto->getTotalCount(); 68 | } else { 69 | $totalcount = 0; 70 | } 71 | 72 | $data = [ 73 | 'chat_id' => $chat_id, 74 | 'reply_to_message_id' => $message_id, 75 | ]; 76 | 77 | if ($totalcount > 0) { 78 | $photos = $UserProfilePhoto->getPhotos(); 79 | //I pick the latest photo with the hight definition 80 | $photo = $photos[0][2]; 81 | $file_id = $photo->getFileId(); 82 | 83 | $data['photo'] = $file_id; 84 | $data['caption'] = $caption; 85 | 86 | $result = Request::sendPhoto($data); 87 | 88 | //Download the image pictures 89 | //Download after send message response to speedup response 90 | $file_id = $photo->getFileId(); 91 | $ServerResponse = Request::getFile(['file_id' => $file_id]); 92 | if ($ServerResponse->isOk()) { 93 | Request::downloadFile($ServerResponse->getResult()); 94 | } 95 | } else { 96 | //No Photo just send text 97 | $data['text'] = $caption; 98 | $result = Request::sendMessage($data); 99 | } 100 | 101 | return $result; 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /Commands/YiiChatCommand.php: -------------------------------------------------------------------------------- 1 | modules['telegram']->API_KEY, \Yii::$app->modules['telegram']->BOT_NAME); 26 | $data = []; 27 | 28 | $session = \Yii::$app->session; 29 | if(!$session->has('tlgrm_chat_id')){ 30 | throw new UserException('Unknown tlgrm_chat_id'); 31 | } 32 | $tlgrmChatId = $session->get('tlgrm_chat_id'); 33 | $data['text'] = htmlentities($message['message']); 34 | //сохраняем сообщение в БД 35 | $isSaved = false; 36 | try { 37 | $message = new Message(); 38 | $message->client_chat_id = $tlgrmChatId; 39 | $message->message = $data['text']; 40 | $message->direction = 0; 41 | $message->time = date("Y-m-d H:i:s", time()); 42 | $isSaved = $message->save(); 43 | } catch (\Exception $e){ 44 | var_dump('error saving to db'); 45 | //continue anyway 46 | } 47 | //проверяем ведется ли уже диалог 48 | if ($isSaved) { 49 | $handledChat = AuthorizedManagerChat::find()->where(['client_chat_id' => $session->get('tlgrm_chat_id')])->one(); 50 | if ($handledChat) { 51 | $data['chat_id'] = $handledChat->chat_id; 52 | Request::sendMessage($data); 53 | return $message; 54 | } 55 | //delete old chat handlers (who forgot execute /leavedialog) 56 | try { 57 | $timeBeforeResetChatHandler = intval(\Yii::$app->modules['telegram']->timeBeforeResetChatHandler); 58 | if ($timeBeforeResetChatHandler > 0) { 59 | AuthorizedManagerChat::updateAll(['client_chat_id' => null], ['<', 'timestamp', 'now() - 60 * ' . $timeBeforeResetChatHandler]); 60 | } 61 | }catch (\Exception $e){ 62 | var_dump($e->getMessage()); 63 | } 64 | //если нет то шлем всем свободным 65 | $authChats = AuthorizedManagerChat::find()->where(['client_chat_id' => null])->all(); 66 | if (empty($authChats)) { 67 | $waitMessage = new Message(); 68 | $waitMessage->client_chat_id = $tlgrmChatId; 69 | $waitMessage->message = Yii::t('tlgrm', 'At the moment, there are no available operators. Please, try to write later.'); 70 | $waitMessage->direction = 1; 71 | $waitMessage->time = date("Y-m-d H:i:s", time() + 1); 72 | $waitMessage->save(); 73 | return $message; //нет свободных 74 | } 75 | try{ 76 | $yiiUsername = Yii::$app->getUser()->getIdentity()->username; 77 | } catch (\Exception $e){ 78 | $yiiUsername = 'guest'; 79 | } 80 | $data['text'] = $yiiUsername . Yii::t('tlgrm', " writes:") . "\r\n>" . $data['text']; 81 | foreach ($authChats as $authChat) { 82 | $data['chat_id'] = $authChat->chat_id; 83 | $inline_keyboard = [ 84 | new InlineKeyboardButton(['text' => Yii::t('tlgrm', 'Start conversation'), 'callback_data' => 'client_chat_id ' . $tlgrmChatId]), 85 | ]; 86 | $data['reply_markup'] = new InlineKeyboardMarkup( 87 | ['inline_keyboard' => [$inline_keyboard]]); 88 | Request::sendMessage($data); 89 | } 90 | } 91 | return $message; 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Module.php: -------------------------------------------------------------------------------- 1 | API_KEY) || empty($this->BOT_NAME) || empty($this->hook_url)) 38 | throw new UserException('You must set API_KEY, BOT_NAME, hook_url'); 39 | if (empty($this->PASSPHRASE)) 40 | throw new UserException('You must set PASSPHRASE'); 41 | 42 | 43 | 44 | parent::init(); 45 | 46 | // set up i8n 47 | if (empty(\Yii::$app->i18n->translations['tlgrm'])) { 48 | \Yii::$app->i18n->translations['tlgrm'] = [ 49 | 'class' => 'yii\i18n\PhpMessageSource', 50 | 'basePath' => __DIR__ . '/messages', 51 | //'forceTranslation' => true, 52 | ]; 53 | } 54 | 55 | $this->options = [ 56 | 'initChat' => Url::to(['/telegram/default/init-chat']), 57 | 'destroyChat' => Url::to(['/telegram/default/destroy-chat']), 58 | 'getAllMessages' => Url::to(['/telegram/chat/get-all-messages']), 59 | 'getLastMessages' => Url::to(['/telegram/chat/get-last-messages']), 60 | 'initialMessage' => \Yii::t('tlgrm', 'Write your question...'), 61 | ]; 62 | 63 | } 64 | 65 | public function bootstrap($app) 66 | { 67 | if ($app instanceof \yii\console\Application) { 68 | $this->controllerNamespace = 'onmotion\telegram\commands'; 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # **Telegram support Bot for Yii2** 2 | [![Latest Stable Version](https://poser.pugx.org/onmotion/yii2-telegram/v/stable)](https://packagist.org/packages/onmotion/yii2-telegram) [![Total Downloads](https://poser.pugx.org/onmotion/yii2-telegram/downloads)](https://packagist.org/packages/onmotion/yii2-telegram) [![License](https://poser.pugx.org/onmotion/yii2-telegram/license)](https://packagist.org/packages/onmotion/yii2-telegram) [![Daily Downloads](https://poser.pugx.org/onmotion/yii2-telegram/d/daily)](https://packagist.org/packages/onmotion/yii2-telegram) [![Monthly Downloads](https://poser.pugx.org/onmotion/yii2-telegram/d/monthly)](https://packagist.org/packages/onmotion/yii2-telegram) 3 | 4 | **Support chat for site based on Telegram bot** 5 | 6 | The Bot logic based on [akalongman/php-telegram-bot](https://github.com/akalongman/php-telegram-bot), so you can read Instructions by longman how to register Telegram Bot and etc. 7 | 8 | ***Now only telegram webhook api support. You need SSL cert! Doesn't work on http!*** 9 | 10 | **Installation** 11 | ------------ 12 | 13 | The preferred way to install this extension is through [composer](http://getcomposer.org/download/). 14 | 15 | Run 16 | 17 | 18 | composer require onmotion/yii2-telegram 19 | 20 | 21 | add to your web config: 22 | 23 | 'modules' => [ 24 | //... 25 | 'telegram' => [ 26 | 'class' => 'onmotion\telegram\Module', 27 | 'API_KEY' => 'forexample241875489:AdfgdfFuVJdsKa1cycuxra36g4dfgt66', 28 | 'BOT_NAME' => 'YourBotName_bot', 29 | 'hook_url' => 'https://yourhost.com/telegram/default/hook', // must be https! (if not prettyUrl https://yourhost.com/index.php?r=telegram/default/hook) 30 | 'PASSPHRASE' => 'passphrase for login', 31 | // 'db' => 'db2', //db file name from config dir 32 | // 'userCommandsPath' => '@app/modules/telegram/UserCommands', 33 | // 'timeBeforeResetChatHandler' => 60 34 | ] 35 | //more... 36 | ] 37 | 38 | and to console config: 39 | 40 | 'bootstrap' => [ 41 | //other bootstrap components... 42 | 'telegram'], 43 | 'modules' => [ 44 | //... 45 | 'telegram' => [ 46 | 'class' => 'onmotion\telegram\Module', 47 | 'API_KEY' => 'forexample241875489:AdfgdfFuVJdsKa1cycuxra36g4dfgt66', 48 | 'BOT_NAME' => 'YourBotName_bot', 49 | 'hook_url' => 'https://yourhost.com/telegram/default/hook', // must be https! (if not prettyUrl https://yourhost.com/index.php?r=telegram/default/hook) 50 | 'PASSPHRASE' => 'passphrase for login', 51 | ] 52 | ], 53 | 54 | run migrations: 55 | 56 | php yii migrate --migrationPath=@vendor/onmotion/yii2-telegram/migrations #that add 4 tables in your DB 57 | 58 | or add to your config file 59 | ``` 60 | 'controllerMap' => [ 61 | ... 62 | 'migrate' => [ 63 | 'class' => 'yii\console\controllers\MigrateController', 64 | 'migrationNamespaces' => [ 65 | 'onmotion\telegram\migrations', 66 | ], 67 | ], 68 | ... 69 | ], 70 | ``` 71 | and run 72 | 73 | ``` 74 | php yii migrate/up 75 | ``` 76 | 77 | go to https://yourhost.com/telegram/default/set-webhook (if not prettyUrl https://yourhost.com/index.php?r=telegram/default/set-webhook) 78 | 79 | Now you can place where you want 80 | 81 | echo \onmotion\telegram\Telegram::widget(); //that add chat button in the page 82 | 83 | in bottom right corner you can see: 84 | 85 | ![chat button](https://github.com/onmotion/yii2-telegram/blob/wiki/_wiki/04.png?raw=true) 86 | 87 | if you click it: 88 | 89 | ![client chat](https://github.com/onmotion/yii2-telegram/blob/wiki/_wiki/03.png?raw=true) 90 | 91 | and server side: 92 | 93 | ![client chat](https://github.com/onmotion/yii2-telegram/blob/wiki/_wiki/02.png?raw=true) 94 | 95 | If you want to limit the storage period of messages history, add to you crontab: 96 | 97 | #leave 5 days (if empty - default = 7) 98 | php yii telegram/messages/clean 5 99 | 100 | Also you can use custom commands. To do this, you can copy UserCommands dir from /vendor/onmotion/yii2-telegram/Commands and add path to this in config, for example: 101 | 102 | 'userCommandsPath' => '@app/modules/telegram/UserCommands' 103 | 104 | 105 | **timeBeforeResetChatHandler** - the number of minutes before chat handler will be killed (if he forgot do /leavedialog). Never kill if 0 or not setted. 106 | -------------------------------------------------------------------------------- /Telegram.php: -------------------------------------------------------------------------------- 1 | i18n->translations['tlgrm'])) { 26 | \Yii::$app->i18n->translations['tlgrm'] = [ 27 | 'class' => 'yii\i18n\PhpMessageSource', 28 | 'basePath' => __DIR__ . '/messages', 29 | //'forceTranslation' => true, 30 | ]; 31 | } 32 | 33 | parent::init(); 34 | } 35 | 36 | public function run() 37 | { 38 | $view = $this->getView(); 39 | TelegramAsset::register($view); 40 | $this->renderInitiateBtn(); 41 | } 42 | 43 | private function renderInitiateBtn() 44 | { 45 | echo $this->render('default/button.php'); 46 | } 47 | 48 | } -------------------------------------------------------------------------------- /TelegramAsset.php: -------------------------------------------------------------------------------- 1 | sourcePath = __DIR__ . '/assets'; 17 | parent::init(); 18 | } 19 | 20 | public $css = [ 21 | 'css/telegram.css', 22 | ]; 23 | public $js = [ 24 | 'js/telegram.js', 25 | 'js/jquery.nicescroll.min.js', 26 | ]; 27 | public $depends = [ 28 | 'yii\web\YiiAsset', 29 | ]; 30 | } 31 | -------------------------------------------------------------------------------- /assets/css/telegram.css: -------------------------------------------------------------------------------- 1 | #tlgrm-chat{width:300px;height:450px;background:#fff;display:inline-block;border-radius:5px;bottom:10px;position:fixed;right:10px;border:none;box-shadow:1px 10px 8px #bbb;z-index:2}#tlgrm-chat #tlgrm-chat-head{height:50px;background:#337ab7}#tlgrm-chat #tlgrm-chat-head #tlgrm-chat-head-caption{color:#fff;position:absolute;top:15px;left:15px}#tlgrm-chat #tlgrm-chat-head #tlgrm-close-btn{position:absolute;top:3px;right:7px;width:40px;height:40px;cursor:pointer;opacity:.3;-webkit-transition:opacity .1s;transition:opacity .1s}#tlgrm-chat #tlgrm-chat-head #tlgrm-close-btn:before,#tlgrm-chat #tlgrm-chat-head #tlgrm-close-btn:after{content:"";position:absolute;top:21px;left:10px;width:26px;height:2px;background:#ffffff}#tlgrm-chat #tlgrm-chat-head #tlgrm-close-btn:before{-webkit-transform:rotate(45deg);-ms-transform:rotate(45deg);transform:rotate(45deg)}#tlgrm-chat #tlgrm-chat-head #tlgrm-close-btn:after{-webkit-transform:rotate(-45deg);-ms-transform:rotate(-45deg);transform:rotate(-45deg)}#tlgrm-chat #tlgrm-chat-head #tlgrm-close-btn:hover{opacity:1}#tlgrm-chat #tlgrm-chat-flow{width:100%;height:320px;overflow:auto;padding-bottom:10px}#tlgrm-chat #tlgrm-chat-flow .tlgrm-msg{padding:8px;margin:5px;width:200px;border-radius:5px}#tlgrm-chat #tlgrm-chat-flow .tlgrm-msg.tlgrm-incoming{float:left;background:#F0F8FF}#tlgrm-chat #tlgrm-chat-flow .tlgrm-msg.tlgrm-outgoing{float:right;background:#eee}#tlgrm-chat #tlgrm-chat-send-panel{width:100%;height:80px;background:#eee;position:absolute;bottom:0;border-top:1px solid #ccc}#tlgrm-chat #tlgrm-chat-send-panel #tlgrm-send-btn{float:right;height:80px;width:38px;padding:0}#tlgrm-chat #tlgrm-chat-send-panel #tlgrm-chat-msg{height:80px;display:inline-block;width:260px;float:left;resize:none;border:1px solid #fff}#tlgrm-init-btn{display:inline-block;bottom:10px;position:fixed;right:10px}@media (max-width: 400px){#tlgrm-init-btn span{display:none}} 2 | -------------------------------------------------------------------------------- /assets/css/telegram.css.map: -------------------------------------------------------------------------------- 1 | { 2 | "version": 3, 3 | "mappings": "AAAA,WAAY;EACV,KAAK,EAAE,KAAK;EACZ,MAAM,EAAE,KAAK;EACb,UAAU,EAAE,IAAI;EAChB,OAAO,EAAE,YAAY;EACrB,aAAa,EAAE,GAAG;EAClB,MAAM,EAAE,IAAI;EACZ,QAAQ,EAAE,KAAK;EACf,KAAK,EAAE,IAAI;EACX,MAAM,EAAE,IAAI;EACZ,UAAU,EAAE,iBAAiB;EAC7B,OAAO,EAAE,CAAC;EACV,4BAAgB;IACd,MAAM,EAAE,IAAI;IACZ,UAAU,EAAE,OAAO;IACnB,qDAAyB;MACvB,KAAK,EAAE,IAAI;MACX,QAAQ,EAAE,QAAQ;MAClB,GAAG,EAAE,IAAI;MACT,IAAI,EAAE,IAAI;IAEZ,6CAAgB;MACd,QAAQ,EAAE,QAAQ;MAClB,GAAG,EAAE,GAAG;MACR,KAAK,EAAE,GAAG;MACV,KAAK,EAAE,IAAI;MACX,MAAM,EAAE,IAAI;MACZ,MAAM,EAAE,OAAO;MACf,OAAO,EAAE,EAAE;MACX,UAAU,EAAE,WAAW;MACvB,yGAAiB;QACf,OAAO,EAAE,EAAE;QACX,QAAQ,EAAE,QAAQ;QAClB,GAAG,EAAE,IAAI;QACT,IAAI,EAAE,IAAI;QACV,KAAK,EAAE,IAAI;QACX,MAAM,EAAE,GAAG;QACX,UAAU,EAAE,OAAO;MAErB,oDAAS;QACP,SAAS,EAAE,aAAa;MAE1B,mDAAQ;QACN,SAAS,EAAE,cAAc;MAE3B,mDAAQ;QACN,OAAO,EAAE,CAAC;EAIhB,4BAAgB;IACd,KAAK,EAAE,IAAI;IACX,MAAM,EAAE,KAAK;IACb,QAAQ,EAAE,IAAI;IACd,cAAc,EAAE,IAAI;IACpB,uCAAU;MACR,OAAO,EAAE,GAAG;MACZ,MAAM,EAAE,GAAG;MACX,KAAK,EAAE,KAAK;MACZ,aAAa,EAAE,GAAG;MAClB,sDAAgB;QACd,KAAK,EAAE,IAAI;QACX,UAAU,EAAE,OAAO;MAErB,sDAAgB;QACd,KAAK,EAAE,KAAK;QACZ,UAAU,EAAE,IAAI;EAItB,kCAAuB;IACrB,KAAK,EAAE,IAAI;IACX,MAAM,EAAE,IAAI;IACZ,UAAU,EAAE,IAAI;IAChB,QAAQ,EAAE,QAAQ;IAClB,MAAM,EAAE,CAAC;IACT,UAAU,EAAE,cAAc;IAC1B,kDAAe;MACb,KAAK,EAAE,KAAK;MACZ,MAAM,EAAE,IAAI;MACZ,KAAK,EAAE,IAAI;MACX,OAAO,EAAE,CAAC;IAEZ,kDAAe;MACb,MAAM,EAAE,IAAI;MACZ,OAAO,EAAE,YAAY;MACrB,KAAK,EAAE,KAAK;MACZ,KAAK,EAAE,IAAI;MACX,MAAM,EAAE,IAAI;MACZ,MAAM,EAAE,cAAc;;AAI5B,eAAe;EACb,OAAO,EAAE,YAAY;EACrB,MAAM,EAAE,IAAI;EACZ,QAAQ,EAAE,KAAK;EACf,KAAK,EAAE,IAAI;;AAEb,yBAA0B;EACxB,oBAAoB;IAClB,OAAO,EAAE,IAAI", 4 | "sources": ["telegram.scss"], 5 | "names": [], 6 | "file": "telegram.css" 7 | } 8 | -------------------------------------------------------------------------------- /assets/css/telegram.scss: -------------------------------------------------------------------------------- 1 | #tlgrm-chat { 2 | width: 300px; 3 | height: 450px; 4 | background: #fff; 5 | display: inline-block; 6 | border-radius: 5px; 7 | bottom: 10px; 8 | position: fixed; 9 | right: 10px; 10 | border: none; 11 | box-shadow: 1px 10px 8px #bbb; 12 | z-index: 2; 13 | #tlgrm-chat-head{ 14 | height: 50px; 15 | background: #337ab7; 16 | #tlgrm-chat-head-caption { 17 | color: #fff; 18 | position: absolute; 19 | top: 15px; 20 | left: 15px; 21 | } 22 | #tlgrm-close-btn{ 23 | position: absolute; 24 | top: 3px; 25 | right: 7px; 26 | width: 40px; 27 | height: 40px; 28 | cursor: pointer; 29 | opacity: .3; 30 | transition: opacity .1s; 31 | &:before, &:after{ 32 | content: ""; 33 | position: absolute; 34 | top: 21px; 35 | left: 10px; 36 | width: 26px; 37 | height: 2px; 38 | background: #ffffff; 39 | } 40 | &:before { 41 | transform: rotate(45deg); 42 | } 43 | &:after { 44 | transform: rotate(-45deg); 45 | } 46 | &:hover { 47 | opacity: 1; 48 | } 49 | } 50 | } 51 | #tlgrm-chat-flow{ 52 | width: 100%; 53 | height: 320px; 54 | overflow: auto; 55 | padding-bottom: 10px; 56 | .tlgrm-msg{ 57 | padding: 8px; 58 | margin: 5px; 59 | width: 200px; 60 | border-radius: 5px; 61 | &.tlgrm-incoming{ 62 | float: left; 63 | background: #F0F8FF; 64 | } 65 | &.tlgrm-outgoing{ 66 | float: right; 67 | background: #eee; 68 | } 69 | } 70 | } 71 | #tlgrm-chat-send-panel { 72 | width: 100%; 73 | height: 80px; 74 | background: #eee; 75 | position: absolute; 76 | bottom: 0; 77 | border-top: 1px solid #ccc; 78 | #tlgrm-send-btn{ 79 | float: right; 80 | height: 80px; 81 | width: 38px; 82 | padding: 0; 83 | } 84 | #tlgrm-chat-msg{ 85 | height: 80px; 86 | display: inline-block; 87 | width: 260px; 88 | float: left; 89 | resize: none; 90 | border: 1px solid #fff; 91 | } 92 | } 93 | } 94 | #tlgrm-init-btn{ 95 | display: inline-block; 96 | bottom: 10px; 97 | position: fixed; 98 | right: 10px; 99 | } 100 | @media (max-width: 400px) { 101 | #tlgrm-init-btn span{ 102 | display: none; 103 | } 104 | } -------------------------------------------------------------------------------- /assets/js/jquery.nicescroll.min.js: -------------------------------------------------------------------------------- 1 | /* jquery.nicescroll 3.6.8 InuYaksa*2015 MIT http://nicescroll.areaaperta.com */(function(f){"function"===typeof define&&define.amd?define(["jquery"],f):"object"===typeof exports?module.exports=f(require("jquery")):f(jQuery)})(function(f){var B=!1,F=!1,O=0,P=2E3,A=0,J=["webkit","ms","moz","o"],v=window.requestAnimationFrame||!1,w=window.cancelAnimationFrame||!1;if(!v)for(var Q in J){var G=J[Q];if(v=window[G+"RequestAnimationFrame"]){w=window[G+"CancelAnimationFrame"]||window[G+"CancelRequestAnimationFrame"];break}}var x=window.MutationObserver||window.WebKitMutationObserver|| 2 | !1,K={zindex:"auto",cursoropacitymin:0,cursoropacitymax:1,cursorcolor:"#424242",cursorwidth:"6px",cursorborder:"1px solid #fff",cursorborderradius:"5px",scrollspeed:60,mousescrollstep:24,touchbehavior:!1,hwacceleration:!0,usetransition:!0,boxzoom:!1,dblclickzoom:!0,gesturezoom:!0,grabcursorenabled:!0,autohidemode:!0,background:"",iframeautoresize:!0,cursorminheight:32,preservenativescrolling:!0,railoffset:!1,railhoffset:!1,bouncescroll:!0,spacebarenabled:!0,railpadding:{top:0,right:0,left:0,bottom:0}, 3 | disableoutline:!0,horizrailenabled:!0,railalign:"right",railvalign:"bottom",enabletranslate3d:!0,enablemousewheel:!0,enablekeyboard:!0,smoothscroll:!0,sensitiverail:!0,enablemouselockapi:!0,cursorfixedheight:!1,directionlockdeadzone:6,hidecursordelay:400,nativeparentscrolling:!0,enablescrollonselection:!0,overflowx:!0,overflowy:!0,cursordragspeed:.3,rtlmode:"auto",cursordragontouch:!1,oneaxismousemode:"auto",scriptpath:function(){var f=document.getElementsByTagName("script"),f=f.length?f[f.length- 4 | 1].src.split("?")[0]:"";return 0d?a.getScrollLeft()>=a.page.maxw:0>=a.getScrollLeft())&&(e=d,d=0));a.isrtlmode&&(d=-d);d&&(a.scrollmom&&a.scrollmom.stop(),a.lastdeltax+=d,a.debounced("mousewheelx",function(){var b=a.lastdeltax;a.lastdeltax=0;a.rail.drag||a.doScrollLeftBy(b)},15));if(e){if(a.opt.nativeparentscrolling&&c&&!a.ispage&&!a.zoomactive)if(0>e){if(a.getScrollTop()>=a.page.maxh)return!0}else if(0>=a.getScrollTop())return!0;a.scrollmom&&a.scrollmom.stop();a.lastdeltay+=e; 14 | a.synched("mousewheely",function(){var b=a.lastdeltay;a.lastdeltay=0;a.rail.drag||a.doScrollBy(b)},15)}b.stopImmediatePropagation();return b.preventDefault()}var a=this;this.version="3.6.8";this.name="nicescroll";this.me=c;this.opt={doc:f("body"),win:!1};f.extend(this.opt,K);this.opt.snapbackspeed=80;if(h)for(var r in a.opt)void 0!==h[r]&&(a.opt[r]=h[r]);a.opt.disablemutationobserver&&(x=!1);this.iddoc=(this.doc=a.opt.doc)&&this.doc[0]?this.doc[0].id||"":"";this.ispage=/^BODY|HTML/.test(a.opt.win? 15 | a.opt.win[0].nodeName:this.doc[0].nodeName);this.haswrapper=!1!==a.opt.win;this.win=a.opt.win||(this.ispage?f(window):this.doc);this.docscroll=this.ispage&&!this.haswrapper?f(window):this.win;this.body=f("body");this.iframe=this.isfixed=this.viewport=!1;this.isiframe="IFRAME"==this.doc[0].nodeName&&"IFRAME"==this.win[0].nodeName;this.istextarea="TEXTAREA"==this.win[0].nodeName;this.forcescreen=!1;this.canshowonmouseevent="scroll"!=a.opt.autohidemode;this.page=this.view=this.onzoomout=this.onzoomin= 16 | this.onscrollcancel=this.onscrollend=this.onscrollstart=this.onclick=this.ongesturezoom=this.onkeypress=this.onmousewheel=this.onmousemove=this.onmouseup=this.onmousedown=!1;this.scroll={x:0,y:0};this.scrollratio={x:0,y:0};this.cursorheight=20;this.scrollvaluemax=0;if("auto"==this.opt.rtlmode){r=this.win[0]==window?this.body:this.win;var p=r.css("writing-mode")||r.css("-webkit-writing-mode")||r.css("-ms-writing-mode")||r.css("-moz-writing-mode");"horizontal-tb"==p||"lr-tb"==p||""==p?(this.isrtlmode= 17 | "rtl"==r.css("direction"),this.isvertical=!1):(this.isrtlmode="vertical-rl"==p||"tb"==p||"tb-rl"==p||"rl-tb"==p,this.isvertical="vertical-rl"==p||"tb"==p||"tb-rl"==p)}else this.isrtlmode=!0===this.opt.rtlmode,this.isvertical=!1;this.observerbody=this.observerremover=this.observer=this.scrollmom=this.scrollrunning=!1;do this.id="ascrail"+P++;while(document.getElementById(this.id));this.hasmousefocus=this.hasfocus=this.zoomactive=this.zoom=this.selectiondrag=this.cursorfreezed=this.cursor=this.rail= 18 | !1;this.visibility=!0;this.hidden=this.locked=this.railslocked=!1;this.cursoractive=!0;this.wheelprevented=!1;this.overflowx=a.opt.overflowx;this.overflowy=a.opt.overflowy;this.nativescrollingarea=!1;this.checkarea=0;this.events=[];this.saved={};this.delaylist={};this.synclist={};this.lastdeltay=this.lastdeltax=0;this.detected=R();var e=f.extend({},this.detected);this.ishwscroll=(this.canhwscroll=e.hastransform&&a.opt.hwacceleration)&&a.haswrapper;this.hasreversehr=this.isrtlmode?this.isvertical? 19 | !(e.iswebkit||e.isie||e.isie11):!(e.iswebkit||e.isie&&!e.isie10&&!e.isie11):!1;this.istouchcapable=!1;e.cantouch||!e.hasw3ctouch&&!e.hasmstouch?!e.cantouch||e.isios||e.isandroid||!e.iswebkit&&!e.ismozilla||(this.istouchcapable=!0):this.istouchcapable=!0;a.opt.enablemouselockapi||(e.hasmousecapture=!1,e.haspointerlock=!1);this.debounced=function(b,g,c){a&&(a.delaylist[b]||(g.call(a),a.delaylist[b]={h:v(function(){a.delaylist[b].fn.call(a);a.delaylist[b]=!1},c)}),a.delaylist[b].fn=g)};var I=!1;this.synched= 20 | function(b,g){a.synclist[b]=g;(function(){I||(v(function(){if(a){I=!1;for(var b in a.synclist){var g=a.synclist[b];g&&g.call(a);a.synclist[b]=!1}}}),I=!0)})();return b};this.unsynched=function(b){a.synclist[b]&&(a.synclist[b]=!1)};this.css=function(b,g){for(var c in g)a.saved.css.push([b,c,b.css(c)]),b.css(c,g[c])};this.scrollTop=function(b){return void 0===b?a.getScrollTop():a.setScrollTop(b)};this.scrollLeft=function(b){return void 0===b?a.getScrollLeft():a.setScrollLeft(b)};var D=function(a,g, 21 | c,d,e,f,k){this.st=a;this.ed=g;this.spd=c;this.p1=d||0;this.p2=e||1;this.p3=f||0;this.p4=k||1;this.ts=(new Date).getTime();this.df=this.ed-this.st};D.prototype={B2:function(a){return 3*a*a*(1-a)},B3:function(a){return 3*a*(1-a)*(1-a)},B4:function(a){return(1-a)*(1-a)*(1-a)},getNow:function(){var a=1-((new Date).getTime()-this.ts)/this.spd,g=this.B2(a)+this.B3(a)+this.B4(a);return 0>a?this.ed:this.st+Math.round(this.df*g)},update:function(a,g){this.st=this.getNow();this.ed=a;this.spd=g;this.ts=(new Date).getTime(); 22 | this.df=this.ed-this.st;return this}};if(this.ishwscroll){this.doc.translate={x:0,y:0,tx:"0px",ty:"0px"};e.hastranslate3d&&e.isios&&this.doc.css("-webkit-backface-visibility","hidden");this.getScrollTop=function(b){if(!b){if(b=k())return 16==b.length?-b[13]:-b[5];if(a.timerscroll&&a.timerscroll.bz)return a.timerscroll.bz.getNow()}return a.doc.translate.y};this.getScrollLeft=function(b){if(!b){if(b=k())return 16==b.length?-b[12]:-b[4];if(a.timerscroll&&a.timerscroll.bh)return a.timerscroll.bh.getNow()}return a.doc.translate.x}; 23 | this.notifyScrollEvent=function(a){var g=document.createEvent("UIEvents");g.initUIEvent("scroll",!1,!0,window,1);g.niceevent=!0;a.dispatchEvent(g)};var y=this.isrtlmode?1:-1;e.hastranslate3d&&a.opt.enabletranslate3d?(this.setScrollTop=function(b,g){a.doc.translate.y=b;a.doc.translate.ty=-1*b+"px";a.doc.css(e.trstyle,"translate3d("+a.doc.translate.tx+","+a.doc.translate.ty+",0px)");g||a.notifyScrollEvent(a.win[0])},this.setScrollLeft=function(b,g){a.doc.translate.x=b;a.doc.translate.tx=b*y+"px";a.doc.css(e.trstyle, 24 | "translate3d("+a.doc.translate.tx+","+a.doc.translate.ty+",0px)");g||a.notifyScrollEvent(a.win[0])}):(this.setScrollTop=function(b,g){a.doc.translate.y=b;a.doc.translate.ty=-1*b+"px";a.doc.css(e.trstyle,"translate("+a.doc.translate.tx+","+a.doc.translate.ty+")");g||a.notifyScrollEvent(a.win[0])},this.setScrollLeft=function(b,g){a.doc.translate.x=b;a.doc.translate.tx=b*y+"px";a.doc.css(e.trstyle,"translate("+a.doc.translate.tx+","+a.doc.translate.ty+")");g||a.notifyScrollEvent(a.win[0])})}else this.getScrollTop= 25 | function(){return a.docscroll.scrollTop()},this.setScrollTop=function(b){return setTimeout(function(){a&&a.docscroll.scrollTop(b)},1)},this.getScrollLeft=function(){return a.hasreversehr?a.detected.ismozilla?a.page.maxw-Math.abs(a.docscroll.scrollLeft()):a.page.maxw-a.docscroll.scrollLeft():a.docscroll.scrollLeft()},this.setScrollLeft=function(b){return setTimeout(function(){if(a)return a.hasreversehr&&(b=a.detected.ismozilla?-(a.page.maxw-b):a.page.maxw-b),a.docscroll.scrollLeft(b)},1)};this.getTarget= 26 | function(a){return a?a.target?a.target:a.srcElement?a.srcElement:!1:!1};this.hasParent=function(a,g){if(!a)return!1;for(var c=a.target||a.srcElement||a||!1;c&&c.id!=g;)c=c.parentNode||!1;return!1!==c};var z={thin:1,medium:3,thick:5};this.getDocumentScrollOffset=function(){return{top:window.pageYOffset||document.documentElement.scrollTop,left:window.pageXOffset||document.documentElement.scrollLeft}};this.getOffset=function(){if(a.isfixed){var b=a.win.offset(),g=a.getDocumentScrollOffset();b.top-=g.top; 27 | b.left-=g.left;return b}b=a.win.offset();if(!a.viewport)return b;g=a.viewport.offset();return{top:b.top-g.top,left:b.left-g.left}};this.updateScrollBar=function(b){var g,c,e;if(a.ishwscroll)a.rail.css({height:a.win.innerHeight()-(a.opt.railpadding.top+a.opt.railpadding.bottom)}),a.railh&&a.railh.css({width:a.win.innerWidth()-(a.opt.railpadding.left+a.opt.railpadding.right)});else{var f=a.getOffset();g=f.top;c=f.left-(a.opt.railpadding.left+a.opt.railpadding.right);g+=d(a.win,"border-top-width",!0); 28 | c+=a.rail.align?a.win.outerWidth()-d(a.win,"border-right-width")-a.rail.width:d(a.win,"border-left-width");if(e=a.opt.railoffset)e.top&&(g+=e.top),e.left&&(c+=e.left);a.railslocked||a.rail.css({top:g,left:c,height:(b?b.h:a.win.innerHeight())-(a.opt.railpadding.top+a.opt.railpadding.bottom)});a.zoom&&a.zoom.css({top:g+1,left:1==a.rail.align?c-20:c+a.rail.width+4});if(a.railh&&!a.railslocked){g=f.top;c=f.left;if(e=a.opt.railhoffset)e.top&&(g+=e.top),e.left&&(c+=e.left);b=a.railh.align?g+d(a.win,"border-top-width", 29 | !0)+a.win.innerHeight()-a.railh.height:g+d(a.win,"border-top-width",!0);c+=d(a.win,"border-left-width");a.railh.css({top:b-(a.opt.railpadding.top+a.opt.railpadding.bottom),left:c,width:a.railh.width})}}};this.doRailClick=function(b,g,c){var d;a.railslocked||(a.cancelEvent(b),g?(g=c?a.doScrollLeft:a.doScrollTop,d=c?(b.pageX-a.railh.offset().left-a.cursorwidth/2)*a.scrollratio.x:(b.pageY-a.rail.offset().top-a.cursorheight/2)*a.scrollratio.y,g(d)):(g=c?a.doScrollLeftBy:a.doScrollBy,d=c?a.scroll.x:a.scroll.y, 30 | b=c?b.pageX-a.railh.offset().left:b.pageY-a.rail.offset().top,c=c?a.view.w:a.view.h,g(d>=b?c:-c)))};a.hasanimationframe=v;a.hascancelanimationframe=w;a.hasanimationframe?a.hascancelanimationframe||(w=function(){a.cancelAnimationFrame=!0}):(v=function(a){return setTimeout(a,15-Math.floor(+new Date/1E3)%16)},w=clearTimeout);this.init=function(){a.saved.css=[];if(e.isie7mobile||e.isoperamini)return!0;e.hasmstouch&&a.css(a.ispage?f("html"):a.win,{_touchaction:"none"});var b=e.ismodernie||e.isie10?{"-ms-overflow-style":"none"}: 31 | {"overflow-y":"hidden"};a.zindex="auto";a.zindex=a.ispage||"auto"!=a.opt.zindex?a.opt.zindex:l()||"auto";!a.ispage&&"auto"!=a.zindex&&a.zindex>A&&(A=a.zindex);a.isie&&0==a.zindex&&"auto"==a.opt.zindex&&(a.zindex="auto");if(!a.ispage||!e.cantouch&&!e.isieold&&!e.isie9mobile){var c=a.docscroll;a.ispage&&(c=a.haswrapper?a.win:a.doc);e.isie9mobile||a.css(c,b);a.ispage&&e.isie7&&("BODY"==a.doc[0].nodeName?a.css(f("html"),{"overflow-y":"hidden"}):"HTML"==a.doc[0].nodeName&&a.css(f("body"),b));!e.isios|| 32 | a.ispage||a.haswrapper||a.css(f("body"),{"-webkit-overflow-scrolling":"touch"});var d=f(document.createElement("div"));d.css({position:"relative",top:0,"float":"right",width:a.opt.cursorwidth,height:0,"background-color":a.opt.cursorcolor,border:a.opt.cursorborder,"background-clip":"padding-box","-webkit-border-radius":a.opt.cursorborderradius,"-moz-border-radius":a.opt.cursorborderradius,"border-radius":a.opt.cursorborderradius});d.hborder=parseFloat(d.outerHeight()-d.innerHeight());d.addClass("nicescroll-cursors"); 33 | a.cursor=d;var m=f(document.createElement("div"));m.attr("id",a.id);m.addClass("nicescroll-rails nicescroll-rails-vr");var k,h,p=["left","right","top","bottom"],L;for(L in p)h=p[L],(k=a.opt.railpadding[h])?m.css("padding-"+h,k+"px"):a.opt.railpadding[h]=0;m.append(d);m.width=Math.max(parseFloat(a.opt.cursorwidth),d.outerWidth());m.css({width:m.width+"px",zIndex:a.zindex,background:a.opt.background,cursor:"default"});m.visibility=!0;m.scrollable=!0;m.align="left"==a.opt.railalign?0:1;a.rail=m;d=a.rail.drag= 34 | !1;!a.opt.boxzoom||a.ispage||e.isieold||(d=document.createElement("div"),a.bind(d,"click",a.doZoom),a.bind(d,"mouseenter",function(){a.zoom.css("opacity",a.opt.cursoropacitymax)}),a.bind(d,"mouseleave",function(){a.zoom.css("opacity",a.opt.cursoropacitymin)}),a.zoom=f(d),a.zoom.css({cursor:"pointer",zIndex:a.zindex,backgroundImage:"url("+a.opt.scriptpath+"zoomico.png)",height:18,width:18,backgroundPosition:"0px 0px"}),a.opt.dblclickzoom&&a.bind(a.win,"dblclick",a.doZoom),e.cantouch&&a.opt.gesturezoom&& 35 | (a.ongesturezoom=function(b){1.5b.scale&&a.doZoomOut(b);return a.cancelEvent(b)},a.bind(a.win,"gestureend",a.ongesturezoom)));a.railh=!1;var n;a.opt.horizrailenabled&&(a.css(c,{overflowX:"hidden"}),d=f(document.createElement("div")),d.css({position:"absolute",top:0,height:a.opt.cursorwidth,width:0,backgroundColor:a.opt.cursorcolor,border:a.opt.cursorborder,backgroundClip:"padding-box","-webkit-border-radius":a.opt.cursorborderradius,"-moz-border-radius":a.opt.cursorborderradius, 36 | "border-radius":a.opt.cursorborderradius}),e.isieold&&d.css("overflow","hidden"),d.wborder=parseFloat(d.outerWidth()-d.innerWidth()),d.addClass("nicescroll-cursors"),a.cursorh=d,n=f(document.createElement("div")),n.attr("id",a.id+"-hr"),n.addClass("nicescroll-rails nicescroll-rails-hr"),n.height=Math.max(parseFloat(a.opt.cursorwidth),d.outerHeight()),n.css({height:n.height+"px",zIndex:a.zindex,background:a.opt.background}),n.append(d),n.visibility=!0,n.scrollable=!0,n.align="top"==a.opt.railvalign? 37 | 0:1,a.railh=n,a.railh.drag=!1);a.ispage?(m.css({position:"fixed",top:0,height:"100%"}),m.align?m.css({right:0}):m.css({left:0}),a.body.append(m),a.railh&&(n.css({position:"fixed",left:0,width:"100%"}),n.align?n.css({bottom:0}):n.css({top:0}),a.body.append(n))):(a.ishwscroll?("static"==a.win.css("position")&&a.css(a.win,{position:"relative"}),c="HTML"==a.win[0].nodeName?a.body:a.win,f(c).scrollTop(0).scrollLeft(0),a.zoom&&(a.zoom.css({position:"absolute",top:1,right:0,"margin-right":m.width+4}),c.append(a.zoom)), 38 | m.css({position:"absolute",top:0}),m.align?m.css({right:0}):m.css({left:0}),c.append(m),n&&(n.css({position:"absolute",left:0,bottom:0}),n.align?n.css({bottom:0}):n.css({top:0}),c.append(n))):(a.isfixed="fixed"==a.win.css("position"),c=a.isfixed?"fixed":"absolute",a.isfixed||(a.viewport=a.getViewport(a.win[0])),a.viewport&&(a.body=a.viewport,0==/fixed|absolute/.test(a.viewport.css("position"))&&a.css(a.viewport,{position:"relative"})),m.css({position:c}),a.zoom&&a.zoom.css({position:c}),a.updateScrollBar(), 39 | a.body.append(m),a.zoom&&a.body.append(a.zoom),a.railh&&(n.css({position:c}),a.body.append(n))),e.isios&&a.css(a.win,{"-webkit-tap-highlight-color":"rgba(0,0,0,0)","-webkit-touch-callout":"none"}),e.isie&&a.opt.disableoutline&&a.win.attr("hideFocus","true"),e.iswebkit&&a.opt.disableoutline&&a.win.css("outline","none"));!1===a.opt.autohidemode?(a.autohidedom=!1,a.rail.css({opacity:a.opt.cursoropacitymax}),a.railh&&a.railh.css({opacity:a.opt.cursoropacitymax})):!0===a.opt.autohidemode||"leave"===a.opt.autohidemode? 40 | (a.autohidedom=f().add(a.rail),e.isie8&&(a.autohidedom=a.autohidedom.add(a.cursor)),a.railh&&(a.autohidedom=a.autohidedom.add(a.railh)),a.railh&&e.isie8&&(a.autohidedom=a.autohidedom.add(a.cursorh))):"scroll"==a.opt.autohidemode?(a.autohidedom=f().add(a.rail),a.railh&&(a.autohidedom=a.autohidedom.add(a.railh))):"cursor"==a.opt.autohidemode?(a.autohidedom=f().add(a.cursor),a.railh&&(a.autohidedom=a.autohidedom.add(a.cursorh))):"hidden"==a.opt.autohidemode&&(a.autohidedom=!1,a.hide(),a.railslocked= 41 | !1);if(e.isie9mobile)a.scrollmom=new M(a),a.onmangotouch=function(){var b=a.getScrollTop(),c=a.getScrollLeft();if(b==a.scrollmom.lastscrolly&&c==a.scrollmom.lastscrollx)return!0;var g=b-a.mangotouch.sy,d=c-a.mangotouch.sx;if(0!=Math.round(Math.sqrt(Math.pow(d,2)+Math.pow(g,2)))){var e=0>g?-1:1,f=0>d?-1:1,u=+new Date;a.mangotouch.lazy&&clearTimeout(a.mangotouch.lazy);80h?h=Math.round(h/2):h>a.page.maxh&&(h=a.page.maxh+Math.round((h-a.page.maxh)/2)):(0>h&&(u=h=0),h>a.page.maxh&&(h=a.page.maxh,u=0));var l;a.railh&&a.railh.scrollable&&(l=a.isrtlmode?k-a.rail.drag.sl:a.rail.drag.sl-k,a.ishwscroll&&a.opt.bouncescroll?0>l?l=Math.round(l/2):l>a.page.maxw&&(l=a.page.maxw+Math.round((l-a.page.maxw)/ 50 | 2)):(0>l&&(m=l=0),l>a.page.maxw&&(l=a.page.maxw,m=0)));g=!1;if(a.rail.drag.dl)g=!0,"v"==a.rail.drag.dl?l=a.rail.drag.sl:"h"==a.rail.drag.dl&&(h=a.rail.drag.st);else{d=Math.abs(d);var k=Math.abs(k),C=a.opt.directionlockdeadzone;if("v"==a.rail.drag.ck){if(d>C&&k<=.3*d)return a.rail.drag=!1,!0;k>C&&(a.rail.drag.dl="f",f("body").scrollTop(f("body").scrollTop()))}else if("h"==a.rail.drag.ck){if(k>C&&d<=.3*k)return a.rail.drag=!1,!0;d>C&&(a.rail.drag.dl="f",f("body").scrollLeft(f("body").scrollLeft()))}}a.synched("touchmove", 51 | function(){a.rail.drag&&2==a.rail.drag.pt&&(a.prepareTransition&&a.prepareTransition(0),a.rail.scrollable&&a.setScrollTop(h),a.scrollmom.update(m,u),a.railh&&a.railh.scrollable?(a.setScrollLeft(l),a.showCursor(h,l)):a.showCursor(h),e.isie10&&document.selection.clear())});e.ischrome&&a.istouchcapable&&(g=!1);if(g)return a.cancelEvent(b)}else if(1==a.rail.drag.pt)return a.onmousemove(b)}}a.onmousedown=function(b,c){if(!a.rail.drag||1==a.rail.drag.pt){if(a.railslocked)return a.cancelEvent(b);a.cancelScroll(); 52 | a.rail.drag={x:b.clientX,y:b.clientY,sx:a.scroll.x,sy:a.scroll.y,pt:1,hr:!!c};var g=a.getTarget(b);!a.ispage&&e.hasmousecapture&&g.setCapture();a.isiframe&&!e.hasmousecapture&&(a.saved.csspointerevents=a.doc.css("pointer-events"),a.css(a.doc,{"pointer-events":"none"}));a.hasmoving=!1;return a.cancelEvent(b)}};a.onmouseup=function(b){if(a.rail.drag){if(1!=a.rail.drag.pt)return!0;e.hasmousecapture&&document.releaseCapture();a.isiframe&&!e.hasmousecapture&&a.doc.css("pointer-events",a.saved.csspointerevents); 53 | a.rail.drag=!1;a.hasmoving&&a.triggerScrollEnd();return a.cancelEvent(b)}};a.onmousemove=function(b){if(a.rail.drag){if(1==a.rail.drag.pt){if(e.ischrome&&0==b.which)return a.onmouseup(b);a.cursorfreezed=!0;a.hasmoving=!0;if(a.rail.drag.hr){a.scroll.x=a.rail.drag.sx+(b.clientX-a.rail.drag.x);0>a.scroll.x&&(a.scroll.x=0);var c=a.scrollvaluemaxw;a.scroll.x>c&&(a.scroll.x=c)}else a.scroll.y=a.rail.drag.sy+(b.clientY-a.rail.drag.y),0>a.scroll.y&&(a.scroll.y=0),c=a.scrollvaluemax,a.scroll.y>c&&(a.scroll.y= 54 | c);a.synched("mousemove",function(){a.rail.drag&&1==a.rail.drag.pt&&(a.showCursor(),a.rail.drag.hr?a.hasreversehr?a.doScrollLeft(a.scrollvaluemaxw-Math.round(a.scroll.x*a.scrollratio.x),a.opt.cursordragspeed):a.doScrollLeft(Math.round(a.scroll.x*a.scrollratio.x),a.opt.cursordragspeed):a.doScrollTop(Math.round(a.scroll.y*a.scrollratio.y),a.opt.cursordragspeed))});return a.cancelEvent(b)}}else a.checkarea=0};if(e.cantouch||a.opt.touchbehavior)a.onpreventclick=function(b){if(a.preventclick)return a.preventclick.tg.onclick= 55 | a.preventclick.click,a.preventclick=!1,a.cancelEvent(b)},a.bind(a.win,"mousedown",a.ontouchstart),a.onclick=e.isios?!1:function(b){return a.lastmouseup?(a.lastmouseup=!1,a.cancelEvent(b)):!0},a.opt.grabcursorenabled&&e.cursorgrabvalue&&(a.css(a.ispage?a.doc:a.win,{cursor:e.cursorgrabvalue}),a.css(a.rail,{cursor:e.cursorgrabvalue}));else{var r=function(b){if(a.selectiondrag){if(b){var c=a.win.outerHeight();b=b.pageY-a.selectiondrag.top;0=c&&(b-=c);a.selectiondrag.df=b}0!=a.selectiondrag.df&& 56 | (a.doScrollBy(2*-Math.floor(a.selectiondrag.df/6)),a.debounced("doselectionscroll",function(){r()},50))}};a.hasTextSelected="getSelection"in document?function(){return 0a.page.maxh?a.doScrollTop(a.page.maxh):(a.scroll.y=Math.round(a.getScrollTop()* 82 | (1/a.scrollratio.y)),a.scroll.x=Math.round(a.getScrollLeft()*(1/a.scrollratio.x)),a.cursoractive&&a.noticeCursor());a.scroll.y&&0==a.getScrollTop()&&a.doScrollTo(Math.floor(a.scroll.y*a.scrollratio.y));return a};this.resize=a.onResize;this.hlazyresize=0;this.lazyResize=function(b){a.haswrapper||a.hide();a.hlazyresize&&clearTimeout(a.hlazyresize);a.hlazyresize=setTimeout(function(){a&&a.show().resize()},240);return a};this.jqbind=function(b,c,d){a.events.push({e:b,n:c,f:d,q:!0});f(b).bind(c,d)};this.mousewheel= 83 | function(b,c,d){b="jquery"in b?b[0]:b;if("onwheel"in document.createElement("div"))a._bind(b,"wheel",c,d||!1);else{var e=void 0!==document.onmousewheel?"mousewheel":"DOMMouseScroll";q(b,e,c,d||!1);"DOMMouseScroll"==e&&q(b,"MozMousePixelScroll",c,d||!1)}};e.haseventlistener?(this.bind=function(b,c,d,e){a._bind("jquery"in b?b[0]:b,c,d,e||!1)},this._bind=function(b,c,d,e){a.events.push({e:b,n:c,f:d,b:e,q:!1});b.addEventListener(c,d,e||!1)},this.cancelEvent=function(a){if(!a)return!1;a=a.original?a.original: 84 | a;a.cancelable&&a.preventDefault();a.stopPropagation();a.preventManipulation&&a.preventManipulation();return!1},this.stopPropagation=function(a){if(!a)return!1;a=a.original?a.original:a;a.stopPropagation();return!1},this._unbind=function(a,c,d,e){a.removeEventListener(c,d,e)}):(this.bind=function(b,c,d,e){var f="jquery"in b?b[0]:b;a._bind(f,c,function(b){(b=b||window.event||!1)&&b.srcElement&&(b.target=b.srcElement);"pageY"in b||(b.pageX=b.clientX+document.documentElement.scrollLeft,b.pageY=b.clientY+ 85 | document.documentElement.scrollTop);return!1===d.call(f,b)||!1===e?a.cancelEvent(b):!0})},this._bind=function(b,c,d,e){a.events.push({e:b,n:c,f:d,b:e,q:!1});b.attachEvent?b.attachEvent("on"+c,d):b["on"+c]=d},this.cancelEvent=function(a){a=window.event||!1;if(!a)return!1;a.cancelBubble=!0;a.cancel=!0;return a.returnValue=!1},this.stopPropagation=function(a){a=window.event||!1;if(!a)return!1;a.cancelBubble=!0;return!1},this._unbind=function(a,c,d,e){a.detachEvent?a.detachEvent("on"+c,d):a["on"+c]=!1}); 86 | this.unbindAll=function(){for(var b=0;b(a.newscrolly-f)*(c-f)||0>(a.newscrollx-k)*(b-k))&&a.cancelScroll();0==a.opt.bouncescroll&&(0>c?c=0:c>a.page.maxh&&(c=a.page.maxh),0>b?b=0:b>a.page.maxw&&(b=a.page.maxw));if(a.scrollrunning&&b==a.newscrollx&&c==a.newscrolly)return!1;a.newscrolly=c;a.newscrollx=b;a.newscrollspeed=d||!1;if(a.timer)return!1;a.timer=setTimeout(function(){var d=a.getScrollTop(),f=a.getScrollLeft(), 96 | k=Math.round(Math.sqrt(Math.pow(b-f,2)+Math.pow(c-d,2))),k=a.newscrollspeed&&1=a.newscrollspeed&&(k*=a.newscrollspeed);a.prepareTransition(k,!0);a.timerscroll&&a.timerscroll.tm&&clearInterval(a.timerscroll.tm);0b?b=0:b>a.page.maxh&&(b=a.page.maxh);0>c?c=0:c>a.page.maxw&&(c=a.page.maxw);if(b!=a.newscrolly||c!=a.newscrollx)return a.doScrollPos(c, 100 | b,a.opt.snapbackspeed);a.onscrollend&&a.scrollrunning&&a.triggerScrollEnd();a.scrollrunning=!1}):(this.doScrollLeft=function(b,c){var d=a.scrollrunning?a.newscrolly:a.getScrollTop();a.doScrollPos(b,d,c)},this.doScrollTop=function(b,c){var d=a.scrollrunning?a.newscrollx:a.getScrollLeft();a.doScrollPos(d,b,c)},this.doScrollPos=function(b,c,d){function e(){if(a.cancelAnimationFrame)return!0;a.scrollrunning=!0;if(p=1-p)return a.timer=v(e)||1;var b=0,c,d,f=d=a.getScrollTop();if(a.dst.ay){f=a.bzscroll? 101 | a.dst.py+a.bzscroll.getNow()*a.dst.ay:a.newscrolly;c=f-d;if(0>c&&fa.newscrolly)f=a.newscrolly;a.setScrollTop(f);f==a.newscrolly&&(b=1)}else b=1;d=c=a.getScrollLeft();if(a.dst.ax){d=a.bzscroll?a.dst.px+a.bzscroll.getNow()*a.dst.ax:a.newscrollx;c=d-c;if(0>c&&da.newscrollx)d=a.newscrollx;a.setScrollLeft(d);d==a.newscrollx&&(b+=1)}else b+=1;2==b?(a.timer=0,a.cursorfreezed=!1,a.bzscroll=!1,a.scrollrunning=!1,0>f?f=0:f>a.page.maxh&&(f=Math.max(0,a.page.maxh)), 102 | 0>d?d=0:d>a.page.maxw&&(d=a.page.maxw),d!=a.newscrollx||f!=a.newscrolly?a.doScrollPos(d,f):a.onscrollend&&a.triggerScrollEnd()):a.timer=v(e)||1}c=void 0===c||!1===c?a.getScrollTop(!0):c;if(a.timer&&a.newscrolly==c&&a.newscrollx==b)return!0;a.timer&&w(a.timer);a.timer=0;var f=a.getScrollTop(),k=a.getScrollLeft();(0>(a.newscrolly-f)*(c-f)||0>(a.newscrollx-k)*(b-k))&&a.cancelScroll();a.newscrolly=c;a.newscrollx=b;a.bouncescroll&&a.rail.visibility||(0>a.newscrolly?a.newscrolly=0:a.newscrolly>a.page.maxh&& 103 | (a.newscrolly=a.page.maxh));a.bouncescroll&&a.railh.visibility||(0>a.newscrollx?a.newscrollx=0:a.newscrollx>a.page.maxw&&(a.newscrollx=a.page.maxw));a.dst={};a.dst.x=b-k;a.dst.y=c-f;a.dst.px=k;a.dst.py=f;var h=Math.round(Math.sqrt(Math.pow(a.dst.x,2)+Math.pow(a.dst.y,2)));a.dst.ax=a.dst.x/h;a.dst.ay=a.dst.y/h;var l=0,n=h;0==a.dst.x?(l=f,n=c,a.dst.ay=1,a.dst.py=0):0==a.dst.y&&(l=k,n=b,a.dst.ax=1,a.dst.px=0);h=a.getTransitionSpeed(h);d&&1>=d&&(h*=d);a.bzscroll=0=a.page.maxh||k==a.page.maxw&&b>=a.page.maxw)&&a.checkContentSize();var p=1;a.cancelAnimationFrame=!1;a.timer=1;a.onscrollstart&&!a.scrollrunning&&a.onscrollstart.call(a,{type:"scrollstart",current:{x:k,y:f},request:{x:b,y:c},end:{x:a.newscrollx,y:a.newscrolly},speed:h});e();(f==a.page.maxh&&c>=f||k==a.page.maxw&&b>=k)&&a.checkContentSize();a.noticeCursor()}},this.cancelScroll=function(){a.timer&&w(a.timer);a.timer=0;a.bzscroll=!1;a.scrollrunning= 105 | !1;return a}):(this.doScrollLeft=function(b,c){var d=a.getScrollTop();a.doScrollPos(b,d,c)},this.doScrollTop=function(b,c){var d=a.getScrollLeft();a.doScrollPos(d,b,c)},this.doScrollPos=function(b,c,d){var e=b>a.page.maxw?a.page.maxw:b;0>e&&(e=0);var f=c>a.page.maxh?a.page.maxh:c;0>f&&(f=0);a.synched("scroll",function(){a.setScrollTop(f);a.setScrollLeft(e)})},this.cancelScroll=function(){});this.doScrollBy=function(b,c){var d=0,d=c?Math.floor((a.scroll.y-b)*a.scrollratio.y):(a.timer?a.newscrolly: 106 | a.getScrollTop(!0))-b;if(a.bouncescroll){var e=Math.round(a.view.h/2);d<-e?d=-e:d>a.page.maxh+e&&(d=a.page.maxh+e)}a.cursorfreezed=!1;e=a.getScrollTop(!0);if(0>d&&0>=e)return a.noticeCursor();if(d>a.page.maxh&&e>=a.page.maxh)return a.checkContentSize(),a.noticeCursor();a.doScrollTop(d)};this.doScrollLeftBy=function(b,c){var d=0,d=c?Math.floor((a.scroll.x-b)*a.scrollratio.x):(a.timer?a.newscrollx:a.getScrollLeft(!0))-b;if(a.bouncescroll){var e=Math.round(a.view.w/2);d<-e?d=-e:d>a.page.maxw+e&&(d=a.page.maxw+ 107 | e)}a.cursorfreezed=!1;e=a.getScrollLeft(!0);if(0>d&&0>=e||d>a.page.maxw&&e>=a.page.maxw)return a.noticeCursor();a.doScrollLeft(d)};this.doScrollTo=function(b,c){a.cursorfreezed=!1;a.doScrollTop(b)};this.checkContentSize=function(){var b=a.getContentSize();b.h==a.page.h&&b.w==a.page.w||a.resize(!1,b)};a.onscroll=function(b){a.rail.drag||a.cursorfreezed||a.synched("scroll",function(){a.scroll.y=Math.round(a.getScrollTop()*(1/a.scrollratio.y));a.railh&&(a.scroll.x=Math.round(a.getScrollLeft()*(1/a.scrollratio.x))); 108 | a.noticeCursor()})};a.bind(a.docscroll,"scroll",a.onscroll);this.doZoomIn=function(b){if(!a.zoomactive){a.zoomactive=!0;a.zoomrestore={style:{}};var c="position top left zIndex backgroundColor marginTop marginBottom marginLeft marginRight".split(" "),d=a.win[0].style,k;for(k in c){var h=c[k];a.zoomrestore.style[h]=void 0!==d[h]?d[h]:""}a.zoomrestore.style.width=a.win.css("width");a.zoomrestore.style.height=a.win.css("height");a.zoomrestore.padding={w:a.win.outerWidth()-a.win.width(),h:a.win.outerHeight()- 109 | a.win.height()};e.isios4&&(a.zoomrestore.scrollTop=f(window).scrollTop(),f(window).scrollTop(0));a.win.css({position:e.isios4?"absolute":"fixed",top:0,left:0,zIndex:A+100,margin:0});c=a.win.css("backgroundColor");(""==c||/transparent|rgba\(0, 0, 0, 0\)|rgba\(0,0,0,0\)/.test(c))&&a.win.css("backgroundColor","#fff");a.rail.css({zIndex:A+101});a.zoom.css({zIndex:A+102});a.zoom.css("backgroundPosition","0px -18px");a.resizeZoom();a.onzoomin&&a.onzoomin.call(a);return a.cancelEvent(b)}};this.doZoomOut= 110 | function(b){if(a.zoomactive)return a.zoomactive=!1,a.win.css("margin",""),a.win.css(a.zoomrestore.style),e.isios4&&f(window).scrollTop(a.zoomrestore.scrollTop),a.rail.css({"z-index":a.zindex}),a.zoom.css({"z-index":a.zindex}),a.zoomrestore=!1,a.zoom.css("backgroundPosition","0px 0px"),a.onResize(),a.onzoomout&&a.onzoomout.call(a),a.cancelEvent(b)};this.doZoom=function(b){return a.zoomactive?a.doZoomOut(b):a.doZoomIn(b)};this.resizeZoom=function(){if(a.zoomactive){var b=a.getScrollTop();a.win.css({width:f(window).width()- 111 | a.zoomrestore.padding.w+"px",height:f(window).height()-a.zoomrestore.padding.h+"px"});a.onResize();a.setScrollTop(Math.min(a.page.maxh,b))}};this.init();f.nicescroll.push(this)},M=function(f){var c=this;this.nc=f;this.steptime=this.lasttime=this.speedy=this.speedx=this.lasty=this.lastx=0;this.snapy=this.snapx=!1;this.demuly=this.demulx=0;this.lastscrolly=this.lastscrollx=-1;this.timer=this.chky=this.chkx=0;this.time=function(){return+new Date};this.reset=function(f,h){c.stop();var d=c.time();c.steptime= 112 | 0;c.lasttime=d;c.speedx=0;c.speedy=0;c.lastx=f;c.lasty=h;c.lastscrollx=-1;c.lastscrolly=-1};this.update=function(f,h){var d=c.time();c.steptime=d-c.lasttime;c.lasttime=d;var d=h-c.lasty,q=f-c.lastx,t=c.nc.getScrollTop(),a=c.nc.getScrollLeft(),t=t+d,a=a+q;c.snapx=0>a||a>c.nc.page.maxw;c.snapy=0>t||t>c.nc.page.maxh;c.speedx=q;c.speedy=d;c.lastx=f;c.lasty=h};this.stop=function(){c.nc.unsynched("domomentum2d");c.timer&&clearTimeout(c.timer);c.timer=0;c.lastscrollx=-1;c.lastscrolly=-1};this.doSnapy=function(f, 113 | h){var d=!1;0>h?(h=0,d=!0):h>c.nc.page.maxh&&(h=c.nc.page.maxh,d=!0);0>f?(f=0,d=!0):f>c.nc.page.maxw&&(f=c.nc.page.maxw,d=!0);d?c.nc.doScrollPos(f,h,c.nc.opt.snapbackspeed):c.nc.triggerScrollEnd()};this.doMomentum=function(f){var h=c.time(),d=f?h+f:c.lasttime;f=c.nc.getScrollLeft();var q=c.nc.getScrollTop(),t=c.nc.page.maxh,a=c.nc.page.maxw;c.speedx=0=h-d;if(0>q||q>t||0>f||f>a)d=!1;f=c.speedx&&d?c.speedx:!1;if(c.speedy&&d&&c.speedy|| 114 | f){var r=Math.max(16,c.steptime);50p||p>a)&&(d=.1);c.speedy&&(e=Math.floor(c.lastscrolly-c.speedy*(1-c.demulxy)),c.lastscrolly=e,0>e||e>t)&&(d=.1);c.demulxy=Math.min(1,c.demulxy+ 115 | d);c.nc.synched("domomentum2d",function(){c.speedx&&(c.nc.getScrollLeft(),c.chkx=p,c.nc.setScrollLeft(p));c.speedy&&(c.nc.getScrollTop(),c.chky=e,c.nc.setScrollTop(e));c.timer||(c.nc.hideCursor(),c.doSnapy(p,e))});1>c.demulxy?c.timer=setTimeout(v,r):(c.stop(),c.nc.hideCursor(),c.doSnapy(p,e))};v()}else c.doSnapy(c.nc.getScrollLeft(),c.nc.getScrollTop())}},y=f.fn.scrollTop;f.cssHooks.pageYOffset={get:function(h,c,k){return(c=f.data(h,"__nicescroll")||!1)&&c.ishwscroll?c.getScrollTop():y.call(h)},set:function(h, 116 | c){var k=f.data(h,"__nicescroll")||!1;k&&k.ishwscroll?k.setScrollTop(parseInt(c)):y.call(h,c);return this}};f.fn.scrollTop=function(h){if(void 0===h){var c=this[0]?f.data(this[0],"__nicescroll")||!1:!1;return c&&c.ishwscroll?c.getScrollTop():y.call(this)}return this.each(function(){var c=f.data(this,"__nicescroll")||!1;c&&c.ishwscroll?c.setScrollTop(parseInt(h)):y.call(f(this),h)})};var z=f.fn.scrollLeft;f.cssHooks.pageXOffset={get:function(h,c,k){return(c=f.data(h,"__nicescroll")||!1)&&c.ishwscroll? 117 | c.getScrollLeft():z.call(h)},set:function(h,c){var k=f.data(h,"__nicescroll")||!1;k&&k.ishwscroll?k.setScrollLeft(parseInt(c)):z.call(h,c);return this}};f.fn.scrollLeft=function(h){if(void 0===h){var c=this[0]?f.data(this[0],"__nicescroll")||!1:!1;return c&&c.ishwscroll?c.getScrollLeft():z.call(this)}return this.each(function(){var c=f.data(this,"__nicescroll")||!1;c&&c.ishwscroll?c.setScrollLeft(parseInt(h)):z.call(f(this),h)})};var E=function(h){var c=this;this.length=0;this.name="nicescrollarray"; 118 | this.each=function(d){f.each(c,d);return c};this.push=function(d){c[c.length]=d;c.length++};this.eq=function(d){return c[d]};if(h)for(var k=0;k 0) { 82 | $.each(data, function (index, element) { 83 | element.direction == 1 ? 84 | appendIncoming(element) : 85 | appendOutgoing(element); 86 | }); 87 | } else { 88 | appendIncoming({time: "0000-00-00", message: telegramOptions.initialMessage}); 89 | } 90 | chatFlow.animate({scrollTop: chatFlow[0].scrollHeight}, "slow"); 91 | getUpdates(); 92 | }, 93 | error: function error(xhr, textStatus, errorThrown) { 94 | console.log(xhr); 95 | } 96 | }); 97 | } 98 | 99 | function getUpdates() { 100 | updater = setInterval(function () { 101 | var lastMsg = $('.tlgrm-msg:last'); 102 | $.ajax({ 103 | type: 'post', 104 | url: telegramOptions.getLastMessages, 105 | data: {lastMsgTime: lastMsg.attr('data-time') || null}, 106 | dataType: 'json', 107 | beforeSend: function () { 108 | }, 109 | success: function success(response) { 110 | if (response) { 111 | $.each(response, function (index, element) { 112 | if (element.direction == 1) 113 | appendIncoming(element) 114 | }); 115 | chatFlow.animate({scrollTop: chatFlow[0].scrollHeight}, "slow"); 116 | } 117 | }, 118 | error: function error(xhr, textStatus, errorThrown) { 119 | console.log(xhr); 120 | } 121 | }); 122 | }, 10000); 123 | } 124 | 125 | function appendIncoming(data) { 126 | var msg = '

' + data.message + '

'; 127 | chatFlow.append(msg); 128 | 129 | } 130 | 131 | function appendOutgoing(data) { 132 | var msg = '

' + data.message + '

'; 133 | chatFlow.append(msg); 134 | } 135 | 136 | }); -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "onmotion/yii2-telegram", 3 | "description": "Support chat for site based on Telegram bot", 4 | "type": "yii2-extension", 5 | "keywords": ["yii2","extension","module","chat", "telegram", "bot"], 6 | "license": "MIT", 7 | "authors": [ 8 | { 9 | "name": "Alexandr Kozhevnikov", 10 | "email": "onmotion1@gmail.com", 11 | "homepage": "http://kozhevnikov.me", 12 | "role": "Developer" 13 | } 14 | ], 15 | "require": { 16 | "php": ">=5.5.0", 17 | "yiisoft/yii2": ">=2.0.1", 18 | "longman/telegram-bot": "^0.35.0" 19 | }, 20 | "autoload": { 21 | "psr-4": { 22 | "onmotion\\telegram\\": "" 23 | } 24 | }, 25 | "extra": { 26 | "asset-installer-paths": { 27 | "npm-asset-library": "vendor/npm", 28 | "bower-asset-library": "vendor/bower" 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /controllers/ChatController.php: -------------------------------------------------------------------------------- 1 | [ 25 | 'class' => VerbFilter::className(), 26 | 'actions' => [ 27 | 'send-msg' => ['post'], 28 | 'get-all-messages' => ['post'], 29 | 'get-last-messages' => ['post'], 30 | ], 31 | ], 32 | ]; 33 | } 34 | 35 | public function actionSendMsg() 36 | { 37 | \Yii::$app->response->format = Response::FORMAT_JSON; 38 | $postData = \Yii::$app->request->post(); 39 | 40 | try { 41 | $result = YiiChatCommand::sendToAuthorized($postData); 42 | } catch (TelegramException $e){ 43 | throw new UserException($e->getMessage()); 44 | } 45 | 46 | return $result; 47 | } 48 | 49 | public function actionGetAllMessages() 50 | { 51 | \Yii::$app->response->format = Response::FORMAT_JSON; 52 | $session = \Yii::$app->session; 53 | if($session->has('tlgrm_chat_id')){ 54 | $tlgrmChatId = $session->get('tlgrm_chat_id'); 55 | }else{ 56 | return false; 57 | } 58 | 59 | try { 60 | $messages = Message::find()->where(['client_chat_id' => $tlgrmChatId])->asArray()->all(); 61 | } catch (TelegramException $e){ 62 | throw new UserException('Messages load error'); 63 | } 64 | if (!empty($messages)) return $messages; 65 | 66 | return false; 67 | } 68 | 69 | public function actionGetLastMessages() 70 | { 71 | \Yii::$app->response->format = Response::FORMAT_JSON; 72 | $postData = \Yii::$app->request->post(); 73 | $session = \Yii::$app->session; 74 | if($session->has('tlgrm_chat_id')){ 75 | $tlgrmChatId = $session->get('tlgrm_chat_id'); 76 | }else{ 77 | return false; 78 | } 79 | try { 80 | $messages = Message::find()->where(['client_chat_id' => $tlgrmChatId])->andWhere(['>', 'time', $postData['lastMsgTime']])->asArray()->all(); 81 | } catch (TelegramException $e){ 82 | throw new UserException('Messages load error'); 83 | } 84 | if (!empty($messages)) return $messages; 85 | 86 | return false; 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /controllers/DefaultController.php: -------------------------------------------------------------------------------- 1 | modules['telegram']->API_KEY); 18 | define('BOT_NAME', \Yii::$app->modules['telegram']->BOT_NAME); 19 | define('hook_url', \Yii::$app->modules['telegram']->hook_url); 20 | define('PASSPHRASE', \Yii::$app->modules['telegram']->PASSPHRASE); 21 | 22 | 23 | /** 24 | * Default controller for the `telegram` module 25 | */ 26 | class DefaultController extends Controller 27 | { 28 | 29 | public function behaviors() 30 | { 31 | return [ 32 | 'verbs' => [ 33 | 'class' => VerbFilter::className(), 34 | 'actions' => [ 35 | 'destroy-chat' => ['post'], 36 | 'init-chat' => ['post'], 37 | 'hook' => ['post'], 38 | ], 39 | ], 40 | ]; 41 | } 42 | 43 | public function beforeAction($action) 44 | { 45 | if ($action->id == 'hook') { 46 | $this->enableCsrfValidation = false; 47 | } 48 | return parent::beforeAction($action); 49 | } 50 | 51 | public function actionDestroyChat() 52 | { 53 | return $this->renderPartial('button'); 54 | } 55 | public function actionInitChat() 56 | { 57 | $session = \Yii::$app->session; 58 | if(!$session->has('tlgrm_chat_id')) { 59 | if (isset($_COOKIE['tlgrm_chat_id'])) { 60 | $tlgrmChatId = $_COOKIE['tlgrm_chat_id']; 61 | $session->set('tlgrm_chat_id', $tlgrmChatId); 62 | } else { 63 | $tlgrmChatId = uniqid(); 64 | $session->set('tlgrm_chat_id', $tlgrmChatId); 65 | setcookie("tlgrm_chat_id", $tlgrmChatId, time() + 1800); 66 | } 67 | } 68 | return $this->renderPartial('chat'); 69 | } 70 | 71 | public function actionSetWebhook(){ 72 | try { 73 | // Create Telegram API object 74 | $telegram = new Telegram(API_KEY, BOT_NAME); 75 | 76 | if (!empty(\Yii::$app->modules['telegram']->userCommandsPath)){ 77 | if(!$commandsPath = realpath(\Yii::getAlias(\Yii::$app->modules['telegram']->userCommandsPath))){ 78 | $commandsPath = realpath(\Yii::getAlias('@app') . \Yii::$app->modules['telegram']->userCommandsPath); 79 | } 80 | if(!is_dir($commandsPath)) throw new UserException('dir ' . \Yii::$app->modules['telegram']->userCommandsPath . ' not found!'); 81 | } 82 | 83 | // Set webhook 84 | $result = $telegram->setWebHook(hook_url); 85 | if ($result->isOk()) { 86 | echo $result->getDescription(); 87 | } 88 | } catch (TelegramException $e) { 89 | echo $e->getMessage(); 90 | } 91 | return null; 92 | } 93 | public function actionUnsetWebhook(){ 94 | if (\Yii::$app->user->isGuest) throw new ForbiddenHttpException(); 95 | try { 96 | // Create Telegram API object 97 | $telegram = new Telegram(API_KEY, BOT_NAME); 98 | 99 | // Unset webhook 100 | $result = $telegram->unsetWebHook(); 101 | 102 | if ($result->isOk()) { 103 | echo $result->getDescription(); 104 | } 105 | } catch (TelegramException $e) { 106 | echo $e->getMessage(); 107 | } 108 | } 109 | 110 | public function actionHook(){ 111 | try { 112 | // Create Telegram API object 113 | $telegram = new Telegram(API_KEY, BOT_NAME); 114 | $basePath = \Yii::$app->getModule('telegram')->basePath; 115 | // $commandsPath = realpath($basePath . '/Commands/SystemCommands'); 116 | $commandsPath = realpath($basePath . '/Commands/UserCommands'); 117 | $telegram->addCommandsPath($commandsPath); 118 | if (!empty(\Yii::$app->modules['telegram']->userCommandsPath)){ 119 | if(!$commandsPath = realpath(\Yii::getAlias(\Yii::$app->modules['telegram']->userCommandsPath))){ 120 | $commandsPath = realpath(\Yii::getAlias('@app') . \Yii::$app->modules['telegram']->userCommandsPath); 121 | } 122 | $telegram->addCommandsPath($commandsPath); 123 | } 124 | // Handle telegram webhook request 125 | $telegram->handle(); 126 | } catch (TelegramException $e) { 127 | // Silence is golden! 128 | // log telegram errors 129 | var_dump($e->getMessage()); 130 | } 131 | return null; 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /messages/es/tlgrm.php: -------------------------------------------------------------------------------- 1 | 'En este momento, no hay operadores disponibles. Intente más tarde.', 9 | 'Start conversation with chat ' => 'Iniciar conversación por chat ', 10 | 'Start conversation' => 'Iniciar conversación', 11 | 'Login to the support system' => 'Ingresar al sistema de soporte', 12 | 'Conversation already in progress in this chat. Responsible: ' => 'Conversación ya en progreso en este chat. Responsable: ', 13 | 'Seems conversation already in progress in this chat.' => 'Parece que la conversación ya está en progreso en este chat.', 14 | 'Unknown command.' => 'Comando desconocido.', 15 | "Passphrase is correct, now you'll get the messages." => 'La contraseña es correcta, ahora recibirá los mensajes.', 16 | "You are already subscribed to receive messages." => 'Ya está suscripto para recibir mensajes.', 17 | 'Incorrect passphrase.' => 'Contraseña incorrecta.', 18 | 'Try to enter the command, such as /help' => 'Intente ingresar el comando, tal como /help', 19 | 'Show bot commands help' => 'Muestra la ayuda de comandos', 20 | 'End the currently active conversation and switch to standby mode.' => 'Finaliza la conversación activa y cambia al modo de espera.', 21 | 'You are not authorized!' => 'Usted no está autorizado!', 22 | 'Completed conversation in chat ' => 'Conversación completada por chat ', 23 | 'You have no active conversations.' => 'Usted no tiene ninguna conversación activa.', 24 | 'Enter passphrase:' => 'Ingrese contraseña:', 25 | 'You are already logged in as ' => 'Ya ingresó como ', 26 | 'You are not logged in.' => 'No ha ingresado.', 27 | 'You will no longer receive messages.' => 'Ya no recibirá mensajes.', 28 | 'Logout from the support system.' => 'Salir del sistema de soporte.', 29 | 'Online support' => 'Soporte en línea', 30 | 'Write your question...' => 'Escriba su pregunta...', 31 | " writes:" => ' escribe:' 32 | ]; 33 | -------------------------------------------------------------------------------- /messages/ru/tlgrm.php: -------------------------------------------------------------------------------- 1 | 'На данный момент нет свободных операторов. Попробуйте написать позже.', 8 | 'Start conversation with chat ' => 'Начат диалог с чатом ', 9 | 'Start conversation' => 'Начать диалог', 10 | 'Login to the support system' => 'Вход в систему поддержки', 11 | 'Conversation already in progress in this chat. Responsible: ' => 'В данном чате уже ведется диалог. Ответственный: ', 12 | 'Seems conversation already in progress in this chat.' => 'Вроде в данном чате уже ведется диалог. Не могу найти ответственного в базе...', 13 | 'Unknown command.' => 'Неизвестная команда.', 14 | "Passphrase is correct, now you'll get the messages." => 'Верная фраза, теперь вы будете получать сообщения.', 15 | "You are already subscribed to receive messages." => 'Вы уже подписаны на получение сообщений.', 16 | 'Incorrect passphrase.' => 'Неверная фраза.', 17 | 'Try to enter the command, such as /help' => 'Попробуйте ввести команду, например /help', 18 | 'Show bot commands help' => 'Помощь по командам бота', 19 | 'End the currently active conversation and switch to standby mode.' => 'Закончить текущий активный диалог и перейти в режим ожидания.', 20 | 'You are not authorized!' => 'Вы не авторизовались!', 21 | 'Completed conversation in chat ' => 'Завершен диалог в чате ', 22 | 'You have no active conversations.' => 'У вас нет активных диалогов.', 23 | 'Enter passphrase:' => 'Введите passphrase:', 24 | 'You are already logged in as ' => 'Вы уже вошли в систему как ', 25 | 'You are not logged in.' => 'Вы не вошли в систему.', 26 | 'You will no longer receive messages.' => 'Вы больше не будете получать сообщения.', 27 | 'Logout from the support system.' => 'Выход из системы поддержки.', 28 | 'Online support' => 'Онлайн помощь', 29 | 'Write your question...' => 'Напишите здесь свой вопрос...', 30 | " writes:" => ' пишет:' 31 | 32 | ]; 33 | -------------------------------------------------------------------------------- /migrations/m160808_112253_onmotion_yii2_telegram.php: -------------------------------------------------------------------------------- 1 | db->driverName === 'mysql') { 19 | $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB'; 20 | } 21 | 22 | $this->createTable('tlgrm_actions', [ 23 | 'chat_id' => $this->integer(11), 24 | 'action' => $this->string(62), 25 | ], $tableOptions); 26 | $this->addPrimaryKey('tlgrm_actions_PK', 'tlgrm_actions', 'chat_id'); 27 | 28 | $this->createTable('tlgrm_auth_mngr_chats', [ 29 | 'chat_id' => $this->integer(11), 30 | 'client_chat_id' => $this->string(16)->unique(), 31 | ], $tableOptions); 32 | $this->addPrimaryKey('tlgrm_auth_mngr_chats_PK', 'tlgrm_auth_mngr_chats', 'chat_id'); 33 | 34 | $this->createTable('tlgrm_messages', [ 35 | 'time' => $this->timestamp(), 36 | 'client_chat_id' => $this->string(16)->notNull(), 37 | 'message' => $this->string(4100), 38 | 'direction' => $this->smallInteger(1) 39 | ], $tableOptions); 40 | $this->addPrimaryKey('tlgrm_messages_PK', 'tlgrm_messages', 'time'); 41 | 42 | $this->createTable('tlgrm_usernames', [ 43 | 'id' => $this->primaryKey()->notNull(), 44 | 'chat_id' => $this->integer(11), 45 | 'user_id' => $this->integer(11), 46 | 'username' => $this->string(100) 47 | ], $tableOptions); 48 | $this->createIndex('tlgrm_usernames_uniq', 'tlgrm_usernames', ['chat_id', 'user_id', 'username']); 49 | } 50 | 51 | public function safeDown() 52 | { 53 | try { 54 | $this->dropTable('tlgrm_actions'); 55 | $this->dropTable('tlgrm_auth_mngr_chats'); 56 | $this->dropTable('tlgrm_messages'); 57 | $this->dropTable('tlgrm_usernames'); 58 | } catch (Exception $e){ 59 | var_dump($e->getMessage()); 60 | return false; 61 | } 62 | 63 | return "m160808_112253_onmotion_yii2_telegram was reverted.\n"; 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /migrations/m161122_112253_onmotion_yii2_telegram.php: -------------------------------------------------------------------------------- 1 | addColumn('tlgrm_actions', 'param', $this->string(62)); 18 | $this->addColumn('tlgrm_auth_mngr_chats', 'timestamp', $this->timestamp()); 19 | } 20 | 21 | public function safeDown() 22 | { 23 | try { 24 | $this->dropColumn('tlgrm_actions', 'param'); 25 | $this->dropColumn('tlgrm_auth_mngr_chats', 'timestamp'); 26 | } catch (Exception $e){ 27 | var_dump($e->getMessage()); 28 | return false; 29 | } 30 | 31 | return "m160808_112253_onmotion_yii2_telegram was reverted.\n"; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /models/Actions.php: -------------------------------------------------------------------------------- 1 | controller->module->db; 34 | return Yii::$app->get($db); 35 | } 36 | 37 | /** 38 | * @inheritdoc 39 | */ 40 | public function rules() 41 | { 42 | return [ 43 | [['chat_id'], 'required'], 44 | [['chat_id'], 'integer'], 45 | [['action', 'param'], 'string', 'max' => 45], 46 | ]; 47 | } 48 | 49 | /** 50 | * @inheritdoc 51 | */ 52 | public function attributeLabels() 53 | { 54 | return [ 55 | 'chat_id' => 'User ID', 56 | 'action' => 'Action', 57 | 'param' => 'Parameter', 58 | ]; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /models/AuthorizedManagerChat.php: -------------------------------------------------------------------------------- 1 | controller->module->db; 34 | return Yii::$app->get($db); 35 | } 36 | 37 | /** 38 | * @inheritdoc 39 | */ 40 | public function rules() 41 | { 42 | return [ 43 | [['chat_id'], 'required'], 44 | [['chat_id'], 'integer'], 45 | [['client_chat_id'], 'string'], 46 | [['client_chat_id'], 'unique'], 47 | [['timestamp'], 'safe'], 48 | ]; 49 | } 50 | 51 | /** 52 | * @inheritdoc 53 | */ 54 | public function attributeLabels() 55 | { 56 | return [ 57 | 'chat_id' => 'Chat ID', 58 | ]; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /models/Message.php: -------------------------------------------------------------------------------- 1 | controller->module->db; 36 | return Yii::$app->get($db); 37 | } 38 | 39 | /** 40 | * @inheritdoc 41 | */ 42 | public function rules() 43 | { 44 | return [ 45 | [['client_chat_id'], 'required'], 46 | // [['message'], 'string', 'max' => 4100], 47 | ]; 48 | } 49 | 50 | /** 51 | * @inheritdoc 52 | */ 53 | public function attributeLabels() 54 | { 55 | return [ 56 | 57 | ]; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /models/Usernames.php: -------------------------------------------------------------------------------- 1 | controller->module->db; 34 | return Yii::$app->get($db); 35 | } 36 | 37 | /** 38 | * @inheritdoc 39 | */ 40 | public function rules() 41 | { 42 | return [ 43 | [['chat_id'], 'required'], 44 | [['chat_id', 'user_id'], 'integer'], 45 | [['username'], 'string', 'max' => 100], 46 | ]; 47 | } 48 | 49 | /** 50 | * @inheritdoc 51 | */ 52 | public function attributeLabels() 53 | { 54 | return [ 55 | 'chat_id' => 'User ID', 56 | 'username' => 'username', 57 | ]; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /views/default/button.php: -------------------------------------------------------------------------------- 1 | ' . Yii::t('tlgrm', 'Online support') . '', ['class' => 'btn btn-primary', 'id' => 'tlgrm-init-btn']); 13 | 14 | $options = \yii\helpers\Json::htmlEncode(\Yii::$app->getModule('telegram')->options); 15 | $this->registerJs(<< 'tlgrm-chat']); 11 | echo Html::beginTag('div', ['id' => 'tlgrm-chat-head']); 12 | echo Html::beginTag('div', ['id' => 'tlgrm-chat-head-caption']); 13 | echo ' ' . Yii::t('tlgrm', 'Online support') . ''; 14 | echo Html::endTag('div'); 15 | echo Html::tag('div', '',['id' => 'tlgrm-close-btn']); 16 | echo Html::endTag('div'); 17 | echo Html::tag('div', '',['id' => 'tlgrm-chat-flow']); 18 | echo Html::beginTag('div', ['id' => 'tlgrm-chat-send-panel']); 19 | echo Html::beginForm(yii\helpers\Url::to(['/telegram/chat/send-msg']), 'post', ['id' => 'tlgrm-chat-form']); 20 | echo Html::textarea('message', '', ['class' => "form-control", 'id' => 'tlgrm-chat-msg', 'minlength'=>"1", 'required' => 'required',]); 21 | echo Html::submitButton('', ['class' => 'btn btn-primary', 'id' => 'tlgrm-send-btn']); 22 | echo Html::endForm(); 23 | echo Html::endTag('div'); 24 | echo Html::endTag('div'); --------------------------------------------------------------------------------