forked from lnp2pBot/bot
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcommandlogging.ts
More file actions
71 lines (63 loc) · 2.09 KB
/
commandlogging.ts
File metadata and controls
71 lines (63 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { MiddlewareFn } from 'telegraf';
import { CommunityContext } from '../modules/community/communityContext';
import winston from 'winston';
const logFile = process.env.COMMAND_LOG_FILE || 'commands.log';
const logger = winston.createLogger({
format: winston.format.combine(
winston.format.timestamp({
format: 'YYYY-MM-DDTHH:mm:ss.SSSZ',
}),
winston.format.printf(info => {
return `[${info.timestamp}] ${info.level}: ${info.message} ${
info.stack ? info.stack : ''
}`;
}),
),
levels: winston.config.syslog.levels,
level: 'debug',
transports: [
new winston.transports.File({
filename: logFile,
maxsize: 5 * 1024 * 1024 * 1000, // 5GB
}),
],
exitOnError: false,
});
export function commandLogger(): MiddlewareFn<CommunityContext> {
return async (ctx, next) => {
try {
if (ctx.message && 'text' in ctx.message) {
const msg = ctx.message;
const text = msg.text.trim();
const userId = msg.from?.id ?? 'unknown';
let command: string | null = null;
let args: string[] = [];
let isCommand: boolean;
if (text.startsWith('/')) {
const parts = text.split(/\s+/);
command = parts[0];
args = parts.slice(1);
isCommand = true;
} else {
isCommand = false;
command = text;
}
const userName = msg.from?.username ?? '';
logger.info(`User @${userName} [${userId}] ${isCommand? 'executed command:' : 'sent message:'} ${command} with args: [${args.join(', ')}]`);
} else if (ctx.callbackQuery && 'data' in ctx.callbackQuery) {
let msgText: string;
// Safely attempt to get message text
msgText = (ctx.callbackQuery?.message as any)?.text ?? '';
const callbackData = ctx.callbackQuery.data;
const userName = ctx.callbackQuery.from?.username ?? '';
const userId = ctx.callbackQuery.from?.id ?? '';
logger.info(`User @${userName} [${userId}] sent callback query with data: ${callbackData}. Message text: '${msgText}'`);
} else {
logger.info(`Received non-command message or update from user.`);
}
} catch (err) {
logger.error('logging middleware failed', err);
}
return next();
};
}