Compare commits

..

8 Commits

3 changed files with 375 additions and 123 deletions

View File

@ -1,6 +1,5 @@
# Viber chat-robot # Telegram chat-robot for task registering
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 Chat-robot Telegram for accepting applications for employees from [mirzaev/ebala](https://git.mirzaev.sexy/mirzaev/ebala)
~~😼 Developed in 1 day for 100000 rubles ($1200)~~ shit happens
**DEVELOPMENT COMPLETED. PROJECT CLOSED.**

View File

@ -19,6 +19,45 @@ require __DIR__ . '/../../../../../../../vendor/autoload.php';
$arangodb = new connection(require __DIR__ . '/../settings/arangodb.php'); $arangodb = new connection(require __DIR__ . '/../settings/arangodb.php');
/* ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1); */
function escape(string $text)
{
return str_replace(
[
'#',
'*',
'_',
'=',
'.',
'[',
']',
'(',
')',
'-',
'>',
'<'
],
[
'\#',
'\*',
'\_',
'\\=',
'\.',
'\[',
'\]',
'\(',
'\)',
'\-',
'\>',
'\<'
],
$text
);
}
/** /**
* Авторизация * Авторизация
* *
@ -75,7 +114,7 @@ function worker(string $id): _document|null|false
LIMIT 1 LIMIT 1
RETURN e RETURN e
) )
FILTER d._id == e[0]._to && d.active == true FILTER d._id == e[0]._to
SORT d.created DESC, d._key DESC SORT d.created DESC, d._key DESC
LIMIT 1 LIMIT 1
RETURN d RETURN d
@ -168,23 +207,46 @@ 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())) {
// Успешная авторизация // Успешная авторизация
$ctx->sendMessage('👋 Здравствуйте, ' . preg_replace('/([._\-()!#])/', '\\\$1', $account->name['first']), [ if (!$account->active) $ctx->sendMessage('⚠️ Свяжитесь с оператором');
'reply_markup' => [ else if ($account->banned) $ctx->sendMessage('⚠️ Свяжитесь с оператором');
'inline_keyboard' => [ else if (!($worker = worker($account->getId()))->active) $ctx->sendMessage('⚠️ Свяжитесь с оператором');
[ else if ($worker->fired) $ctx->sendMessage('⚠️ Свяжитесь с оператором');
['text' => '🔍 Активные заявки', 'callback_data' => 'search'] else {
] // Активен аккаунт
],
'remove_keyboard' => true $ctx->sendMessage('👋 Здравствуйте, ' . preg_replace('/([._\-()!#])/', '\\\$1', $account->name['first']), [
] 'reply_markup' => [
]); 'inline_keyboard' => [
[
['text' => '🔍 Активные заявки', 'callback_data' => 'day']
]
],
'remove_keyboard' => true
]
])->then(function ($message) use ($ctx) {
$ctx->setChatDataItem("menu", $message);
});
}
} }
} }
function requests(int $amount = 5, int $page = 1): Cursor /**
* Прочитать заявки из ArangoDB
*
* @param int $amount Количество
* @param ?string $date За какую дату (unixtime)
* @param int $page Страница
* @param _document $worker Сотрудник
*
* @return Cursor
*/
function requests(int $amount = 5, ?string $date = null, int $page = 1, _document $worker): Cursor
{ {
global $arangodb; global $arangodb;
// Инициализация значения даты по умолчанию
$date ??= time();
// Фильтрация номера страницы // Фильтрация номера страницы
if ($page < 1) $page = 1; if ($page < 1) $page = 1;
@ -198,12 +260,15 @@ function requests(int $amount = 5, int $page = 1): Cursor
$arangodb->session, $arangodb->session,
[ [
'query' => sprintf( 'query' => sprintf(
"FOR d IN task FILTER d.date >= %s && d.worker == null && d.confirmed != true && d.published == true && d.completed != true SORT d.created DESC, d._key DESC LIMIT %d, %d RETURN d", // d.date < %s там специально, не менять на <=
/* "FOR d IN task FILTER d.date >= %s && d.date <= %s && d.worker == null && d.confirmed != true && d.published == true && d.completed != true 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 && (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",
(new DateTime('now'))->setTime(7, 0)->format('U'), $from = (new DateTime("@$date"))->setTime(0, 0)->format('U'),
/* (new DateTime('tomorrow'))->setTime(7, 0)->format('U'), */ $to = (new DateTime("@$date"))->modify('+1 day')->setTime(0, 0)->format('U'),
$to,
(new DateTime("@$date"))->modify('+2 day')->setTime(0, 0)->format('U'),
$worker->id,
$offset, $offset,
$amount + $offset $amount + $offset - ($page > 0)
), ),
"batchSize" => 1000, "batchSize" => 1000,
"sanitize" => true "sanitize" => true
@ -219,7 +284,7 @@ function generateEmojis(): string
function requests_next(Context $ctx): void function requests_next(Context $ctx): void
{ {
$ctx->getChatDataItem('requests_page')->then(function ($page) use ($ctx) { $ctx->getChatDataItem('requests_page')->then(function ($page) use ($ctx) {
$ctx->setChatDataItem('requests_page', ($page ?? 1) + 1)->then(function () use ($ctx) { $ctx->setChatDataItem('requests_page', ($page ?? 1) + 1)->then(function () use ($ctx, $page) {
search($ctx); search($ctx);
}); });
}); });
@ -235,40 +300,156 @@ 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) {
// Авторизован // Авторизован
// Инициализация ключа инстанции task в базе данных $ctx->getChatDataItem("request_confirmation_target")->then(function ($_key) use ($ctx, $arangodb, $account) {
preg_match('/^#(\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 RETURN d", $_key)); $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));
if ($worker = worker($account->getId())) { if ($task instanceof _document) {
// Найден сотрудник // Найдена заявка (подразумевается, что не занята)
// Запись идентификатора нового сотрудника if ($worker ??= worker($account->getId())) {
$task->worker = $worker->getKey(); // Найден сотрудник
// Снятие с публикации // Запись идентификатора нового сотрудника
$task->published = false; $task->worker = $worker->id;
if (document::update($arangodb->session, $task)) { // Снятие с публикации
// Записано обновление в базу данных $task->published = false;
$ctx->sendMessage("✅ *Заявка принята:* \#$_key", ['reply_markup' => ['remove_keyboard' => true]])->then(function () use ($ctx) { if (document::update($arangodb->session, $task)) {
// Записано обновление в базу данных
$ctx->getChatDataItem("request_all")->then(function ($requests = []) 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);
});
} 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) { } 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) { });
}
}
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); generateMenu($ctx);
}); });
// End of the process
$ctx->endConversation();
});
}
function day(Context $ctx): void
{
if (($account = authorization($ctx->getMessage()?->getFrom()?->getId() ?? $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 {
// Активен аккаунт
// Инициализация буфера клавиатуры
$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) {
// Отправка меню
$ctx->sendMessage('📅 Выберите дату', [
'reply_markup' => [
'inline_keyboard' => $keyboard
]
])->then(function ($message) use ($ctx) {
$ctx->getChatDataItem("menu")->then(function ($message) use ($ctx) {
// Удаление главного меню
if ($message) $ctx->deleteMessage($message->getChat()->getId(), $message->getMessageId());
$ctx->setChatDataItem("menu", null);
});
// Запись сообщения в кеш (на случай необходимости его удаления при смене страницы)
$ctx->setChatDataItem("request_day", $message);
});
});
$ctx->nextStep("search");
}
} }
} }
@ -276,107 +457,153 @@ function search(Context $ctx): void
{ {
global $arangodb; global $arangodb;
if (authorization($ctx->getMessage()?->getFrom()?->getId() ?? $ctx->getCallbackQuery()->getFrom()->getId()) instanceof _document) { if (($account = authorization($ctx->getMessage()?->getFrom()?->getId() ?? $ctx->getCallbackQuery()->getFrom()->getId())) instanceof _document) {
// Авторизован // Авторизован
$ctx->getChatDataItem('requests_page')->then(function ($page) use ($ctx, $arangodb) { 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 {
// Активен аккаунт
// Значение страницы по умолчанию $ctx->getChatDataItem('requests_page')->then(function ($page) use ($ctx, $arangodb, $worker) {
if (empty($page)) { // Найдена текущая страница
$page = 1;
$ctx->setChatDataItem('requests_page', 1);
}
// Поиск заявок из базы данных // Значение страницы по умолчанию
$tasks = requests(6, $page); if (empty($page)) {
$page = 1;
$ctx->setChatDataItem('requests_page', 1);
}
// Подсчёт количества прочитанных заявок из базы данных $generate = function ($date) use ($ctx, $page, $arangodb, $worker) {
$count = $tasks->getCount(); // Поиск заявок в ArangoDB
$tasks = requests(4, (string) $date, $page, $worker);
// Проверка существования избытка // Подсчёт количества прочитанных заявок из базы данных
$excess = $count % 6 === 0; $count = $tasks->getCount();
// Обрезка заявок до размера страницы // Проверка существования избытка
$tasks = array_slice($tasks->getAll(), 0, 5); $excess = $count > 3;
if ($count === 0) $ctx->sendMessage('📦 *Заявок нет*'); // Обрезка заявок до размера страницы (3 заявки на 1 странице)
else { $tasks = array_slice($tasks->getAll(), 0, 3);
// Найдены заявки
foreach ($tasks as $i => $task) { if ($count === 0) {
// Перебор найденных заявок $ctx->sendMessage('📦 *Заявок нет*')->then(function ($message) use ($ctx) {
$ctx->getChatDataItem("request_all")->then(function ($requests = []) use ($ctx, $message) {
if (($market = collection::search( // Удаление сообщений связанных с запросом
$arangodb->session, foreach ($requests ?? [] as $_message) $ctx->deleteMessage($_message->getChat()->getId(), $_message->getMessageId());
sprintf( $ctx->setChatDataItem("request_all", $requests = [$message]);
"FOR d IN market FILTER d._key == '%s' RETURN d", });
$task->market
)
)) instanceof _document) {
// Найден магазин
$ctx->getChatDataItem("request_$i")->then(function ($message) use ($ctx) {
// Удаление предыдущего сообщения на этой позиции
$ctx->deleteMessage($message->getChat()->getId(), $message->getMessageId());
}); });
} else {
// Найдены заявки
// Генерация эмодзи $ctx->getChatDataItem("request_day")->then(function ($message) use ($ctx, $arangodb, $tasks, $page, $excess) {
/* $emoji = generateEmojis(); */ // Удаление предыдущего меню с выбором даты
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());
$ctx->setChatDataItem("request_all", [])->then(function () use ($ctx, $arangodb, $tasks, $excess, $page) {
foreach ($tasks as $i => $task) {
// Перебор найденных заявок
// Отправка сообщения if (($market = collection::search(
$ctx->sendMessage( $arangodb->session,
preg_replace( sprintf(
'/([._\-()!#])/', "FOR d IN market FILTER d.id == '%s' RETURN d",
'\\\$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) {
[ // Найден магазин
'reply_markup' => [ $ctx->getChatDataItem("request_$i")->then(function ($message) use ($ctx, $task, $market, $tasks, $i, $page, $excess) {
'inline_keyboard' => [ // Удаление предыдущего сообщения на этой позиции
[ if ($message) $ctx->deleteMessage($message->getChat()->getId(), $message->getMessageId());
['text' => '✅ Отправить запрос', 'callback_data' => 'request_choose'] $ctx->setChatDataItem("request_$i", null)->then(function () use ($ctx, $task, $market, $tasks, $i, $page, $excess) {
] // Генерация эмодзи
] /* $emoji = generateEmojis(); */
]
]
)->then(function ($message) use ($ctx, $tasks, $i, $page, $excess) {
// Запись сообщения в кеш (на случай необходимости его удаления при смене страницы)
$ctx->setChatDataItem("request_$i", $message)->then(function () use ($ctx, $tasks, $i, $page, $excess) {
if ($i === array_key_last($tasks)) { // Отправка сообщения
// Удаление предыдущего меню $ctx->sendMessage(
$ctx->getChatDataItem("request_menu")->then(function ($message) use ($ctx) { preg_replace(
$ctx->deleteMessage($message->getChat()->getId(), $message->getMessageId()); '/([._\-()!#])/',
'\\\$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) {
// Запись сообщения в кеш (на случай необходимости его удаления при смене страницы)
$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_all", $requests = ($requests ?? []) + [count($requests) => $message])->then(function () use ($ctx, $tasks, $i, $page, $excess) {
if ($i === array_key_last($tasks)) {
// End of the process
$ctx->endConversation();
// Удаление предыдущего меню
$ctx->getChatDataItem("request_menu")->then(function ($message) use ($ctx, $page, $excess) {
if ($message) $ctx->deleteMessage($message->getChat()->getId(), $message->getMessageId());
$ctx->setChatDataItem("request_menu", null)->then(function () use ($ctx, $page, $excess) {
// Инициализация буфера для меню поиска
$keyboard = [];
// Генерация кнопки: "Предыдущая страница"
if ($page > 1) $keyboard[] = ['text' => 'Назад', 'callback_data' => 'requests_previous'];
// Генерация кнопки: "Отображённая страница"
$keyboard[] = ['text' => $page, 'callback_data' => 'requests_current'];
// Генерация кнопки: "Следующая страница"
if ($excess) $keyboard[] = ['text' => 'Вперёд', 'callback_data' => 'requests_next'];
// Отправка меню
$ctx->sendMessage('🔍 Выберите заявку', [
'reply_markup' => [
'inline_keyboard' => [
$keyboard
]
]
])->then(function ($message) use ($ctx) {
// Запись сообщения в кеш (на случай необходимости его удаления при смене страницы)
$ctx->setChatDataItem("request_menu", $message);
});
});
});
}
});
});
});
});
});
});
}
}
}); });
});
// Инициализация буфера для меню поиска
$keyboard = [];
// Генерация кнопки: "Предыдущая страница"
if ($page > 1) $keyboard[] = ['text' => 'Назад ⬅️', 'callback_data' => 'requests_previous'];
// Генерация кнопки: "Следующая страница"
if ($excess) $keyboard[] = ['text' => '➡️ Вперёд', 'callback_data' => 'requests_next'];
// Отправка меню
$ctx->sendMessage('🔍 Выберите заявку', [
'reply_markup' => [
'inline_keyboard' => [
$keyboard
]
]
])->then(function ($message) use ($ctx) {
// Запись сообщения в кеш (на случай необходимости его удаления при смене страницы)
$ctx->setChatDataItem("request_menu", $message);
});
}
}); });
}); });
} }
} };
}
}); // Инициализация даты и генерация
$ctx->getChatDataItem('requests_date')->then(function ($old) use ($ctx, $generate) {
$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));
else $generate($old);
});
});
}
} }
} }
@ -416,13 +643,33 @@ $bot->onUpdate(function (Context $ctx) use (&$stop): void {
$bot->onCommand('start', function (Context $ctx) use ($stop): void { $bot->onCommand('start', function (Context $ctx) use ($stop): void {
if ($stop) return; if ($stop) return;
$ctx->getChatDataItem("request_all")->then(function ($requests = []) use ($ctx) {
// Удаление сообщений связанных с запросом
foreach ($requests ?? [] as $_message) $ctx->deleteMessage($_message->getChat()->getId(), $_message->getMessageId());
$ctx->setChatDataItem("request_all", []);
});
$ctx->getChatDataItem("menu")->then(function ($message) use ($ctx) {
// Удаление главного меню
if ($message) $ctx->deleteMessage($message->getChat()->getId(), $message->getMessageId());
$ctx->setChatDataItem("menu", null);
});
$ctx->getChatDataItem("request_day")->then(function ($message) use ($ctx) {
// Удаление меню выбора даты
if ($message) $ctx->deleteMessage($message->getChat()->getId(), $message->getMessageId());
$ctx->setChatDataItem("request_day", null);
});
generateMenu($ctx); generateMenu($ctx);
}); });
$bot->onCommand('search', fn ($ctx) => search($ctx));
$bot->onCbQueryData(['search'], fn ($ctx) => search($ctx));
$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->onCbQueryData(['day'], fn ($ctx) => day($ctx));
$bot->run(); $bot->run();

View File

@ -1,6 +1,9 @@
[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
@ -8,3 +11,6 @@ RemainAfterExit=no
RuntimeMaxSec=3600s RuntimeMaxSec=3600s
Restart=always Restart=always
RestartSec=5s RestartSec=5s
[Install]
WantedBy=multi-user.target