-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAlertBot.java
More file actions
240 lines (200 loc) · 10.2 KB
/
AlertBot.java
File metadata and controls
240 lines (200 loc) · 10.2 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
package dev.vality.alerting.tg.bot.service;
import dev.vality.alerting.tg.bot.config.properties.AlertBotProperties;
import dev.vality.alerting.tg.bot.model.Webhook;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Service;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.methods.forum.CreateForumTopic;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import java.util.*;
@Slf4j
@Service
@RequiredArgsConstructor
@EnableScheduling
public class AlertBot extends TelegramLongPollingBot {
private final AlertBotProperties properties;
private static final Map<Long, List<String>> activeTopics = new HashMap<>();
private static final Set<Long> waitingForTopicName = new HashSet<>();
@Override
public String getBotUsername() {
return properties.getName();
}
@Override
public String getBotToken() {
return properties.getToken();
}
@Override
public void onUpdateReceived(Update update) {
if (update.hasMessage() && update.getMessage().hasText()) {
log.debug("Получено сообщение: message={}, chatId={}, threadId={}, user=@{}, text='{}'",
update.getMessage(),
update.getMessage().getChatId(),
update.getMessage().getMessageThreadId(),
update.getMessage().getFrom() != null ? update.getMessage().getFrom().getUserName() : null,
update.getMessage().getText().replace('\n', ' ')
);
Message message = update.getMessage();
Long chatId = message.getChatId();
Integer threadId = message.getMessageThreadId();
// ❗ Фильтруем команды — они должны выполняться только в командном топике
if (!threadId.equals(properties.getTopics().getCommands())) {
return;
}
String text = message.getText();
if (text.startsWith("/create_alert_topic")) {
promptForTopicName(chatId);
} else if (waitingForTopicName.contains(chatId)) {
createTopic(chatId, text);
} else if (text.startsWith("/delete_alert_topic")) {
deleteTopic(chatId);
} else {
sendResponse(chatId, properties.getTopics().getCommands(), "Неизвестная команда.", null);
}
}
}
public void sendAlertMessage(Webhook webhook) {
sendResponse(properties.getChatId(), properties.getTopics().getCommands(), webhook.getAlerts().toString(),
null);
}
public void sendScheduledMetrics() {
send5xxErrorsMetrics(properties.getChatId());
sendFailedMachinesMetrics(properties.getChatId());
sendPendingPaymentsMetrics(properties.getChatId());
sendAltPayConversionMetrics(properties.getChatId());
sendMessageToLastTopic(properties.getChatId());
}
// Просим ввести название топика (только в командном топике)
private void promptForTopicName(Long chatId) {
waitingForTopicName.add(chatId);
sendResponse(chatId, properties.getTopics().getCommands(), "Введите название для нового топика:", null);
}
// Создание топика по введённому названию
private void createTopic(Long chatId, String topicName) {
try {
waitingForTopicName.remove(chatId);
CreateForumTopic createForumTopic = CreateForumTopic.builder()
.chatId(chatId.toString())
.name(topicName)
.build();
Integer messageThreadId = execute(createForumTopic).getMessageThreadId();
// activeTopics.put(chatId, String.valueOf(messageThreadId));
// Добавляем топик в список, если у чата уже есть созданные топики
activeTopics.computeIfAbsent(chatId, k -> new ArrayList<>()).add(String.valueOf(messageThreadId));
sendResponse(chatId, properties.getTopics().getCommands(), "✅ Топик '" + topicName + "' создан.", null);
sendResponse(chatId, null, "✅ Топик '" + topicName + "' создан.", null);
} catch (TelegramApiException e) {
log.error("Ошибка при создании топика", e);
sendResponse(chatId, properties.getTopics().getCommands(), "❌ Ошибка при создании топика.", null);
}
}
// Удаление топика (пока API не поддерживает удаление)
private void deleteTopic(Long chatId) {
sendResponse(chatId, properties.getTopics().getCommands(),
"🗑 Топик удалён (на самом деле, нет, API не поддерживает).", null);
}
private void sendMessageToLastTopic(Long chatId) {
List<String> topics = activeTopics.get(chatId);
if (topics != null && !topics.isEmpty()) {
String lastTopic = topics.get(topics.size() - 1);
String messageText = send5xxAlert();
sendResponse(chatId, Integer.parseInt(lastTopic), messageText, "MarkdownV2");
}
}
// Заглушка для отправки метрики "Рост числа 5xx кодов при обращении к API процессинга"
private void send5xxErrorsMetrics(Long chatId) {
String messageText = String.format("""
```
Рост числа 5xx кодов при обращении к API процессинга за последние 24h
prov | term | count
--------------------------------
%-10d | %-10d | %-10d
%-10d | %-10d | %-10d
%-10d | %-10d | %-10d
```
""",
197, 1435, 35,
492, 7223, 42,
545, 9998, 55);
sendResponse(chatId, properties.getTopics().getErrors5xx(), messageText, "MarkdownV2");
}
// Заглушка для отправки метрики "Рост числа платежей без финального статуса"
private void sendPendingPaymentsMetrics(Long chatId) {
String messageText = String.format("""
```
Рост числа платежей без финального статуса за последние 24h
prov | term | count
--------------------------------
%-10d | %-10d | %-10d
%-10d | %-10d | %-10d
%-10d | %-10d | %-10d
```
""",
314, 1234, 35,
244, 7556, 42,
345, 1129, 55);
sendResponse(chatId, properties.getTopics().getPendingPayments(), messageText, "MarkdownV2");
}
// Заглушка для отправки метрики "Рост числа упавших машин"
private void sendFailedMachinesMetrics(Long chatId) {
String messageText = String.format("""
```
Рост числа упавших машин за последние 24h
prov | term | count
--------------------------------
%-10d | %-10d | %-10d
%-10d | %-10d | %-10d
%-10d | %-10d | %-10d
```
""",
221, 1569, 35,
234, 7034, 42,
595, 9032, 55);
sendResponse(chatId, properties.getTopics().getFailedMachines(), messageText, "MarkdownV2");
}
// Заглушка для отправки метрики "Конверсия альтернативных платежей"
private void sendAltPayConversionMetrics(Long chatId) {
String messageText = String.format("""
```
Конверсия альтернативных платежей за последние 24h
prov | term | state | curr | avg
-----------------------------------------------
%-10d | %-10d | %-6s | %-5.2f | %-5.2f
%-10d | %-10d | %-6s | %-5.2f | %-5.2f
%-10d | %-10d | %-6s | %-5.2f | %-5.2f
```
""",
160, 1456, "alive", 70.23, 61.56,
240, 7234, "dead", 15.85, 90.02,
538, 9456, "alive", 50.10, 40.20);
sendResponse(chatId, properties.getTopics().getAltpayConversion(), messageText, "MarkdownV2");
}
// Заглушка для отправки алерта по 5xx кодам для одного провайдера и терминала
private String send5xxAlert() {
return String.format("""
```
Рост числа 5xx кодов при обращении к API процессинга за последние %dh
Количество 5xx: %d
```
""",
24, 87);
}
// Отправка сообщения в командный топик
private void sendResponse(Long chatId, Integer threadId, String messageText, String parseMode) {
SendMessage message = SendMessage.builder()
.chatId(chatId.toString())
.messageThreadId(threadId)
.text(messageText)
.parseMode(parseMode)
.build();
try {
execute(message);
} catch (TelegramApiException e) {
log.error("Ошибка при отправке сообщения", e);
}
}
}