-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCommandProcessor.cs
More file actions
302 lines (241 loc) · 10.1 KB
/
CommandProcessor.cs
File metadata and controls
302 lines (241 loc) · 10.1 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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
using Botticelli.Analytics.Shared.Metrics;
using Botticelli.Bot.Interfaces.Processors;
using Botticelli.Bot.Utils;
using Botticelli.Client.Analytics;
using Botticelli.Framework.Commands.Utils;
using Botticelli.Framework.Commands.Validators;
using Botticelli.Framework.SendOptions;
using Botticelli.Interfaces;
using Botticelli.Shared.API.Client.Requests;
using Botticelli.Shared.ValueObjects;
using FluentValidation;
using Microsoft.Extensions.Logging;
namespace Botticelli.Framework.Commands.Processors;
public abstract class CommandProcessor<TCommand> : ICommandProcessor
where TCommand : class, ICommand
{
private readonly string _command;
private readonly ICommandValidator<TCommand> _commandValidator;
private readonly IValidator<Message> _messageValidator;
private readonly MetricsProcessor? _metricsProcessor;
protected readonly ILogger Logger;
protected IBot? _bot;
protected CommandProcessor(ILogger logger,
ICommandValidator<TCommand> commandValidator,
IValidator<Message> messageValidator)
{
Logger = logger;
_commandValidator = commandValidator;
_messageValidator = messageValidator;
_command = GetOldFashionedCommandName(typeof(TCommand).Name);
}
protected CommandProcessor(ILogger logger,
ICommandValidator<TCommand> commandValidator,
IValidator<Message> messageValidator,
MetricsProcessor? metricsProcessor)
{
Logger = logger;
_commandValidator = commandValidator;
_metricsProcessor = metricsProcessor;
_messageValidator = messageValidator;
_command = GetOldFashionedCommandName(typeof(TCommand).Name);
}
public virtual async Task ProcessAsync(Message message, CancellationToken token)
{
try
{
var messageValidationResult = await _messageValidator.ValidateAsync(message, token);
if (!messageValidationResult.IsValid)
{
_metricsProcessor?.Process(MetricNames.BotError, BotDataUtils.GetBotId());
Logger.LogError($"Error in {GetType().Name} invalid input message:" +
$" {messageValidationResult.Errors.Select(e => $"({e.PropertyName} : {e.ErrorCode} : {e.ErrorMessage})")}");
return;
}
if (message.Poll != null)
{
await InnerProcessPoll(message, token);
return;
}
if (message.From?.Id != null && message.From!.Id!.Equals(_bot?.BotUserId, StringComparison.InvariantCulture)) return;
Classify(ref message);
if (string.IsNullOrWhiteSpace(message.Body) &&
message.Attachments == null &&
message.Location == null &&
message.Contact == null &&
message.Poll == null &&
message.CallbackData == null)
{
Logger.LogWarning("Message {MsgId} is empty! Skipping...", message.Uid);
return;
}
// if we've any callback data, lets assume , that it is a command, if not - see in a message body
var body = GetBody(message);
if (CommandUtils.SimpleCommandRegex.IsMatch(body))
{
var match = CommandUtils.SimpleCommandRegex.Matches(body)
.FirstOrDefault();
if (match == null) return;
var commandName = GetOldFashionedCommandName(match.Groups[1].Value);
if (commandName != _command) return;
await ValidateAndProcess(message, token);
SendMetric(MetricNames.CommandReceived);
}
else if (CommandUtils.ArgsCommandRegex.IsMatch(body))
{
var match = CommandUtils.ArgsCommandRegex.Matches(body)
.FirstOrDefault();
if (match == null) return;
var commandName = GetOldFashionedCommandName(match.Groups[1].Value);
if (commandName != _command) return;
await ValidateAndProcess(message, token);
SendMetric(MetricNames.CommandReceived);
}
else
{
if (GetType().IsAssignableTo(typeof(CommandChainProcessor<TCommand>)))
await ValidateAndProcess(message,
token);
}
if (message.Location != null) await InnerProcessLocation(message, token);
if (message.Poll != null) await InnerProcessPoll(message, token);
if (message.Contact != null) await InnerProcessContact(message, token);
}
catch (Exception ex)
{
_metricsProcessor?.Process(MetricNames.BotError, BotDataUtils.GetBotId());
Logger.LogError(ex, "Error in {Name}: {ExMessage}", GetType().Name, ex.Message);
await InnerProcessError(message, ex, token);
}
}
public virtual void SetBot(IBot bot)
{
_bot = bot;
}
public void SetServiceProvider(IServiceProvider sp)
{
}
protected static void Classify(ref Message message)
{
var body = GetBody(message);
if (CommandUtils.SimpleCommandRegex.IsMatch(body) || CommandUtils.ArgsCommandRegex.IsMatch(body))
message.Type = Message.MessageType.Command;
else
message.Type = Message.MessageType.Messaging;
}
private static string GetBody(Message message)
{
return !string.IsNullOrWhiteSpace(message.CallbackData) ? message.CallbackData
: !string.IsNullOrWhiteSpace(message.Body) ? message.Body
: string.Empty;
}
private void SendMetric(string metricName)
{
_metricsProcessor?.Process(metricName, BotDataUtils.GetBotId()!);
}
private void SendMetric()
{
_metricsProcessor?.Process(GetOldFashionedCommandName($"{GetType().Name.Replace("Processor", string.Empty)}Command"),
BotDataUtils.GetBotId()!);
}
private string GetOldFashionedCommandName(string fullCommand)
{
return fullCommand.ToLowerInvariant().Replace("command", "");
}
private async Task ValidateAndProcess(Message message,
CancellationToken token)
{
if (_bot == null) return;
if (message.Type == Message.MessageType.Messaging)
{
SendMetric();
await InnerProcess(message, token);
return;
}
if (await _commandValidator.Validate(message))
{
SendMetric();
await InnerProcess(message, token);
}
else
{
var errMessageRequest = new SendMessageRequest
{
Message =
{
Body = _commandValidator.Help()
}
};
await SendMessage(errMessageRequest, token);
}
}
protected async Task DeleteMessage(DeleteMessageRequest request, CancellationToken token)
{
if (_bot == null) return;
await _bot.DeleteMessageAsync(request, token);
}
protected async Task DeleteMessage(Message message, CancellationToken token)
{
if (_bot == null) return;
foreach (var request in message.ChatIds.Select(chatId => new DeleteMessageRequest(message.Uid, chatId))) await _bot.DeleteMessageAsync(request, token);
}
protected async Task SendMessage(Message message, CancellationToken token)
{
if (_bot == null) return;
var request = new SendMessageRequest
{
Message = message
};
await SendMessage(request, token);
}
protected async Task SendMessage(SendMessageRequest request, CancellationToken token)
{
if (_bot == null) return;
await _bot.SendMessageAsync(request, token);
}
protected async Task SendMessage<TReplyMarkup>(SendMessageRequest request,
SendOptionsBuilder<TReplyMarkup>? options,
CancellationToken token)
where TReplyMarkup : class
{
if (_bot == null) return;
await _bot.SendMessageAsync(request, options, token);
}
protected async Task UpdateMessage<TSendOptions>(Message message,
ISendOptionsBuilder<TSendOptions>? options,
CancellationToken token)
where TSendOptions : class
{
if (_bot == null) return;
await _bot.UpdateMessageAsync(new SendMessageRequest
{
ExpectPartialResponse = false,
Message = new Message
{
Body = message.CallbackData,
Uid = message.Uid,
ChatIds = message.ChatIds,
ChatIdInnerIdLinks = message.ChatIdInnerIdLinks
}
},
options,
token);
}
protected virtual Task InnerProcessContact(Message message, CancellationToken token)
{
return Task.CompletedTask;
}
protected virtual Task InnerProcessPoll(Message message, CancellationToken token)
{
return Task.CompletedTask;
}
protected virtual Task InnerProcessLocation(Message message, CancellationToken token)
{
return Task.CompletedTask;
}
protected abstract Task InnerProcess(Message message, CancellationToken token);
protected virtual Task InnerProcessError(Message message, Exception? ex, CancellationToken token)
{
return Task.CompletedTask;
}
}