-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
268 lines (267 loc) · 12.1 KB
/
Program.cs
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
using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using telbot.handle;
using telbot.models;
using telbot.Helpers;
namespace telbot;
public class Program
{
private TelegramBotClient bot;
private Configuration cfg;
public Program(Configuration cfg)
{
this.cfg = cfg;
// instantiates a new telegram bot api client with the specified token
bot = new TelegramBotClient(cfg.BOT_TOKEN);
//
using (var cts = new CancellationTokenSource())
{
bot.StartReceiving(updateHandler: HandleUpdate, pollingErrorHandler: HandleError, cancellationToken: cts.Token);
Console.WriteLine($"< {DateTime.Now} Manager: Start listening for updates. Press enter to stop.");
var msg = new handle.HandleMessage(bot);
if(cfg.IS_DEVELOPMENT == false) HandleAnnouncement.Comunicado(msg, cfg);
if(cfg.SAP_VENCIMENTO) HandleAnnouncement.Vencimento(msg, cfg, "vencimento", 7);
if(cfg.SAP_BANDEIRADA) HandleAnnouncement.Vencimento(msg, cfg, "bandeirada", 7);
if(cfg.OFS_MONITORAMENTO) HandleAnnouncement.Monitorado(msg, cfg);
if(cfg.OFS_FINALIZACAO) HandleAnnouncement.Finalizacao(msg, cfg);
if(cfg.PRL_SUBSISTEMA) HandleAnnouncement.Faturamento(msg, cfg);
Console.ReadLine();
cts.Cancel();
}
}
async Task HandleUpdate(ITelegramBotClient _, Update update, CancellationToken cancellationToken)
{
if(cfg.IS_DEVELOPMENT)
{
ConsoleWrapper.Debug(Entidade.Usuario, System.Text.Json.JsonSerializer.Serialize<Update>(update));
}
var msg = new HandleMessage(bot);
await Recovery.ErrorSendMessageRecovery(msg);
if (update.Type == UpdateType.Message)
{
if (update.Message!.Type == MessageType.Contact && update.Message.Contact != null)
{
Database.inserirTelefone(update.Message.From!.Id, Int64.Parse(update.Message.Contact.PhoneNumber));
await msg.RemoveRequest(update.Message.From.Id, update.Message.Contact.PhoneNumber);
return;
}
else
{
while(true)
{
if(!System.IO.File.Exists(cfg.SAP_LOCKFILE)) break;
else System.Threading.Thread.Sleep(1_000);
}
System.IO.File.Create(cfg.SAP_LOCKFILE).Close();
await HandleMessage(msg, update.Message!);
System.IO.File.Delete(cfg.SAP_LOCKFILE);
}
}
else await msg.ErrorReport(id: cfg.ID_ADM_BOT, error: new InvalidOperationException(update.ToString()));
return;
}
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
async Task HandleError(ITelegramBotClient _, Exception exception, CancellationToken cancellationToken)
{
ConsoleWrapper.Error(Entidade.Manager, exception);
return;
}
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
async Task HandleMessage(HandleMessage msg, Message message)
{
if (message.From is null) return;
var user = Database.recuperarUsuario(message.From.Id);
if(user is null)
{
user = new(message.From.Id);
Database.inserirUsuario(user);
await msg.sendTextMesssageWraper(message.From.Id, "Seja bem vindo ao sistema de atendimento automático do chatbot!");
await msg.sendTextMesssageWraper(message.From.Id, "Eu não estou autorizado a te passar informações no momento");
await msg.sendTextMesssageWraper(message.From.Id, $"Seu identificador do Telegram é `{message.From.Id}`.");
await msg.sendTextMesssageWraper(message.From.Id, "Informe ao seu supervisor esse identificador para ter acesso");
return;
}
var has_jpg = message.Photo != null ? message.Photo.First().FileId : null;
var has_mp4 = message.Video != null ? message.Video.FileId : null;
var has_doc = message.Document != null ? message.Document.FileId : null;
var has_txt = message.Text != null && message.Text.Length > 50;
if(user.pode_transmitir() && (has_txt || has_jpg != null || has_mp4 != null || has_doc != null))
{
var has_media = has_jpg != null || has_mp4 != null || has_doc != null;
var section = has_media ? message.Caption : message.Text;
var footer = $"*ENVIADO POR: {message.From.FirstName} {message.From.LastName}*";
var mensagem = $"{section}\n\n{footer}";
var usuarios = Database.recuperarUsuario(u =>
(
u.has_privilege == UsersModel.userLevel.proprietario ||
u.has_privilege == UsersModel.userLevel.administrador ||
u.has_privilege == UsersModel.userLevel.comunicador ||
(u.has_privilege == UsersModel.userLevel.eletricista && u.update_at.AddDays(cfg.DIAS_EXPIRACAO) < DateTime.Now) ||
(u.has_privilege == UsersModel.userLevel.controlador && u.update_at.AddDays(cfg.DIAS_EXPIRACAO) < DateTime.Now) ||
(u.has_privilege == UsersModel.userLevel.supervisor && u.update_at.AddDays(cfg.DIAS_EXPIRACAO * 3) < DateTime.Now)
)
);
ConsoleWrapper.Debug(Entidade.Advertiser, $"Usuários selecionados: {usuarios.Count()}");
await HandleAnnouncement.Comunicado(usuarios, msg, cfg, user.id, mensagem, has_jpg, has_mp4, has_doc);
await msg.sendTextMesssageWraper(user.id, "Comunicado enviado com sucesso!");
return;
}
if (message.Text is null) return;
Console.WriteLine($"> {message.Date.ToLocalTime()} usuario: {message.From.Id} escreveu: {message.Text}");
if(user.has_privilege == UsersModel.userLevel.desautorizar)
{
await msg.sendTextMesssageWraper(message.From.Id, "Eu não estou autorizado a te passar informações no momento");
await msg.sendTextMesssageWraper(message.From.Id, "Para restaurar o seu acesso ao sistema, solicite ao seu supervisor o acesso ao BOT.");
await msg.sendTextMesssageWraper(message.From.Id, $"Seu identificador do telegram é `{message.From.Id}`, esse número deverá ser informado ao seu supervisor.");
return;
}
if(user.phone_number == 0)
{
await msg.RequestContact(message.From.Id);
return;
}
if(!user.pode_promover())
{
var prazo_expiracao = (user.has_privilege == UsersModel.userLevel.supervisor)
? cfg.DIAS_EXPIRACAO * 3 : cfg.DIAS_EXPIRACAO;
// verifica se o cadastro de eletricistas expirou
DateTime expiracao = user.update_at.AddDays(prazo_expiracao);
DateTime sinalizar = user.update_at.AddDays(prazo_expiracao - 7);
if(System.DateTime.Compare(DateTime.Now, expiracao) > 0)
{
await msg.sendTextMesssageWraper(message.From.Id, "Sua autorização expirou e não posso mais te passar informações");
await msg.sendTextMesssageWraper(message.From.Id, "Solicite a autorização novamente para o seu supervisor!");
await msg.sendTextMesssageWraper(message.From.Id, $"Seu identificador do Telegram é {message.From.Id}.");
return;
}
// Verifica se o cadastro está perto de expirar (7 dias antes) e avisa
if(System.DateTime.Compare(DateTime.Now, sinalizar) >= 0)
{
await msg.sendTextMesssageWraper(message.From.Id, "Sua autorização está quase expirando!");
await msg.sendTextMesssageWraper(message.From.Id, "Solicite a **atualização** para o seu supervisor!");
await msg.sendTextMesssageWraper(message.From.Id, $"Seu identificador do Telegram é {message.From.Id}.");
}
}
var request = Validador.isRequest(message.Text, message.Date.ToLocalTime(), message.MessageId);
if (request is null)
{
await msg.sendTextMesssageWraper(user.id, "Verifique o formato da informação e tente novamente da forma correta!");
await msg.sendTextMesssageWraper(user.id, "Se tiver em dúvida de como usar o bot, digite /ajuda.");
return;
}
if(cfg.SAP_OFFLINE && request.tipo != TypeRequest.gestao && request.tipo != TypeRequest.comando && request.tipo != TypeRequest.ofsInfo)
{
var messagem = "O ChatBOT não está funcionando no momento devido ao sistema SAP estar fora do ar.\n\nO BOT não tem como funcionar sem o SAP.";
await msg.sendTextMesssageWraper(message.From.Id, messagem);
return;
}
// Gets the installation of the request and since every request will be made by the installation
if(request.tipo != TypeRequest.gestao && request.tipo != TypeRequest.comando && request.tipo != TypeRequest.xlsInfo && request.tipo != TypeRequest.ofsInfo)
{
var knockout = DateTime.Now.AddMinutes(-5);
if(System.DateTime.Compare(knockout, request.received_at) > 0)
{
await msg.ErrorReport(user.id, new Exception(), request, "Sua solicitação expirou! Solicite novamente!");
return;
}
var resposta = telbot.Temporary.executar(cfg, "instalacao", request.informacao!);
if(resposta == null)
{
await msg.ErrorReport(user.id, new IndexOutOfRangeException("Não foi recebida nenhuma resposta do SAP"), request);
return;
}
if(!resposta.Any())
{
await msg.ErrorReport(user.id, new IndexOutOfRangeException("Não foi recebida nenhuma resposta do SAP"), request);
return;
}
if(!resposta.First().StartsWith("ERRO"))
{
request.informacao = Int64.Parse(resposta.First());
}
else
{
await msg.ErrorReport(user.id, new Exception(), request, String.Join('\n', resposta));
return;
}
if(cfg.IS_DEVELOPMENT == false)
{
if(Database.verificarRelatorio(request, user.id))
{
await msg.sendTextMesssageWraper(user.id, "Essa solicitação já foi respondida! Verifique a resposta enviada e se necessário solicite esclarecimentos para a monitora.");
return;
}
}
}
// When we get a command, we react accordingly
switch(request.tipo)
{
case TypeRequest.comando:
await Command.HandleCommand(msg, user, request, cfg);
break;
case TypeRequest.gestao:
if(!user.pode_autorizar())
{
await msg.sendTextMesssageWraper(user.id, "Você não tem permissão para alterar usuários!");
break;
}
await Manager.HandleManager(msg, cfg, user, request);
break;
case TypeRequest.anyInfo:
await Information.SendMultiples(msg, cfg, user, request);
break;
case TypeRequest.txtInfo:
await Information.SendManuscripts(msg, cfg, user, request);
break;
case TypeRequest.xyzInfo:
await Information.SendCoordinates(msg, cfg, user, request);
break;
case TypeRequest.picInfo:
await Information.SendPicture(msg, cfg, user, request);
break;
case TypeRequest.xlsInfo:
if(!user.pode_relatorios())
{
await msg.sendTextMesssageWraper(user.id, "Você não tem permissão para gerar relatórios!");
break;
}
await Information.SendWorksheet(msg, cfg, user, request);
break;
case TypeRequest.pdfInfo:
if(!cfg.GERAR_FATURAS)
{
await msg.ErrorReport(user.id, new Exception(), request, "O sistema SAP não está gerando faturas!");
await msg.sendTextMesssageWraper(user.id, "Solicitando o envio do código de barras por SMS...");
await Information.SendManuscripts(msg, cfg, user, request);
break;
}
if(request.aplicacao == "passivo" && (DateTime.Today.DayOfWeek == DayOfWeek.Friday || DateTime.Today.DayOfWeek == DayOfWeek.Saturday))
{
await msg.ErrorReport(user.id, new Exception(), request, "Essa aplicação não deve ser usada na sexta e no sábado!");
break;
}
if(cfg.PRL_SUBSISTEMA)
{
await Information.SendMultiples(msg, cfg, user, request);
break;
}
if(!await Information.SendDocument(msg, cfg, user, request))
{
await msg.sendTextMesssageWraper(user.id, "Solicitando o envio do código de barras por SMS...");
request.aplicacao = "codbarra";
await Information.SendManuscripts(msg, cfg, user, request);
}
break;
case TypeRequest.ofsInfo:
if(!user.pode_relatorios())
{
await msg.sendTextMesssageWraper(user.id, "Você não tem permissão para receber evidências!");
break;
}
await Information.SendMultiples(msg, cfg, user, request);
break;
}
return;
}
}