-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathUpdatesHandler.cs
398 lines (387 loc) · 17.8 KB
/
UpdatesHandler.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
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
using System;
using System.Threading;
using System.Threading.Tasks;
using Telegram.Td;
using Telegram.Td.Api;
namespace AutoReplyUserBot
{
public class UpdatesHandler : ClientResultHandler
{
public async void OnResult(BaseObject @object)
{
if (@object is UpdateAuthorizationState updAuthState)
{
await OnAuthorizationState(updAuthState.AuthorizationState);
}
else if (@object is UpdateNewMessage updMessage)
{
await OnMessage(updMessage.Message);
}
else if (@object is UpdateConnectionState updConnState && AppData.ConnectionStateUpdates)
{
if (updConnState.State is ConnectionStateReady)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Connected!");
Console.ResetColor();
}
else if (updConnState.State is ConnectionStateUpdating)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("Updating...");
Console.ResetColor();
}
else if (updConnState.State is ConnectionStateWaitingForNetwork)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Error.WriteLine("Waiting for network..!");
Console.ResetColor();
}
else if (updConnState.State is ConnectionStateConnecting)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("Connecting...");
Console.ResetColor();
}
else if (updConnState.State is ConnectionStateConnectingToProxy)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("Connecting to proxy...");
Console.ResetColor();
}
}
else if (@object is UpdateOption updOpt)
{
Console.ForegroundColor = ConsoleColor.Gray;
if (updOpt.Name == "version")
{
Program.TDLibVersion = (updOpt.Value as OptionValueString).Value;
if (AppData.TDLibVersion)
Console.WriteLine($"TDLib Version: {Program.TDLibVersion}");
}
//else if (updOpt.Name == "version" && AppOptions.AllowOutput && false)
//{
// Console.WriteLine($"TDLib Version: {(updOpt.Value as OptionValueString).Value}");
//}
Console.ResetColor();
}
else
{
// Console.WriteLine(@object);
}
}
public async Task OnAuthorizationState(AuthorizationState authState)
{
try
{
if (authState is AuthorizationStateWaitTdlibParameters)
{
await Program.App.SendAsync(new SetTdlibParameters(new TdlibParameters(
TDLibData.UseTestDc,
"AutoReplyUserBotDB",
"AutoReplyUserBotFiles",
TDLibData.UseFilesDB,
TDLibData.UseChatsDB,
TDLibData.UseMessagesDB,
TDLibData.UseSecretChats,
TDLibData.API_ID,
TDLibData.API_HASH,
Helper.GetSystemLanguage(),
Helper.GetDeviceModel(),
Helper.GetOSVersion(),
Helper.GetAppVersion(),
TDLibData.EnableStorageOptimizer,
true
)));
}
else if (authState is AuthorizationStateWaitEncryptionKey)
{
await Program.App.SendAsync(new SetDatabaseEncryptionKey());
}
else if (authState is AuthorizationStateWaitPhoneNumber)
{
Console.Write("Enter phone number: ");
await Program.App.SendAsync(
new SetAuthenticationPhoneNumber(
Console.ReadLine(), // Phone number
new PhoneNumberAuthenticationSettings(false, true, false, false, new string[] { })
)
);
}
else if (authState is AuthorizationStateWaitCode code)
{
string type = "unknown";
string length = "unknown";
if (code.CodeInfo.Type is AuthenticationCodeTypeTelegramMessage message)
{
type = "message";
length = message.Length.ToString();
}
else if (code.CodeInfo.Type is AuthenticationCodeTypeSms sms)
{
type = "SMS";
length = sms.Length.ToString();
}
else if (code.CodeInfo.Type is AuthenticationCodeTypeMissedCall missedCall)
{
type = "Missed call";
length = missedCall.Length.ToString();
}
else if (code.CodeInfo.Type is AuthenticationCodeTypeFlashCall flashCall)
{
type = "Flash call";
//length = flashCall.Length.ToString();
}
else if (code.CodeInfo.Type is AuthenticationCodeTypeCall call)
{
type = "Call";
length = call.Length.ToString();
}
Console.WriteLine($"An authentication code received by {type}");
Console.Write($"Enter code (Length: {length}): ");
await Program.App.SendAsync(new CheckAuthenticationCode(Console.ReadLine()));
}
else if (authState is AuthorizationStateWaitPassword password)
{
EnterCloudPassword:
Console.WriteLine("CLOUD PASSWORD (If empty means resetting your password)");
Console.Write($"Enter your cloud password ({password.PasswordHint}): ");
string passwordStr = Console.ReadLine();
if (passwordStr == "")
{
if (password.HasRecoveryEmailAddress)
{
await Program.App.SendAsync(new RequestAuthenticationPasswordRecovery());
Console.WriteLine($"Sent recovery code to {password.RecoveryEmailAddressPattern}");
Console.Write("Enter recovery code: ");
await Program.App.SendAsync(new CheckRecoveryEmailAddressCode(Console.ReadLine()));
}
else
{
Console.WriteLine("There's no recovery email, Use Some logged in account to reset it");
goto EnterCloudPassword;
}
}
else
{
await Program.App.SendAsync(new CheckAuthenticationPassword(passwordStr));
}
}
else if (authState is AuthorizationStateReady)
{
var me = await Program.App.SendAsync(new GetMe()) as User;
if (AppData.AuthenticatedMessage)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Authenticated!");
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine($"Hi, {me.FirstName}. your ID is {me.Id} :)");
Program.Me = me;
// Converting unix-timestmap
var authDate = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
BaseObject authDateOpt = await Program.App.SendAsync(new GetOption("authorization_date"));
long unixAuthDate = (authDateOpt as OptionValueInteger).Value;
Program.AuthorizationDate = authDate.AddSeconds(unixAuthDate).ToLocalTime();
#if DEBUG
Console.WriteLine("Auth Date: " + unixAuthDate);
#endif
Console.ResetColor();
}
Thread.Sleep(1000);
}
else if (authState is AuthorizationStateLoggingOut)
{
Console.WriteLine("Logging out..");
}
else if (authState is AuthorizationStateClosing)
{
Console.WriteLine("Closing..");
}
else if (authState is AuthorizationStateClosed)
{
Console.WriteLine("The App closed!");
}
}
catch (TDLibException ex)
{
// Output in red color
Console.ForegroundColor = ConsoleColor.Red;
Console.Error.WriteLine($"Error[{ex.Code}]: {ex.Message}");
Console.ResetColor();
Thread.Sleep(1000);
if (ex.Message == "Valid api_id must be provided. Can be obtained at https://my.telegram.org")
{
Program.Exit = true;
}
else
{
// Repeat authorization
await OnAuthorizationState(authState);
}
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Error.WriteLine($"Error[Unknown] in {ex.Source}: {ex.Message}");
Console.ResetColor();
}
}
public async Task OnMessage(Message message)
{
var me = (await Program.App.SendAsync(new GetMe()) as User);
if (message.Content is MessageText text)
{
if (message.ChatId == me.Id && message.Id != Program.LastMessageID)
{
string txt = text.Text.Text;
string botReply = "";
if (txt[0] == '/')
{
if (txt == "/cancel")
{
Program.State = "canceled";
botReply = "Ok, Last command was canceled";
}
else if (txt == "/add")
{
Program.State = "waiting_command";
botReply = "Good, Now send the command";
}
else if (txt == "/auto_replies")
{
Program.State = "auto_replies_sent";
botReply = "Auto-replies is:";
foreach (var autoReply in Program.AutoReplies)
{
botReply += $"\n{autoReply.Key} == {autoReply.Value.Text}";
}
}
else if (txt == "/state")
{
botReply = @$"<b>Auto-reply userbot info:</b>
Userbot version: <code>v{Helper.GetAppVersion()}</code>
Your ID: <code>{Program.Me.Id}</code>
TDLib version: <code>{Program.TDLibVersion}</code>
Auth date: <code>{Program.AuthorizationDate.ToString("yyyy/M/d t h:m:s")}</code>
Run time: <code>{Program.RunTime}</code>
Auto-replies count: {Program.AutoReplies.Count}
Auto-reply signature: <i>{(AppData.UseAutoReplySigniture ? AppData.AutoReplySignitureText : "")}</i>
Auto-reply state: <code>{Program.State}</code>
Only in private chats: <code>{AppData.OnlyInPrivateChats}</code>";
Program.State = "state_sent";
}
else if (txt == "/signature")
{
Program.State = "waiting_signature";
botReply = "Send the new signature.\nIf you don't want a signature, send <i>\"disable\"</i>";
}
else if (txt == "/clear")
{
Program.AutoReplies.Clear();
Program.State = "auto_replies_cleared";
botReply = "Deleted all commands successfully";
}
else if (txt == "/allow_reply_when_online")
{
AppData.ReplyWhenOnline = true;
Program.State = "allowed_reply_when_online";
botReply = "Now the userbot <b>will reply</b> even if you are online";
}
else if (txt == "/disallow_reply_when_online")
{
AppData.ReplyWhenOnline = false;
Program.State = "disallowed_reply_when_online";
botReply = "Now the userbot <b>won't</b> reply even if you are online";
}
else
{
botReply = @"Please use a valid command, Commands is:
/add - Adds new auto-reply
/auto_replies - Shows all stored auto-replies
/clear - Clears all auto-replies
/state - Getting info about the userbot
/signature - Editing/Disabling signature
/allow_reply_when_online - Allowing userbot to reply when online
/disallow_reply_when_online - Disallowing userbot to reply when online
/cancel - Cancels last operation";
}
}
else if (Program.State == "waiting_command")
{
if (Program.AutoReplies.ContainsKey(text.Text.Text))
{
botReply = "This command is already in replies!";
}
else
{
Program.currentCommand = text.Text.Text;
Program.State = "waiting_reply";
botReply = "Command added, Now add the reply";
}
}
else if (Program.State == "waiting_reply")
{
Program.AutoReplies.Add(Program.currentCommand, text.Text);
Program.State = "auto_reply_added";
botReply = $"the Auto-reply added, Now you have {Program.AutoReplies.Count} Auto-replies..";
}
else if (Program.State == "waiting_siganture")
{
if (txt == "false" || txt == "no" || txt == "disable")
{
AppData.UseAutoReplySigniture = false;
botReply = "Auto-reply signature was disabled!";
}
else
{
AppData.AutoReplySignitureText = txt;
AppData.UseAutoReplySigniture = true;
botReply = "Auto-reply signature was enabled!";
}
Program.State = "signature_edited";
}
if (botReply != "")
{
Message lastMsg = await Program.App.SendAsync(
new SendMessage(me.Id,
0,
message.Id,
new MessageSendOptions(),
null,
new InputMessageText(Client.Execute(new ParseTextEntities(botReply, new TextParseModeHTML())) as FormattedText, true, false)
)
) as Message;
Program.LastMessageID = lastMsg.Id;
}
}
else if (!(me.Status is UserStatusOnline) || !AppData.ReplyWhenOnline && message.ChatId != me.Id)
{
Chat chat = await Program.App.SendAsync(new GetChat(message.ChatId)) as Chat;
// Replies only in private chats
if (chat.Type is ChatTypePrivate)
{
foreach (var reply in Program.AutoReplies)
{
if (text.Text.Text.Contains(reply.Key))
{
FormattedText editedReply = reply.Value;
editedReply.Text += (AppData.UseAutoReplySigniture ? "\n\n" + AppData.AutoReplySignitureText : "");
await Program.App.SendAsync(
new SendMessage(
message.ChatId,
0,
message.Id,
new MessageSendOptions(),
null,
new InputMessageText(editedReply, false, false)
)
);
}
}
}
await Program.App.SendAsync(new SetOption("online", new OptionValueBoolean(false)));
}
}
}
}
}