53 lines
1.6 KiB
JavaScript
53 lines
1.6 KiB
JavaScript
const fs = require("fs");
|
|
|
|
/**
|
|
* Middleware для логирования всех действий в боте.
|
|
*/
|
|
function logMiddleware(ctx, next) {
|
|
const logEntry = {
|
|
timestamp: new Date().toISOString(),
|
|
user: {
|
|
id: ctx.from?.id || "unknown",
|
|
username: ctx.from?.username || "unknown",
|
|
first_name: ctx.from?.first_name || "unknown",
|
|
last_name: ctx.from?.last_name || "",
|
|
},
|
|
chat: ctx.chat ? { id: ctx.chat.id, type: ctx.chat.type } : null,
|
|
type: ctx.updateType, // Тип обновления (message, callback_query и т.д.)
|
|
data: getDataFromContext(ctx), // Извлечение данных из контекста
|
|
};
|
|
|
|
const logString = JSON.stringify(logEntry, null, 2);
|
|
|
|
// Сохраняем лог в файл
|
|
fs.appendFile('./json/logs.json', logString + "\n", (err) => {
|
|
if (err) {
|
|
console.error("Ошибка при записи лога:", err);
|
|
}
|
|
});
|
|
|
|
// Вызываем следующий middleware
|
|
return next();
|
|
}
|
|
|
|
/**
|
|
* Извлечение данных из контекста (например, текст сообщения или данные кнопки).
|
|
*/
|
|
function getDataFromContext(ctx) {
|
|
if (ctx.message) {
|
|
return { text: ctx.message.text || "нет текста", message_id: ctx.message.message_id };
|
|
}
|
|
|
|
if (ctx.callbackQuery) {
|
|
return { data: ctx.callbackQuery.data || "нет данных", id: ctx.callbackQuery.id };
|
|
}
|
|
|
|
if (ctx.inlineQuery) {
|
|
return { query: ctx.inlineQuery.query || "пустой запрос" };
|
|
}
|
|
|
|
return "неизвестное событие";
|
|
}
|
|
|
|
module.exports = logMiddleware;
|