-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStartup.cs
197 lines (197 loc) · 7.58 KB
/
Startup.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
using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using telbot.handle;
using telbot.models;
using telbot.Helpers;
using telbot.Services;
using Microsoft.Extensions.Logging;
namespace telbot;
class Startup
{
static async Task Main(String[] args)
{
var logger = Logger.GetInstance<Startup>();
logger.LogInformation("#############################################");
logger.LogInformation("# BOT de atendimento automágico MestreRuan #");
logger.LogInformation("# Author: decimo3 (github.com/decimo3) #");
logger.LogInformation("# Repository: TelegramBotForFieldTeamHelper #");
logger.LogInformation("#############################################");
var config = Configuration.GetInstance(System.Environment.GetCommandLineArgs());
if(HandleAnnouncement.Executador("bot.exe") > 1)
{
logger.LogError("Já tem uma instância do chatbot rodando!");
logger.LogInformation("Aperte qualquer tecla para sair.");
Console.ReadKey();
System.Environment.Exit(1);
}
var oldExecutableFile = System.IO.Path.Combine(
System.AppContext.BaseDirectory, "bot.exe.old");
if(System.IO.File.Exists(oldExecutableFile))
System.IO.File.Delete(oldExecutableFile);
telbot.Helpers.Updater.Update();
Database.GetInstance(config);
var bot = new TelegramBotClient(config.BOT_TOKEN);
var msg = HandleMessage.GetInstance(bot);
using (var cts = new CancellationTokenSource())
{
bot.StartReceiving(updateHandler: HandleUpdate, pollingErrorHandler: HandleError, cancellationToken: cts.Token);
logger.LogInformation("Start listening for updates. Press enter to stop.");
if(config.IS_DEVELOPMENT == false) HandleAnnouncement.Comunicado();
if(config.SAP_VENCIMENTO) HandleAnnouncement.Vencimento("vencimento", 7);
if(config.SAP_BANDEIRADA) HandleAnnouncement.Vencimento("bandeirada", 7);
if(config.OFS_MONITORAMENTO)
{
var filhos = new String[] {"ofs.exe", "chrome.exe", "chromedriver.exe"};
HandleAnnouncement.Executador("ofs.exe", new String[] {"slower"}, filhos);
}
if(config.PRL_SUBSISTEMA)
{
var filhos = new String[] {"prl.exe", "chrome.exe", "chromedriver.exe"};
HandleAnnouncement.Executador("prl.exe", new String[] {"slower"}, filhos);
}
HandleAnnouncement.Executador("cscript.exe", new String[] {"erroDialog.vbs"}, null);
var sap_instance_check_args = new String[] { "instancia", "5", "0"};
HandleAnnouncement.Executador("sap.exe", sap_instance_check_args, null);
# pragma warning disable CS4014
// Set chief method to answer normal requests
var normal_max_instance = (int)Math.Ceiling(config.SAP_INSTANCIA / 2.0);
HandleAsynchronous.Chief
(
minInstance: 0,
maxInstance: normal_max_instance,
s => s.typeRequest != TypeRequest.pdfInfo &&
s.typeRequest != TypeRequest.gestao &&
s.typeRequest != TypeRequest.comando
);
// Set chief method to answer invoice requests
HandleAsynchronous.Chief
(
minInstance: normal_max_instance,
maxInstance: config.SAP_INSTANCIA,
s => s.typeRequest == TypeRequest.pdfInfo
);
# pragma warning restore CS4014
PdfHandle.Watch();
Console.ReadLine();
cts.Cancel();
}
}
private static async Task HandleUpdate(ITelegramBotClient _, Update update, CancellationToken cancellationToken)
{
var logger = Logger.GetInstance<Startup>();
var chatbot = HandleMessage.GetInstance();
var msg2json = System.Text.Json.JsonSerializer.Serialize<Update>(update);
if(Configuration.GetInstance().IS_DEVELOPMENT)
{
logger.LogDebug(msg2json);
}
//##################################################//
// Ignora updates que não sejam mensagens //
//##################################################//
if (update.Type != UpdateType.Message || update.Message == null || update.Message.From == null) return;
//##################################################//
// Verifica se o usuário possui autorização //
//##################################################//
var usuario = await Manager.HandleSecury(
identificador: update.Message.From.Id,
recebido_em: update.Message.Date
);
if(usuario == null) return;
//##################################################//
// Verifica se o usuário possui telefone //
//##################################################//
if(usuario.phone_number == 0 && update.Message.Type != MessageType.Contact)
{
await chatbot.RequestContact(update.Message.From.Id);
return;
}
//##################################################//
// direciona para um método correspondente ao tipo //
//##################################################//
switch (update.Message.Type)
{
case MessageType.Text:
{
await HandleTypeMessage.ManuscriptsType(
usuario: usuario,
recebido_em: update.Message.Date.ToUniversalTime(),
mensagem: update.Message.Text!
);
break;
}
case MessageType.Contact:
{
await HandleTypeMessage.PhoneNumberType(
usuario: usuario,
telefone: Convert.ToInt64(update.Message.Contact!.PhoneNumber.Replace("+", "")),
username: update.Message.From.FirstName + " " + update.Message.From.LastName
);
break;
}
case MessageType.Photo:
{
await HandleTypeMessage.PhotographType(
usuario: usuario,
recebido_em: update.Message.Date.ToUniversalTime(),
photograph: update.Message.Photo!.First().FileId,
caption: update.Message.Caption
);
break;
}
case MessageType.Document:
{
await HandleTypeMessage.DocumentType(
usuario: usuario,
recebido_em: update.Message.Date.ToUniversalTime(),
document: update.Message.Document!.FileId,
caption: update.Message.Caption
);
break;
}
case MessageType.Video:
{
await HandleTypeMessage.VideoclipType(
usuario: usuario,
recebido_em: update.Message.Date.ToUniversalTime(),
videoclip: update.Message.Video!.FileId,
caption: update.Message.Caption
);
break;
}
case MessageType.Location:
{
await HandleTypeMessage.CoordinatesType(
usuario: usuario,
recebido_em: update.Message.Date.ToUniversalTime(),
lat: update.Message.Location!.Latitude,
lon: update.Message.Location!.Longitude
);
break;
}
default:
{
var erroMessage = "O formato da mensagem não é reconhecido!";
await chatbot.ErrorReport(
error: new Exception(erroMessage),
request: new logsModel() {
identifier = update.Message.From.Id,
application = "nullmessage",
received_at = update.Message.Date.ToUniversalTime(),
response_at = DateTime.Now,
typeRequest = TypeRequest.nullInfo,
status = 400
});
}
break;
}
}
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
private static async Task HandleError(ITelegramBotClient _, Exception exception, CancellationToken cancellationToken)
{
Logger.GetInstance<Startup>().LogError(
exception, "Erro crítico que poderia parar a aplicação: "
);
}
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
}