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())) {
// Успешная авторизация // Успешная авторизация
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->sendMessage('👋 Здравствуйте, ' . preg_replace('/([._\-()!#])/', '\\\$1', $account->name['first']), [ $ctx->sendMessage('👋 Здравствуйте, ' . preg_replace('/([._\-()!#])/', '\\\$1', $account->name['first']), [
'reply_markup' => [ 'reply_markup' => [
'inline_keyboard' => [ 'inline_keyboard' => [
[ [
['text' => '🔍 Активные заявки', 'callback_data' => 'search'] ['text' => '🔍 Активные заявки', 'callback_data' => 'day']
] ]
], ],
'remove_keyboard' => true '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,24 +300,62 @@ 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->worker = $worker->id;
// Снятие с публикации // Снятие с публикации
$task->published = false; $task->published = false;
@ -260,7 +363,24 @@ function request_choose(Context $ctx): void
if (document::update($arangodb->session, $task)) { if (document::update($arangodb->session, $task)) {
// Записано обновление в базу данных // Записано обновление в базу данных
$ctx->sendMessage("✅ *Заявка принята:* \#$_key", ['reply_markup' => ['remove_keyboard' => true]])->then(function () use ($ctx) { $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); 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) {
@ -269,6 +389,67 @@ function request_choose(Context $ctx): void
} 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);
}); });
});
}
}
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
{
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,10 +457,17 @@ 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) {
// Найдена текущая страница // Найдена текущая страница
// Значение страницы по умолчанию // Значение страницы по умолчанию
@ -288,39 +476,53 @@ function search(Context $ctx): void
$ctx->setChatDataItem('requests_page', 1); $ctx->setChatDataItem('requests_page', 1);
} }
// Поиск заявок из базы данных $generate = function ($date) use ($ctx, $page, $arangodb, $worker) {
$tasks = requests(6, $page); // Поиск заявок в ArangoDB
$tasks = requests(4, (string) $date, $page, $worker);
// Подсчёт количества прочитанных заявок из базы данных // Подсчёт количества прочитанных заявок из базы данных
$count = $tasks->getCount(); $count = $tasks->getCount();
// Проверка существования избытка // Проверка существования избытка
$excess = $count % 6 === 0; $excess = $count > 3;
// Обрезка заявок до размера страницы // Обрезка заявок до размера страницы (3 заявки на 1 странице)
$tasks = array_slice($tasks->getAll(), 0, 5); $tasks = array_slice($tasks->getAll(), 0, 3);
if ($count === 0) $ctx->sendMessage('📦 *Заявок нет*'); if ($count === 0) {
else { $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 {
// Найдены заявки // Найдены заявки
$ctx->getChatDataItem("request_day")->then(function ($message) use ($ctx, $arangodb, $tasks, $page, $excess) {
// Удаление предыдущего меню с выбором даты
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) { foreach ($tasks as $i => $task) {
// Перебор найденных заявок // Перебор найденных заявок
if (($market = collection::search( if (($market = collection::search(
$arangodb->session, $arangodb->session,
sprintf( sprintf(
"FOR d IN market FILTER d._key == '%s' RETURN d", "FOR d IN market FILTER d.id == '%s' RETURN d",
$task->market $task->market
) )
)) instanceof _document) { )) instanceof _document) {
// Найден магазин // Найден магазин
$ctx->getChatDataItem("request_$i")->then(function ($message) use ($ctx, $task, $market, $tasks, $i, $page, $excess) {
$ctx->getChatDataItem("request_$i")->then(function ($message) use ($ctx) {
// Удаление предыдущего сообщения на этой позиции // Удаление предыдущего сообщения на этой позиции
$ctx->deleteMessage($message->getChat()->getId(), $message->getMessageId()); 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(); */ /* $emoji = generateEmojis(); */
@ -329,7 +531,7 @@ function search(Context $ctx): void
preg_replace( preg_replace(
'/([._\-()!#])/', '/([._\-()!#])/',
'\\\$1', '\\\$1',
"*#{$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" : '') "*#$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' => [ 'reply_markup' => [
@ -342,22 +544,28 @@ function search(Context $ctx): void
] ]
)->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, $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)) { if ($i === array_key_last($tasks)) {
// Удаление предыдущего меню // End of the process
$ctx->getChatDataItem("request_menu")->then(function ($message) use ($ctx) { $ctx->endConversation();
$ctx->deleteMessage($message->getChat()->getId(), $message->getMessageId());
});
// Удаление предыдущего меню
$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 = []; $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'];
// Генерация кнопки: "Следующая страница" // Генерация кнопки: "Следующая страница"
if ($excess) $keyboard[] = ['text' => '➡️ Вперёд', 'callback_data' => 'requests_next']; if ($excess) $keyboard[] = ['text' => 'Вперёд', 'callback_data' => 'requests_next'];
// Отправка меню // Отправка меню
$ctx->sendMessage('🔍 Выберите заявку', [ $ctx->sendMessage('🔍 Выберите заявку', [
@ -370,13 +578,32 @@ function search(Context $ctx): void
// Запись сообщения в кеш (на случай необходимости его удаления при смене страницы) // Запись сообщения в кеш (на случай необходимости его удаления при смене страницы)
$ctx->setChatDataItem("request_menu", $message); $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