Compare commits

..

No commits in common. "stable" and "1.1.0" have entirely different histories.

3 changed files with 168 additions and 302 deletions

View File

@ -1,5 +1,6 @@
# Telegram chat-robot for task registering # Viber chat-robot
Chat-robot Telegram for accepting applications for employees from [mirzaev/ebala](https://git.mirzaev.sexy/mirzaev/ebala) Sending requests from [mirzaev/spetsresurs-google_sheets-parser](https://git.mirzaev.sexy/mirzaev/spetsresurs-google_sheets-parser) to [mirzaev/arangodb](https://git.mirzaev.sexy/mirzaev/arangodb) and vice versa
~~😼 Developed in 1 day for 100000 rubles ($1200)~~ shit happens
**DEVELOPMENT COMPLETED. PROJECT CLOSED.**

View File

@ -23,41 +23,6 @@ $arangodb = new connection(require __DIR__ . '/../settings/arangodb.php');
ini_set('display_errors', 1); ini_set('display_errors', 1);
ini_set('display_startup_errors', 1); */ ini_set('display_startup_errors', 1); */
function escape(string $text)
{
return str_replace(
[
'#',
'*',
'_',
'=',
'.',
'[',
']',
'(',
')',
'-',
'>',
'<'
],
[
'\#',
'\*',
'\_',
'\\=',
'\.',
'\[',
'\]',
'\(',
'\)',
'\-',
'\>',
'\<'
],
$text
);
}
/** /**
* Авторизация * Авторизация
* *
@ -114,7 +79,7 @@ function worker(string $id): _document|null|false
LIMIT 1 LIMIT 1
RETURN e RETURN e
) )
FILTER d._id == e[0]._to FILTER d._id == e[0]._to && d.active == true
SORT d.created DESC, d._key DESC SORT d.created DESC, d._key DESC
LIMIT 1 LIMIT 1
RETURN d RETURN d
@ -207,26 +172,18 @@ function generateMenu(Context $ctx): void
if ($account = authorization($ctx->getMessage()?->getFrom()?->getId() ?? $ctx->getCallbackQuery()->getFrom()->getId())) { if ($account = authorization($ctx->getMessage()?->getFrom()?->getId() ?? $ctx->getCallbackQuery()->getFrom()->getId())) {
// Успешная авторизация // Успешная авторизация
if (!$account->active) $ctx->sendMessage('⚠️ Свяжитесь с оператором'); $ctx->sendMessage('👋 Здравствуйте, ' . preg_replace('/([._\-()!#])/', '\\\$1', $account->name['first']), [
else if ($account->banned) $ctx->sendMessage('⚠️ Свяжитесь с оператором'); 'reply_markup' => [
else if (!($worker = worker($account->getId()))->active) $ctx->sendMessage('⚠️ Свяжитесь с оператором'); 'inline_keyboard' => [
else if ($worker->fired) $ctx->sendMessage('⚠️ Свяжитесь с оператором'); [
else { ['text' => '🔍 Активные заявки', 'callback_data' => 'day']
// Активен аккаунт ]
],
$ctx->sendMessage('👋 Здравствуйте, ' . preg_replace('/([._\-()!#])/', '\\\$1', $account->name['first']), [ 'remove_keyboard' => true
'reply_markup' => [ ]
'inline_keyboard' => [ ])->then(function ($message) use ($ctx) {
[ $ctx->setChatDataItem("menu", $message);
['text' => '🔍 Активные заявки', 'callback_data' => 'day'] });
]
],
'remove_keyboard' => true
]
])->then(function ($message) use ($ctx) {
$ctx->setChatDataItem("menu", $message);
});
}
} }
} }
@ -236,11 +193,10 @@ function generateMenu(Context $ctx): void
* @param int $amount Количество * @param int $amount Количество
* @param ?string $date За какую дату (unixtime) * @param ?string $date За какую дату (unixtime)
* @param int $page Страница * @param int $page Страница
* @param _document $worker Сотрудник
* *
* @return Cursor * @return Cursor
*/ */
function requests(int $amount = 5, ?string $date = null, int $page = 1, _document $worker): Cursor function requests(int $amount = 5, ?string $date = null, int $page = 1): Cursor
{ {
global $arangodb; global $arangodb;
@ -261,12 +217,11 @@ function requests(int $amount = 5, ?string $date = null, int $page = 1, _documen
[ [
'query' => sprintf( 'query' => sprintf(
// d.date < %s там специально, не менять на <= // d.date < %s там специально, не менять на <=
"FOR d IN task FILTER ((d.date >= %s && d.date < %s && d.start >= '05:00') || (d.date >= %s && d.date < %s && d.start < '05:00')) && d.worker == null && d.market != null && d.confirmed != true && d.published == true && d.completed != true && (FOR m IN market FILTER m.id == d.market && IS_ARRAY(m.bans) SORT m.created DESC, m._key DESC LIMIT 1 RETURN !POSITION(m.bans, \"%s\"))[0] SORT d.created DESC, d._key DESC LIMIT %d, %d RETURN d", "FOR d IN task FILTER ((d.date >= %s && d.date < %s && d.start >= '05:00') || (d.date >= %s && d.date < %s && d.start < '05:00')) && d.worker == null && d.market != null && d.confirmed != true && d.published == true && d.completed != true SORT d.created DESC, d._key DESC LIMIT %d, %d RETURN d",
$from = (new DateTime("@$date"))->setTime(0, 0)->format('U'), $from = (new DateTime("@$date"))->setTime(0, 0)->format('U'),
$to = (new DateTime("@$date"))->modify('+1 day')->setTime(0, 0)->format('U'), $to = (new DateTime("@$date"))->modify('+1 day')->setTime(0, 0)->format('U'),
$to, $to,
(new DateTime("@$date"))->modify('+2 day')->setTime(0, 0)->format('U'), (new DateTime("@$date"))->modify('+2 day')->setTime(0, 0)->format('U'),
$worker->id,
$offset, $offset,
$amount + $offset - ($page > 0) $amount + $offset - ($page > 0)
), ),
@ -300,156 +255,82 @@ function requests_previous(Context $ctx): void
} }
function request_choose(Context $ctx): void function request_choose(Context $ctx): void
{
if (($account = authorization($ctx->getCallbackQuery()->getFrom()->getId())) instanceof _document) {
// Авторизован
if (!$account->active) $ctx->sendMessage('⚠️ Свяжитесь с оператором');
else if ($account->banned) $ctx->sendMessage('⚠️ Свяжитесь с оператором');
else if (!($worker = worker($account->getId()))->active) $ctx->sendMessage('⚠️ Свяжитесь с оператором');
else if ($worker->fired) $ctx->sendMessage('⚠️ Свяжитесь с оператором');
else {
// Активен аккаунт
// Инициализация ключа инстанции task в базе данных
preg_match('/\->\s#(\d+)\n/', $ctx->getCallbackQuery()->getMessage()->getText(), $matches);
// Запись ключа инстанции task (заявка на которую регистрируется сотрудник)
$ctx->setChatDataItem("request_confirmation_target", $matches[1]);
// Запрос подтверждения
$ctx->sendMessage("⚡ *Подтверждение записи*\n\n" . preg_replace('/(^[^:\s\n\r]+:)/m', '*$1*', preg_replace('/(\\\#\d+)/', '*$1*', escape($ctx->getCallbackQuery()->getMessage()->getText()))) . "\n\n*⚠️ Вы подтверждаете отправку запроса?*", [
'reply_markup' => [
'inline_keyboard' => [
[
['text' => 'Подтвердить', 'callback_data' => 'request_confirmed'],
['text' => 'Отменить', 'callback_data' => 'request_rejected']
]
]
]
])->then(function ($message) use ($ctx) {
// Запись сообщения в кеш (на случай необходимости его удаления)
$ctx->setChatDataItem("request_confirmation", $message);
});
}
}
}
function request_confirmed(Context $ctx): void
{ {
global $arangodb; global $arangodb;
if (($account = authorization($ctx->getCallbackQuery()->getFrom()->getId())) instanceof _document) { if (($account = authorization($ctx->getCallbackQuery()->getFrom()->getId())) instanceof _document) {
// Авторизован // Авторизован
$ctx->getChatDataItem("request_confirmation_target")->then(function ($_key) use ($ctx, $arangodb, $account) { // Инициализация ключа инстанции task в базе данных
// Прочитана запрашиваемая заявка preg_match('/\->\s#(\d+)\n/', $ctx->getCallbackQuery()->getMessage()->getText(), $matches);
$_key = $matches[1];
// Инициализация инстанции task в базе данных (выбранного задания) // Инициализация инстанции task в базе данных (выбранного задания)
$task = collection::search($arangodb->session, sprintf("FOR d IN task FILTER d._key == '%s' && d.published == true && d.completed != true && worker == null RETURN d", $_key)); $task = collection::search($arangodb->session, sprintf("FOR d IN task FILTER d._key == '%s' && d.published == true && d.completed != true RETURN d", $_key));
if ($task instanceof _document) { if ($worker = worker($account->getId())) {
// Найдена заявка (подразумевается, что не занята) // Найден сотрудник
if ($worker ??= worker($account->getId())) { // Запись идентификатора нового сотрудника
// Найден сотрудник $task->worker = $worker->id;
// Запись идентификатора нового сотрудника // Снятие с публикации
$task->worker = $worker->id; $task->published = false;
// Снятие с публикации if (document::update($arangodb->session, $task)) {
$task->published = false; // Записано обновление в базу данных
if (document::update($arangodb->session, $task)) { $ctx->getChatDataItem("request_all")->then(function ($requests = []) use ($ctx, $_key) {
// Записано обновление в базу данных // Удаление сообщений связанных с запросом
foreach ($requests ?? [] as $_message) $ctx->deleteMessage($_message->getChat()->getId(), $_message->getMessageId());
$ctx->setChatDataItem("request_all", []);
$ctx->getChatDataItem("request_all")->then(function ($requests = []) use ($ctx) { $ctx->sendMessage("✅ *Заявка принята:* \#$_key", ['reply_markup' => ['remove_keyboard' => true]])->then(function () use ($ctx) {
// Удаление сообщений связанных с запросом
foreach ($requests ?? [] as $_message) $ctx->deleteMessage($_message->getChat()->getId(), $_message->getMessageId());
});
$ctx->setChatDataItem("request_all", []);
$ctx->getChatDataItem("request_confirmation")->then(function ($message) use ($ctx) {
$ctx->deleteMessage($message->getChat()->getId(), $message->getMessageId());
});
$ctx->setChatDataItem("request_confirmation_target", null);
$ctx->sendMessage("✅ *Вы зарегистрировались на заявку:* \#$_key", ['reply_markup' => ['remove_keyboard' => true]])->then(function () use ($ctx) {
generateMenu($ctx);
});
// End of the process
$ctx->endConversation();
} else $ctx->sendMessage("❎ *Не удалось принять заявку:* \#$_key", ['reply_markup' => ['remove_keyboard' => true]])->then(function () use ($ctx) {
generateMenu($ctx); generateMenu($ctx);
}); });
} else $ctx->sendMessage("❎ *Не удалось принять заявку:* \#$_key", ['reply_markup' => ['remove_keyboard' => true]])->then(function () use ($ctx) {
generateMenu($ctx); // End of the process
$ctx->endConversation();
}); });
} else $ctx->sendMessage("❎ *Не удалось принять заявку:* \#$_key", ['reply_markup' => ['remove_keyboard' => true]])->then(function () use ($ctx) { } else $ctx->sendMessage("❎ *Не удалось принять заявку:* \#$_key", ['reply_markup' => ['remove_keyboard' => true]])->then(function () use ($ctx) {
generateMenu($ctx); generateMenu($ctx);
}); });
} else $ctx->sendMessage("❎ *Не удалось принять заявку:* \#$_key", ['reply_markup' => ['remove_keyboard' => true]])->then(function () use ($ctx) {
generateMenu($ctx);
}); });
} }
} }
function request_rejected(Context $ctx): void
{
$ctx->getChatDataItem("request_confirmation_target")->then(function ($_key) use ($ctx) {
// Прочитана запрашиваемая заявка
$ctx->getChatDataItem("request_confirmation")->then(function ($message) use ($ctx) {
$ctx->deleteMessage($message->getChat()->getId(), $message->getMessageId());
});
$ctx->setChatDataItem("request_confirmation_target", null);
$ctx->sendMessage("✅ *Вы отменили регистрацию на заявку:* \#$_key", ['reply_markup' => ['remove_keyboard' => true]])->then(function () use ($ctx) {
generateMenu($ctx);
});
// End of the process
$ctx->endConversation();
});
}
function day(Context $ctx): void function day(Context $ctx): void
{ {
if (($account = authorization($ctx->getMessage()?->getFrom()?->getId() ?? $ctx->getCallbackQuery()->getFrom()->getId())) instanceof _document) { if (authorization($ctx->getMessage()?->getFrom()?->getId() ?? $ctx->getCallbackQuery()->getFrom()->getId()) instanceof _document) {
// Авторизован // Авторизован
if (!$account->active) $ctx->sendMessage('⚠️ Свяжитесь с оператором'); // Инициализация буфера клавиатуры
else if ($account->banned) $ctx->sendMessage('⚠️ Свяжитесь с оператором'); $keyboard = [];
else if (!($worker = worker($account->getId()))->active) $ctx->sendMessage('⚠️ Свяжитесь с оператором');
else if ($worker->fired) $ctx->sendMessage('⚠️ Свяжитесь с оператором');
else {
// Активен аккаунт
// Инициализация буфера клавиатуры // Генерация кнопок с выбором даты
$keyboard = []; for ($i = 1, $r = 0; $i < 15; ++$i) $keyboard[$i > 4 * ($r + 1) ? ++$r : $r][] = ['text' => ($date = (new DateTime)->modify("+$i day"))->format('d.m.Y'), 'callback_data' => $date->format('U')];
// Генерация кнопок с выбором даты $ctx->setChatDataItem('requests_page', 1)->then(function () use ($ctx, $keyboard) {
for ($i = 1, $r = 0; $i < 15; ++$i) $keyboard[$i > 4 * ($r + 1) ? ++$r : $r][] = ['text' => ($date = (new DateTime)->modify("+$i day"))->format('d.m.Y'), 'callback_data' => $date->format('U')]; // Отправка меню
$ctx->sendMessage('📅 Выберите дату', [
$ctx->setChatDataItem('requests_page', 1)->then(function () use ($ctx, $keyboard) { 'reply_markup' => [
// Отправка меню 'inline_keyboard' => $keyboard
$ctx->sendMessage('📅 Выберите дату', [ ]
'reply_markup' => [ ])->then(function ($message) use ($ctx) {
'inline_keyboard' => $keyboard $ctx->getChatDataItem("menu")->then(function ($message) use ($ctx) {
] // Удаление главного меню
])->then(function ($message) use ($ctx) { if ($message) $ctx->deleteMessage($message->getChat()->getId(), $message->getMessageId());
$ctx->getChatDataItem("menu")->then(function ($message) use ($ctx) { $ctx->setChatDataItem("menu", null);
// Удаление главного меню
if ($message) $ctx->deleteMessage($message->getChat()->getId(), $message->getMessageId());
$ctx->setChatDataItem("menu", null);
});
// Запись сообщения в кеш (на случай необходимости его удаления при смене страницы)
$ctx->setChatDataItem("request_day", $message);
}); });
});
$ctx->nextStep("search"); // Запись сообщения в кеш (на случай необходимости его удаления при смене страницы)
} $ctx->setChatDataItem("request_day", $message);
});
});
$ctx->nextStep("search");
} }
} }
@ -457,153 +338,145 @@ function search(Context $ctx): void
{ {
global $arangodb; global $arangodb;
if (($account = authorization($ctx->getMessage()?->getFrom()?->getId() ?? $ctx->getCallbackQuery()->getFrom()->getId())) instanceof _document) { if (authorization($ctx->getMessage()?->getFrom()?->getId() ?? $ctx->getCallbackQuery()->getFrom()->getId()) instanceof _document) {
// Авторизован // Авторизован
if (!$account->active) $ctx->sendMessage('⚠️ Свяжитесь с оператором'); $ctx->getChatDataItem('requests_page')->then(function ($page) use ($ctx, $arangodb) {
else if ($account->banned) $ctx->sendMessage('⚠️ Свяжитесь с оператором'); // Найдена текущая страница
else if (!($worker = worker($account->getId()))->active) $ctx->sendMessage('⚠️ Свяжитесь с оператором');
else if ($worker->fired) $ctx->sendMessage('⚠️ Свяжитесь с оператором');
else {
// Активен аккаунт
$ctx->getChatDataItem('requests_page')->then(function ($page) use ($ctx, $arangodb, $worker) { // Значение страницы по умолчанию
// Найдена текущая страница if (empty($page)) {
$page = 1;
$ctx->setChatDataItem('requests_page', 1);
}
// Значение страницы по умолчанию $generate = function ($date) use ($ctx, $page, $arangodb) {
if (empty($page)) { // Поиск заявок в ArangoDB
$page = 1; $tasks = requests(4, (string) $date, $page);
$ctx->setChatDataItem('requests_page', 1);
}
$generate = function ($date) use ($ctx, $page, $arangodb, $worker) { // Подсчёт количества прочитанных заявок из базы данных
// Поиск заявок в ArangoDB $count = $tasks->getCount();
$tasks = requests(4, (string) $date, $page, $worker);
// Подсчёт количества прочитанных заявок из базы данных // Проверка существования избытка
$count = $tasks->getCount(); $excess = $count > 3;
// Проверка существования избытка // Обрезка заявок до размера страницы (3 заявки на 1 странице)
$excess = $count > 3; $tasks = array_slice($tasks->getAll(), 0, 3);
// Обрезка заявок до размера страницы (3 заявки на 1 странице) if ($count === 0) {
$tasks = array_slice($tasks->getAll(), 0, 3); $ctx->sendMessage('📦 *Заявок нет*')->then(function ($message) use ($ctx) {
$ctx->getChatDataItem("request_all")->then(function ($requests = []) use ($ctx, $message) {
// Удаление сообщений связанных с запросом
foreach ($requests ?? [] as $_message) $ctx->deleteMessage($_message->getChat()->getId(), $_message->getMessageId());
$ctx->setChatDataItem("request_all", $requests = [$message]);
});
});
} else {
// Найдены заявки
if ($count === 0) { $ctx->getChatDataItem("request_day")->then(function ($message) use ($ctx, $arangodb, $tasks, $page, $excess) {
$ctx->sendMessage('📦 *Заявок нет*')->then(function ($message) use ($ctx) { // Удаление предыдущего меню с выбором даты
$ctx->getChatDataItem("request_all")->then(function ($requests = []) use ($ctx, $message) { if ($message) $ctx->deleteMessage($message->getChat()->getId(), $message->getMessageId());
$ctx->setChatDataItem("request_day", null)->then(function () use ($ctx, $arangodb, $tasks, $page, $excess) {
$ctx->getChatDataItem("request_all")->then(function ($requests = []) use ($ctx, $arangodb, $tasks, $excess, $page) {
// Удаление сообщений связанных с запросом // Удаление сообщений связанных с запросом
foreach ($requests ?? [] as $_message) $ctx->deleteMessage($_message->getChat()->getId(), $_message->getMessageId()); foreach ($requests ?? [] as $_message) $ctx->deleteMessage($_message->getChat()->getId(), $_message->getMessageId());
$ctx->setChatDataItem("request_all", $requests = [$message]); $ctx->setChatDataItem("request_all", [])->then(function () use ($ctx, $arangodb, $tasks, $excess, $page) {
}); foreach ($tasks as $i => $task) {
}); // Перебор найденных заявок
} else {
// Найдены заявки
$ctx->getChatDataItem("request_day")->then(function ($message) use ($ctx, $arangodb, $tasks, $page, $excess) { if (($market = collection::search(
// Удаление предыдущего меню с выбором даты $arangodb->session,
if ($message) $ctx->deleteMessage($message->getChat()->getId(), $message->getMessageId()); sprintf(
$ctx->setChatDataItem("request_day", null)->then(function () use ($ctx, $arangodb, $tasks, $page, $excess) { "FOR d IN market FILTER d.id == '%s' RETURN d",
$ctx->getChatDataItem("request_all")->then(function ($requests = []) use ($ctx, $arangodb, $tasks, $excess, $page) { $task->market
// Удаление сообщений связанных с запросом )
foreach ($requests ?? [] as $_message) $ctx->deleteMessage($_message->getChat()->getId(), $_message->getMessageId()); )) instanceof _document) {
$ctx->setChatDataItem("request_all", [])->then(function () use ($ctx, $arangodb, $tasks, $excess, $page) { // Найден магазин
foreach ($tasks as $i => $task) { $ctx->getChatDataItem("request_$i")->then(function ($message) use ($ctx, $task, $market, $tasks, $i, $page, $excess) {
// Перебор найденных заявок // Удаление предыдущего сообщения на этой позиции
if ($message) $ctx->deleteMessage($message->getChat()->getId(), $message->getMessageId());
$ctx->setChatDataItem("request_$i", null)->then(function () use ($ctx, $task, $market, $tasks, $i, $page, $excess) {
// Генерация эмодзи
/* $emoji = generateEmojis(); */
if (($market = collection::search( // Отправка сообщения
$arangodb->session, $ctx->sendMessage(
sprintf( preg_replace(
"FOR d IN market FILTER d.id == '%s' RETURN d", '/([._\-()!#])/',
$task->market '\\\$1',
) "*#$task->market* -\> *#{$task->getKey()}*\n" . (new DateTime('@' . $task->date))->format('d.m.Y') . " (" . $task->start . " - " . $task->end . ")\n\n*Город:* $market->city\n*Адрес:* $market->address\n*Работа:* $task->work" . (mb_strlen($task->description) > 0 ? "\n\n$task->description" : '')
)) instanceof _document) { ),
// Найден магазин [
$ctx->getChatDataItem("request_$i")->then(function ($message) use ($ctx, $task, $market, $tasks, $i, $page, $excess) { 'reply_markup' => [
// Удаление предыдущего сообщения на этой позиции 'inline_keyboard' => [
if ($message) $ctx->deleteMessage($message->getChat()->getId(), $message->getMessageId()); [
$ctx->setChatDataItem("request_$i", null)->then(function () use ($ctx, $task, $market, $tasks, $i, $page, $excess) { ['text' => '✅ Отправить запрос', 'callback_data' => 'request_choose']
// Генерация эмодзи
/* $emoji = generateEmojis(); */
// Отправка сообщения
$ctx->sendMessage(
preg_replace(
'/([._\-()!#])/',
'\\\$1',
"*#$task->market* -\> *#{$task->getKey()}*\n" . (new DateTime('@' . $task->date))->format('d.m.Y') . " (" . $task->start . " - " . $task->end . ")\n\n*Город:* $market->city\n*Адрес:* $market->address\n*Работа:* $task->work" . (mb_strlen($task->description) > 0 ? "\n\n$task->description" : '')
),
[
'reply_markup' => [
'inline_keyboard' => [
[
['text' => '✅ Отправить запрос', 'callback_data' => 'request_choose']
]
] ]
] ]
] ]
)->then(function ($message) use ($ctx, $tasks, $i, $page, $excess) { ]
// Запись сообщения в кеш (на случай необходимости его удаления при смене страницы) )->then(function ($message) use ($ctx, $tasks, $i, $page, $excess) {
$ctx->setChatDataItem("request_$i", $message)->then(function () use ($ctx, $message, $tasks, $i, $page, $excess) { // Запись сообщения в кеш (на случай необходимости его удаления при смене страницы)
$ctx->getChatDataItem("request_all")->then(function ($requests = []) use ($ctx, $message, $tasks, $i, $page, $excess) { $ctx->setChatDataItem("request_$i", $message)->then(function () use ($ctx, $message, $tasks, $i, $page, $excess) {
$ctx->setChatDataItem("request_all", $requests = ($requests ?? []) + [count($requests) => $message])->then(function () use ($ctx, $tasks, $i, $page, $excess) { $ctx->getChatDataItem("request_all")->then(function ($requests = []) use ($ctx, $message, $tasks, $i, $page, $excess) {
if ($i === array_key_last($tasks)) { $ctx->setChatDataItem("request_all", $requests = ($requests ?? []) + [count($requests) => $message])->then(function () use ($ctx, $tasks, $i, $page, $excess) {
// End of the process if ($i === array_key_last($tasks)) {
$ctx->endConversation(); // End of the process
$ctx->endConversation();
// Удаление предыдущего меню // Удаление предыдущего меню
$ctx->getChatDataItem("request_menu")->then(function ($message) use ($ctx, $page, $excess) { $ctx->getChatDataItem("request_menu")->then(function ($message) use ($ctx, $page, $excess) {
if ($message) $ctx->deleteMessage($message->getChat()->getId(), $message->getMessageId()); if ($message) $ctx->deleteMessage($message->getChat()->getId(), $message->getMessageId());
$ctx->setChatDataItem("request_menu", null)->then(function () use ($ctx, $page, $excess) { $ctx->setChatDataItem("request_menu", null)->then(function () use ($ctx, $page, $excess) {
// Инициализация буфера для меню поиска // Инициализация буфера для меню поиска
$keyboard = []; $keyboard = [];
// Генерация кнопки: "Предыдущая страница" // Генерация кнопки: "Предыдущая страница"
if ($page > 1) $keyboard[] = ['text' => 'Назад', 'callback_data' => 'requests_previous']; if ($page > 1) $keyboard[] = ['text' => 'Назад', 'callback_data' => 'requests_previous'];
// Генерация кнопки: "Отображённая страница" // Генерация кнопки: "Отображённая страница"
$keyboard[] = ['text' => $page, 'callback_data' => 'requests_current']; $keyboard[] = ['text' => $page, 'callback_data' => 'requests_current'];
// Генерация кнопки: "Следующая страница" // Генерация кнопки: "Следующая страница"
if ($excess) $keyboard[] = ['text' => 'Вперёд', 'callback_data' => 'requests_next']; if ($excess) $keyboard[] = ['text' => 'Вперёд', 'callback_data' => 'requests_next'];
// Отправка меню // Отправка меню
$ctx->sendMessage('🔍 Выберите заявку', [ $ctx->sendMessage('🔍 Выберите заявку', [
'reply_markup' => [ 'reply_markup' => [
'inline_keyboard' => [ 'inline_keyboard' => [
$keyboard $keyboard
]
] ]
])->then(function ($message) use ($ctx) { ]
// Запись сообщения в кеш (на случай необходимости его удаления при смене страницы) ])->then(function ($message) use ($ctx) {
$ctx->setChatDataItem("request_menu", $message); // Запись сообщения в кеш (на случай необходимости его удаления при смене страницы)
}); $ctx->setChatDataItem("request_menu", $message);
}); });
}); });
} });
}); }
}); });
}); });
}); });
}); });
}); });
} });
} }
}); }
}); });
}); });
}); });
} });
}; }
};
// Инициализация даты и генерация // Инициализация даты и генерация
$ctx->getChatDataItem('requests_date')->then(function ($old) use ($ctx, $generate) { $ctx->getChatDataItem('requests_date')->then(function ($old) use ($ctx, $generate) {
$new = $ctx->getCallbackQuery()->getData(); $new = $ctx->getCallbackQuery()->getData();
if ($new === (string) (int) $new && $new <= PHP_INT_MAX && $new >= ~PHP_INT_MAX) $ctx->setChatDataItem('requests_date', $new)->then(fn () => $generate($new)); if ($new === (string) (int) $new && $new <= PHP_INT_MAX && $new >= ~PHP_INT_MAX) $ctx->setChatDataItem('requests_date', $new)->then(fn () => $generate($new));
else $generate($old); else $generate($old);
});
}); });
} });
} }
} }
@ -667,8 +540,6 @@ $bot->onCommand('start', function (Context $ctx) use ($stop): void {
$bot->onCbQueryData(['requests_next'], fn ($ctx) => requests_next($ctx)); $bot->onCbQueryData(['requests_next'], fn ($ctx) => requests_next($ctx));
$bot->onCbQueryData(['requests_previous'], fn ($ctx) => requests_previous($ctx)); $bot->onCbQueryData(['requests_previous'], fn ($ctx) => requests_previous($ctx));
$bot->onCbQueryData(['request_choose'], fn ($ctx) => request_choose($ctx)); $bot->onCbQueryData(['request_choose'], fn ($ctx) => request_choose($ctx));
$bot->onCbQueryData(['request_confirmed'], fn ($ctx) => request_confirmed($ctx));
$bot->onCbQueryData(['request_rejected'], fn ($ctx) => request_rejected($ctx));
$bot->onCommand('day', fn ($ctx) => day($ctx)); $bot->onCommand('day', fn ($ctx) => day($ctx));
$bot->onCbQueryData(['day'], fn ($ctx) => day($ctx)); $bot->onCbQueryData(['day'], fn ($ctx) => day($ctx));

View File

@ -1,9 +1,6 @@
[Unit] [Unit]
Description=Telegram-robot Description=Telegram-robot
Wants=network.target
After=syslog.target network-online.target
[Service] [Service]
ExecStart=sudo -u www-data /usr/bin/php /var/www/spetsresurs-telegram-registry-requests/mirzaev/spetsresurs/telegram/registry/requests/system/public/robot.php ExecStart=sudo -u www-data /usr/bin/php /var/www/spetsresurs-telegram-registry-requests/mirzaev/spetsresurs/telegram/registry/requests/system/public/robot.php
PIDFile=/var/run/php/telegram-robot.pid PIDFile=/var/run/php/telegram-robot.pid
@ -11,6 +8,3 @@ RemainAfterExit=no
RuntimeMaxSec=3600s RuntimeMaxSec=3600s
Restart=always Restart=always
RestartSec=5s RestartSec=5s
[Install]
WantedBy=multi-user.target